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 ltimeout_list;
379 struct list_head cq_overflow_list;
380 struct xarray io_buffers;
381 struct xarray personalities;
383 unsigned sq_thread_idle;
384 } ____cacheline_aligned_in_smp;
386 /* IRQ completion list, under ->completion_lock */
387 struct list_head locked_free_list;
388 unsigned int locked_free_nr;
390 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
391 struct io_sq_data *sq_data; /* if using sq thread polling */
393 struct wait_queue_head sqo_sq_wait;
394 struct list_head sqd_list;
396 unsigned long check_cq_overflow;
399 unsigned cached_cq_tail;
401 struct eventfd_ctx *cq_ev_fd;
402 struct wait_queue_head poll_wait;
403 struct wait_queue_head cq_wait;
405 atomic_t cq_timeouts;
406 struct fasync_struct *cq_fasync;
407 unsigned cq_last_tm_flush;
408 } ____cacheline_aligned_in_smp;
411 spinlock_t completion_lock;
413 spinlock_t timeout_lock;
416 * ->iopoll_list is protected by the ctx->uring_lock for
417 * io_uring instances that don't use IORING_SETUP_SQPOLL.
418 * For SQPOLL, only the single threaded io_sq_thread() will
419 * manipulate the list, hence no extra locking is needed there.
421 struct list_head iopoll_list;
422 struct hlist_head *cancel_hash;
423 unsigned cancel_hash_bits;
424 bool poll_multi_queue;
425 } ____cacheline_aligned_in_smp;
427 struct io_restriction restrictions;
429 /* slow path rsrc auxilary data, used by update/register */
431 struct io_rsrc_node *rsrc_backup_node;
432 struct io_mapped_ubuf *dummy_ubuf;
433 struct io_rsrc_data *file_data;
434 struct io_rsrc_data *buf_data;
436 struct delayed_work rsrc_put_work;
437 struct llist_head rsrc_put_llist;
438 struct list_head rsrc_ref_list;
439 spinlock_t rsrc_ref_lock;
442 /* Keep this last, we don't need it for the fast path */
444 #if defined(CONFIG_UNIX)
445 struct socket *ring_sock;
447 /* hashed buffered write serialization */
448 struct io_wq_hash *hash_map;
450 /* Only used for accounting purposes */
451 struct user_struct *user;
452 struct mm_struct *mm_account;
454 /* ctx exit and cancelation */
455 struct llist_head fallback_llist;
456 struct delayed_work fallback_work;
457 struct work_struct exit_work;
458 struct list_head tctx_list;
459 struct completion ref_comp;
463 struct io_uring_task {
464 /* submission side */
467 struct wait_queue_head wait;
468 const struct io_ring_ctx *last;
470 struct percpu_counter inflight;
471 atomic_t inflight_tracked;
474 spinlock_t task_lock;
475 struct io_wq_work_list task_list;
476 struct callback_head task_work;
481 * First field must be the file pointer in all the
482 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
484 struct io_poll_iocb {
486 struct wait_queue_head *head;
490 struct wait_queue_entry wait;
493 struct io_poll_update {
499 bool update_user_data;
507 struct io_timeout_data {
508 struct io_kiocb *req;
509 struct hrtimer timer;
510 struct timespec64 ts;
511 enum hrtimer_mode mode;
517 struct sockaddr __user *addr;
518 int __user *addr_len;
521 unsigned long nofile;
541 struct list_head list;
542 /* head of the link, used by linked timeouts only */
543 struct io_kiocb *head;
544 /* for linked completions */
545 struct io_kiocb *prev;
548 struct io_timeout_rem {
553 struct timespec64 ts;
559 /* NOTE: kiocb has the file as the first member, so don't do it here */
567 struct sockaddr __user *addr;
574 struct compat_msghdr __user *umsg_compat;
575 struct user_msghdr __user *umsg;
581 struct io_buffer *kbuf;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
624 struct file *file_in;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
670 struct io_completion {
675 struct io_async_connect {
676 struct sockaddr_storage address;
679 struct io_async_msghdr {
680 struct iovec fast_iov[UIO_FASTIOV];
681 /* points to an allocated iov, if NULL we use fast_iov instead */
682 struct iovec *free_iov;
683 struct sockaddr __user *uaddr;
685 struct sockaddr_storage addr;
689 struct iovec fast_iov[UIO_FASTIOV];
690 const struct iovec *free_iovec;
691 struct iov_iter iter;
693 struct wait_page_queue wpq;
697 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
698 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
699 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
700 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
701 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
702 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
704 /* first byte is taken by user flags, shift it to not overlap */
709 REQ_F_LINK_TIMEOUT_BIT,
710 REQ_F_NEED_CLEANUP_BIT,
712 REQ_F_BUFFER_SELECTED_BIT,
713 REQ_F_COMPLETE_INLINE_BIT,
715 REQ_F_DONT_REISSUE_BIT,
718 REQ_F_ARM_LTIMEOUT_BIT,
719 /* keep async read/write and isreg together and in order */
720 REQ_F_NOWAIT_READ_BIT,
721 REQ_F_NOWAIT_WRITE_BIT,
724 /* not a real bit, just to check we're not overflowing the space */
730 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
731 /* drain existing IO first */
732 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
734 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
735 /* doesn't sever on completion < 0 */
736 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
738 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
739 /* IOSQE_BUFFER_SELECT */
740 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
742 /* fail rest of links */
743 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
744 /* on inflight list, should be cancelled and waited on exit reliably */
745 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
746 /* read/write uses file position */
747 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
748 /* must not punt to workers */
749 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
750 /* has or had linked timeout */
751 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
753 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
754 /* already went through poll handler */
755 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
756 /* buffer already selected */
757 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
758 /* completion is deferred through io_comp_state */
759 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
760 /* caller should reissue async */
761 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
762 /* don't attempt request reissue, see io_rw_reissue() */
763 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
764 /* supports async reads */
765 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
766 /* supports async writes */
767 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
769 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
770 /* has creds assigned */
771 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
772 /* skip refcounting if not set */
773 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
774 /* there is a linked timeout that has to be armed */
775 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
779 struct io_poll_iocb poll;
780 struct io_poll_iocb *double_poll;
783 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
785 struct io_task_work {
787 struct io_wq_work_node node;
788 struct llist_node fallback_node;
790 io_req_tw_func_t func;
794 IORING_RSRC_FILE = 0,
795 IORING_RSRC_BUFFER = 1,
799 * NOTE! Each of the iocb union members has the file pointer
800 * as the first entry in their struct definition. So you can
801 * access the file pointer through any of the sub-structs,
802 * or directly as just 'ki_filp' in this struct.
808 struct io_poll_iocb poll;
809 struct io_poll_update poll_update;
810 struct io_accept accept;
812 struct io_cancel cancel;
813 struct io_timeout timeout;
814 struct io_timeout_rem timeout_rem;
815 struct io_connect connect;
816 struct io_sr_msg sr_msg;
818 struct io_close close;
819 struct io_rsrc_update rsrc_update;
820 struct io_fadvise fadvise;
821 struct io_madvise madvise;
822 struct io_epoll epoll;
823 struct io_splice splice;
824 struct io_provide_buf pbuf;
825 struct io_statx statx;
826 struct io_shutdown shutdown;
827 struct io_rename rename;
828 struct io_unlink unlink;
829 /* use only after cleaning per-op data, see io_clean_op() */
830 struct io_completion compl;
833 /* opcode allocated if it needs to store data for async defer */
836 /* polled IO has completed */
842 struct io_ring_ctx *ctx;
845 struct task_struct *task;
848 struct io_kiocb *link;
849 struct percpu_ref *fixed_rsrc_refs;
851 /* used with ctx->iopoll_list with reads/writes */
852 struct list_head inflight_entry;
853 struct io_task_work io_task_work;
854 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
855 struct hlist_node hash_node;
856 struct async_poll *apoll;
857 struct io_wq_work work;
858 const struct cred *creds;
860 /* store used ubuf, so we can prevent reloading */
861 struct io_mapped_ubuf *imu;
864 struct io_tctx_node {
865 struct list_head ctx_node;
866 struct task_struct *task;
867 struct io_ring_ctx *ctx;
870 struct io_defer_entry {
871 struct list_head list;
872 struct io_kiocb *req;
877 /* needs req->file assigned */
878 unsigned needs_file : 1;
879 /* hash wq insertion if file is a regular file */
880 unsigned hash_reg_file : 1;
881 /* unbound wq insertion if file is a non-regular file */
882 unsigned unbound_nonreg_file : 1;
883 /* opcode is not supported by this kernel */
884 unsigned not_supported : 1;
885 /* set if opcode supports polled "wait" */
887 unsigned pollout : 1;
888 /* op supports buffer selection */
889 unsigned buffer_select : 1;
890 /* do prep async if is going to be punted */
891 unsigned needs_async_setup : 1;
892 /* should block plug */
894 /* size of async data needed, if any */
895 unsigned short async_size;
898 static const struct io_op_def io_op_defs[] = {
899 [IORING_OP_NOP] = {},
900 [IORING_OP_READV] = {
902 .unbound_nonreg_file = 1,
905 .needs_async_setup = 1,
907 .async_size = sizeof(struct io_async_rw),
909 [IORING_OP_WRITEV] = {
912 .unbound_nonreg_file = 1,
914 .needs_async_setup = 1,
916 .async_size = sizeof(struct io_async_rw),
918 [IORING_OP_FSYNC] = {
921 [IORING_OP_READ_FIXED] = {
923 .unbound_nonreg_file = 1,
926 .async_size = sizeof(struct io_async_rw),
928 [IORING_OP_WRITE_FIXED] = {
931 .unbound_nonreg_file = 1,
934 .async_size = sizeof(struct io_async_rw),
936 [IORING_OP_POLL_ADD] = {
938 .unbound_nonreg_file = 1,
940 [IORING_OP_POLL_REMOVE] = {},
941 [IORING_OP_SYNC_FILE_RANGE] = {
944 [IORING_OP_SENDMSG] = {
946 .unbound_nonreg_file = 1,
948 .needs_async_setup = 1,
949 .async_size = sizeof(struct io_async_msghdr),
951 [IORING_OP_RECVMSG] = {
953 .unbound_nonreg_file = 1,
956 .needs_async_setup = 1,
957 .async_size = sizeof(struct io_async_msghdr),
959 [IORING_OP_TIMEOUT] = {
960 .async_size = sizeof(struct io_timeout_data),
962 [IORING_OP_TIMEOUT_REMOVE] = {
963 /* used by timeout updates' prep() */
965 [IORING_OP_ACCEPT] = {
967 .unbound_nonreg_file = 1,
970 [IORING_OP_ASYNC_CANCEL] = {},
971 [IORING_OP_LINK_TIMEOUT] = {
972 .async_size = sizeof(struct io_timeout_data),
974 [IORING_OP_CONNECT] = {
976 .unbound_nonreg_file = 1,
978 .needs_async_setup = 1,
979 .async_size = sizeof(struct io_async_connect),
981 [IORING_OP_FALLOCATE] = {
984 [IORING_OP_OPENAT] = {},
985 [IORING_OP_CLOSE] = {},
986 [IORING_OP_FILES_UPDATE] = {},
987 [IORING_OP_STATX] = {},
990 .unbound_nonreg_file = 1,
994 .async_size = sizeof(struct io_async_rw),
996 [IORING_OP_WRITE] = {
999 .unbound_nonreg_file = 1,
1002 .async_size = sizeof(struct io_async_rw),
1004 [IORING_OP_FADVISE] = {
1007 [IORING_OP_MADVISE] = {},
1008 [IORING_OP_SEND] = {
1010 .unbound_nonreg_file = 1,
1013 [IORING_OP_RECV] = {
1015 .unbound_nonreg_file = 1,
1019 [IORING_OP_OPENAT2] = {
1021 [IORING_OP_EPOLL_CTL] = {
1022 .unbound_nonreg_file = 1,
1024 [IORING_OP_SPLICE] = {
1027 .unbound_nonreg_file = 1,
1029 [IORING_OP_PROVIDE_BUFFERS] = {},
1030 [IORING_OP_REMOVE_BUFFERS] = {},
1034 .unbound_nonreg_file = 1,
1036 [IORING_OP_SHUTDOWN] = {
1039 [IORING_OP_RENAMEAT] = {},
1040 [IORING_OP_UNLINKAT] = {},
1043 /* requests with any of those set should undergo io_disarm_next() */
1044 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1046 static bool io_disarm_next(struct io_kiocb *req);
1047 static void io_uring_del_tctx_node(unsigned long index);
1048 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1049 struct task_struct *task,
1051 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1053 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1054 long res, unsigned int cflags);
1055 static void io_put_req(struct io_kiocb *req);
1056 static void io_put_req_deferred(struct io_kiocb *req);
1057 static void io_dismantle_req(struct io_kiocb *req);
1058 static void io_queue_linked_timeout(struct io_kiocb *req);
1059 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1060 struct io_uring_rsrc_update2 *up,
1062 static void io_clean_op(struct io_kiocb *req);
1063 static struct file *io_file_get(struct io_ring_ctx *ctx,
1064 struct io_kiocb *req, int fd, bool fixed);
1065 static void __io_queue_sqe(struct io_kiocb *req);
1066 static void io_rsrc_put_work(struct work_struct *work);
1068 static void io_req_task_queue(struct io_kiocb *req);
1069 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1070 static int io_req_prep_async(struct io_kiocb *req);
1072 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1073 unsigned int issue_flags, u32 slot_index);
1074 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1076 static struct kmem_cache *req_cachep;
1078 static const struct file_operations io_uring_fops;
1080 struct sock *io_uring_get_socket(struct file *file)
1082 #if defined(CONFIG_UNIX)
1083 if (file->f_op == &io_uring_fops) {
1084 struct io_ring_ctx *ctx = file->private_data;
1086 return ctx->ring_sock->sk;
1091 EXPORT_SYMBOL(io_uring_get_socket);
1093 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1096 mutex_lock(&ctx->uring_lock);
1101 #define io_for_each_link(pos, head) \
1102 for (pos = (head); pos; pos = pos->link)
1105 * Shamelessly stolen from the mm implementation of page reference checking,
1106 * see commit f958d7b528b1 for details.
1108 #define req_ref_zero_or_close_to_overflow(req) \
1109 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1111 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1113 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1114 return atomic_inc_not_zero(&req->refs);
1117 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1119 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1122 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1123 return atomic_dec_and_test(&req->refs);
1126 static inline void req_ref_put(struct io_kiocb *req)
1128 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1129 WARN_ON_ONCE(req_ref_put_and_test(req));
1132 static inline void req_ref_get(struct io_kiocb *req)
1134 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1135 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1136 atomic_inc(&req->refs);
1139 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1141 if (!(req->flags & REQ_F_REFCOUNT)) {
1142 req->flags |= REQ_F_REFCOUNT;
1143 atomic_set(&req->refs, nr);
1147 static inline void io_req_set_refcount(struct io_kiocb *req)
1149 __io_req_set_refcount(req, 1);
1152 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1154 struct io_ring_ctx *ctx = req->ctx;
1156 if (!req->fixed_rsrc_refs) {
1157 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1158 percpu_ref_get(req->fixed_rsrc_refs);
1162 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1164 bool got = percpu_ref_tryget(ref);
1166 /* already at zero, wait for ->release() */
1168 wait_for_completion(compl);
1169 percpu_ref_resurrect(ref);
1171 percpu_ref_put(ref);
1174 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1177 struct io_kiocb *req;
1179 if (task && head->task != task)
1184 io_for_each_link(req, head) {
1185 if (req->flags & REQ_F_INFLIGHT)
1191 static inline void req_set_fail(struct io_kiocb *req)
1193 req->flags |= REQ_F_FAIL;
1196 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1202 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1204 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1206 complete(&ctx->ref_comp);
1209 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1211 return !req->timeout.off;
1214 static void io_fallback_req_func(struct work_struct *work)
1216 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1217 fallback_work.work);
1218 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1219 struct io_kiocb *req, *tmp;
1220 bool locked = false;
1222 percpu_ref_get(&ctx->refs);
1223 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1224 req->io_task_work.func(req, &locked);
1227 if (ctx->submit_state.compl_nr)
1228 io_submit_flush_completions(ctx);
1229 mutex_unlock(&ctx->uring_lock);
1231 percpu_ref_put(&ctx->refs);
1235 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1237 struct io_ring_ctx *ctx;
1240 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1245 * Use 5 bits less than the max cq entries, that should give us around
1246 * 32 entries per hash list if totally full and uniformly spread.
1248 hash_bits = ilog2(p->cq_entries);
1252 ctx->cancel_hash_bits = hash_bits;
1253 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1255 if (!ctx->cancel_hash)
1257 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1259 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1260 if (!ctx->dummy_ubuf)
1262 /* set invalid range, so io_import_fixed() fails meeting it */
1263 ctx->dummy_ubuf->ubuf = -1UL;
1265 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1266 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1269 ctx->flags = p->flags;
1270 init_waitqueue_head(&ctx->sqo_sq_wait);
1271 INIT_LIST_HEAD(&ctx->sqd_list);
1272 init_waitqueue_head(&ctx->poll_wait);
1273 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1274 init_completion(&ctx->ref_comp);
1275 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1276 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1277 mutex_init(&ctx->uring_lock);
1278 init_waitqueue_head(&ctx->cq_wait);
1279 spin_lock_init(&ctx->completion_lock);
1280 spin_lock_init(&ctx->timeout_lock);
1281 INIT_LIST_HEAD(&ctx->iopoll_list);
1282 INIT_LIST_HEAD(&ctx->defer_list);
1283 INIT_LIST_HEAD(&ctx->timeout_list);
1284 INIT_LIST_HEAD(&ctx->ltimeout_list);
1285 spin_lock_init(&ctx->rsrc_ref_lock);
1286 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1287 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1288 init_llist_head(&ctx->rsrc_put_llist);
1289 INIT_LIST_HEAD(&ctx->tctx_list);
1290 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1291 INIT_LIST_HEAD(&ctx->locked_free_list);
1292 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1295 kfree(ctx->dummy_ubuf);
1296 kfree(ctx->cancel_hash);
1301 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1303 struct io_rings *r = ctx->rings;
1305 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1309 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1311 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1312 struct io_ring_ctx *ctx = req->ctx;
1314 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1320 #define FFS_ASYNC_READ 0x1UL
1321 #define FFS_ASYNC_WRITE 0x2UL
1323 #define FFS_ISREG 0x4UL
1325 #define FFS_ISREG 0x0UL
1327 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1329 static inline bool io_req_ffs_set(struct io_kiocb *req)
1331 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1334 static void io_req_track_inflight(struct io_kiocb *req)
1336 if (!(req->flags & REQ_F_INFLIGHT)) {
1337 req->flags |= REQ_F_INFLIGHT;
1338 atomic_inc(¤t->io_uring->inflight_tracked);
1342 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1344 req->flags &= ~REQ_F_LINK_TIMEOUT;
1347 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1349 if (WARN_ON_ONCE(!req->link))
1352 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1353 req->flags |= REQ_F_LINK_TIMEOUT;
1355 /* linked timeouts should have two refs once prep'ed */
1356 io_req_set_refcount(req);
1357 __io_req_set_refcount(req->link, 2);
1361 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1363 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1365 return __io_prep_linked_timeout(req);
1368 static void io_prep_async_work(struct io_kiocb *req)
1370 const struct io_op_def *def = &io_op_defs[req->opcode];
1371 struct io_ring_ctx *ctx = req->ctx;
1373 if (!(req->flags & REQ_F_CREDS)) {
1374 req->flags |= REQ_F_CREDS;
1375 req->creds = get_current_cred();
1378 req->work.list.next = NULL;
1379 req->work.flags = 0;
1380 if (req->flags & REQ_F_FORCE_ASYNC)
1381 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1383 if (req->flags & REQ_F_ISREG) {
1384 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1385 io_wq_hash_work(&req->work, file_inode(req->file));
1386 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1387 if (def->unbound_nonreg_file)
1388 req->work.flags |= IO_WQ_WORK_UNBOUND;
1391 switch (req->opcode) {
1392 case IORING_OP_SPLICE:
1394 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1395 req->work.flags |= IO_WQ_WORK_UNBOUND;
1400 static void io_prep_async_link(struct io_kiocb *req)
1402 struct io_kiocb *cur;
1404 if (req->flags & REQ_F_LINK_TIMEOUT) {
1405 struct io_ring_ctx *ctx = req->ctx;
1407 spin_lock(&ctx->completion_lock);
1408 io_for_each_link(cur, req)
1409 io_prep_async_work(cur);
1410 spin_unlock(&ctx->completion_lock);
1412 io_for_each_link(cur, req)
1413 io_prep_async_work(cur);
1417 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1419 struct io_ring_ctx *ctx = req->ctx;
1420 struct io_kiocb *link = io_prep_linked_timeout(req);
1421 struct io_uring_task *tctx = req->task->io_uring;
1423 /* must not take the lock, NULL it as a precaution */
1427 BUG_ON(!tctx->io_wq);
1429 /* init ->work of the whole link before punting */
1430 io_prep_async_link(req);
1433 * Not expected to happen, but if we do have a bug where this _can_
1434 * happen, catch it here and ensure the request is marked as
1435 * canceled. That will make io-wq go through the usual work cancel
1436 * procedure rather than attempt to run this request (or create a new
1439 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1440 req->work.flags |= IO_WQ_WORK_CANCEL;
1442 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1443 &req->work, req->flags);
1444 io_wq_enqueue(tctx->io_wq, &req->work);
1446 io_queue_linked_timeout(link);
1449 static void io_kill_timeout(struct io_kiocb *req, int status)
1450 __must_hold(&req->ctx->completion_lock)
1451 __must_hold(&req->ctx->timeout_lock)
1453 struct io_timeout_data *io = req->async_data;
1455 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1456 atomic_set(&req->ctx->cq_timeouts,
1457 atomic_read(&req->ctx->cq_timeouts) + 1);
1458 list_del_init(&req->timeout.list);
1459 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1460 io_put_req_deferred(req);
1464 static void io_queue_deferred(struct io_ring_ctx *ctx)
1466 while (!list_empty(&ctx->defer_list)) {
1467 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1468 struct io_defer_entry, list);
1470 if (req_need_defer(de->req, de->seq))
1472 list_del_init(&de->list);
1473 io_req_task_queue(de->req);
1478 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1479 __must_hold(&ctx->completion_lock)
1481 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1483 spin_lock_irq(&ctx->timeout_lock);
1484 while (!list_empty(&ctx->timeout_list)) {
1485 u32 events_needed, events_got;
1486 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1487 struct io_kiocb, timeout.list);
1489 if (io_is_timeout_noseq(req))
1493 * Since seq can easily wrap around over time, subtract
1494 * the last seq at which timeouts were flushed before comparing.
1495 * Assuming not more than 2^31-1 events have happened since,
1496 * these subtractions won't have wrapped, so we can check if
1497 * target is in [last_seq, current_seq] by comparing the two.
1499 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1500 events_got = seq - ctx->cq_last_tm_flush;
1501 if (events_got < events_needed)
1504 list_del_init(&req->timeout.list);
1505 io_kill_timeout(req, 0);
1507 ctx->cq_last_tm_flush = seq;
1508 spin_unlock_irq(&ctx->timeout_lock);
1511 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1513 if (ctx->off_timeout_used)
1514 io_flush_timeouts(ctx);
1515 if (ctx->drain_active)
1516 io_queue_deferred(ctx);
1519 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1521 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1522 __io_commit_cqring_flush(ctx);
1523 /* order cqe stores with ring update */
1524 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1527 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1529 struct io_rings *r = ctx->rings;
1531 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1534 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1536 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1539 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1541 struct io_rings *rings = ctx->rings;
1542 unsigned tail, mask = ctx->cq_entries - 1;
1545 * writes to the cq entry need to come after reading head; the
1546 * control dependency is enough as we're using WRITE_ONCE to
1549 if (__io_cqring_events(ctx) == ctx->cq_entries)
1552 tail = ctx->cached_cq_tail++;
1553 return &rings->cqes[tail & mask];
1556 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1558 if (likely(!ctx->cq_ev_fd))
1560 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1562 return !ctx->eventfd_async || io_wq_current_is_worker();
1566 * This should only get called when at least one event has been posted.
1567 * Some applications rely on the eventfd notification count only changing
1568 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1569 * 1:1 relationship between how many times this function is called (and
1570 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1572 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1575 * wake_up_all() may seem excessive, but io_wake_function() and
1576 * io_should_wake() handle the termination of the loop and only
1577 * wake as many waiters as we need to.
1579 if (wq_has_sleeper(&ctx->cq_wait))
1580 wake_up_all(&ctx->cq_wait);
1581 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1582 wake_up(&ctx->sq_data->wait);
1583 if (io_should_trigger_evfd(ctx))
1584 eventfd_signal(ctx->cq_ev_fd, 1);
1585 if (waitqueue_active(&ctx->poll_wait)) {
1586 wake_up_interruptible(&ctx->poll_wait);
1587 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1591 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1593 if (ctx->flags & IORING_SETUP_SQPOLL) {
1594 if (wq_has_sleeper(&ctx->cq_wait))
1595 wake_up_all(&ctx->cq_wait);
1597 if (io_should_trigger_evfd(ctx))
1598 eventfd_signal(ctx->cq_ev_fd, 1);
1599 if (waitqueue_active(&ctx->poll_wait)) {
1600 wake_up_interruptible(&ctx->poll_wait);
1601 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1605 /* Returns true if there are no backlogged entries after the flush */
1606 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1608 bool all_flushed, posted;
1610 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1614 spin_lock(&ctx->completion_lock);
1615 while (!list_empty(&ctx->cq_overflow_list)) {
1616 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1617 struct io_overflow_cqe *ocqe;
1621 ocqe = list_first_entry(&ctx->cq_overflow_list,
1622 struct io_overflow_cqe, list);
1624 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1626 io_account_cq_overflow(ctx);
1629 list_del(&ocqe->list);
1633 all_flushed = list_empty(&ctx->cq_overflow_list);
1635 clear_bit(0, &ctx->check_cq_overflow);
1636 WRITE_ONCE(ctx->rings->sq_flags,
1637 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1641 io_commit_cqring(ctx);
1642 spin_unlock(&ctx->completion_lock);
1644 io_cqring_ev_posted(ctx);
1648 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1652 if (test_bit(0, &ctx->check_cq_overflow)) {
1653 /* iopoll syncs against uring_lock, not completion_lock */
1654 if (ctx->flags & IORING_SETUP_IOPOLL)
1655 mutex_lock(&ctx->uring_lock);
1656 ret = __io_cqring_overflow_flush(ctx, false);
1657 if (ctx->flags & IORING_SETUP_IOPOLL)
1658 mutex_unlock(&ctx->uring_lock);
1664 /* must to be called somewhat shortly after putting a request */
1665 static inline void io_put_task(struct task_struct *task, int nr)
1667 struct io_uring_task *tctx = task->io_uring;
1669 if (likely(task == current)) {
1670 tctx->cached_refs += nr;
1672 percpu_counter_sub(&tctx->inflight, nr);
1673 if (unlikely(atomic_read(&tctx->in_idle)))
1674 wake_up(&tctx->wait);
1675 put_task_struct_many(task, nr);
1679 static void io_task_refs_refill(struct io_uring_task *tctx)
1681 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1683 percpu_counter_add(&tctx->inflight, refill);
1684 refcount_add(refill, ¤t->usage);
1685 tctx->cached_refs += refill;
1688 static inline void io_get_task_refs(int nr)
1690 struct io_uring_task *tctx = current->io_uring;
1692 tctx->cached_refs -= nr;
1693 if (unlikely(tctx->cached_refs < 0))
1694 io_task_refs_refill(tctx);
1697 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1698 long res, unsigned int cflags)
1700 struct io_overflow_cqe *ocqe;
1702 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1705 * If we're in ring overflow flush mode, or in task cancel mode,
1706 * or cannot allocate an overflow entry, then we need to drop it
1709 io_account_cq_overflow(ctx);
1712 if (list_empty(&ctx->cq_overflow_list)) {
1713 set_bit(0, &ctx->check_cq_overflow);
1714 WRITE_ONCE(ctx->rings->sq_flags,
1715 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1718 ocqe->cqe.user_data = user_data;
1719 ocqe->cqe.res = res;
1720 ocqe->cqe.flags = cflags;
1721 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1725 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1726 long res, unsigned int cflags)
1728 struct io_uring_cqe *cqe;
1730 trace_io_uring_complete(ctx, user_data, res, cflags);
1733 * If we can't get a cq entry, userspace overflowed the
1734 * submission (by quite a lot). Increment the overflow count in
1737 cqe = io_get_cqe(ctx);
1739 WRITE_ONCE(cqe->user_data, user_data);
1740 WRITE_ONCE(cqe->res, res);
1741 WRITE_ONCE(cqe->flags, cflags);
1744 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1747 /* not as hot to bloat with inlining */
1748 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1749 long res, unsigned int cflags)
1751 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1754 static void io_req_complete_post(struct io_kiocb *req, long res,
1755 unsigned int cflags)
1757 struct io_ring_ctx *ctx = req->ctx;
1759 spin_lock(&ctx->completion_lock);
1760 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1762 * If we're the last reference to this request, add to our locked
1765 if (req_ref_put_and_test(req)) {
1766 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1767 if (req->flags & IO_DISARM_MASK)
1768 io_disarm_next(req);
1770 io_req_task_queue(req->link);
1774 io_dismantle_req(req);
1775 io_put_task(req->task, 1);
1776 list_add(&req->inflight_entry, &ctx->locked_free_list);
1777 ctx->locked_free_nr++;
1779 if (!percpu_ref_tryget(&ctx->refs))
1782 io_commit_cqring(ctx);
1783 spin_unlock(&ctx->completion_lock);
1786 io_cqring_ev_posted(ctx);
1787 percpu_ref_put(&ctx->refs);
1791 static inline bool io_req_needs_clean(struct io_kiocb *req)
1793 return req->flags & IO_REQ_CLEAN_FLAGS;
1796 static void io_req_complete_state(struct io_kiocb *req, long res,
1797 unsigned int cflags)
1799 if (io_req_needs_clean(req))
1802 req->compl.cflags = cflags;
1803 req->flags |= REQ_F_COMPLETE_INLINE;
1806 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1807 long res, unsigned cflags)
1809 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1810 io_req_complete_state(req, res, cflags);
1812 io_req_complete_post(req, res, cflags);
1815 static inline void io_req_complete(struct io_kiocb *req, long res)
1817 __io_req_complete(req, 0, res, 0);
1820 static void io_req_complete_failed(struct io_kiocb *req, long res)
1823 io_req_complete_post(req, res, 0);
1826 static void io_req_complete_fail_submit(struct io_kiocb *req)
1829 * We don't submit, fail them all, for that replace hardlinks with
1830 * normal links. Extra REQ_F_LINK is tolerated.
1832 req->flags &= ~REQ_F_HARDLINK;
1833 req->flags |= REQ_F_LINK;
1834 io_req_complete_failed(req, req->result);
1838 * Don't initialise the fields below on every allocation, but do that in
1839 * advance and keep them valid across allocations.
1841 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1845 req->async_data = NULL;
1846 /* not necessary, but safer to zero */
1850 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1851 struct io_submit_state *state)
1853 spin_lock(&ctx->completion_lock);
1854 list_splice_init(&ctx->locked_free_list, &state->free_list);
1855 ctx->locked_free_nr = 0;
1856 spin_unlock(&ctx->completion_lock);
1859 /* Returns true IFF there are requests in the cache */
1860 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1862 struct io_submit_state *state = &ctx->submit_state;
1866 * If we have more than a batch's worth of requests in our IRQ side
1867 * locked cache, grab the lock and move them over to our submission
1870 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1871 io_flush_cached_locked_reqs(ctx, state);
1873 nr = state->free_reqs;
1874 while (!list_empty(&state->free_list)) {
1875 struct io_kiocb *req = list_first_entry(&state->free_list,
1876 struct io_kiocb, inflight_entry);
1878 list_del(&req->inflight_entry);
1879 state->reqs[nr++] = req;
1880 if (nr == ARRAY_SIZE(state->reqs))
1884 state->free_reqs = nr;
1889 * A request might get retired back into the request caches even before opcode
1890 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1891 * Because of that, io_alloc_req() should be called only under ->uring_lock
1892 * and with extra caution to not get a request that is still worked on.
1894 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1895 __must_hold(&ctx->uring_lock)
1897 struct io_submit_state *state = &ctx->submit_state;
1898 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1901 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1903 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1906 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1910 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1911 * retry single alloc to be on the safe side.
1913 if (unlikely(ret <= 0)) {
1914 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1915 if (!state->reqs[0])
1920 for (i = 0; i < ret; i++)
1921 io_preinit_req(state->reqs[i], ctx);
1922 state->free_reqs = ret;
1925 return state->reqs[state->free_reqs];
1928 static inline void io_put_file(struct file *file)
1934 static void io_dismantle_req(struct io_kiocb *req)
1936 unsigned int flags = req->flags;
1938 if (io_req_needs_clean(req))
1940 if (!(flags & REQ_F_FIXED_FILE))
1941 io_put_file(req->file);
1942 if (req->fixed_rsrc_refs)
1943 percpu_ref_put(req->fixed_rsrc_refs);
1944 if (req->async_data) {
1945 kfree(req->async_data);
1946 req->async_data = NULL;
1950 static void __io_free_req(struct io_kiocb *req)
1952 struct io_ring_ctx *ctx = req->ctx;
1954 io_dismantle_req(req);
1955 io_put_task(req->task, 1);
1957 spin_lock(&ctx->completion_lock);
1958 list_add(&req->inflight_entry, &ctx->locked_free_list);
1959 ctx->locked_free_nr++;
1960 spin_unlock(&ctx->completion_lock);
1962 percpu_ref_put(&ctx->refs);
1965 static inline void io_remove_next_linked(struct io_kiocb *req)
1967 struct io_kiocb *nxt = req->link;
1969 req->link = nxt->link;
1973 static bool io_kill_linked_timeout(struct io_kiocb *req)
1974 __must_hold(&req->ctx->completion_lock)
1975 __must_hold(&req->ctx->timeout_lock)
1977 struct io_kiocb *link = req->link;
1979 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1980 struct io_timeout_data *io = link->async_data;
1982 io_remove_next_linked(req);
1983 link->timeout.head = NULL;
1984 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1985 list_del(&link->timeout.list);
1986 io_cqring_fill_event(link->ctx, link->user_data,
1988 io_put_req_deferred(link);
1995 static void io_fail_links(struct io_kiocb *req)
1996 __must_hold(&req->ctx->completion_lock)
1998 struct io_kiocb *nxt, *link = req->link;
2002 long res = -ECANCELED;
2004 if (link->flags & REQ_F_FAIL)
2010 trace_io_uring_fail_link(req, link);
2011 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2012 io_put_req_deferred(link);
2017 static bool io_disarm_next(struct io_kiocb *req)
2018 __must_hold(&req->ctx->completion_lock)
2020 bool posted = false;
2022 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2023 struct io_kiocb *link = req->link;
2025 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2026 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2027 io_remove_next_linked(req);
2028 io_cqring_fill_event(link->ctx, link->user_data,
2030 io_put_req_deferred(link);
2033 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2034 struct io_ring_ctx *ctx = req->ctx;
2036 spin_lock_irq(&ctx->timeout_lock);
2037 posted = io_kill_linked_timeout(req);
2038 spin_unlock_irq(&ctx->timeout_lock);
2040 if (unlikely((req->flags & REQ_F_FAIL) &&
2041 !(req->flags & REQ_F_HARDLINK))) {
2042 posted |= (req->link != NULL);
2048 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2050 struct io_kiocb *nxt;
2053 * If LINK is set, we have dependent requests in this chain. If we
2054 * didn't fail this request, queue the first one up, moving any other
2055 * dependencies to the next request. In case of failure, fail the rest
2058 if (req->flags & IO_DISARM_MASK) {
2059 struct io_ring_ctx *ctx = req->ctx;
2062 spin_lock(&ctx->completion_lock);
2063 posted = io_disarm_next(req);
2065 io_commit_cqring(req->ctx);
2066 spin_unlock(&ctx->completion_lock);
2068 io_cqring_ev_posted(ctx);
2075 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2077 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2079 return __io_req_find_next(req);
2082 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2087 if (ctx->submit_state.compl_nr)
2088 io_submit_flush_completions(ctx);
2089 mutex_unlock(&ctx->uring_lock);
2092 percpu_ref_put(&ctx->refs);
2095 static void tctx_task_work(struct callback_head *cb)
2097 bool locked = false;
2098 struct io_ring_ctx *ctx = NULL;
2099 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2103 struct io_wq_work_node *node;
2105 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2106 io_submit_flush_completions(ctx);
2108 spin_lock_irq(&tctx->task_lock);
2109 node = tctx->task_list.first;
2110 INIT_WQ_LIST(&tctx->task_list);
2112 tctx->task_running = false;
2113 spin_unlock_irq(&tctx->task_lock);
2118 struct io_wq_work_node *next = node->next;
2119 struct io_kiocb *req = container_of(node, struct io_kiocb,
2122 if (req->ctx != ctx) {
2123 ctx_flush_and_put(ctx, &locked);
2125 /* if not contended, grab and improve batching */
2126 locked = mutex_trylock(&ctx->uring_lock);
2127 percpu_ref_get(&ctx->refs);
2129 req->io_task_work.func(req, &locked);
2136 ctx_flush_and_put(ctx, &locked);
2139 static void io_req_task_work_add(struct io_kiocb *req)
2141 struct task_struct *tsk = req->task;
2142 struct io_uring_task *tctx = tsk->io_uring;
2143 enum task_work_notify_mode notify;
2144 struct io_wq_work_node *node;
2145 unsigned long flags;
2148 WARN_ON_ONCE(!tctx);
2150 spin_lock_irqsave(&tctx->task_lock, flags);
2151 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2152 running = tctx->task_running;
2154 tctx->task_running = true;
2155 spin_unlock_irqrestore(&tctx->task_lock, flags);
2157 /* task_work already pending, we're done */
2162 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2163 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2164 * processing task_work. There's no reliable way to tell if TWA_RESUME
2167 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2168 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2169 wake_up_process(tsk);
2173 spin_lock_irqsave(&tctx->task_lock, flags);
2174 tctx->task_running = false;
2175 node = tctx->task_list.first;
2176 INIT_WQ_LIST(&tctx->task_list);
2177 spin_unlock_irqrestore(&tctx->task_lock, flags);
2180 req = container_of(node, struct io_kiocb, io_task_work.node);
2182 if (llist_add(&req->io_task_work.fallback_node,
2183 &req->ctx->fallback_llist))
2184 schedule_delayed_work(&req->ctx->fallback_work, 1);
2188 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2190 struct io_ring_ctx *ctx = req->ctx;
2192 /* not needed for normal modes, but SQPOLL depends on it */
2193 io_tw_lock(ctx, locked);
2194 io_req_complete_failed(req, req->result);
2197 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2199 struct io_ring_ctx *ctx = req->ctx;
2201 io_tw_lock(ctx, locked);
2202 /* req->task == current here, checking PF_EXITING is safe */
2203 if (likely(!(req->task->flags & PF_EXITING)))
2204 __io_queue_sqe(req);
2206 io_req_complete_failed(req, -EFAULT);
2209 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2212 req->io_task_work.func = io_req_task_cancel;
2213 io_req_task_work_add(req);
2216 static void io_req_task_queue(struct io_kiocb *req)
2218 req->io_task_work.func = io_req_task_submit;
2219 io_req_task_work_add(req);
2222 static void io_req_task_queue_reissue(struct io_kiocb *req)
2224 req->io_task_work.func = io_queue_async_work;
2225 io_req_task_work_add(req);
2228 static inline void io_queue_next(struct io_kiocb *req)
2230 struct io_kiocb *nxt = io_req_find_next(req);
2233 io_req_task_queue(nxt);
2236 static void io_free_req(struct io_kiocb *req)
2242 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2248 struct task_struct *task;
2253 static inline void io_init_req_batch(struct req_batch *rb)
2260 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2261 struct req_batch *rb)
2264 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2266 io_put_task(rb->task, rb->task_refs);
2269 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2270 struct io_submit_state *state)
2273 io_dismantle_req(req);
2275 if (req->task != rb->task) {
2277 io_put_task(rb->task, rb->task_refs);
2278 rb->task = req->task;
2284 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2285 state->reqs[state->free_reqs++] = req;
2287 list_add(&req->inflight_entry, &state->free_list);
2290 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2291 __must_hold(&ctx->uring_lock)
2293 struct io_submit_state *state = &ctx->submit_state;
2294 int i, nr = state->compl_nr;
2295 struct req_batch rb;
2297 spin_lock(&ctx->completion_lock);
2298 for (i = 0; i < nr; i++) {
2299 struct io_kiocb *req = state->compl_reqs[i];
2301 __io_cqring_fill_event(ctx, req->user_data, req->result,
2304 io_commit_cqring(ctx);
2305 spin_unlock(&ctx->completion_lock);
2306 io_cqring_ev_posted(ctx);
2308 io_init_req_batch(&rb);
2309 for (i = 0; i < nr; i++) {
2310 struct io_kiocb *req = state->compl_reqs[i];
2312 if (req_ref_put_and_test(req))
2313 io_req_free_batch(&rb, req, &ctx->submit_state);
2316 io_req_free_batch_finish(ctx, &rb);
2317 state->compl_nr = 0;
2321 * Drop reference to request, return next in chain (if there is one) if this
2322 * was the last reference to this request.
2324 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2326 struct io_kiocb *nxt = NULL;
2328 if (req_ref_put_and_test(req)) {
2329 nxt = io_req_find_next(req);
2335 static inline void io_put_req(struct io_kiocb *req)
2337 if (req_ref_put_and_test(req))
2341 static inline void io_put_req_deferred(struct io_kiocb *req)
2343 if (req_ref_put_and_test(req)) {
2344 req->io_task_work.func = io_free_req_work;
2345 io_req_task_work_add(req);
2349 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2351 /* See comment at the top of this file */
2353 return __io_cqring_events(ctx);
2356 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2358 struct io_rings *rings = ctx->rings;
2360 /* make sure SQ entry isn't read before tail */
2361 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2364 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2366 unsigned int cflags;
2368 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2369 cflags |= IORING_CQE_F_BUFFER;
2370 req->flags &= ~REQ_F_BUFFER_SELECTED;
2375 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2377 struct io_buffer *kbuf;
2379 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2381 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2382 return io_put_kbuf(req, kbuf);
2385 static inline bool io_run_task_work(void)
2387 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2388 __set_current_state(TASK_RUNNING);
2389 tracehook_notify_signal();
2397 * Find and free completed poll iocbs
2399 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2400 struct list_head *done)
2402 struct req_batch rb;
2403 struct io_kiocb *req;
2405 /* order with ->result store in io_complete_rw_iopoll() */
2408 io_init_req_batch(&rb);
2409 while (!list_empty(done)) {
2410 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2411 list_del(&req->inflight_entry);
2413 if (READ_ONCE(req->result) == -EAGAIN &&
2414 !(req->flags & REQ_F_DONT_REISSUE)) {
2415 req->iopoll_completed = 0;
2416 io_req_task_queue_reissue(req);
2420 __io_cqring_fill_event(ctx, req->user_data, req->result,
2421 io_put_rw_kbuf(req));
2424 if (req_ref_put_and_test(req))
2425 io_req_free_batch(&rb, req, &ctx->submit_state);
2428 io_commit_cqring(ctx);
2429 io_cqring_ev_posted_iopoll(ctx);
2430 io_req_free_batch_finish(ctx, &rb);
2433 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2436 struct io_kiocb *req, *tmp;
2441 * Only spin for completions if we don't have multiple devices hanging
2442 * off our complete list, and we're under the requested amount.
2444 spin = !ctx->poll_multi_queue && *nr_events < min;
2446 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2447 struct kiocb *kiocb = &req->rw.kiocb;
2451 * Move completed and retryable entries to our local lists.
2452 * If we find a request that requires polling, break out
2453 * and complete those lists first, if we have entries there.
2455 if (READ_ONCE(req->iopoll_completed)) {
2456 list_move_tail(&req->inflight_entry, &done);
2459 if (!list_empty(&done))
2462 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2463 if (unlikely(ret < 0))
2468 /* iopoll may have completed current req */
2469 if (READ_ONCE(req->iopoll_completed))
2470 list_move_tail(&req->inflight_entry, &done);
2473 if (!list_empty(&done))
2474 io_iopoll_complete(ctx, nr_events, &done);
2480 * We can't just wait for polled events to come to us, we have to actively
2481 * find and complete them.
2483 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2485 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2488 mutex_lock(&ctx->uring_lock);
2489 while (!list_empty(&ctx->iopoll_list)) {
2490 unsigned int nr_events = 0;
2492 io_do_iopoll(ctx, &nr_events, 0);
2494 /* let it sleep and repeat later if can't complete a request */
2498 * Ensure we allow local-to-the-cpu processing to take place,
2499 * in this case we need to ensure that we reap all events.
2500 * Also let task_work, etc. to progress by releasing the mutex
2502 if (need_resched()) {
2503 mutex_unlock(&ctx->uring_lock);
2505 mutex_lock(&ctx->uring_lock);
2508 mutex_unlock(&ctx->uring_lock);
2511 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2513 unsigned int nr_events = 0;
2517 * We disallow the app entering submit/complete with polling, but we
2518 * still need to lock the ring to prevent racing with polled issue
2519 * that got punted to a workqueue.
2521 mutex_lock(&ctx->uring_lock);
2523 * Don't enter poll loop if we already have events pending.
2524 * If we do, we can potentially be spinning for commands that
2525 * already triggered a CQE (eg in error).
2527 if (test_bit(0, &ctx->check_cq_overflow))
2528 __io_cqring_overflow_flush(ctx, false);
2529 if (io_cqring_events(ctx))
2533 * If a submit got punted to a workqueue, we can have the
2534 * application entering polling for a command before it gets
2535 * issued. That app will hold the uring_lock for the duration
2536 * of the poll right here, so we need to take a breather every
2537 * now and then to ensure that the issue has a chance to add
2538 * the poll to the issued list. Otherwise we can spin here
2539 * forever, while the workqueue is stuck trying to acquire the
2542 if (list_empty(&ctx->iopoll_list)) {
2543 u32 tail = ctx->cached_cq_tail;
2545 mutex_unlock(&ctx->uring_lock);
2547 mutex_lock(&ctx->uring_lock);
2549 /* some requests don't go through iopoll_list */
2550 if (tail != ctx->cached_cq_tail ||
2551 list_empty(&ctx->iopoll_list))
2554 ret = io_do_iopoll(ctx, &nr_events, min);
2555 } while (!ret && nr_events < min && !need_resched());
2557 mutex_unlock(&ctx->uring_lock);
2561 static void kiocb_end_write(struct io_kiocb *req)
2564 * Tell lockdep we inherited freeze protection from submission
2567 if (req->flags & REQ_F_ISREG) {
2568 struct super_block *sb = file_inode(req->file)->i_sb;
2570 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2576 static bool io_resubmit_prep(struct io_kiocb *req)
2578 struct io_async_rw *rw = req->async_data;
2581 return !io_req_prep_async(req);
2582 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2583 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2587 static bool io_rw_should_reissue(struct io_kiocb *req)
2589 umode_t mode = file_inode(req->file)->i_mode;
2590 struct io_ring_ctx *ctx = req->ctx;
2592 if (!S_ISBLK(mode) && !S_ISREG(mode))
2594 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2595 !(ctx->flags & IORING_SETUP_IOPOLL)))
2598 * If ref is dying, we might be running poll reap from the exit work.
2599 * Don't attempt to reissue from that path, just let it fail with
2602 if (percpu_ref_is_dying(&ctx->refs))
2605 * Play it safe and assume not safe to re-import and reissue if we're
2606 * not in the original thread group (or in task context).
2608 if (!same_thread_group(req->task, current) || !in_task())
2613 static bool io_resubmit_prep(struct io_kiocb *req)
2617 static bool io_rw_should_reissue(struct io_kiocb *req)
2623 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2625 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2626 kiocb_end_write(req);
2627 if (res != req->result) {
2628 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2629 io_rw_should_reissue(req)) {
2630 req->flags |= REQ_F_REISSUE;
2639 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2641 unsigned int cflags = io_put_rw_kbuf(req);
2642 long res = req->result;
2645 struct io_ring_ctx *ctx = req->ctx;
2646 struct io_submit_state *state = &ctx->submit_state;
2648 io_req_complete_state(req, res, cflags);
2649 state->compl_reqs[state->compl_nr++] = req;
2650 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2651 io_submit_flush_completions(ctx);
2653 io_req_complete_post(req, res, cflags);
2657 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2658 unsigned int issue_flags)
2660 if (__io_complete_rw_common(req, res))
2662 __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2665 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2667 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2669 if (__io_complete_rw_common(req, res))
2672 req->io_task_work.func = io_req_task_complete;
2673 io_req_task_work_add(req);
2676 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2678 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2680 if (kiocb->ki_flags & IOCB_WRITE)
2681 kiocb_end_write(req);
2682 if (unlikely(res != req->result)) {
2683 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2684 io_resubmit_prep(req))) {
2686 req->flags |= REQ_F_DONT_REISSUE;
2690 WRITE_ONCE(req->result, res);
2691 /* order with io_iopoll_complete() checking ->result */
2693 WRITE_ONCE(req->iopoll_completed, 1);
2697 * After the iocb has been issued, it's safe to be found on the poll list.
2698 * Adding the kiocb to the list AFTER submission ensures that we don't
2699 * find it from a io_do_iopoll() thread before the issuer is done
2700 * accessing the kiocb cookie.
2702 static void io_iopoll_req_issued(struct io_kiocb *req)
2704 struct io_ring_ctx *ctx = req->ctx;
2705 const bool in_async = io_wq_current_is_worker();
2707 /* workqueue context doesn't hold uring_lock, grab it now */
2708 if (unlikely(in_async))
2709 mutex_lock(&ctx->uring_lock);
2712 * Track whether we have multiple files in our lists. This will impact
2713 * how we do polling eventually, not spinning if we're on potentially
2714 * different devices.
2716 if (list_empty(&ctx->iopoll_list)) {
2717 ctx->poll_multi_queue = false;
2718 } else if (!ctx->poll_multi_queue) {
2719 struct io_kiocb *list_req;
2720 unsigned int queue_num0, queue_num1;
2722 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2725 if (list_req->file != req->file) {
2726 ctx->poll_multi_queue = true;
2728 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2729 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2730 if (queue_num0 != queue_num1)
2731 ctx->poll_multi_queue = true;
2736 * For fast devices, IO may have already completed. If it has, add
2737 * it to the front so we find it first.
2739 if (READ_ONCE(req->iopoll_completed))
2740 list_add(&req->inflight_entry, &ctx->iopoll_list);
2742 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2744 if (unlikely(in_async)) {
2746 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2747 * in sq thread task context or in io worker task context. If
2748 * current task context is sq thread, we don't need to check
2749 * whether should wake up sq thread.
2751 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2752 wq_has_sleeper(&ctx->sq_data->wait))
2753 wake_up(&ctx->sq_data->wait);
2755 mutex_unlock(&ctx->uring_lock);
2759 static bool io_bdev_nowait(struct block_device *bdev)
2761 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2765 * If we tracked the file through the SCM inflight mechanism, we could support
2766 * any file. For now, just ensure that anything potentially problematic is done
2769 static bool __io_file_supports_nowait(struct file *file, int rw)
2771 umode_t mode = file_inode(file)->i_mode;
2773 if (S_ISBLK(mode)) {
2774 if (IS_ENABLED(CONFIG_BLOCK) &&
2775 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2781 if (S_ISREG(mode)) {
2782 if (IS_ENABLED(CONFIG_BLOCK) &&
2783 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2784 file->f_op != &io_uring_fops)
2789 /* any ->read/write should understand O_NONBLOCK */
2790 if (file->f_flags & O_NONBLOCK)
2793 if (!(file->f_mode & FMODE_NOWAIT))
2797 return file->f_op->read_iter != NULL;
2799 return file->f_op->write_iter != NULL;
2802 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2804 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2806 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2809 return __io_file_supports_nowait(req->file, rw);
2812 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2814 struct io_ring_ctx *ctx = req->ctx;
2815 struct kiocb *kiocb = &req->rw.kiocb;
2816 struct file *file = req->file;
2820 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2821 req->flags |= REQ_F_ISREG;
2823 kiocb->ki_pos = READ_ONCE(sqe->off);
2824 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2825 req->flags |= REQ_F_CUR_POS;
2826 kiocb->ki_pos = file->f_pos;
2828 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2829 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2830 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2834 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2835 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2836 req->flags |= REQ_F_NOWAIT;
2838 ioprio = READ_ONCE(sqe->ioprio);
2840 ret = ioprio_check_cap(ioprio);
2844 kiocb->ki_ioprio = ioprio;
2846 kiocb->ki_ioprio = get_current_ioprio();
2848 if (ctx->flags & IORING_SETUP_IOPOLL) {
2849 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2850 !kiocb->ki_filp->f_op->iopoll)
2853 kiocb->ki_flags |= IOCB_HIPRI;
2854 kiocb->ki_complete = io_complete_rw_iopoll;
2855 req->iopoll_completed = 0;
2857 if (kiocb->ki_flags & IOCB_HIPRI)
2859 kiocb->ki_complete = io_complete_rw;
2862 if (req->opcode == IORING_OP_READ_FIXED ||
2863 req->opcode == IORING_OP_WRITE_FIXED) {
2865 io_req_set_rsrc_node(req);
2868 req->rw.addr = READ_ONCE(sqe->addr);
2869 req->rw.len = READ_ONCE(sqe->len);
2870 req->buf_index = READ_ONCE(sqe->buf_index);
2874 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2880 case -ERESTARTNOINTR:
2881 case -ERESTARTNOHAND:
2882 case -ERESTART_RESTARTBLOCK:
2884 * We can't just restart the syscall, since previously
2885 * submitted sqes may already be in progress. Just fail this
2891 kiocb->ki_complete(kiocb, ret, 0);
2895 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2896 unsigned int issue_flags)
2898 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2899 struct io_async_rw *io = req->async_data;
2900 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2902 /* add previously done IO, if any */
2903 if (io && io->bytes_done > 0) {
2905 ret = io->bytes_done;
2907 ret += io->bytes_done;
2910 if (req->flags & REQ_F_CUR_POS)
2911 req->file->f_pos = kiocb->ki_pos;
2912 if (ret >= 0 && check_reissue)
2913 __io_complete_rw(req, ret, 0, issue_flags);
2915 io_rw_done(kiocb, ret);
2917 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2918 req->flags &= ~REQ_F_REISSUE;
2919 if (io_resubmit_prep(req)) {
2920 io_req_task_queue_reissue(req);
2923 __io_req_complete(req, issue_flags, ret,
2924 io_put_rw_kbuf(req));
2929 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2930 struct io_mapped_ubuf *imu)
2932 size_t len = req->rw.len;
2933 u64 buf_end, buf_addr = req->rw.addr;
2936 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2938 /* not inside the mapped region */
2939 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2943 * May not be a start of buffer, set size appropriately
2944 * and advance us to the beginning.
2946 offset = buf_addr - imu->ubuf;
2947 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2951 * Don't use iov_iter_advance() here, as it's really slow for
2952 * using the latter parts of a big fixed buffer - it iterates
2953 * over each segment manually. We can cheat a bit here, because
2956 * 1) it's a BVEC iter, we set it up
2957 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2958 * first and last bvec
2960 * So just find our index, and adjust the iterator afterwards.
2961 * If the offset is within the first bvec (or the whole first
2962 * bvec, just use iov_iter_advance(). This makes it easier
2963 * since we can just skip the first segment, which may not
2964 * be PAGE_SIZE aligned.
2966 const struct bio_vec *bvec = imu->bvec;
2968 if (offset <= bvec->bv_len) {
2969 iov_iter_advance(iter, offset);
2971 unsigned long seg_skip;
2973 /* skip first vec */
2974 offset -= bvec->bv_len;
2975 seg_skip = 1 + (offset >> PAGE_SHIFT);
2977 iter->bvec = bvec + seg_skip;
2978 iter->nr_segs -= seg_skip;
2979 iter->count -= bvec->bv_len + offset;
2980 iter->iov_offset = offset & ~PAGE_MASK;
2987 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2989 struct io_ring_ctx *ctx = req->ctx;
2990 struct io_mapped_ubuf *imu = req->imu;
2991 u16 index, buf_index = req->buf_index;
2994 if (unlikely(buf_index >= ctx->nr_user_bufs))
2996 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2997 imu = READ_ONCE(ctx->user_bufs[index]);
3000 return __io_import_fixed(req, rw, iter, imu);
3003 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3006 mutex_unlock(&ctx->uring_lock);
3009 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3012 * "Normal" inline submissions always hold the uring_lock, since we
3013 * grab it from the system call. Same is true for the SQPOLL offload.
3014 * The only exception is when we've detached the request and issue it
3015 * from an async worker thread, grab the lock for that case.
3018 mutex_lock(&ctx->uring_lock);
3021 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3022 int bgid, struct io_buffer *kbuf,
3025 struct io_buffer *head;
3027 if (req->flags & REQ_F_BUFFER_SELECTED)
3030 io_ring_submit_lock(req->ctx, needs_lock);
3032 lockdep_assert_held(&req->ctx->uring_lock);
3034 head = xa_load(&req->ctx->io_buffers, bgid);
3036 if (!list_empty(&head->list)) {
3037 kbuf = list_last_entry(&head->list, struct io_buffer,
3039 list_del(&kbuf->list);
3042 xa_erase(&req->ctx->io_buffers, bgid);
3044 if (*len > kbuf->len)
3047 kbuf = ERR_PTR(-ENOBUFS);
3050 io_ring_submit_unlock(req->ctx, needs_lock);
3055 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3058 struct io_buffer *kbuf;
3061 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3062 bgid = req->buf_index;
3063 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3066 req->rw.addr = (u64) (unsigned long) kbuf;
3067 req->flags |= REQ_F_BUFFER_SELECTED;
3068 return u64_to_user_ptr(kbuf->addr);
3071 #ifdef CONFIG_COMPAT
3072 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3075 struct compat_iovec __user *uiov;
3076 compat_ssize_t clen;
3080 uiov = u64_to_user_ptr(req->rw.addr);
3081 if (!access_ok(uiov, sizeof(*uiov)))
3083 if (__get_user(clen, &uiov->iov_len))
3089 buf = io_rw_buffer_select(req, &len, needs_lock);
3091 return PTR_ERR(buf);
3092 iov[0].iov_base = buf;
3093 iov[0].iov_len = (compat_size_t) len;
3098 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3101 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3105 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3108 len = iov[0].iov_len;
3111 buf = io_rw_buffer_select(req, &len, needs_lock);
3113 return PTR_ERR(buf);
3114 iov[0].iov_base = buf;
3115 iov[0].iov_len = len;
3119 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3122 if (req->flags & REQ_F_BUFFER_SELECTED) {
3123 struct io_buffer *kbuf;
3125 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3126 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3127 iov[0].iov_len = kbuf->len;
3130 if (req->rw.len != 1)
3133 #ifdef CONFIG_COMPAT
3134 if (req->ctx->compat)
3135 return io_compat_import(req, iov, needs_lock);
3138 return __io_iov_buffer_select(req, iov, needs_lock);
3141 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3142 struct iov_iter *iter, bool needs_lock)
3144 void __user *buf = u64_to_user_ptr(req->rw.addr);
3145 size_t sqe_len = req->rw.len;
3146 u8 opcode = req->opcode;
3149 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3151 return io_import_fixed(req, rw, iter);
3154 /* buffer index only valid with fixed read/write, or buffer select */
3155 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3158 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3159 if (req->flags & REQ_F_BUFFER_SELECT) {
3160 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3162 return PTR_ERR(buf);
3163 req->rw.len = sqe_len;
3166 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3171 if (req->flags & REQ_F_BUFFER_SELECT) {
3172 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3174 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3179 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3183 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3185 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3189 * For files that don't have ->read_iter() and ->write_iter(), handle them
3190 * by looping over ->read() or ->write() manually.
3192 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3194 struct kiocb *kiocb = &req->rw.kiocb;
3195 struct file *file = req->file;
3199 * Don't support polled IO through this interface, and we can't
3200 * support non-blocking either. For the latter, this just causes
3201 * the kiocb to be handled from an async context.
3203 if (kiocb->ki_flags & IOCB_HIPRI)
3205 if (kiocb->ki_flags & IOCB_NOWAIT)
3208 while (iov_iter_count(iter)) {
3212 if (!iov_iter_is_bvec(iter)) {
3213 iovec = iov_iter_iovec(iter);
3215 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3216 iovec.iov_len = req->rw.len;
3220 nr = file->f_op->read(file, iovec.iov_base,
3221 iovec.iov_len, io_kiocb_ppos(kiocb));
3223 nr = file->f_op->write(file, iovec.iov_base,
3224 iovec.iov_len, io_kiocb_ppos(kiocb));
3233 if (nr != iovec.iov_len)
3237 iov_iter_advance(iter, nr);
3243 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3244 const struct iovec *fast_iov, struct iov_iter *iter)
3246 struct io_async_rw *rw = req->async_data;
3248 memcpy(&rw->iter, iter, sizeof(*iter));
3249 rw->free_iovec = iovec;
3251 /* can only be fixed buffers, no need to do anything */
3252 if (iov_iter_is_bvec(iter))
3255 unsigned iov_off = 0;
3257 rw->iter.iov = rw->fast_iov;
3258 if (iter->iov != fast_iov) {
3259 iov_off = iter->iov - fast_iov;
3260 rw->iter.iov += iov_off;
3262 if (rw->fast_iov != fast_iov)
3263 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3264 sizeof(struct iovec) * iter->nr_segs);
3266 req->flags |= REQ_F_NEED_CLEANUP;
3270 static inline int io_alloc_async_data(struct io_kiocb *req)
3272 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3273 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3274 return req->async_data == NULL;
3277 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3278 const struct iovec *fast_iov,
3279 struct iov_iter *iter, bool force)
3281 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3283 if (!req->async_data) {
3284 if (io_alloc_async_data(req)) {
3289 io_req_map_rw(req, iovec, fast_iov, iter);
3294 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3296 struct io_async_rw *iorw = req->async_data;
3297 struct iovec *iov = iorw->fast_iov;
3300 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3301 if (unlikely(ret < 0))
3304 iorw->bytes_done = 0;
3305 iorw->free_iovec = iov;
3307 req->flags |= REQ_F_NEED_CLEANUP;
3311 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3313 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3315 return io_prep_rw(req, sqe);
3319 * This is our waitqueue callback handler, registered through lock_page_async()
3320 * when we initially tried to do the IO with the iocb armed our waitqueue.
3321 * This gets called when the page is unlocked, and we generally expect that to
3322 * happen when the page IO is completed and the page is now uptodate. This will
3323 * queue a task_work based retry of the operation, attempting to copy the data
3324 * again. If the latter fails because the page was NOT uptodate, then we will
3325 * do a thread based blocking retry of the operation. That's the unexpected
3328 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3329 int sync, void *arg)
3331 struct wait_page_queue *wpq;
3332 struct io_kiocb *req = wait->private;
3333 struct wait_page_key *key = arg;
3335 wpq = container_of(wait, struct wait_page_queue, wait);
3337 if (!wake_page_match(wpq, key))
3340 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3341 list_del_init(&wait->entry);
3342 io_req_task_queue(req);
3347 * This controls whether a given IO request should be armed for async page
3348 * based retry. If we return false here, the request is handed to the async
3349 * worker threads for retry. If we're doing buffered reads on a regular file,
3350 * we prepare a private wait_page_queue entry and retry the operation. This
3351 * will either succeed because the page is now uptodate and unlocked, or it
3352 * will register a callback when the page is unlocked at IO completion. Through
3353 * that callback, io_uring uses task_work to setup a retry of the operation.
3354 * That retry will attempt the buffered read again. The retry will generally
3355 * succeed, or in rare cases where it fails, we then fall back to using the
3356 * async worker threads for a blocking retry.
3358 static bool io_rw_should_retry(struct io_kiocb *req)
3360 struct io_async_rw *rw = req->async_data;
3361 struct wait_page_queue *wait = &rw->wpq;
3362 struct kiocb *kiocb = &req->rw.kiocb;
3364 /* never retry for NOWAIT, we just complete with -EAGAIN */
3365 if (req->flags & REQ_F_NOWAIT)
3368 /* Only for buffered IO */
3369 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3373 * just use poll if we can, and don't attempt if the fs doesn't
3374 * support callback based unlocks
3376 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3379 wait->wait.func = io_async_buf_func;
3380 wait->wait.private = req;
3381 wait->wait.flags = 0;
3382 INIT_LIST_HEAD(&wait->wait.entry);
3383 kiocb->ki_flags |= IOCB_WAITQ;
3384 kiocb->ki_flags &= ~IOCB_NOWAIT;
3385 kiocb->ki_waitq = wait;
3389 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3391 if (req->file->f_op->read_iter)
3392 return call_read_iter(req->file, &req->rw.kiocb, iter);
3393 else if (req->file->f_op->read)
3394 return loop_rw_iter(READ, req, iter);
3399 static bool need_read_all(struct io_kiocb *req)
3401 return req->flags & REQ_F_ISREG ||
3402 S_ISBLK(file_inode(req->file)->i_mode);
3405 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3407 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3408 struct kiocb *kiocb = &req->rw.kiocb;
3409 struct iov_iter __iter, *iter = &__iter;
3410 struct io_async_rw *rw = req->async_data;
3411 ssize_t io_size, ret, ret2;
3412 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3418 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3422 io_size = iov_iter_count(iter);
3423 req->result = io_size;
3425 /* Ensure we clear previously set non-block flag */
3426 if (!force_nonblock)
3427 kiocb->ki_flags &= ~IOCB_NOWAIT;
3429 kiocb->ki_flags |= IOCB_NOWAIT;
3431 /* If the file doesn't support async, just async punt */
3432 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3433 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3434 return ret ?: -EAGAIN;
3437 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3438 if (unlikely(ret)) {
3443 ret = io_iter_do_read(req, iter);
3445 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3446 req->flags &= ~REQ_F_REISSUE;
3447 /* IOPOLL retry should happen for io-wq threads */
3448 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3450 /* no retry on NONBLOCK nor RWF_NOWAIT */
3451 if (req->flags & REQ_F_NOWAIT)
3453 /* some cases will consume bytes even on error returns */
3454 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3456 } else if (ret == -EIOCBQUEUED) {
3458 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3459 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3460 /* read all, failed, already did sync or don't want to retry */
3464 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3469 rw = req->async_data;
3470 /* now use our persistent iterator, if we aren't already */
3475 rw->bytes_done += ret;
3476 /* if we can retry, do so with the callbacks armed */
3477 if (!io_rw_should_retry(req)) {
3478 kiocb->ki_flags &= ~IOCB_WAITQ;
3483 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3484 * we get -EIOCBQUEUED, then we'll get a notification when the
3485 * desired page gets unlocked. We can also get a partial read
3486 * here, and if we do, then just retry at the new offset.
3488 ret = io_iter_do_read(req, iter);
3489 if (ret == -EIOCBQUEUED)
3491 /* we got some bytes, but not all. retry. */
3492 kiocb->ki_flags &= ~IOCB_WAITQ;
3493 } while (ret > 0 && ret < io_size);
3495 kiocb_done(kiocb, ret, issue_flags);
3497 /* it's faster to check here then delegate to kfree */
3503 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3505 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3507 return io_prep_rw(req, sqe);
3510 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3512 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3513 struct kiocb *kiocb = &req->rw.kiocb;
3514 struct iov_iter __iter, *iter = &__iter;
3515 struct io_async_rw *rw = req->async_data;
3516 ssize_t ret, ret2, io_size;
3517 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3523 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3527 io_size = iov_iter_count(iter);
3528 req->result = io_size;
3530 /* Ensure we clear previously set non-block flag */
3531 if (!force_nonblock)
3532 kiocb->ki_flags &= ~IOCB_NOWAIT;
3534 kiocb->ki_flags |= IOCB_NOWAIT;
3536 /* If the file doesn't support async, just async punt */
3537 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3540 /* file path doesn't support NOWAIT for non-direct_IO */
3541 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3542 (req->flags & REQ_F_ISREG))
3545 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3550 * Open-code file_start_write here to grab freeze protection,
3551 * which will be released by another thread in
3552 * io_complete_rw(). Fool lockdep by telling it the lock got
3553 * released so that it doesn't complain about the held lock when
3554 * we return to userspace.
3556 if (req->flags & REQ_F_ISREG) {
3557 sb_start_write(file_inode(req->file)->i_sb);
3558 __sb_writers_release(file_inode(req->file)->i_sb,
3561 kiocb->ki_flags |= IOCB_WRITE;
3563 if (req->file->f_op->write_iter)
3564 ret2 = call_write_iter(req->file, kiocb, iter);
3565 else if (req->file->f_op->write)
3566 ret2 = loop_rw_iter(WRITE, req, iter);
3570 if (req->flags & REQ_F_REISSUE) {
3571 req->flags &= ~REQ_F_REISSUE;
3576 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3577 * retry them without IOCB_NOWAIT.
3579 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3581 /* no retry on NONBLOCK nor RWF_NOWAIT */
3582 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3584 if (!force_nonblock || ret2 != -EAGAIN) {
3585 /* IOPOLL retry should happen for io-wq threads */
3586 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3589 kiocb_done(kiocb, ret2, issue_flags);
3592 /* some cases will consume bytes even on error returns */
3593 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3594 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3595 return ret ?: -EAGAIN;
3598 /* it's reportedly faster than delegating the null check to kfree() */
3604 static int io_renameat_prep(struct io_kiocb *req,
3605 const struct io_uring_sqe *sqe)
3607 struct io_rename *ren = &req->rename;
3608 const char __user *oldf, *newf;
3610 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3612 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3614 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3617 ren->old_dfd = READ_ONCE(sqe->fd);
3618 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3619 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3620 ren->new_dfd = READ_ONCE(sqe->len);
3621 ren->flags = READ_ONCE(sqe->rename_flags);
3623 ren->oldpath = getname(oldf);
3624 if (IS_ERR(ren->oldpath))
3625 return PTR_ERR(ren->oldpath);
3627 ren->newpath = getname(newf);
3628 if (IS_ERR(ren->newpath)) {
3629 putname(ren->oldpath);
3630 return PTR_ERR(ren->newpath);
3633 req->flags |= REQ_F_NEED_CLEANUP;
3637 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3639 struct io_rename *ren = &req->rename;
3642 if (issue_flags & IO_URING_F_NONBLOCK)
3645 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3646 ren->newpath, ren->flags);
3648 req->flags &= ~REQ_F_NEED_CLEANUP;
3651 io_req_complete(req, ret);
3655 static int io_unlinkat_prep(struct io_kiocb *req,
3656 const struct io_uring_sqe *sqe)
3658 struct io_unlink *un = &req->unlink;
3659 const char __user *fname;
3661 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3663 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3666 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3669 un->dfd = READ_ONCE(sqe->fd);
3671 un->flags = READ_ONCE(sqe->unlink_flags);
3672 if (un->flags & ~AT_REMOVEDIR)
3675 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3676 un->filename = getname(fname);
3677 if (IS_ERR(un->filename))
3678 return PTR_ERR(un->filename);
3680 req->flags |= REQ_F_NEED_CLEANUP;
3684 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3686 struct io_unlink *un = &req->unlink;
3689 if (issue_flags & IO_URING_F_NONBLOCK)
3692 if (un->flags & AT_REMOVEDIR)
3693 ret = do_rmdir(un->dfd, un->filename);
3695 ret = do_unlinkat(un->dfd, un->filename);
3697 req->flags &= ~REQ_F_NEED_CLEANUP;
3700 io_req_complete(req, ret);
3704 static int io_shutdown_prep(struct io_kiocb *req,
3705 const struct io_uring_sqe *sqe)
3707 #if defined(CONFIG_NET)
3708 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3710 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3711 sqe->buf_index || sqe->splice_fd_in))
3714 req->shutdown.how = READ_ONCE(sqe->len);
3721 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3723 #if defined(CONFIG_NET)
3724 struct socket *sock;
3727 if (issue_flags & IO_URING_F_NONBLOCK)
3730 sock = sock_from_file(req->file);
3731 if (unlikely(!sock))
3734 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3737 io_req_complete(req, ret);
3744 static int __io_splice_prep(struct io_kiocb *req,
3745 const struct io_uring_sqe *sqe)
3747 struct io_splice *sp = &req->splice;
3748 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3750 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3754 sp->len = READ_ONCE(sqe->len);
3755 sp->flags = READ_ONCE(sqe->splice_flags);
3757 if (unlikely(sp->flags & ~valid_flags))
3760 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3761 (sp->flags & SPLICE_F_FD_IN_FIXED));
3764 req->flags |= REQ_F_NEED_CLEANUP;
3768 static int io_tee_prep(struct io_kiocb *req,
3769 const struct io_uring_sqe *sqe)
3771 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3773 return __io_splice_prep(req, sqe);
3776 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3778 struct io_splice *sp = &req->splice;
3779 struct file *in = sp->file_in;
3780 struct file *out = sp->file_out;
3781 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3784 if (issue_flags & IO_URING_F_NONBLOCK)
3787 ret = do_tee(in, out, sp->len, flags);
3789 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3791 req->flags &= ~REQ_F_NEED_CLEANUP;
3795 io_req_complete(req, ret);
3799 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3801 struct io_splice *sp = &req->splice;
3803 sp->off_in = READ_ONCE(sqe->splice_off_in);
3804 sp->off_out = READ_ONCE(sqe->off);
3805 return __io_splice_prep(req, sqe);
3808 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3810 struct io_splice *sp = &req->splice;
3811 struct file *in = sp->file_in;
3812 struct file *out = sp->file_out;
3813 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3814 loff_t *poff_in, *poff_out;
3817 if (issue_flags & IO_URING_F_NONBLOCK)
3820 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3821 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3824 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3826 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3828 req->flags &= ~REQ_F_NEED_CLEANUP;
3832 io_req_complete(req, ret);
3837 * IORING_OP_NOP just posts a completion event, nothing else.
3839 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3841 struct io_ring_ctx *ctx = req->ctx;
3843 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3846 __io_req_complete(req, issue_flags, 0, 0);
3850 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3852 struct io_ring_ctx *ctx = req->ctx;
3857 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3859 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
3863 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3864 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3867 req->sync.off = READ_ONCE(sqe->off);
3868 req->sync.len = READ_ONCE(sqe->len);
3872 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3874 loff_t end = req->sync.off + req->sync.len;
3877 /* fsync always requires a blocking context */
3878 if (issue_flags & IO_URING_F_NONBLOCK)
3881 ret = vfs_fsync_range(req->file, req->sync.off,
3882 end > 0 ? end : LLONG_MAX,
3883 req->sync.flags & IORING_FSYNC_DATASYNC);
3886 io_req_complete(req, ret);
3890 static int io_fallocate_prep(struct io_kiocb *req,
3891 const struct io_uring_sqe *sqe)
3893 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
3896 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3899 req->sync.off = READ_ONCE(sqe->off);
3900 req->sync.len = READ_ONCE(sqe->addr);
3901 req->sync.mode = READ_ONCE(sqe->len);
3905 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3909 /* fallocate always requiring blocking context */
3910 if (issue_flags & IO_URING_F_NONBLOCK)
3912 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3916 io_req_complete(req, ret);
3920 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3922 const char __user *fname;
3925 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3927 if (unlikely(sqe->ioprio || sqe->buf_index))
3929 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3932 /* open.how should be already initialised */
3933 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3934 req->open.how.flags |= O_LARGEFILE;
3936 req->open.dfd = READ_ONCE(sqe->fd);
3937 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3938 req->open.filename = getname(fname);
3939 if (IS_ERR(req->open.filename)) {
3940 ret = PTR_ERR(req->open.filename);
3941 req->open.filename = NULL;
3945 req->open.file_slot = READ_ONCE(sqe->file_index);
3946 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
3949 req->open.nofile = rlimit(RLIMIT_NOFILE);
3950 req->flags |= REQ_F_NEED_CLEANUP;
3954 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3956 u64 mode = READ_ONCE(sqe->len);
3957 u64 flags = READ_ONCE(sqe->open_flags);
3959 req->open.how = build_open_how(flags, mode);
3960 return __io_openat_prep(req, sqe);
3963 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3965 struct open_how __user *how;
3969 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3970 len = READ_ONCE(sqe->len);
3971 if (len < OPEN_HOW_SIZE_VER0)
3974 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3979 return __io_openat_prep(req, sqe);
3982 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3984 struct open_flags op;
3986 bool resolve_nonblock, nonblock_set;
3987 bool fixed = !!req->open.file_slot;
3990 ret = build_open_flags(&req->open.how, &op);
3993 nonblock_set = op.open_flag & O_NONBLOCK;
3994 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3995 if (issue_flags & IO_URING_F_NONBLOCK) {
3997 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3998 * it'll always -EAGAIN
4000 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4002 op.lookup_flags |= LOOKUP_CACHED;
4003 op.open_flag |= O_NONBLOCK;
4007 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4012 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4015 * We could hang on to this 'fd' on retrying, but seems like
4016 * marginal gain for something that is now known to be a slower
4017 * path. So just put it, and we'll get a new one when we retry.
4022 ret = PTR_ERR(file);
4023 /* only retry if RESOLVE_CACHED wasn't already set by application */
4024 if (ret == -EAGAIN &&
4025 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4030 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4031 file->f_flags &= ~O_NONBLOCK;
4032 fsnotify_open(file);
4035 fd_install(ret, file);
4037 ret = io_install_fixed_file(req, file, issue_flags,
4038 req->open.file_slot - 1);
4040 putname(req->open.filename);
4041 req->flags &= ~REQ_F_NEED_CLEANUP;
4044 __io_req_complete(req, issue_flags, ret, 0);
4048 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4050 return io_openat2(req, issue_flags);
4053 static int io_remove_buffers_prep(struct io_kiocb *req,
4054 const struct io_uring_sqe *sqe)
4056 struct io_provide_buf *p = &req->pbuf;
4059 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4063 tmp = READ_ONCE(sqe->fd);
4064 if (!tmp || tmp > USHRT_MAX)
4067 memset(p, 0, sizeof(*p));
4069 p->bgid = READ_ONCE(sqe->buf_group);
4073 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4074 int bgid, unsigned nbufs)
4078 /* shouldn't happen */
4082 /* the head kbuf is the list itself */
4083 while (!list_empty(&buf->list)) {
4084 struct io_buffer *nxt;
4086 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4087 list_del(&nxt->list);
4094 xa_erase(&ctx->io_buffers, bgid);
4099 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4101 struct io_provide_buf *p = &req->pbuf;
4102 struct io_ring_ctx *ctx = req->ctx;
4103 struct io_buffer *head;
4105 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4107 io_ring_submit_lock(ctx, !force_nonblock);
4109 lockdep_assert_held(&ctx->uring_lock);
4112 head = xa_load(&ctx->io_buffers, p->bgid);
4114 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4118 /* complete before unlock, IOPOLL may need the lock */
4119 __io_req_complete(req, issue_flags, ret, 0);
4120 io_ring_submit_unlock(ctx, !force_nonblock);
4124 static int io_provide_buffers_prep(struct io_kiocb *req,
4125 const struct io_uring_sqe *sqe)
4127 unsigned long size, tmp_check;
4128 struct io_provide_buf *p = &req->pbuf;
4131 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4134 tmp = READ_ONCE(sqe->fd);
4135 if (!tmp || tmp > USHRT_MAX)
4138 p->addr = READ_ONCE(sqe->addr);
4139 p->len = READ_ONCE(sqe->len);
4141 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4144 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4147 size = (unsigned long)p->len * p->nbufs;
4148 if (!access_ok(u64_to_user_ptr(p->addr), size))
4151 p->bgid = READ_ONCE(sqe->buf_group);
4152 tmp = READ_ONCE(sqe->off);
4153 if (tmp > USHRT_MAX)
4159 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4161 struct io_buffer *buf;
4162 u64 addr = pbuf->addr;
4163 int i, bid = pbuf->bid;
4165 for (i = 0; i < pbuf->nbufs; i++) {
4166 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4171 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4176 INIT_LIST_HEAD(&buf->list);
4179 list_add_tail(&buf->list, &(*head)->list);
4183 return i ? i : -ENOMEM;
4186 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4188 struct io_provide_buf *p = &req->pbuf;
4189 struct io_ring_ctx *ctx = req->ctx;
4190 struct io_buffer *head, *list;
4192 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4194 io_ring_submit_lock(ctx, !force_nonblock);
4196 lockdep_assert_held(&ctx->uring_lock);
4198 list = head = xa_load(&ctx->io_buffers, p->bgid);
4200 ret = io_add_buffers(p, &head);
4201 if (ret >= 0 && !list) {
4202 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4204 __io_remove_buffers(ctx, head, p->bgid, -1U);
4208 /* complete before unlock, IOPOLL may need the lock */
4209 __io_req_complete(req, issue_flags, ret, 0);
4210 io_ring_submit_unlock(ctx, !force_nonblock);
4214 static int io_epoll_ctl_prep(struct io_kiocb *req,
4215 const struct io_uring_sqe *sqe)
4217 #if defined(CONFIG_EPOLL)
4218 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4220 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4223 req->epoll.epfd = READ_ONCE(sqe->fd);
4224 req->epoll.op = READ_ONCE(sqe->len);
4225 req->epoll.fd = READ_ONCE(sqe->off);
4227 if (ep_op_has_event(req->epoll.op)) {
4228 struct epoll_event __user *ev;
4230 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4231 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4241 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4243 #if defined(CONFIG_EPOLL)
4244 struct io_epoll *ie = &req->epoll;
4246 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4248 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4249 if (force_nonblock && ret == -EAGAIN)
4254 __io_req_complete(req, issue_flags, ret, 0);
4261 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4263 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4264 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4266 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4269 req->madvise.addr = READ_ONCE(sqe->addr);
4270 req->madvise.len = READ_ONCE(sqe->len);
4271 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4278 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4280 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4281 struct io_madvise *ma = &req->madvise;
4284 if (issue_flags & IO_URING_F_NONBLOCK)
4287 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4290 io_req_complete(req, ret);
4297 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4299 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4301 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4304 req->fadvise.offset = READ_ONCE(sqe->off);
4305 req->fadvise.len = READ_ONCE(sqe->len);
4306 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4310 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4312 struct io_fadvise *fa = &req->fadvise;
4315 if (issue_flags & IO_URING_F_NONBLOCK) {
4316 switch (fa->advice) {
4317 case POSIX_FADV_NORMAL:
4318 case POSIX_FADV_RANDOM:
4319 case POSIX_FADV_SEQUENTIAL:
4326 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4329 __io_req_complete(req, issue_flags, ret, 0);
4333 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4335 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4337 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4339 if (req->flags & REQ_F_FIXED_FILE)
4342 req->statx.dfd = READ_ONCE(sqe->fd);
4343 req->statx.mask = READ_ONCE(sqe->len);
4344 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4345 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4346 req->statx.flags = READ_ONCE(sqe->statx_flags);
4351 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4353 struct io_statx *ctx = &req->statx;
4356 if (issue_flags & IO_URING_F_NONBLOCK)
4359 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4364 io_req_complete(req, ret);
4368 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4370 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4372 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4373 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4375 if (req->flags & REQ_F_FIXED_FILE)
4378 req->close.fd = READ_ONCE(sqe->fd);
4382 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4384 struct files_struct *files = current->files;
4385 struct io_close *close = &req->close;
4386 struct fdtable *fdt;
4387 struct file *file = NULL;
4390 spin_lock(&files->file_lock);
4391 fdt = files_fdtable(files);
4392 if (close->fd >= fdt->max_fds) {
4393 spin_unlock(&files->file_lock);
4396 file = fdt->fd[close->fd];
4397 if (!file || file->f_op == &io_uring_fops) {
4398 spin_unlock(&files->file_lock);
4403 /* if the file has a flush method, be safe and punt to async */
4404 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4405 spin_unlock(&files->file_lock);
4409 ret = __close_fd_get_file(close->fd, &file);
4410 spin_unlock(&files->file_lock);
4417 /* No ->flush() or already async, safely close from here */
4418 ret = filp_close(file, current->files);
4424 __io_req_complete(req, issue_flags, ret, 0);
4428 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4430 struct io_ring_ctx *ctx = req->ctx;
4432 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4434 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4438 req->sync.off = READ_ONCE(sqe->off);
4439 req->sync.len = READ_ONCE(sqe->len);
4440 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4444 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4448 /* sync_file_range always requires a blocking context */
4449 if (issue_flags & IO_URING_F_NONBLOCK)
4452 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4456 io_req_complete(req, ret);
4460 #if defined(CONFIG_NET)
4461 static int io_setup_async_msg(struct io_kiocb *req,
4462 struct io_async_msghdr *kmsg)
4464 struct io_async_msghdr *async_msg = req->async_data;
4468 if (io_alloc_async_data(req)) {
4469 kfree(kmsg->free_iov);
4472 async_msg = req->async_data;
4473 req->flags |= REQ_F_NEED_CLEANUP;
4474 memcpy(async_msg, kmsg, sizeof(*kmsg));
4475 async_msg->msg.msg_name = &async_msg->addr;
4476 /* if were using fast_iov, set it to the new one */
4477 if (!async_msg->free_iov)
4478 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4483 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4484 struct io_async_msghdr *iomsg)
4486 iomsg->msg.msg_name = &iomsg->addr;
4487 iomsg->free_iov = iomsg->fast_iov;
4488 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4489 req->sr_msg.msg_flags, &iomsg->free_iov);
4492 static int io_sendmsg_prep_async(struct io_kiocb *req)
4496 ret = io_sendmsg_copy_hdr(req, req->async_data);
4498 req->flags |= REQ_F_NEED_CLEANUP;
4502 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4504 struct io_sr_msg *sr = &req->sr_msg;
4506 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4509 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4510 sr->len = READ_ONCE(sqe->len);
4511 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4512 if (sr->msg_flags & MSG_DONTWAIT)
4513 req->flags |= REQ_F_NOWAIT;
4515 #ifdef CONFIG_COMPAT
4516 if (req->ctx->compat)
4517 sr->msg_flags |= MSG_CMSG_COMPAT;
4522 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4524 struct io_async_msghdr iomsg, *kmsg;
4525 struct socket *sock;
4530 sock = sock_from_file(req->file);
4531 if (unlikely(!sock))
4534 kmsg = req->async_data;
4536 ret = io_sendmsg_copy_hdr(req, &iomsg);
4542 flags = req->sr_msg.msg_flags;
4543 if (issue_flags & IO_URING_F_NONBLOCK)
4544 flags |= MSG_DONTWAIT;
4545 if (flags & MSG_WAITALL)
4546 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4548 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4549 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4550 return io_setup_async_msg(req, kmsg);
4551 if (ret == -ERESTARTSYS)
4554 /* fast path, check for non-NULL to avoid function call */
4556 kfree(kmsg->free_iov);
4557 req->flags &= ~REQ_F_NEED_CLEANUP;
4560 __io_req_complete(req, issue_flags, ret, 0);
4564 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4566 struct io_sr_msg *sr = &req->sr_msg;
4569 struct socket *sock;
4574 sock = sock_from_file(req->file);
4575 if (unlikely(!sock))
4578 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4582 msg.msg_name = NULL;
4583 msg.msg_control = NULL;
4584 msg.msg_controllen = 0;
4585 msg.msg_namelen = 0;
4587 flags = req->sr_msg.msg_flags;
4588 if (issue_flags & IO_URING_F_NONBLOCK)
4589 flags |= MSG_DONTWAIT;
4590 if (flags & MSG_WAITALL)
4591 min_ret = iov_iter_count(&msg.msg_iter);
4593 msg.msg_flags = flags;
4594 ret = sock_sendmsg(sock, &msg);
4595 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4597 if (ret == -ERESTARTSYS)
4602 __io_req_complete(req, issue_flags, ret, 0);
4606 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4607 struct io_async_msghdr *iomsg)
4609 struct io_sr_msg *sr = &req->sr_msg;
4610 struct iovec __user *uiov;
4614 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4615 &iomsg->uaddr, &uiov, &iov_len);
4619 if (req->flags & REQ_F_BUFFER_SELECT) {
4622 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4624 sr->len = iomsg->fast_iov[0].iov_len;
4625 iomsg->free_iov = NULL;
4627 iomsg->free_iov = iomsg->fast_iov;
4628 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4629 &iomsg->free_iov, &iomsg->msg.msg_iter,
4638 #ifdef CONFIG_COMPAT
4639 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4640 struct io_async_msghdr *iomsg)
4642 struct io_sr_msg *sr = &req->sr_msg;
4643 struct compat_iovec __user *uiov;
4648 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4653 uiov = compat_ptr(ptr);
4654 if (req->flags & REQ_F_BUFFER_SELECT) {
4655 compat_ssize_t clen;
4659 if (!access_ok(uiov, sizeof(*uiov)))
4661 if (__get_user(clen, &uiov->iov_len))
4666 iomsg->free_iov = NULL;
4668 iomsg->free_iov = iomsg->fast_iov;
4669 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4670 UIO_FASTIOV, &iomsg->free_iov,
4671 &iomsg->msg.msg_iter, true);
4680 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4681 struct io_async_msghdr *iomsg)
4683 iomsg->msg.msg_name = &iomsg->addr;
4685 #ifdef CONFIG_COMPAT
4686 if (req->ctx->compat)
4687 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4690 return __io_recvmsg_copy_hdr(req, iomsg);
4693 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4696 struct io_sr_msg *sr = &req->sr_msg;
4697 struct io_buffer *kbuf;
4699 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4704 req->flags |= REQ_F_BUFFER_SELECTED;
4708 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4710 return io_put_kbuf(req, req->sr_msg.kbuf);
4713 static int io_recvmsg_prep_async(struct io_kiocb *req)
4717 ret = io_recvmsg_copy_hdr(req, req->async_data);
4719 req->flags |= REQ_F_NEED_CLEANUP;
4723 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4725 struct io_sr_msg *sr = &req->sr_msg;
4727 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4730 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4731 sr->len = READ_ONCE(sqe->len);
4732 sr->bgid = READ_ONCE(sqe->buf_group);
4733 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4734 if (sr->msg_flags & MSG_DONTWAIT)
4735 req->flags |= REQ_F_NOWAIT;
4737 #ifdef CONFIG_COMPAT
4738 if (req->ctx->compat)
4739 sr->msg_flags |= MSG_CMSG_COMPAT;
4744 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4746 struct io_async_msghdr iomsg, *kmsg;
4747 struct socket *sock;
4748 struct io_buffer *kbuf;
4751 int ret, cflags = 0;
4752 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4754 sock = sock_from_file(req->file);
4755 if (unlikely(!sock))
4758 kmsg = req->async_data;
4760 ret = io_recvmsg_copy_hdr(req, &iomsg);
4766 if (req->flags & REQ_F_BUFFER_SELECT) {
4767 kbuf = io_recv_buffer_select(req, !force_nonblock);
4769 return PTR_ERR(kbuf);
4770 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4771 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4772 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4773 1, req->sr_msg.len);
4776 flags = req->sr_msg.msg_flags;
4778 flags |= MSG_DONTWAIT;
4779 if (flags & MSG_WAITALL)
4780 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4782 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4783 kmsg->uaddr, flags);
4784 if (force_nonblock && ret == -EAGAIN)
4785 return io_setup_async_msg(req, kmsg);
4786 if (ret == -ERESTARTSYS)
4789 if (req->flags & REQ_F_BUFFER_SELECTED)
4790 cflags = io_put_recv_kbuf(req);
4791 /* fast path, check for non-NULL to avoid function call */
4793 kfree(kmsg->free_iov);
4794 req->flags &= ~REQ_F_NEED_CLEANUP;
4795 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4797 __io_req_complete(req, issue_flags, ret, cflags);
4801 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4803 struct io_buffer *kbuf;
4804 struct io_sr_msg *sr = &req->sr_msg;
4806 void __user *buf = sr->buf;
4807 struct socket *sock;
4811 int ret, cflags = 0;
4812 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4814 sock = sock_from_file(req->file);
4815 if (unlikely(!sock))
4818 if (req->flags & REQ_F_BUFFER_SELECT) {
4819 kbuf = io_recv_buffer_select(req, !force_nonblock);
4821 return PTR_ERR(kbuf);
4822 buf = u64_to_user_ptr(kbuf->addr);
4825 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4829 msg.msg_name = NULL;
4830 msg.msg_control = NULL;
4831 msg.msg_controllen = 0;
4832 msg.msg_namelen = 0;
4833 msg.msg_iocb = NULL;
4836 flags = req->sr_msg.msg_flags;
4838 flags |= MSG_DONTWAIT;
4839 if (flags & MSG_WAITALL)
4840 min_ret = iov_iter_count(&msg.msg_iter);
4842 ret = sock_recvmsg(sock, &msg, flags);
4843 if (force_nonblock && ret == -EAGAIN)
4845 if (ret == -ERESTARTSYS)
4848 if (req->flags & REQ_F_BUFFER_SELECTED)
4849 cflags = io_put_recv_kbuf(req);
4850 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4852 __io_req_complete(req, issue_flags, ret, cflags);
4856 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4858 struct io_accept *accept = &req->accept;
4860 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4862 if (sqe->ioprio || sqe->len || sqe->buf_index)
4865 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4866 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4867 accept->flags = READ_ONCE(sqe->accept_flags);
4868 accept->nofile = rlimit(RLIMIT_NOFILE);
4870 accept->file_slot = READ_ONCE(sqe->file_index);
4871 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
4872 (accept->flags & SOCK_CLOEXEC)))
4874 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4876 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4877 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4881 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4883 struct io_accept *accept = &req->accept;
4884 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4885 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4886 bool fixed = !!accept->file_slot;
4890 if (req->file->f_flags & O_NONBLOCK)
4891 req->flags |= REQ_F_NOWAIT;
4894 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4895 if (unlikely(fd < 0))
4898 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4903 ret = PTR_ERR(file);
4904 if (ret == -EAGAIN && force_nonblock)
4906 if (ret == -ERESTARTSYS)
4909 } else if (!fixed) {
4910 fd_install(fd, file);
4913 ret = io_install_fixed_file(req, file, issue_flags,
4914 accept->file_slot - 1);
4916 __io_req_complete(req, issue_flags, ret, 0);
4920 static int io_connect_prep_async(struct io_kiocb *req)
4922 struct io_async_connect *io = req->async_data;
4923 struct io_connect *conn = &req->connect;
4925 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4928 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4930 struct io_connect *conn = &req->connect;
4932 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4934 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
4938 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4939 conn->addr_len = READ_ONCE(sqe->addr2);
4943 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4945 struct io_async_connect __io, *io;
4946 unsigned file_flags;
4948 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4950 if (req->async_data) {
4951 io = req->async_data;
4953 ret = move_addr_to_kernel(req->connect.addr,
4954 req->connect.addr_len,
4961 file_flags = force_nonblock ? O_NONBLOCK : 0;
4963 ret = __sys_connect_file(req->file, &io->address,
4964 req->connect.addr_len, file_flags);
4965 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4966 if (req->async_data)
4968 if (io_alloc_async_data(req)) {
4972 memcpy(req->async_data, &__io, sizeof(__io));
4975 if (ret == -ERESTARTSYS)
4980 __io_req_complete(req, issue_flags, ret, 0);
4983 #else /* !CONFIG_NET */
4984 #define IO_NETOP_FN(op) \
4985 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4987 return -EOPNOTSUPP; \
4990 #define IO_NETOP_PREP(op) \
4992 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4994 return -EOPNOTSUPP; \
4997 #define IO_NETOP_PREP_ASYNC(op) \
4999 static int io_##op##_prep_async(struct io_kiocb *req) \
5001 return -EOPNOTSUPP; \
5004 IO_NETOP_PREP_ASYNC(sendmsg);
5005 IO_NETOP_PREP_ASYNC(recvmsg);
5006 IO_NETOP_PREP_ASYNC(connect);
5007 IO_NETOP_PREP(accept);
5010 #endif /* CONFIG_NET */
5012 struct io_poll_table {
5013 struct poll_table_struct pt;
5014 struct io_kiocb *req;
5019 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5020 __poll_t mask, io_req_tw_func_t func)
5022 /* for instances that support it check for an event match first: */
5023 if (mask && !(mask & poll->events))
5026 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5028 list_del_init(&poll->wait.entry);
5031 req->io_task_work.func = func;
5034 * If this fails, then the task is exiting. When a task exits, the
5035 * work gets canceled, so just cancel this request as well instead
5036 * of executing it. We can't safely execute it anyway, as we may not
5037 * have the needed state needed for it anyway.
5039 io_req_task_work_add(req);
5043 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5044 __acquires(&req->ctx->completion_lock)
5046 struct io_ring_ctx *ctx = req->ctx;
5048 /* req->task == current here, checking PF_EXITING is safe */
5049 if (unlikely(req->task->flags & PF_EXITING))
5050 WRITE_ONCE(poll->canceled, true);
5052 if (!req->result && !READ_ONCE(poll->canceled)) {
5053 struct poll_table_struct pt = { ._key = poll->events };
5055 req->result = vfs_poll(req->file, &pt) & poll->events;
5058 spin_lock(&ctx->completion_lock);
5059 if (!req->result && !READ_ONCE(poll->canceled)) {
5060 add_wait_queue(poll->head, &poll->wait);
5067 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5069 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5070 if (req->opcode == IORING_OP_POLL_ADD)
5071 return req->async_data;
5072 return req->apoll->double_poll;
5075 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5077 if (req->opcode == IORING_OP_POLL_ADD)
5079 return &req->apoll->poll;
5082 static void io_poll_remove_double(struct io_kiocb *req)
5083 __must_hold(&req->ctx->completion_lock)
5085 struct io_poll_iocb *poll = io_poll_get_double(req);
5087 lockdep_assert_held(&req->ctx->completion_lock);
5089 if (poll && poll->head) {
5090 struct wait_queue_head *head = poll->head;
5092 spin_lock_irq(&head->lock);
5093 list_del_init(&poll->wait.entry);
5094 if (poll->wait.private)
5097 spin_unlock_irq(&head->lock);
5101 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5102 __must_hold(&req->ctx->completion_lock)
5104 struct io_ring_ctx *ctx = req->ctx;
5105 unsigned flags = IORING_CQE_F_MORE;
5108 if (READ_ONCE(req->poll.canceled)) {
5110 req->poll.events |= EPOLLONESHOT;
5112 error = mangle_poll(mask);
5114 if (req->poll.events & EPOLLONESHOT)
5116 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5117 req->poll.done = true;
5120 if (flags & IORING_CQE_F_MORE)
5123 io_commit_cqring(ctx);
5124 return !(flags & IORING_CQE_F_MORE);
5127 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5129 struct io_ring_ctx *ctx = req->ctx;
5130 struct io_kiocb *nxt;
5132 if (io_poll_rewait(req, &req->poll)) {
5133 spin_unlock(&ctx->completion_lock);
5137 done = io_poll_complete(req, req->result);
5139 io_poll_remove_double(req);
5140 hash_del(&req->hash_node);
5143 add_wait_queue(req->poll.head, &req->poll.wait);
5145 spin_unlock(&ctx->completion_lock);
5146 io_cqring_ev_posted(ctx);
5149 nxt = io_put_req_find_next(req);
5151 io_req_task_submit(nxt, locked);
5156 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5157 int sync, void *key)
5159 struct io_kiocb *req = wait->private;
5160 struct io_poll_iocb *poll = io_poll_get_single(req);
5161 __poll_t mask = key_to_poll(key);
5162 unsigned long flags;
5164 /* for instances that support it check for an event match first: */
5165 if (mask && !(mask & poll->events))
5167 if (!(poll->events & EPOLLONESHOT))
5168 return poll->wait.func(&poll->wait, mode, sync, key);
5170 list_del_init(&wait->entry);
5175 spin_lock_irqsave(&poll->head->lock, flags);
5176 done = list_empty(&poll->wait.entry);
5178 list_del_init(&poll->wait.entry);
5179 /* make sure double remove sees this as being gone */
5180 wait->private = NULL;
5181 spin_unlock_irqrestore(&poll->head->lock, flags);
5183 /* use wait func handler, so it matches the rq type */
5184 poll->wait.func(&poll->wait, mode, sync, key);
5191 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5192 wait_queue_func_t wake_func)
5196 poll->canceled = false;
5197 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5198 /* mask in events that we always want/need */
5199 poll->events = events | IO_POLL_UNMASK;
5200 INIT_LIST_HEAD(&poll->wait.entry);
5201 init_waitqueue_func_entry(&poll->wait, wake_func);
5204 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5205 struct wait_queue_head *head,
5206 struct io_poll_iocb **poll_ptr)
5208 struct io_kiocb *req = pt->req;
5211 * The file being polled uses multiple waitqueues for poll handling
5212 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5215 if (unlikely(pt->nr_entries)) {
5216 struct io_poll_iocb *poll_one = poll;
5218 /* double add on the same waitqueue head, ignore */
5219 if (poll_one->head == head)
5221 /* already have a 2nd entry, fail a third attempt */
5223 if ((*poll_ptr)->head == head)
5225 pt->error = -EINVAL;
5229 * Can't handle multishot for double wait for now, turn it
5230 * into one-shot mode.
5232 if (!(poll_one->events & EPOLLONESHOT))
5233 poll_one->events |= EPOLLONESHOT;
5234 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5236 pt->error = -ENOMEM;
5239 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5241 poll->wait.private = req;
5248 if (poll->events & EPOLLEXCLUSIVE)
5249 add_wait_queue_exclusive(head, &poll->wait);
5251 add_wait_queue(head, &poll->wait);
5254 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5255 struct poll_table_struct *p)
5257 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5258 struct async_poll *apoll = pt->req->apoll;
5260 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5263 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5265 struct async_poll *apoll = req->apoll;
5266 struct io_ring_ctx *ctx = req->ctx;
5268 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5270 if (io_poll_rewait(req, &apoll->poll)) {
5271 spin_unlock(&ctx->completion_lock);
5275 hash_del(&req->hash_node);
5276 io_poll_remove_double(req);
5277 spin_unlock(&ctx->completion_lock);
5279 if (!READ_ONCE(apoll->poll.canceled))
5280 io_req_task_submit(req, locked);
5282 io_req_complete_failed(req, -ECANCELED);
5285 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5288 struct io_kiocb *req = wait->private;
5289 struct io_poll_iocb *poll = &req->apoll->poll;
5291 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5294 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5297 static void io_poll_req_insert(struct io_kiocb *req)
5299 struct io_ring_ctx *ctx = req->ctx;
5300 struct hlist_head *list;
5302 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5303 hlist_add_head(&req->hash_node, list);
5306 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5307 struct io_poll_iocb *poll,
5308 struct io_poll_table *ipt, __poll_t mask,
5309 wait_queue_func_t wake_func)
5310 __acquires(&ctx->completion_lock)
5312 struct io_ring_ctx *ctx = req->ctx;
5313 bool cancel = false;
5315 INIT_HLIST_NODE(&req->hash_node);
5316 io_init_poll_iocb(poll, mask, wake_func);
5317 poll->file = req->file;
5318 poll->wait.private = req;
5320 ipt->pt._key = mask;
5323 ipt->nr_entries = 0;
5325 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5326 if (unlikely(!ipt->nr_entries) && !ipt->error)
5327 ipt->error = -EINVAL;
5329 spin_lock(&ctx->completion_lock);
5330 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5331 io_poll_remove_double(req);
5332 if (likely(poll->head)) {
5333 spin_lock_irq(&poll->head->lock);
5334 if (unlikely(list_empty(&poll->wait.entry))) {
5340 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5341 list_del_init(&poll->wait.entry);
5343 WRITE_ONCE(poll->canceled, true);
5344 else if (!poll->done) /* actually waiting for an event */
5345 io_poll_req_insert(req);
5346 spin_unlock_irq(&poll->head->lock);
5358 static int io_arm_poll_handler(struct io_kiocb *req)
5360 const struct io_op_def *def = &io_op_defs[req->opcode];
5361 struct io_ring_ctx *ctx = req->ctx;
5362 struct async_poll *apoll;
5363 struct io_poll_table ipt;
5364 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5367 if (!req->file || !file_can_poll(req->file))
5368 return IO_APOLL_ABORTED;
5369 if (req->flags & REQ_F_POLLED)
5370 return IO_APOLL_ABORTED;
5371 if (!def->pollin && !def->pollout)
5372 return IO_APOLL_ABORTED;
5376 mask |= POLLIN | POLLRDNORM;
5378 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5379 if ((req->opcode == IORING_OP_RECVMSG) &&
5380 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5384 mask |= POLLOUT | POLLWRNORM;
5387 /* if we can't nonblock try, then no point in arming a poll handler */
5388 if (!io_file_supports_nowait(req, rw))
5389 return IO_APOLL_ABORTED;
5391 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5392 if (unlikely(!apoll))
5393 return IO_APOLL_ABORTED;
5394 apoll->double_poll = NULL;
5396 req->flags |= REQ_F_POLLED;
5397 ipt.pt._qproc = io_async_queue_proc;
5398 io_req_set_refcount(req);
5400 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5402 spin_unlock(&ctx->completion_lock);
5403 if (ret || ipt.error)
5404 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5406 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5407 mask, apoll->poll.events);
5411 static bool __io_poll_remove_one(struct io_kiocb *req,
5412 struct io_poll_iocb *poll, bool do_cancel)
5413 __must_hold(&req->ctx->completion_lock)
5415 bool do_complete = false;
5419 spin_lock_irq(&poll->head->lock);
5421 WRITE_ONCE(poll->canceled, true);
5422 if (!list_empty(&poll->wait.entry)) {
5423 list_del_init(&poll->wait.entry);
5426 spin_unlock_irq(&poll->head->lock);
5427 hash_del(&req->hash_node);
5431 static bool io_poll_remove_one(struct io_kiocb *req)
5432 __must_hold(&req->ctx->completion_lock)
5436 io_poll_remove_double(req);
5437 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5440 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5441 io_commit_cqring(req->ctx);
5443 io_put_req_deferred(req);
5449 * Returns true if we found and killed one or more poll requests
5451 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5454 struct hlist_node *tmp;
5455 struct io_kiocb *req;
5458 spin_lock(&ctx->completion_lock);
5459 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5460 struct hlist_head *list;
5462 list = &ctx->cancel_hash[i];
5463 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5464 if (io_match_task(req, tsk, cancel_all))
5465 posted += io_poll_remove_one(req);
5468 spin_unlock(&ctx->completion_lock);
5471 io_cqring_ev_posted(ctx);
5476 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5478 __must_hold(&ctx->completion_lock)
5480 struct hlist_head *list;
5481 struct io_kiocb *req;
5483 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5484 hlist_for_each_entry(req, list, hash_node) {
5485 if (sqe_addr != req->user_data)
5487 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5494 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5496 __must_hold(&ctx->completion_lock)
5498 struct io_kiocb *req;
5500 req = io_poll_find(ctx, sqe_addr, poll_only);
5503 if (io_poll_remove_one(req))
5509 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5514 events = READ_ONCE(sqe->poll32_events);
5516 events = swahw32(events);
5518 if (!(flags & IORING_POLL_ADD_MULTI))
5519 events |= EPOLLONESHOT;
5520 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5523 static int io_poll_update_prep(struct io_kiocb *req,
5524 const struct io_uring_sqe *sqe)
5526 struct io_poll_update *upd = &req->poll_update;
5529 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5531 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5533 flags = READ_ONCE(sqe->len);
5534 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5535 IORING_POLL_ADD_MULTI))
5537 /* meaningless without update */
5538 if (flags == IORING_POLL_ADD_MULTI)
5541 upd->old_user_data = READ_ONCE(sqe->addr);
5542 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5543 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5545 upd->new_user_data = READ_ONCE(sqe->off);
5546 if (!upd->update_user_data && upd->new_user_data)
5548 if (upd->update_events)
5549 upd->events = io_poll_parse_events(sqe, flags);
5550 else if (sqe->poll32_events)
5556 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5559 struct io_kiocb *req = wait->private;
5560 struct io_poll_iocb *poll = &req->poll;
5562 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5565 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5566 struct poll_table_struct *p)
5568 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5570 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5573 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5575 struct io_poll_iocb *poll = &req->poll;
5578 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5580 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5582 flags = READ_ONCE(sqe->len);
5583 if (flags & ~IORING_POLL_ADD_MULTI)
5586 io_req_set_refcount(req);
5587 poll->events = io_poll_parse_events(sqe, flags);
5591 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5593 struct io_poll_iocb *poll = &req->poll;
5594 struct io_ring_ctx *ctx = req->ctx;
5595 struct io_poll_table ipt;
5598 ipt.pt._qproc = io_poll_queue_proc;
5600 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5603 if (mask) { /* no async, we'd stolen it */
5605 io_poll_complete(req, mask);
5607 spin_unlock(&ctx->completion_lock);
5610 io_cqring_ev_posted(ctx);
5611 if (poll->events & EPOLLONESHOT)
5617 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5619 struct io_ring_ctx *ctx = req->ctx;
5620 struct io_kiocb *preq;
5624 spin_lock(&ctx->completion_lock);
5625 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5631 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5633 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5638 * Don't allow racy completion with singleshot, as we cannot safely
5639 * update those. For multishot, if we're racing with completion, just
5640 * let completion re-add it.
5642 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5643 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5647 /* we now have a detached poll request. reissue. */
5651 spin_unlock(&ctx->completion_lock);
5653 io_req_complete(req, ret);
5656 /* only mask one event flags, keep behavior flags */
5657 if (req->poll_update.update_events) {
5658 preq->poll.events &= ~0xffff;
5659 preq->poll.events |= req->poll_update.events & 0xffff;
5660 preq->poll.events |= IO_POLL_UNMASK;
5662 if (req->poll_update.update_user_data)
5663 preq->user_data = req->poll_update.new_user_data;
5664 spin_unlock(&ctx->completion_lock);
5666 /* complete update request, we're done with it */
5667 io_req_complete(req, ret);
5670 ret = io_poll_add(preq, issue_flags);
5673 io_req_complete(preq, ret);
5679 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5682 io_req_complete_post(req, -ETIME, 0);
5685 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5687 struct io_timeout_data *data = container_of(timer,
5688 struct io_timeout_data, timer);
5689 struct io_kiocb *req = data->req;
5690 struct io_ring_ctx *ctx = req->ctx;
5691 unsigned long flags;
5693 spin_lock_irqsave(&ctx->timeout_lock, flags);
5694 list_del_init(&req->timeout.list);
5695 atomic_set(&req->ctx->cq_timeouts,
5696 atomic_read(&req->ctx->cq_timeouts) + 1);
5697 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5699 req->io_task_work.func = io_req_task_timeout;
5700 io_req_task_work_add(req);
5701 return HRTIMER_NORESTART;
5704 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5706 __must_hold(&ctx->timeout_lock)
5708 struct io_timeout_data *io;
5709 struct io_kiocb *req;
5712 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5713 found = user_data == req->user_data;
5718 return ERR_PTR(-ENOENT);
5720 io = req->async_data;
5721 if (hrtimer_try_to_cancel(&io->timer) == -1)
5722 return ERR_PTR(-EALREADY);
5723 list_del_init(&req->timeout.list);
5727 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5728 __must_hold(&ctx->completion_lock)
5729 __must_hold(&ctx->timeout_lock)
5731 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5734 return PTR_ERR(req);
5737 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5738 io_put_req_deferred(req);
5742 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5744 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5745 case IORING_TIMEOUT_BOOTTIME:
5746 return CLOCK_BOOTTIME;
5747 case IORING_TIMEOUT_REALTIME:
5748 return CLOCK_REALTIME;
5750 /* can't happen, vetted at prep time */
5754 return CLOCK_MONOTONIC;
5758 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5759 struct timespec64 *ts, enum hrtimer_mode mode)
5760 __must_hold(&ctx->timeout_lock)
5762 struct io_timeout_data *io;
5763 struct io_kiocb *req;
5766 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5767 found = user_data == req->user_data;
5774 io = req->async_data;
5775 if (hrtimer_try_to_cancel(&io->timer) == -1)
5777 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5778 io->timer.function = io_link_timeout_fn;
5779 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5783 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5784 struct timespec64 *ts, enum hrtimer_mode mode)
5785 __must_hold(&ctx->timeout_lock)
5787 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5788 struct io_timeout_data *data;
5791 return PTR_ERR(req);
5793 req->timeout.off = 0; /* noseq */
5794 data = req->async_data;
5795 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5796 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5797 data->timer.function = io_timeout_fn;
5798 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5802 static int io_timeout_remove_prep(struct io_kiocb *req,
5803 const struct io_uring_sqe *sqe)
5805 struct io_timeout_rem *tr = &req->timeout_rem;
5807 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5809 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5811 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5814 tr->ltimeout = false;
5815 tr->addr = READ_ONCE(sqe->addr);
5816 tr->flags = READ_ONCE(sqe->timeout_flags);
5817 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5818 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5820 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5821 tr->ltimeout = true;
5822 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5824 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5826 } else if (tr->flags) {
5827 /* timeout removal doesn't support flags */
5834 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5836 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5841 * Remove or update an existing timeout command
5843 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5845 struct io_timeout_rem *tr = &req->timeout_rem;
5846 struct io_ring_ctx *ctx = req->ctx;
5849 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5850 spin_lock(&ctx->completion_lock);
5851 spin_lock_irq(&ctx->timeout_lock);
5852 ret = io_timeout_cancel(ctx, tr->addr);
5853 spin_unlock_irq(&ctx->timeout_lock);
5854 spin_unlock(&ctx->completion_lock);
5856 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5858 spin_lock_irq(&ctx->timeout_lock);
5860 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5862 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5863 spin_unlock_irq(&ctx->timeout_lock);
5868 io_req_complete_post(req, ret, 0);
5872 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5873 bool is_timeout_link)
5875 struct io_timeout_data *data;
5877 u32 off = READ_ONCE(sqe->off);
5879 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5881 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5884 if (off && is_timeout_link)
5886 flags = READ_ONCE(sqe->timeout_flags);
5887 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
5889 /* more than one clock specified is invalid, obviously */
5890 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5893 INIT_LIST_HEAD(&req->timeout.list);
5894 req->timeout.off = off;
5895 if (unlikely(off && !req->ctx->off_timeout_used))
5896 req->ctx->off_timeout_used = true;
5898 if (!req->async_data && io_alloc_async_data(req))
5901 data = req->async_data;
5903 data->flags = flags;
5905 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5908 data->mode = io_translate_timeout_mode(flags);
5909 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5911 if (is_timeout_link) {
5912 struct io_submit_link *link = &req->ctx->submit_state.link;
5916 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5918 req->timeout.head = link->last;
5919 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5924 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5926 struct io_ring_ctx *ctx = req->ctx;
5927 struct io_timeout_data *data = req->async_data;
5928 struct list_head *entry;
5929 u32 tail, off = req->timeout.off;
5931 spin_lock_irq(&ctx->timeout_lock);
5934 * sqe->off holds how many events that need to occur for this
5935 * timeout event to be satisfied. If it isn't set, then this is
5936 * a pure timeout request, sequence isn't used.
5938 if (io_is_timeout_noseq(req)) {
5939 entry = ctx->timeout_list.prev;
5943 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5944 req->timeout.target_seq = tail + off;
5946 /* Update the last seq here in case io_flush_timeouts() hasn't.
5947 * This is safe because ->completion_lock is held, and submissions
5948 * and completions are never mixed in the same ->completion_lock section.
5950 ctx->cq_last_tm_flush = tail;
5953 * Insertion sort, ensuring the first entry in the list is always
5954 * the one we need first.
5956 list_for_each_prev(entry, &ctx->timeout_list) {
5957 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5960 if (io_is_timeout_noseq(nxt))
5962 /* nxt.seq is behind @tail, otherwise would've been completed */
5963 if (off >= nxt->timeout.target_seq - tail)
5967 list_add(&req->timeout.list, entry);
5968 data->timer.function = io_timeout_fn;
5969 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5970 spin_unlock_irq(&ctx->timeout_lock);
5974 struct io_cancel_data {
5975 struct io_ring_ctx *ctx;
5979 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5981 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5982 struct io_cancel_data *cd = data;
5984 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5987 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5988 struct io_ring_ctx *ctx)
5990 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5991 enum io_wq_cancel cancel_ret;
5994 if (!tctx || !tctx->io_wq)
5997 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5998 switch (cancel_ret) {
5999 case IO_WQ_CANCEL_OK:
6002 case IO_WQ_CANCEL_RUNNING:
6005 case IO_WQ_CANCEL_NOTFOUND:
6013 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6015 struct io_ring_ctx *ctx = req->ctx;
6018 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6020 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6024 spin_lock(&ctx->completion_lock);
6025 spin_lock_irq(&ctx->timeout_lock);
6026 ret = io_timeout_cancel(ctx, sqe_addr);
6027 spin_unlock_irq(&ctx->timeout_lock);
6030 ret = io_poll_cancel(ctx, sqe_addr, false);
6032 spin_unlock(&ctx->completion_lock);
6036 static int io_async_cancel_prep(struct io_kiocb *req,
6037 const struct io_uring_sqe *sqe)
6039 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6041 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6043 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6047 req->cancel.addr = READ_ONCE(sqe->addr);
6051 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6053 struct io_ring_ctx *ctx = req->ctx;
6054 u64 sqe_addr = req->cancel.addr;
6055 struct io_tctx_node *node;
6058 ret = io_try_cancel_userdata(req, sqe_addr);
6062 /* slow path, try all io-wq's */
6063 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6065 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6066 struct io_uring_task *tctx = node->task->io_uring;
6068 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6072 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6076 io_req_complete_post(req, ret, 0);
6080 static int io_rsrc_update_prep(struct io_kiocb *req,
6081 const struct io_uring_sqe *sqe)
6083 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6085 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6088 req->rsrc_update.offset = READ_ONCE(sqe->off);
6089 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6090 if (!req->rsrc_update.nr_args)
6092 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6096 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6098 struct io_ring_ctx *ctx = req->ctx;
6099 struct io_uring_rsrc_update2 up;
6102 if (issue_flags & IO_URING_F_NONBLOCK)
6105 up.offset = req->rsrc_update.offset;
6106 up.data = req->rsrc_update.arg;
6111 mutex_lock(&ctx->uring_lock);
6112 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6113 &up, req->rsrc_update.nr_args);
6114 mutex_unlock(&ctx->uring_lock);
6118 __io_req_complete(req, issue_flags, ret, 0);
6122 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6124 switch (req->opcode) {
6127 case IORING_OP_READV:
6128 case IORING_OP_READ_FIXED:
6129 case IORING_OP_READ:
6130 return io_read_prep(req, sqe);
6131 case IORING_OP_WRITEV:
6132 case IORING_OP_WRITE_FIXED:
6133 case IORING_OP_WRITE:
6134 return io_write_prep(req, sqe);
6135 case IORING_OP_POLL_ADD:
6136 return io_poll_add_prep(req, sqe);
6137 case IORING_OP_POLL_REMOVE:
6138 return io_poll_update_prep(req, sqe);
6139 case IORING_OP_FSYNC:
6140 return io_fsync_prep(req, sqe);
6141 case IORING_OP_SYNC_FILE_RANGE:
6142 return io_sfr_prep(req, sqe);
6143 case IORING_OP_SENDMSG:
6144 case IORING_OP_SEND:
6145 return io_sendmsg_prep(req, sqe);
6146 case IORING_OP_RECVMSG:
6147 case IORING_OP_RECV:
6148 return io_recvmsg_prep(req, sqe);
6149 case IORING_OP_CONNECT:
6150 return io_connect_prep(req, sqe);
6151 case IORING_OP_TIMEOUT:
6152 return io_timeout_prep(req, sqe, false);
6153 case IORING_OP_TIMEOUT_REMOVE:
6154 return io_timeout_remove_prep(req, sqe);
6155 case IORING_OP_ASYNC_CANCEL:
6156 return io_async_cancel_prep(req, sqe);
6157 case IORING_OP_LINK_TIMEOUT:
6158 return io_timeout_prep(req, sqe, true);
6159 case IORING_OP_ACCEPT:
6160 return io_accept_prep(req, sqe);
6161 case IORING_OP_FALLOCATE:
6162 return io_fallocate_prep(req, sqe);
6163 case IORING_OP_OPENAT:
6164 return io_openat_prep(req, sqe);
6165 case IORING_OP_CLOSE:
6166 return io_close_prep(req, sqe);
6167 case IORING_OP_FILES_UPDATE:
6168 return io_rsrc_update_prep(req, sqe);
6169 case IORING_OP_STATX:
6170 return io_statx_prep(req, sqe);
6171 case IORING_OP_FADVISE:
6172 return io_fadvise_prep(req, sqe);
6173 case IORING_OP_MADVISE:
6174 return io_madvise_prep(req, sqe);
6175 case IORING_OP_OPENAT2:
6176 return io_openat2_prep(req, sqe);
6177 case IORING_OP_EPOLL_CTL:
6178 return io_epoll_ctl_prep(req, sqe);
6179 case IORING_OP_SPLICE:
6180 return io_splice_prep(req, sqe);
6181 case IORING_OP_PROVIDE_BUFFERS:
6182 return io_provide_buffers_prep(req, sqe);
6183 case IORING_OP_REMOVE_BUFFERS:
6184 return io_remove_buffers_prep(req, sqe);
6186 return io_tee_prep(req, sqe);
6187 case IORING_OP_SHUTDOWN:
6188 return io_shutdown_prep(req, sqe);
6189 case IORING_OP_RENAMEAT:
6190 return io_renameat_prep(req, sqe);
6191 case IORING_OP_UNLINKAT:
6192 return io_unlinkat_prep(req, sqe);
6195 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6200 static int io_req_prep_async(struct io_kiocb *req)
6202 if (!io_op_defs[req->opcode].needs_async_setup)
6204 if (WARN_ON_ONCE(req->async_data))
6206 if (io_alloc_async_data(req))
6209 switch (req->opcode) {
6210 case IORING_OP_READV:
6211 return io_rw_prep_async(req, READ);
6212 case IORING_OP_WRITEV:
6213 return io_rw_prep_async(req, WRITE);
6214 case IORING_OP_SENDMSG:
6215 return io_sendmsg_prep_async(req);
6216 case IORING_OP_RECVMSG:
6217 return io_recvmsg_prep_async(req);
6218 case IORING_OP_CONNECT:
6219 return io_connect_prep_async(req);
6221 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6226 static u32 io_get_sequence(struct io_kiocb *req)
6228 u32 seq = req->ctx->cached_sq_head;
6230 /* need original cached_sq_head, but it was increased for each req */
6231 io_for_each_link(req, req)
6236 static bool io_drain_req(struct io_kiocb *req)
6238 struct io_kiocb *pos;
6239 struct io_ring_ctx *ctx = req->ctx;
6240 struct io_defer_entry *de;
6244 if (req->flags & REQ_F_FAIL) {
6245 io_req_complete_fail_submit(req);
6250 * If we need to drain a request in the middle of a link, drain the
6251 * head request and the next request/link after the current link.
6252 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6253 * maintained for every request of our link.
6255 if (ctx->drain_next) {
6256 req->flags |= REQ_F_IO_DRAIN;
6257 ctx->drain_next = false;
6259 /* not interested in head, start from the first linked */
6260 io_for_each_link(pos, req->link) {
6261 if (pos->flags & REQ_F_IO_DRAIN) {
6262 ctx->drain_next = true;
6263 req->flags |= REQ_F_IO_DRAIN;
6268 /* Still need defer if there is pending req in defer list. */
6269 if (likely(list_empty_careful(&ctx->defer_list) &&
6270 !(req->flags & REQ_F_IO_DRAIN))) {
6271 ctx->drain_active = false;
6275 seq = io_get_sequence(req);
6276 /* Still a chance to pass the sequence check */
6277 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6280 ret = io_req_prep_async(req);
6283 io_prep_async_link(req);
6284 de = kmalloc(sizeof(*de), GFP_KERNEL);
6288 io_req_complete_failed(req, ret);
6292 spin_lock(&ctx->completion_lock);
6293 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6294 spin_unlock(&ctx->completion_lock);
6296 io_queue_async_work(req, NULL);
6300 trace_io_uring_defer(ctx, req, req->user_data);
6303 list_add_tail(&de->list, &ctx->defer_list);
6304 spin_unlock(&ctx->completion_lock);
6308 static void io_clean_op(struct io_kiocb *req)
6310 if (req->flags & REQ_F_BUFFER_SELECTED) {
6311 switch (req->opcode) {
6312 case IORING_OP_READV:
6313 case IORING_OP_READ_FIXED:
6314 case IORING_OP_READ:
6315 kfree((void *)(unsigned long)req->rw.addr);
6317 case IORING_OP_RECVMSG:
6318 case IORING_OP_RECV:
6319 kfree(req->sr_msg.kbuf);
6324 if (req->flags & REQ_F_NEED_CLEANUP) {
6325 switch (req->opcode) {
6326 case IORING_OP_READV:
6327 case IORING_OP_READ_FIXED:
6328 case IORING_OP_READ:
6329 case IORING_OP_WRITEV:
6330 case IORING_OP_WRITE_FIXED:
6331 case IORING_OP_WRITE: {
6332 struct io_async_rw *io = req->async_data;
6334 kfree(io->free_iovec);
6337 case IORING_OP_RECVMSG:
6338 case IORING_OP_SENDMSG: {
6339 struct io_async_msghdr *io = req->async_data;
6341 kfree(io->free_iov);
6344 case IORING_OP_SPLICE:
6346 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6347 io_put_file(req->splice.file_in);
6349 case IORING_OP_OPENAT:
6350 case IORING_OP_OPENAT2:
6351 if (req->open.filename)
6352 putname(req->open.filename);
6354 case IORING_OP_RENAMEAT:
6355 putname(req->rename.oldpath);
6356 putname(req->rename.newpath);
6358 case IORING_OP_UNLINKAT:
6359 putname(req->unlink.filename);
6363 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6364 kfree(req->apoll->double_poll);
6368 if (req->flags & REQ_F_INFLIGHT) {
6369 struct io_uring_task *tctx = req->task->io_uring;
6371 atomic_dec(&tctx->inflight_tracked);
6373 if (req->flags & REQ_F_CREDS)
6374 put_cred(req->creds);
6376 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6379 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6381 struct io_ring_ctx *ctx = req->ctx;
6382 const struct cred *creds = NULL;
6385 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6386 creds = override_creds(req->creds);
6388 switch (req->opcode) {
6390 ret = io_nop(req, issue_flags);
6392 case IORING_OP_READV:
6393 case IORING_OP_READ_FIXED:
6394 case IORING_OP_READ:
6395 ret = io_read(req, issue_flags);
6397 case IORING_OP_WRITEV:
6398 case IORING_OP_WRITE_FIXED:
6399 case IORING_OP_WRITE:
6400 ret = io_write(req, issue_flags);
6402 case IORING_OP_FSYNC:
6403 ret = io_fsync(req, issue_flags);
6405 case IORING_OP_POLL_ADD:
6406 ret = io_poll_add(req, issue_flags);
6408 case IORING_OP_POLL_REMOVE:
6409 ret = io_poll_update(req, issue_flags);
6411 case IORING_OP_SYNC_FILE_RANGE:
6412 ret = io_sync_file_range(req, issue_flags);
6414 case IORING_OP_SENDMSG:
6415 ret = io_sendmsg(req, issue_flags);
6417 case IORING_OP_SEND:
6418 ret = io_send(req, issue_flags);
6420 case IORING_OP_RECVMSG:
6421 ret = io_recvmsg(req, issue_flags);
6423 case IORING_OP_RECV:
6424 ret = io_recv(req, issue_flags);
6426 case IORING_OP_TIMEOUT:
6427 ret = io_timeout(req, issue_flags);
6429 case IORING_OP_TIMEOUT_REMOVE:
6430 ret = io_timeout_remove(req, issue_flags);
6432 case IORING_OP_ACCEPT:
6433 ret = io_accept(req, issue_flags);
6435 case IORING_OP_CONNECT:
6436 ret = io_connect(req, issue_flags);
6438 case IORING_OP_ASYNC_CANCEL:
6439 ret = io_async_cancel(req, issue_flags);
6441 case IORING_OP_FALLOCATE:
6442 ret = io_fallocate(req, issue_flags);
6444 case IORING_OP_OPENAT:
6445 ret = io_openat(req, issue_flags);
6447 case IORING_OP_CLOSE:
6448 ret = io_close(req, issue_flags);
6450 case IORING_OP_FILES_UPDATE:
6451 ret = io_files_update(req, issue_flags);
6453 case IORING_OP_STATX:
6454 ret = io_statx(req, issue_flags);
6456 case IORING_OP_FADVISE:
6457 ret = io_fadvise(req, issue_flags);
6459 case IORING_OP_MADVISE:
6460 ret = io_madvise(req, issue_flags);
6462 case IORING_OP_OPENAT2:
6463 ret = io_openat2(req, issue_flags);
6465 case IORING_OP_EPOLL_CTL:
6466 ret = io_epoll_ctl(req, issue_flags);
6468 case IORING_OP_SPLICE:
6469 ret = io_splice(req, issue_flags);
6471 case IORING_OP_PROVIDE_BUFFERS:
6472 ret = io_provide_buffers(req, issue_flags);
6474 case IORING_OP_REMOVE_BUFFERS:
6475 ret = io_remove_buffers(req, issue_flags);
6478 ret = io_tee(req, issue_flags);
6480 case IORING_OP_SHUTDOWN:
6481 ret = io_shutdown(req, issue_flags);
6483 case IORING_OP_RENAMEAT:
6484 ret = io_renameat(req, issue_flags);
6486 case IORING_OP_UNLINKAT:
6487 ret = io_unlinkat(req, issue_flags);
6495 revert_creds(creds);
6498 /* If the op doesn't have a file, we're not polling for it */
6499 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6500 io_iopoll_req_issued(req);
6505 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6507 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6509 req = io_put_req_find_next(req);
6510 return req ? &req->work : NULL;
6513 static void io_wq_submit_work(struct io_wq_work *work)
6515 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6516 struct io_kiocb *timeout;
6519 /* one will be dropped by ->io_free_work() after returning to io-wq */
6520 if (!(req->flags & REQ_F_REFCOUNT))
6521 __io_req_set_refcount(req, 2);
6525 timeout = io_prep_linked_timeout(req);
6527 io_queue_linked_timeout(timeout);
6529 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6530 if (work->flags & IO_WQ_WORK_CANCEL)
6535 ret = io_issue_sqe(req, 0);
6537 * We can get EAGAIN for polled IO even though we're
6538 * forcing a sync submission from here, since we can't
6539 * wait for request slots on the block side.
6547 /* avoid locking problems by failing it from a clean context */
6549 io_req_task_queue_fail(req, ret);
6552 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6555 return &table->files[i];
6558 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6561 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6563 return (struct file *) (slot->file_ptr & FFS_MASK);
6566 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6568 unsigned long file_ptr = (unsigned long) file;
6570 if (__io_file_supports_nowait(file, READ))
6571 file_ptr |= FFS_ASYNC_READ;
6572 if (__io_file_supports_nowait(file, WRITE))
6573 file_ptr |= FFS_ASYNC_WRITE;
6574 if (S_ISREG(file_inode(file)->i_mode))
6575 file_ptr |= FFS_ISREG;
6576 file_slot->file_ptr = file_ptr;
6579 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6580 struct io_kiocb *req, int fd)
6583 unsigned long file_ptr;
6585 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6587 fd = array_index_nospec(fd, ctx->nr_user_files);
6588 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6589 file = (struct file *) (file_ptr & FFS_MASK);
6590 file_ptr &= ~FFS_MASK;
6591 /* mask in overlapping REQ_F and FFS bits */
6592 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6593 io_req_set_rsrc_node(req);
6597 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6598 struct io_kiocb *req, int fd)
6600 struct file *file = fget(fd);
6602 trace_io_uring_file_get(ctx, fd);
6604 /* we don't allow fixed io_uring files */
6605 if (file && unlikely(file->f_op == &io_uring_fops))
6606 io_req_track_inflight(req);
6610 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6611 struct io_kiocb *req, int fd, bool fixed)
6614 return io_file_get_fixed(ctx, req, fd);
6616 return io_file_get_normal(ctx, req, fd);
6619 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6621 struct io_kiocb *prev = req->timeout.prev;
6625 ret = io_try_cancel_userdata(req, prev->user_data);
6626 io_req_complete_post(req, ret ?: -ETIME, 0);
6629 io_req_complete_post(req, -ETIME, 0);
6633 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6635 struct io_timeout_data *data = container_of(timer,
6636 struct io_timeout_data, timer);
6637 struct io_kiocb *prev, *req = data->req;
6638 struct io_ring_ctx *ctx = req->ctx;
6639 unsigned long flags;
6641 spin_lock_irqsave(&ctx->timeout_lock, flags);
6642 prev = req->timeout.head;
6643 req->timeout.head = NULL;
6646 * We don't expect the list to be empty, that will only happen if we
6647 * race with the completion of the linked work.
6650 io_remove_next_linked(prev);
6651 if (!req_ref_inc_not_zero(prev))
6654 list_del(&req->timeout.list);
6655 req->timeout.prev = prev;
6656 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6658 req->io_task_work.func = io_req_task_link_timeout;
6659 io_req_task_work_add(req);
6660 return HRTIMER_NORESTART;
6663 static void io_queue_linked_timeout(struct io_kiocb *req)
6665 struct io_ring_ctx *ctx = req->ctx;
6667 spin_lock_irq(&ctx->timeout_lock);
6669 * If the back reference is NULL, then our linked request finished
6670 * before we got a chance to setup the timer
6672 if (req->timeout.head) {
6673 struct io_timeout_data *data = req->async_data;
6675 data->timer.function = io_link_timeout_fn;
6676 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6678 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6680 spin_unlock_irq(&ctx->timeout_lock);
6681 /* drop submission reference */
6685 static void __io_queue_sqe(struct io_kiocb *req)
6686 __must_hold(&req->ctx->uring_lock)
6688 struct io_kiocb *linked_timeout;
6692 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6695 * We async punt it if the file wasn't marked NOWAIT, or if the file
6696 * doesn't support non-blocking read/write attempts
6699 if (req->flags & REQ_F_COMPLETE_INLINE) {
6700 struct io_ring_ctx *ctx = req->ctx;
6701 struct io_submit_state *state = &ctx->submit_state;
6703 state->compl_reqs[state->compl_nr++] = req;
6704 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6705 io_submit_flush_completions(ctx);
6709 linked_timeout = io_prep_linked_timeout(req);
6711 io_queue_linked_timeout(linked_timeout);
6712 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6713 linked_timeout = io_prep_linked_timeout(req);
6715 switch (io_arm_poll_handler(req)) {
6716 case IO_APOLL_READY:
6718 io_unprep_linked_timeout(req);
6720 case IO_APOLL_ABORTED:
6722 * Queued up for async execution, worker will release
6723 * submit reference when the iocb is actually submitted.
6725 io_queue_async_work(req, NULL);
6730 io_queue_linked_timeout(linked_timeout);
6732 io_req_complete_failed(req, ret);
6736 static inline void io_queue_sqe(struct io_kiocb *req)
6737 __must_hold(&req->ctx->uring_lock)
6739 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6742 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6743 __io_queue_sqe(req);
6744 } else if (req->flags & REQ_F_FAIL) {
6745 io_req_complete_fail_submit(req);
6747 int ret = io_req_prep_async(req);
6750 io_req_complete_failed(req, ret);
6752 io_queue_async_work(req, NULL);
6757 * Check SQE restrictions (opcode and flags).
6759 * Returns 'true' if SQE is allowed, 'false' otherwise.
6761 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6762 struct io_kiocb *req,
6763 unsigned int sqe_flags)
6765 if (likely(!ctx->restricted))
6768 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6771 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6772 ctx->restrictions.sqe_flags_required)
6775 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6776 ctx->restrictions.sqe_flags_required))
6782 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6783 const struct io_uring_sqe *sqe)
6784 __must_hold(&ctx->uring_lock)
6786 struct io_submit_state *state;
6787 unsigned int sqe_flags;
6788 int personality, ret = 0;
6790 /* req is partially pre-initialised, see io_preinit_req() */
6791 req->opcode = READ_ONCE(sqe->opcode);
6792 /* same numerical values with corresponding REQ_F_*, safe to copy */
6793 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6794 req->user_data = READ_ONCE(sqe->user_data);
6796 req->fixed_rsrc_refs = NULL;
6797 req->task = current;
6799 /* enforce forwards compatibility on users */
6800 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6802 if (unlikely(req->opcode >= IORING_OP_LAST))
6804 if (!io_check_restriction(ctx, req, sqe_flags))
6807 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6808 !io_op_defs[req->opcode].buffer_select)
6810 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6811 ctx->drain_active = true;
6813 personality = READ_ONCE(sqe->personality);
6815 req->creds = xa_load(&ctx->personalities, personality);
6818 get_cred(req->creds);
6819 req->flags |= REQ_F_CREDS;
6821 state = &ctx->submit_state;
6824 * Plug now if we have more than 1 IO left after this, and the target
6825 * is potentially a read/write to block based storage.
6827 if (!state->plug_started && state->ios_left > 1 &&
6828 io_op_defs[req->opcode].plug) {
6829 blk_start_plug(&state->plug);
6830 state->plug_started = true;
6833 if (io_op_defs[req->opcode].needs_file) {
6834 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6835 (sqe_flags & IOSQE_FIXED_FILE));
6836 if (unlikely(!req->file))
6844 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6845 const struct io_uring_sqe *sqe)
6846 __must_hold(&ctx->uring_lock)
6848 struct io_submit_link *link = &ctx->submit_state.link;
6851 ret = io_init_req(ctx, req, sqe);
6852 if (unlikely(ret)) {
6854 /* fail even hard links since we don't submit */
6857 * we can judge a link req is failed or cancelled by if
6858 * REQ_F_FAIL is set, but the head is an exception since
6859 * it may be set REQ_F_FAIL because of other req's failure
6860 * so let's leverage req->result to distinguish if a head
6861 * is set REQ_F_FAIL because of its failure or other req's
6862 * failure so that we can set the correct ret code for it.
6863 * init result here to avoid affecting the normal path.
6865 if (!(link->head->flags & REQ_F_FAIL))
6866 req_fail_link_node(link->head, -ECANCELED);
6867 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6869 * the current req is a normal req, we should return
6870 * error and thus break the submittion loop.
6872 io_req_complete_failed(req, ret);
6875 req_fail_link_node(req, ret);
6877 ret = io_req_prep(req, sqe);
6882 /* don't need @sqe from now on */
6883 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6885 ctx->flags & IORING_SETUP_SQPOLL);
6888 * If we already have a head request, queue this one for async
6889 * submittal once the head completes. If we don't have a head but
6890 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6891 * submitted sync once the chain is complete. If none of those
6892 * conditions are true (normal request), then just queue it.
6895 struct io_kiocb *head = link->head;
6897 if (!(req->flags & REQ_F_FAIL)) {
6898 ret = io_req_prep_async(req);
6899 if (unlikely(ret)) {
6900 req_fail_link_node(req, ret);
6901 if (!(head->flags & REQ_F_FAIL))
6902 req_fail_link_node(head, -ECANCELED);
6905 trace_io_uring_link(ctx, req, head);
6906 link->last->link = req;
6909 /* last request of a link, enqueue the link */
6910 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6915 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6927 * Batched submission is done, ensure local IO is flushed out.
6929 static void io_submit_state_end(struct io_submit_state *state,
6930 struct io_ring_ctx *ctx)
6932 if (state->link.head)
6933 io_queue_sqe(state->link.head);
6934 if (state->compl_nr)
6935 io_submit_flush_completions(ctx);
6936 if (state->plug_started)
6937 blk_finish_plug(&state->plug);
6941 * Start submission side cache.
6943 static void io_submit_state_start(struct io_submit_state *state,
6944 unsigned int max_ios)
6946 state->plug_started = false;
6947 state->ios_left = max_ios;
6948 /* set only head, no need to init link_last in advance */
6949 state->link.head = NULL;
6952 static void io_commit_sqring(struct io_ring_ctx *ctx)
6954 struct io_rings *rings = ctx->rings;
6957 * Ensure any loads from the SQEs are done at this point,
6958 * since once we write the new head, the application could
6959 * write new data to them.
6961 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6965 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6966 * that is mapped by userspace. This means that care needs to be taken to
6967 * ensure that reads are stable, as we cannot rely on userspace always
6968 * being a good citizen. If members of the sqe are validated and then later
6969 * used, it's important that those reads are done through READ_ONCE() to
6970 * prevent a re-load down the line.
6972 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6974 unsigned head, mask = ctx->sq_entries - 1;
6975 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6978 * The cached sq head (or cq tail) serves two purposes:
6980 * 1) allows us to batch the cost of updating the user visible
6982 * 2) allows the kernel side to track the head on its own, even
6983 * though the application is the one updating it.
6985 head = READ_ONCE(ctx->sq_array[sq_idx]);
6986 if (likely(head < ctx->sq_entries))
6987 return &ctx->sq_sqes[head];
6989 /* drop invalid entries */
6991 WRITE_ONCE(ctx->rings->sq_dropped,
6992 READ_ONCE(ctx->rings->sq_dropped) + 1);
6996 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6997 __must_hold(&ctx->uring_lock)
7001 /* make sure SQ entry isn't read before tail */
7002 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7003 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7005 io_get_task_refs(nr);
7007 io_submit_state_start(&ctx->submit_state, nr);
7008 while (submitted < nr) {
7009 const struct io_uring_sqe *sqe;
7010 struct io_kiocb *req;
7012 req = io_alloc_req(ctx);
7013 if (unlikely(!req)) {
7015 submitted = -EAGAIN;
7018 sqe = io_get_sqe(ctx);
7019 if (unlikely(!sqe)) {
7020 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7023 /* will complete beyond this point, count as submitted */
7025 if (io_submit_sqe(ctx, req, sqe))
7029 if (unlikely(submitted != nr)) {
7030 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7031 int unused = nr - ref_used;
7033 current->io_uring->cached_refs += unused;
7034 percpu_ref_put_many(&ctx->refs, unused);
7037 io_submit_state_end(&ctx->submit_state, ctx);
7038 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7039 io_commit_sqring(ctx);
7044 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7046 return READ_ONCE(sqd->state);
7049 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7051 /* Tell userspace we may need a wakeup call */
7052 spin_lock(&ctx->completion_lock);
7053 WRITE_ONCE(ctx->rings->sq_flags,
7054 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7055 spin_unlock(&ctx->completion_lock);
7058 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7060 spin_lock(&ctx->completion_lock);
7061 WRITE_ONCE(ctx->rings->sq_flags,
7062 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7063 spin_unlock(&ctx->completion_lock);
7066 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7068 unsigned int to_submit;
7071 to_submit = io_sqring_entries(ctx);
7072 /* if we're handling multiple rings, cap submit size for fairness */
7073 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7074 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7076 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7077 unsigned nr_events = 0;
7078 const struct cred *creds = NULL;
7080 if (ctx->sq_creds != current_cred())
7081 creds = override_creds(ctx->sq_creds);
7083 mutex_lock(&ctx->uring_lock);
7084 if (!list_empty(&ctx->iopoll_list))
7085 io_do_iopoll(ctx, &nr_events, 0);
7088 * Don't submit if refs are dying, good for io_uring_register(),
7089 * but also it is relied upon by io_ring_exit_work()
7091 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7092 !(ctx->flags & IORING_SETUP_R_DISABLED))
7093 ret = io_submit_sqes(ctx, to_submit);
7094 mutex_unlock(&ctx->uring_lock);
7096 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7097 wake_up(&ctx->sqo_sq_wait);
7099 revert_creds(creds);
7105 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7107 struct io_ring_ctx *ctx;
7108 unsigned sq_thread_idle = 0;
7110 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7111 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7112 sqd->sq_thread_idle = sq_thread_idle;
7115 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7117 bool did_sig = false;
7118 struct ksignal ksig;
7120 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7121 signal_pending(current)) {
7122 mutex_unlock(&sqd->lock);
7123 if (signal_pending(current))
7124 did_sig = get_signal(&ksig);
7126 mutex_lock(&sqd->lock);
7128 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7131 static int io_sq_thread(void *data)
7133 struct io_sq_data *sqd = data;
7134 struct io_ring_ctx *ctx;
7135 unsigned long timeout = 0;
7136 char buf[TASK_COMM_LEN];
7139 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7140 set_task_comm(current, buf);
7142 if (sqd->sq_cpu != -1)
7143 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7145 set_cpus_allowed_ptr(current, cpu_online_mask);
7146 current->flags |= PF_NO_SETAFFINITY;
7148 mutex_lock(&sqd->lock);
7150 bool cap_entries, sqt_spin = false;
7152 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7153 if (io_sqd_handle_event(sqd))
7155 timeout = jiffies + sqd->sq_thread_idle;
7158 cap_entries = !list_is_singular(&sqd->ctx_list);
7159 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7160 int ret = __io_sq_thread(ctx, cap_entries);
7162 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7165 if (io_run_task_work())
7168 if (sqt_spin || !time_after(jiffies, timeout)) {
7171 timeout = jiffies + sqd->sq_thread_idle;
7175 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7176 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7177 bool needs_sched = true;
7179 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7180 io_ring_set_wakeup_flag(ctx);
7182 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7183 !list_empty_careful(&ctx->iopoll_list)) {
7184 needs_sched = false;
7187 if (io_sqring_entries(ctx)) {
7188 needs_sched = false;
7194 mutex_unlock(&sqd->lock);
7196 mutex_lock(&sqd->lock);
7198 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7199 io_ring_clear_wakeup_flag(ctx);
7202 finish_wait(&sqd->wait, &wait);
7203 timeout = jiffies + sqd->sq_thread_idle;
7206 io_uring_cancel_generic(true, sqd);
7208 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7209 io_ring_set_wakeup_flag(ctx);
7211 mutex_unlock(&sqd->lock);
7213 complete(&sqd->exited);
7217 struct io_wait_queue {
7218 struct wait_queue_entry wq;
7219 struct io_ring_ctx *ctx;
7221 unsigned nr_timeouts;
7224 static inline bool io_should_wake(struct io_wait_queue *iowq)
7226 struct io_ring_ctx *ctx = iowq->ctx;
7227 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7230 * Wake up if we have enough events, or if a timeout occurred since we
7231 * started waiting. For timeouts, we always want to return to userspace,
7232 * regardless of event count.
7234 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7237 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7238 int wake_flags, void *key)
7240 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7244 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7245 * the task, and the next invocation will do it.
7247 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7248 return autoremove_wake_function(curr, mode, wake_flags, key);
7252 static int io_run_task_work_sig(void)
7254 if (io_run_task_work())
7256 if (!signal_pending(current))
7258 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7259 return -ERESTARTSYS;
7263 /* when returns >0, the caller should retry */
7264 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7265 struct io_wait_queue *iowq,
7266 signed long *timeout)
7270 /* make sure we run task_work before checking for signals */
7271 ret = io_run_task_work_sig();
7272 if (ret || io_should_wake(iowq))
7274 /* let the caller flush overflows, retry */
7275 if (test_bit(0, &ctx->check_cq_overflow))
7278 *timeout = schedule_timeout(*timeout);
7279 return !*timeout ? -ETIME : 1;
7283 * Wait until events become available, if we don't already have some. The
7284 * application must reap them itself, as they reside on the shared cq ring.
7286 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7287 const sigset_t __user *sig, size_t sigsz,
7288 struct __kernel_timespec __user *uts)
7290 struct io_wait_queue iowq;
7291 struct io_rings *rings = ctx->rings;
7292 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7296 io_cqring_overflow_flush(ctx);
7297 if (io_cqring_events(ctx) >= min_events)
7299 if (!io_run_task_work())
7304 #ifdef CONFIG_COMPAT
7305 if (in_compat_syscall())
7306 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7310 ret = set_user_sigmask(sig, sigsz);
7317 struct timespec64 ts;
7319 if (get_timespec64(&ts, uts))
7321 timeout = timespec64_to_jiffies(&ts);
7324 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7325 iowq.wq.private = current;
7326 INIT_LIST_HEAD(&iowq.wq.entry);
7328 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7329 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7331 trace_io_uring_cqring_wait(ctx, min_events);
7333 /* if we can't even flush overflow, don't wait for more */
7334 if (!io_cqring_overflow_flush(ctx)) {
7338 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7339 TASK_INTERRUPTIBLE);
7340 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7341 finish_wait(&ctx->cq_wait, &iowq.wq);
7345 restore_saved_sigmask_unless(ret == -EINTR);
7347 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7350 static void io_free_page_table(void **table, size_t size)
7352 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7354 for (i = 0; i < nr_tables; i++)
7359 static void **io_alloc_page_table(size_t size)
7361 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7362 size_t init_size = size;
7365 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7369 for (i = 0; i < nr_tables; i++) {
7370 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7372 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7374 io_free_page_table(table, init_size);
7382 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7384 percpu_ref_exit(&ref_node->refs);
7388 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7390 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7391 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7392 unsigned long flags;
7393 bool first_add = false;
7395 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7398 while (!list_empty(&ctx->rsrc_ref_list)) {
7399 node = list_first_entry(&ctx->rsrc_ref_list,
7400 struct io_rsrc_node, node);
7401 /* recycle ref nodes in order */
7404 list_del(&node->node);
7405 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7407 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7410 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7413 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7415 struct io_rsrc_node *ref_node;
7417 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7421 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7426 INIT_LIST_HEAD(&ref_node->node);
7427 INIT_LIST_HEAD(&ref_node->rsrc_list);
7428 ref_node->done = false;
7432 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7433 struct io_rsrc_data *data_to_kill)
7435 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7436 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7439 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7441 rsrc_node->rsrc_data = data_to_kill;
7442 spin_lock_irq(&ctx->rsrc_ref_lock);
7443 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7444 spin_unlock_irq(&ctx->rsrc_ref_lock);
7446 atomic_inc(&data_to_kill->refs);
7447 percpu_ref_kill(&rsrc_node->refs);
7448 ctx->rsrc_node = NULL;
7451 if (!ctx->rsrc_node) {
7452 ctx->rsrc_node = ctx->rsrc_backup_node;
7453 ctx->rsrc_backup_node = NULL;
7457 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7459 if (ctx->rsrc_backup_node)
7461 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7462 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7465 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7469 /* As we may drop ->uring_lock, other task may have started quiesce */
7473 data->quiesce = true;
7475 ret = io_rsrc_node_switch_start(ctx);
7478 io_rsrc_node_switch(ctx, data);
7480 /* kill initial ref, already quiesced if zero */
7481 if (atomic_dec_and_test(&data->refs))
7483 mutex_unlock(&ctx->uring_lock);
7484 flush_delayed_work(&ctx->rsrc_put_work);
7485 ret = wait_for_completion_interruptible(&data->done);
7487 mutex_lock(&ctx->uring_lock);
7491 atomic_inc(&data->refs);
7492 /* wait for all works potentially completing data->done */
7493 flush_delayed_work(&ctx->rsrc_put_work);
7494 reinit_completion(&data->done);
7496 ret = io_run_task_work_sig();
7497 mutex_lock(&ctx->uring_lock);
7499 data->quiesce = false;
7504 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7506 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7507 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7509 return &data->tags[table_idx][off];
7512 static void io_rsrc_data_free(struct io_rsrc_data *data)
7514 size_t size = data->nr * sizeof(data->tags[0][0]);
7517 io_free_page_table((void **)data->tags, size);
7521 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7522 u64 __user *utags, unsigned nr,
7523 struct io_rsrc_data **pdata)
7525 struct io_rsrc_data *data;
7529 data = kzalloc(sizeof(*data), GFP_KERNEL);
7532 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7540 data->do_put = do_put;
7543 for (i = 0; i < nr; i++) {
7544 u64 *tag_slot = io_get_tag_slot(data, i);
7546 if (copy_from_user(tag_slot, &utags[i],
7552 atomic_set(&data->refs, 1);
7553 init_completion(&data->done);
7557 io_rsrc_data_free(data);
7561 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7563 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7564 GFP_KERNEL_ACCOUNT);
7565 return !!table->files;
7568 static void io_free_file_tables(struct io_file_table *table)
7570 kvfree(table->files);
7571 table->files = NULL;
7574 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7576 #if defined(CONFIG_UNIX)
7577 if (ctx->ring_sock) {
7578 struct sock *sock = ctx->ring_sock->sk;
7579 struct sk_buff *skb;
7581 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7587 for (i = 0; i < ctx->nr_user_files; i++) {
7590 file = io_file_from_index(ctx, i);
7595 io_free_file_tables(&ctx->file_table);
7596 io_rsrc_data_free(ctx->file_data);
7597 ctx->file_data = NULL;
7598 ctx->nr_user_files = 0;
7601 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7605 if (!ctx->file_data)
7607 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7609 __io_sqe_files_unregister(ctx);
7613 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7614 __releases(&sqd->lock)
7616 WARN_ON_ONCE(sqd->thread == current);
7619 * Do the dance but not conditional clear_bit() because it'd race with
7620 * other threads incrementing park_pending and setting the bit.
7622 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7623 if (atomic_dec_return(&sqd->park_pending))
7624 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7625 mutex_unlock(&sqd->lock);
7628 static void io_sq_thread_park(struct io_sq_data *sqd)
7629 __acquires(&sqd->lock)
7631 WARN_ON_ONCE(sqd->thread == current);
7633 atomic_inc(&sqd->park_pending);
7634 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7635 mutex_lock(&sqd->lock);
7637 wake_up_process(sqd->thread);
7640 static void io_sq_thread_stop(struct io_sq_data *sqd)
7642 WARN_ON_ONCE(sqd->thread == current);
7643 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7645 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7646 mutex_lock(&sqd->lock);
7648 wake_up_process(sqd->thread);
7649 mutex_unlock(&sqd->lock);
7650 wait_for_completion(&sqd->exited);
7653 static void io_put_sq_data(struct io_sq_data *sqd)
7655 if (refcount_dec_and_test(&sqd->refs)) {
7656 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7658 io_sq_thread_stop(sqd);
7663 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7665 struct io_sq_data *sqd = ctx->sq_data;
7668 io_sq_thread_park(sqd);
7669 list_del_init(&ctx->sqd_list);
7670 io_sqd_update_thread_idle(sqd);
7671 io_sq_thread_unpark(sqd);
7673 io_put_sq_data(sqd);
7674 ctx->sq_data = NULL;
7678 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7680 struct io_ring_ctx *ctx_attach;
7681 struct io_sq_data *sqd;
7684 f = fdget(p->wq_fd);
7686 return ERR_PTR(-ENXIO);
7687 if (f.file->f_op != &io_uring_fops) {
7689 return ERR_PTR(-EINVAL);
7692 ctx_attach = f.file->private_data;
7693 sqd = ctx_attach->sq_data;
7696 return ERR_PTR(-EINVAL);
7698 if (sqd->task_tgid != current->tgid) {
7700 return ERR_PTR(-EPERM);
7703 refcount_inc(&sqd->refs);
7708 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7711 struct io_sq_data *sqd;
7714 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7715 sqd = io_attach_sq_data(p);
7720 /* fall through for EPERM case, setup new sqd/task */
7721 if (PTR_ERR(sqd) != -EPERM)
7725 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7727 return ERR_PTR(-ENOMEM);
7729 atomic_set(&sqd->park_pending, 0);
7730 refcount_set(&sqd->refs, 1);
7731 INIT_LIST_HEAD(&sqd->ctx_list);
7732 mutex_init(&sqd->lock);
7733 init_waitqueue_head(&sqd->wait);
7734 init_completion(&sqd->exited);
7738 #if defined(CONFIG_UNIX)
7740 * Ensure the UNIX gc is aware of our file set, so we are certain that
7741 * the io_uring can be safely unregistered on process exit, even if we have
7742 * loops in the file referencing.
7744 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7746 struct sock *sk = ctx->ring_sock->sk;
7747 struct scm_fp_list *fpl;
7748 struct sk_buff *skb;
7751 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7755 skb = alloc_skb(0, GFP_KERNEL);
7764 fpl->user = get_uid(current_user());
7765 for (i = 0; i < nr; i++) {
7766 struct file *file = io_file_from_index(ctx, i + offset);
7770 fpl->fp[nr_files] = get_file(file);
7771 unix_inflight(fpl->user, fpl->fp[nr_files]);
7776 fpl->max = SCM_MAX_FD;
7777 fpl->count = nr_files;
7778 UNIXCB(skb).fp = fpl;
7779 skb->destructor = unix_destruct_scm;
7780 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7781 skb_queue_head(&sk->sk_receive_queue, skb);
7783 for (i = 0; i < nr_files; i++)
7794 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7795 * causes regular reference counting to break down. We rely on the UNIX
7796 * garbage collection to take care of this problem for us.
7798 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7800 unsigned left, total;
7804 left = ctx->nr_user_files;
7806 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7808 ret = __io_sqe_files_scm(ctx, this_files, total);
7812 total += this_files;
7818 while (total < ctx->nr_user_files) {
7819 struct file *file = io_file_from_index(ctx, total);
7829 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7835 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7837 struct file *file = prsrc->file;
7838 #if defined(CONFIG_UNIX)
7839 struct sock *sock = ctx->ring_sock->sk;
7840 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7841 struct sk_buff *skb;
7844 __skb_queue_head_init(&list);
7847 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7848 * remove this entry and rearrange the file array.
7850 skb = skb_dequeue(head);
7852 struct scm_fp_list *fp;
7854 fp = UNIXCB(skb).fp;
7855 for (i = 0; i < fp->count; i++) {
7858 if (fp->fp[i] != file)
7861 unix_notinflight(fp->user, fp->fp[i]);
7862 left = fp->count - 1 - i;
7864 memmove(&fp->fp[i], &fp->fp[i + 1],
7865 left * sizeof(struct file *));
7872 __skb_queue_tail(&list, skb);
7882 __skb_queue_tail(&list, skb);
7884 skb = skb_dequeue(head);
7887 if (skb_peek(&list)) {
7888 spin_lock_irq(&head->lock);
7889 while ((skb = __skb_dequeue(&list)) != NULL)
7890 __skb_queue_tail(head, skb);
7891 spin_unlock_irq(&head->lock);
7898 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7900 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7901 struct io_ring_ctx *ctx = rsrc_data->ctx;
7902 struct io_rsrc_put *prsrc, *tmp;
7904 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7905 list_del(&prsrc->list);
7908 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7910 io_ring_submit_lock(ctx, lock_ring);
7911 spin_lock(&ctx->completion_lock);
7912 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7914 io_commit_cqring(ctx);
7915 spin_unlock(&ctx->completion_lock);
7916 io_cqring_ev_posted(ctx);
7917 io_ring_submit_unlock(ctx, lock_ring);
7920 rsrc_data->do_put(ctx, prsrc);
7924 io_rsrc_node_destroy(ref_node);
7925 if (atomic_dec_and_test(&rsrc_data->refs))
7926 complete(&rsrc_data->done);
7929 static void io_rsrc_put_work(struct work_struct *work)
7931 struct io_ring_ctx *ctx;
7932 struct llist_node *node;
7934 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7935 node = llist_del_all(&ctx->rsrc_put_llist);
7938 struct io_rsrc_node *ref_node;
7939 struct llist_node *next = node->next;
7941 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7942 __io_rsrc_put_work(ref_node);
7947 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7948 unsigned nr_args, u64 __user *tags)
7950 __s32 __user *fds = (__s32 __user *) arg;
7959 if (nr_args > IORING_MAX_FIXED_FILES)
7961 if (nr_args > rlimit(RLIMIT_NOFILE))
7963 ret = io_rsrc_node_switch_start(ctx);
7966 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7972 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7975 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7976 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7980 /* allow sparse sets */
7983 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7990 if (unlikely(!file))
7994 * Don't allow io_uring instances to be registered. If UNIX
7995 * isn't enabled, then this causes a reference cycle and this
7996 * instance can never get freed. If UNIX is enabled we'll
7997 * handle it just fine, but there's still no point in allowing
7998 * a ring fd as it doesn't support regular read/write anyway.
8000 if (file->f_op == &io_uring_fops) {
8004 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8007 ret = io_sqe_files_scm(ctx);
8009 __io_sqe_files_unregister(ctx);
8013 io_rsrc_node_switch(ctx, NULL);
8016 for (i = 0; i < ctx->nr_user_files; i++) {
8017 file = io_file_from_index(ctx, i);
8021 io_free_file_tables(&ctx->file_table);
8022 ctx->nr_user_files = 0;
8024 io_rsrc_data_free(ctx->file_data);
8025 ctx->file_data = NULL;
8029 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8032 #if defined(CONFIG_UNIX)
8033 struct sock *sock = ctx->ring_sock->sk;
8034 struct sk_buff_head *head = &sock->sk_receive_queue;
8035 struct sk_buff *skb;
8038 * See if we can merge this file into an existing skb SCM_RIGHTS
8039 * file set. If there's no room, fall back to allocating a new skb
8040 * and filling it in.
8042 spin_lock_irq(&head->lock);
8043 skb = skb_peek(head);
8045 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8047 if (fpl->count < SCM_MAX_FD) {
8048 __skb_unlink(skb, head);
8049 spin_unlock_irq(&head->lock);
8050 fpl->fp[fpl->count] = get_file(file);
8051 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8053 spin_lock_irq(&head->lock);
8054 __skb_queue_head(head, skb);
8059 spin_unlock_irq(&head->lock);
8066 return __io_sqe_files_scm(ctx, 1, index);
8072 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8073 unsigned int issue_flags, u32 slot_index)
8075 struct io_ring_ctx *ctx = req->ctx;
8076 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8077 struct io_fixed_file *file_slot;
8080 io_ring_submit_lock(ctx, !force_nonblock);
8081 if (file->f_op == &io_uring_fops)
8084 if (!ctx->file_data)
8087 if (slot_index >= ctx->nr_user_files)
8090 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8091 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8093 if (file_slot->file_ptr)
8096 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8097 io_fixed_file_set(file_slot, file);
8098 ret = io_sqe_file_register(ctx, file, slot_index);
8100 file_slot->file_ptr = 0;
8106 io_ring_submit_unlock(ctx, !force_nonblock);
8112 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8113 struct io_rsrc_node *node, void *rsrc)
8115 struct io_rsrc_put *prsrc;
8117 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8121 prsrc->tag = *io_get_tag_slot(data, idx);
8123 list_add(&prsrc->list, &node->rsrc_list);
8127 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8128 struct io_uring_rsrc_update2 *up,
8131 u64 __user *tags = u64_to_user_ptr(up->tags);
8132 __s32 __user *fds = u64_to_user_ptr(up->data);
8133 struct io_rsrc_data *data = ctx->file_data;
8134 struct io_fixed_file *file_slot;
8138 bool needs_switch = false;
8140 if (!ctx->file_data)
8142 if (up->offset + nr_args > ctx->nr_user_files)
8145 for (done = 0; done < nr_args; done++) {
8148 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8149 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8153 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8157 if (fd == IORING_REGISTER_FILES_SKIP)
8160 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8161 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8163 if (file_slot->file_ptr) {
8164 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8165 err = io_queue_rsrc_removal(data, up->offset + done,
8166 ctx->rsrc_node, file);
8169 file_slot->file_ptr = 0;
8170 needs_switch = true;
8179 * Don't allow io_uring instances to be registered. If
8180 * UNIX isn't enabled, then this causes a reference
8181 * cycle and this instance can never get freed. If UNIX
8182 * is enabled we'll handle it just fine, but there's
8183 * still no point in allowing a ring fd as it doesn't
8184 * support regular read/write anyway.
8186 if (file->f_op == &io_uring_fops) {
8191 *io_get_tag_slot(data, up->offset + done) = tag;
8192 io_fixed_file_set(file_slot, file);
8193 err = io_sqe_file_register(ctx, file, i);
8195 file_slot->file_ptr = 0;
8203 io_rsrc_node_switch(ctx, data);
8204 return done ? done : err;
8207 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8208 struct task_struct *task)
8210 struct io_wq_hash *hash;
8211 struct io_wq_data data;
8212 unsigned int concurrency;
8214 mutex_lock(&ctx->uring_lock);
8215 hash = ctx->hash_map;
8217 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8219 mutex_unlock(&ctx->uring_lock);
8220 return ERR_PTR(-ENOMEM);
8222 refcount_set(&hash->refs, 1);
8223 init_waitqueue_head(&hash->wait);
8224 ctx->hash_map = hash;
8226 mutex_unlock(&ctx->uring_lock);
8230 data.free_work = io_wq_free_work;
8231 data.do_work = io_wq_submit_work;
8233 /* Do QD, or 4 * CPUS, whatever is smallest */
8234 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8236 return io_wq_create(concurrency, &data);
8239 static int io_uring_alloc_task_context(struct task_struct *task,
8240 struct io_ring_ctx *ctx)
8242 struct io_uring_task *tctx;
8245 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8246 if (unlikely(!tctx))
8249 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8250 if (unlikely(ret)) {
8255 tctx->io_wq = io_init_wq_offload(ctx, task);
8256 if (IS_ERR(tctx->io_wq)) {
8257 ret = PTR_ERR(tctx->io_wq);
8258 percpu_counter_destroy(&tctx->inflight);
8264 init_waitqueue_head(&tctx->wait);
8265 atomic_set(&tctx->in_idle, 0);
8266 atomic_set(&tctx->inflight_tracked, 0);
8267 task->io_uring = tctx;
8268 spin_lock_init(&tctx->task_lock);
8269 INIT_WQ_LIST(&tctx->task_list);
8270 init_task_work(&tctx->task_work, tctx_task_work);
8274 void __io_uring_free(struct task_struct *tsk)
8276 struct io_uring_task *tctx = tsk->io_uring;
8278 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8279 WARN_ON_ONCE(tctx->io_wq);
8280 WARN_ON_ONCE(tctx->cached_refs);
8282 percpu_counter_destroy(&tctx->inflight);
8284 tsk->io_uring = NULL;
8287 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8288 struct io_uring_params *p)
8292 /* Retain compatibility with failing for an invalid attach attempt */
8293 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8294 IORING_SETUP_ATTACH_WQ) {
8297 f = fdget(p->wq_fd);
8300 if (f.file->f_op != &io_uring_fops) {
8306 if (ctx->flags & IORING_SETUP_SQPOLL) {
8307 struct task_struct *tsk;
8308 struct io_sq_data *sqd;
8311 sqd = io_get_sq_data(p, &attached);
8317 ctx->sq_creds = get_current_cred();
8319 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8320 if (!ctx->sq_thread_idle)
8321 ctx->sq_thread_idle = HZ;
8323 io_sq_thread_park(sqd);
8324 list_add(&ctx->sqd_list, &sqd->ctx_list);
8325 io_sqd_update_thread_idle(sqd);
8326 /* don't attach to a dying SQPOLL thread, would be racy */
8327 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8328 io_sq_thread_unpark(sqd);
8335 if (p->flags & IORING_SETUP_SQ_AFF) {
8336 int cpu = p->sq_thread_cpu;
8339 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8346 sqd->task_pid = current->pid;
8347 sqd->task_tgid = current->tgid;
8348 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8355 ret = io_uring_alloc_task_context(tsk, ctx);
8356 wake_up_new_task(tsk);
8359 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8360 /* Can't have SQ_AFF without SQPOLL */
8367 complete(&ctx->sq_data->exited);
8369 io_sq_thread_finish(ctx);
8373 static inline void __io_unaccount_mem(struct user_struct *user,
8374 unsigned long nr_pages)
8376 atomic_long_sub(nr_pages, &user->locked_vm);
8379 static inline int __io_account_mem(struct user_struct *user,
8380 unsigned long nr_pages)
8382 unsigned long page_limit, cur_pages, new_pages;
8384 /* Don't allow more pages than we can safely lock */
8385 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8388 cur_pages = atomic_long_read(&user->locked_vm);
8389 new_pages = cur_pages + nr_pages;
8390 if (new_pages > page_limit)
8392 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8393 new_pages) != cur_pages);
8398 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8401 __io_unaccount_mem(ctx->user, nr_pages);
8403 if (ctx->mm_account)
8404 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8407 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8412 ret = __io_account_mem(ctx->user, nr_pages);
8417 if (ctx->mm_account)
8418 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8423 static void io_mem_free(void *ptr)
8430 page = virt_to_head_page(ptr);
8431 if (put_page_testzero(page))
8432 free_compound_page(page);
8435 static void *io_mem_alloc(size_t size)
8437 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8438 __GFP_NORETRY | __GFP_ACCOUNT;
8440 return (void *) __get_free_pages(gfp_flags, get_order(size));
8443 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8446 struct io_rings *rings;
8447 size_t off, sq_array_size;
8449 off = struct_size(rings, cqes, cq_entries);
8450 if (off == SIZE_MAX)
8454 off = ALIGN(off, SMP_CACHE_BYTES);
8462 sq_array_size = array_size(sizeof(u32), sq_entries);
8463 if (sq_array_size == SIZE_MAX)
8466 if (check_add_overflow(off, sq_array_size, &off))
8472 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8474 struct io_mapped_ubuf *imu = *slot;
8477 if (imu != ctx->dummy_ubuf) {
8478 for (i = 0; i < imu->nr_bvecs; i++)
8479 unpin_user_page(imu->bvec[i].bv_page);
8480 if (imu->acct_pages)
8481 io_unaccount_mem(ctx, imu->acct_pages);
8487 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8489 io_buffer_unmap(ctx, &prsrc->buf);
8493 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8497 for (i = 0; i < ctx->nr_user_bufs; i++)
8498 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8499 kfree(ctx->user_bufs);
8500 io_rsrc_data_free(ctx->buf_data);
8501 ctx->user_bufs = NULL;
8502 ctx->buf_data = NULL;
8503 ctx->nr_user_bufs = 0;
8506 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8513 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8515 __io_sqe_buffers_unregister(ctx);
8519 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8520 void __user *arg, unsigned index)
8522 struct iovec __user *src;
8524 #ifdef CONFIG_COMPAT
8526 struct compat_iovec __user *ciovs;
8527 struct compat_iovec ciov;
8529 ciovs = (struct compat_iovec __user *) arg;
8530 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8533 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8534 dst->iov_len = ciov.iov_len;
8538 src = (struct iovec __user *) arg;
8539 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8545 * Not super efficient, but this is just a registration time. And we do cache
8546 * the last compound head, so generally we'll only do a full search if we don't
8549 * We check if the given compound head page has already been accounted, to
8550 * avoid double accounting it. This allows us to account the full size of the
8551 * page, not just the constituent pages of a huge page.
8553 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8554 int nr_pages, struct page *hpage)
8558 /* check current page array */
8559 for (i = 0; i < nr_pages; i++) {
8560 if (!PageCompound(pages[i]))
8562 if (compound_head(pages[i]) == hpage)
8566 /* check previously registered pages */
8567 for (i = 0; i < ctx->nr_user_bufs; i++) {
8568 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8570 for (j = 0; j < imu->nr_bvecs; j++) {
8571 if (!PageCompound(imu->bvec[j].bv_page))
8573 if (compound_head(imu->bvec[j].bv_page) == hpage)
8581 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8582 int nr_pages, struct io_mapped_ubuf *imu,
8583 struct page **last_hpage)
8587 imu->acct_pages = 0;
8588 for (i = 0; i < nr_pages; i++) {
8589 if (!PageCompound(pages[i])) {
8594 hpage = compound_head(pages[i]);
8595 if (hpage == *last_hpage)
8597 *last_hpage = hpage;
8598 if (headpage_already_acct(ctx, pages, i, hpage))
8600 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8604 if (!imu->acct_pages)
8607 ret = io_account_mem(ctx, imu->acct_pages);
8609 imu->acct_pages = 0;
8613 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8614 struct io_mapped_ubuf **pimu,
8615 struct page **last_hpage)
8617 struct io_mapped_ubuf *imu = NULL;
8618 struct vm_area_struct **vmas = NULL;
8619 struct page **pages = NULL;
8620 unsigned long off, start, end, ubuf;
8622 int ret, pret, nr_pages, i;
8624 if (!iov->iov_base) {
8625 *pimu = ctx->dummy_ubuf;
8629 ubuf = (unsigned long) iov->iov_base;
8630 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8631 start = ubuf >> PAGE_SHIFT;
8632 nr_pages = end - start;
8637 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8641 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8646 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8651 mmap_read_lock(current->mm);
8652 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8654 if (pret == nr_pages) {
8655 /* don't support file backed memory */
8656 for (i = 0; i < nr_pages; i++) {
8657 struct vm_area_struct *vma = vmas[i];
8659 if (vma_is_shmem(vma))
8662 !is_file_hugepages(vma->vm_file)) {
8668 ret = pret < 0 ? pret : -EFAULT;
8670 mmap_read_unlock(current->mm);
8673 * if we did partial map, or found file backed vmas,
8674 * release any pages we did get
8677 unpin_user_pages(pages, pret);
8681 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8683 unpin_user_pages(pages, pret);
8687 off = ubuf & ~PAGE_MASK;
8688 size = iov->iov_len;
8689 for (i = 0; i < nr_pages; i++) {
8692 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8693 imu->bvec[i].bv_page = pages[i];
8694 imu->bvec[i].bv_len = vec_len;
8695 imu->bvec[i].bv_offset = off;
8699 /* store original address for later verification */
8701 imu->ubuf_end = ubuf + iov->iov_len;
8702 imu->nr_bvecs = nr_pages;
8713 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8715 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8716 return ctx->user_bufs ? 0 : -ENOMEM;
8719 static int io_buffer_validate(struct iovec *iov)
8721 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8724 * Don't impose further limits on the size and buffer
8725 * constraints here, we'll -EINVAL later when IO is
8726 * submitted if they are wrong.
8729 return iov->iov_len ? -EFAULT : 0;
8733 /* arbitrary limit, but we need something */
8734 if (iov->iov_len > SZ_1G)
8737 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8743 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8744 unsigned int nr_args, u64 __user *tags)
8746 struct page *last_hpage = NULL;
8747 struct io_rsrc_data *data;
8753 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8755 ret = io_rsrc_node_switch_start(ctx);
8758 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8761 ret = io_buffers_map_alloc(ctx, nr_args);
8763 io_rsrc_data_free(data);
8767 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8768 ret = io_copy_iov(ctx, &iov, arg, i);
8771 ret = io_buffer_validate(&iov);
8774 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8779 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8785 WARN_ON_ONCE(ctx->buf_data);
8787 ctx->buf_data = data;
8789 __io_sqe_buffers_unregister(ctx);
8791 io_rsrc_node_switch(ctx, NULL);
8795 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8796 struct io_uring_rsrc_update2 *up,
8797 unsigned int nr_args)
8799 u64 __user *tags = u64_to_user_ptr(up->tags);
8800 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8801 struct page *last_hpage = NULL;
8802 bool needs_switch = false;
8808 if (up->offset + nr_args > ctx->nr_user_bufs)
8811 for (done = 0; done < nr_args; done++) {
8812 struct io_mapped_ubuf *imu;
8813 int offset = up->offset + done;
8816 err = io_copy_iov(ctx, &iov, iovs, done);
8819 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8823 err = io_buffer_validate(&iov);
8826 if (!iov.iov_base && tag) {
8830 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8834 i = array_index_nospec(offset, ctx->nr_user_bufs);
8835 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8836 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8837 ctx->rsrc_node, ctx->user_bufs[i]);
8838 if (unlikely(err)) {
8839 io_buffer_unmap(ctx, &imu);
8842 ctx->user_bufs[i] = NULL;
8843 needs_switch = true;
8846 ctx->user_bufs[i] = imu;
8847 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8851 io_rsrc_node_switch(ctx, ctx->buf_data);
8852 return done ? done : err;
8855 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8857 __s32 __user *fds = arg;
8863 if (copy_from_user(&fd, fds, sizeof(*fds)))
8866 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8867 if (IS_ERR(ctx->cq_ev_fd)) {
8868 int ret = PTR_ERR(ctx->cq_ev_fd);
8870 ctx->cq_ev_fd = NULL;
8877 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8879 if (ctx->cq_ev_fd) {
8880 eventfd_ctx_put(ctx->cq_ev_fd);
8881 ctx->cq_ev_fd = NULL;
8888 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8890 struct io_buffer *buf;
8891 unsigned long index;
8893 xa_for_each(&ctx->io_buffers, index, buf)
8894 __io_remove_buffers(ctx, buf, index, -1U);
8897 static void io_req_cache_free(struct list_head *list)
8899 struct io_kiocb *req, *nxt;
8901 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8902 list_del(&req->inflight_entry);
8903 kmem_cache_free(req_cachep, req);
8907 static void io_req_caches_free(struct io_ring_ctx *ctx)
8909 struct io_submit_state *state = &ctx->submit_state;
8911 mutex_lock(&ctx->uring_lock);
8913 if (state->free_reqs) {
8914 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8915 state->free_reqs = 0;
8918 io_flush_cached_locked_reqs(ctx, state);
8919 io_req_cache_free(&state->free_list);
8920 mutex_unlock(&ctx->uring_lock);
8923 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8925 if (data && !atomic_dec_and_test(&data->refs))
8926 wait_for_completion(&data->done);
8929 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8931 io_sq_thread_finish(ctx);
8933 if (ctx->mm_account) {
8934 mmdrop(ctx->mm_account);
8935 ctx->mm_account = NULL;
8938 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8939 io_wait_rsrc_data(ctx->buf_data);
8940 io_wait_rsrc_data(ctx->file_data);
8942 mutex_lock(&ctx->uring_lock);
8944 __io_sqe_buffers_unregister(ctx);
8946 __io_sqe_files_unregister(ctx);
8948 __io_cqring_overflow_flush(ctx, true);
8949 mutex_unlock(&ctx->uring_lock);
8950 io_eventfd_unregister(ctx);
8951 io_destroy_buffers(ctx);
8953 put_cred(ctx->sq_creds);
8955 /* there are no registered resources left, nobody uses it */
8957 io_rsrc_node_destroy(ctx->rsrc_node);
8958 if (ctx->rsrc_backup_node)
8959 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8960 flush_delayed_work(&ctx->rsrc_put_work);
8962 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8963 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8965 #if defined(CONFIG_UNIX)
8966 if (ctx->ring_sock) {
8967 ctx->ring_sock->file = NULL; /* so that iput() is called */
8968 sock_release(ctx->ring_sock);
8971 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8973 io_mem_free(ctx->rings);
8974 io_mem_free(ctx->sq_sqes);
8976 percpu_ref_exit(&ctx->refs);
8977 free_uid(ctx->user);
8978 io_req_caches_free(ctx);
8980 io_wq_put_hash(ctx->hash_map);
8981 kfree(ctx->cancel_hash);
8982 kfree(ctx->dummy_ubuf);
8986 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8988 struct io_ring_ctx *ctx = file->private_data;
8991 poll_wait(file, &ctx->poll_wait, wait);
8993 * synchronizes with barrier from wq_has_sleeper call in
8997 if (!io_sqring_full(ctx))
8998 mask |= EPOLLOUT | EPOLLWRNORM;
9001 * Don't flush cqring overflow list here, just do a simple check.
9002 * Otherwise there could possible be ABBA deadlock:
9005 * lock(&ctx->uring_lock);
9007 * lock(&ctx->uring_lock);
9010 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9011 * pushs them to do the flush.
9013 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9014 mask |= EPOLLIN | EPOLLRDNORM;
9019 static int io_uring_fasync(int fd, struct file *file, int on)
9021 struct io_ring_ctx *ctx = file->private_data;
9023 return fasync_helper(fd, file, on, &ctx->cq_fasync);
9026 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9028 const struct cred *creds;
9030 creds = xa_erase(&ctx->personalities, id);
9039 struct io_tctx_exit {
9040 struct callback_head task_work;
9041 struct completion completion;
9042 struct io_ring_ctx *ctx;
9045 static void io_tctx_exit_cb(struct callback_head *cb)
9047 struct io_uring_task *tctx = current->io_uring;
9048 struct io_tctx_exit *work;
9050 work = container_of(cb, struct io_tctx_exit, task_work);
9052 * When @in_idle, we're in cancellation and it's racy to remove the
9053 * node. It'll be removed by the end of cancellation, just ignore it.
9055 if (!atomic_read(&tctx->in_idle))
9056 io_uring_del_tctx_node((unsigned long)work->ctx);
9057 complete(&work->completion);
9060 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9062 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9064 return req->ctx == data;
9067 static void io_ring_exit_work(struct work_struct *work)
9069 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9070 unsigned long timeout = jiffies + HZ * 60 * 5;
9071 unsigned long interval = HZ / 20;
9072 struct io_tctx_exit exit;
9073 struct io_tctx_node *node;
9077 * If we're doing polled IO and end up having requests being
9078 * submitted async (out-of-line), then completions can come in while
9079 * we're waiting for refs to drop. We need to reap these manually,
9080 * as nobody else will be looking for them.
9083 io_uring_try_cancel_requests(ctx, NULL, true);
9085 struct io_sq_data *sqd = ctx->sq_data;
9086 struct task_struct *tsk;
9088 io_sq_thread_park(sqd);
9090 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9091 io_wq_cancel_cb(tsk->io_uring->io_wq,
9092 io_cancel_ctx_cb, ctx, true);
9093 io_sq_thread_unpark(sqd);
9096 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9097 /* there is little hope left, don't run it too often */
9100 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9102 init_completion(&exit.completion);
9103 init_task_work(&exit.task_work, io_tctx_exit_cb);
9106 * Some may use context even when all refs and requests have been put,
9107 * and they are free to do so while still holding uring_lock or
9108 * completion_lock, see io_req_task_submit(). Apart from other work,
9109 * this lock/unlock section also waits them to finish.
9111 mutex_lock(&ctx->uring_lock);
9112 while (!list_empty(&ctx->tctx_list)) {
9113 WARN_ON_ONCE(time_after(jiffies, timeout));
9115 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9117 /* don't spin on a single task if cancellation failed */
9118 list_rotate_left(&ctx->tctx_list);
9119 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9120 if (WARN_ON_ONCE(ret))
9122 wake_up_process(node->task);
9124 mutex_unlock(&ctx->uring_lock);
9125 wait_for_completion(&exit.completion);
9126 mutex_lock(&ctx->uring_lock);
9128 mutex_unlock(&ctx->uring_lock);
9129 spin_lock(&ctx->completion_lock);
9130 spin_unlock(&ctx->completion_lock);
9132 io_ring_ctx_free(ctx);
9135 /* Returns true if we found and killed one or more timeouts */
9136 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9139 struct io_kiocb *req, *tmp;
9142 spin_lock(&ctx->completion_lock);
9143 spin_lock_irq(&ctx->timeout_lock);
9144 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9145 if (io_match_task(req, tsk, cancel_all)) {
9146 io_kill_timeout(req, -ECANCELED);
9150 spin_unlock_irq(&ctx->timeout_lock);
9152 io_commit_cqring(ctx);
9153 spin_unlock(&ctx->completion_lock);
9155 io_cqring_ev_posted(ctx);
9156 return canceled != 0;
9159 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9161 unsigned long index;
9162 struct creds *creds;
9164 mutex_lock(&ctx->uring_lock);
9165 percpu_ref_kill(&ctx->refs);
9167 __io_cqring_overflow_flush(ctx, true);
9168 xa_for_each(&ctx->personalities, index, creds)
9169 io_unregister_personality(ctx, index);
9170 mutex_unlock(&ctx->uring_lock);
9172 io_kill_timeouts(ctx, NULL, true);
9173 io_poll_remove_all(ctx, NULL, true);
9175 /* if we failed setting up the ctx, we might not have any rings */
9176 io_iopoll_try_reap_events(ctx);
9178 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9180 * Use system_unbound_wq to avoid spawning tons of event kworkers
9181 * if we're exiting a ton of rings at the same time. It just adds
9182 * noise and overhead, there's no discernable change in runtime
9183 * over using system_wq.
9185 queue_work(system_unbound_wq, &ctx->exit_work);
9188 static int io_uring_release(struct inode *inode, struct file *file)
9190 struct io_ring_ctx *ctx = file->private_data;
9192 file->private_data = NULL;
9193 io_ring_ctx_wait_and_kill(ctx);
9197 struct io_task_cancel {
9198 struct task_struct *task;
9202 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9204 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9205 struct io_task_cancel *cancel = data;
9208 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9209 struct io_ring_ctx *ctx = req->ctx;
9211 /* protect against races with linked timeouts */
9212 spin_lock(&ctx->completion_lock);
9213 ret = io_match_task(req, cancel->task, cancel->all);
9214 spin_unlock(&ctx->completion_lock);
9216 ret = io_match_task(req, cancel->task, cancel->all);
9221 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9222 struct task_struct *task, bool cancel_all)
9224 struct io_defer_entry *de;
9227 spin_lock(&ctx->completion_lock);
9228 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9229 if (io_match_task(de->req, task, cancel_all)) {
9230 list_cut_position(&list, &ctx->defer_list, &de->list);
9234 spin_unlock(&ctx->completion_lock);
9235 if (list_empty(&list))
9238 while (!list_empty(&list)) {
9239 de = list_first_entry(&list, struct io_defer_entry, list);
9240 list_del_init(&de->list);
9241 io_req_complete_failed(de->req, -ECANCELED);
9247 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9249 struct io_tctx_node *node;
9250 enum io_wq_cancel cret;
9253 mutex_lock(&ctx->uring_lock);
9254 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9255 struct io_uring_task *tctx = node->task->io_uring;
9258 * io_wq will stay alive while we hold uring_lock, because it's
9259 * killed after ctx nodes, which requires to take the lock.
9261 if (!tctx || !tctx->io_wq)
9263 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9264 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9266 mutex_unlock(&ctx->uring_lock);
9271 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9272 struct task_struct *task,
9275 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9276 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9279 enum io_wq_cancel cret;
9283 ret |= io_uring_try_cancel_iowq(ctx);
9284 } else if (tctx && tctx->io_wq) {
9286 * Cancels requests of all rings, not only @ctx, but
9287 * it's fine as the task is in exit/exec.
9289 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9291 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9294 /* SQPOLL thread does its own polling */
9295 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9296 (ctx->sq_data && ctx->sq_data->thread == current)) {
9297 while (!list_empty_careful(&ctx->iopoll_list)) {
9298 io_iopoll_try_reap_events(ctx);
9303 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9304 ret |= io_poll_remove_all(ctx, task, cancel_all);
9305 ret |= io_kill_timeouts(ctx, task, cancel_all);
9307 ret |= io_run_task_work();
9314 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9316 struct io_uring_task *tctx = current->io_uring;
9317 struct io_tctx_node *node;
9320 if (unlikely(!tctx)) {
9321 ret = io_uring_alloc_task_context(current, ctx);
9324 tctx = current->io_uring;
9326 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9327 node = kmalloc(sizeof(*node), GFP_KERNEL);
9331 node->task = current;
9333 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9340 mutex_lock(&ctx->uring_lock);
9341 list_add(&node->ctx_node, &ctx->tctx_list);
9342 mutex_unlock(&ctx->uring_lock);
9349 * Note that this task has used io_uring. We use it for cancelation purposes.
9351 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9353 struct io_uring_task *tctx = current->io_uring;
9355 if (likely(tctx && tctx->last == ctx))
9357 return __io_uring_add_tctx_node(ctx);
9361 * Remove this io_uring_file -> task mapping.
9363 static void io_uring_del_tctx_node(unsigned long index)
9365 struct io_uring_task *tctx = current->io_uring;
9366 struct io_tctx_node *node;
9370 node = xa_erase(&tctx->xa, index);
9374 WARN_ON_ONCE(current != node->task);
9375 WARN_ON_ONCE(list_empty(&node->ctx_node));
9377 mutex_lock(&node->ctx->uring_lock);
9378 list_del(&node->ctx_node);
9379 mutex_unlock(&node->ctx->uring_lock);
9381 if (tctx->last == node->ctx)
9386 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9388 struct io_wq *wq = tctx->io_wq;
9389 struct io_tctx_node *node;
9390 unsigned long index;
9392 xa_for_each(&tctx->xa, index, node)
9393 io_uring_del_tctx_node(index);
9396 * Must be after io_uring_del_task_file() (removes nodes under
9397 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9399 io_wq_put_and_exit(wq);
9404 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9407 return atomic_read(&tctx->inflight_tracked);
9408 return percpu_counter_sum(&tctx->inflight);
9411 static void io_uring_drop_tctx_refs(struct task_struct *task)
9413 struct io_uring_task *tctx = task->io_uring;
9414 unsigned int refs = tctx->cached_refs;
9417 tctx->cached_refs = 0;
9418 percpu_counter_sub(&tctx->inflight, refs);
9419 put_task_struct_many(task, refs);
9424 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9425 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9427 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9429 struct io_uring_task *tctx = current->io_uring;
9430 struct io_ring_ctx *ctx;
9434 WARN_ON_ONCE(sqd && sqd->thread != current);
9436 if (!current->io_uring)
9439 io_wq_exit_start(tctx->io_wq);
9441 atomic_inc(&tctx->in_idle);
9443 io_uring_drop_tctx_refs(current);
9444 /* read completions before cancelations */
9445 inflight = tctx_inflight(tctx, !cancel_all);
9450 struct io_tctx_node *node;
9451 unsigned long index;
9453 xa_for_each(&tctx->xa, index, node) {
9454 /* sqpoll task will cancel all its requests */
9455 if (node->ctx->sq_data)
9457 io_uring_try_cancel_requests(node->ctx, current,
9461 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9462 io_uring_try_cancel_requests(ctx, current,
9466 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9467 io_uring_drop_tctx_refs(current);
9469 * If we've seen completions, retry without waiting. This
9470 * avoids a race where a completion comes in before we did
9471 * prepare_to_wait().
9473 if (inflight == tctx_inflight(tctx, !cancel_all))
9475 finish_wait(&tctx->wait, &wait);
9477 atomic_dec(&tctx->in_idle);
9479 io_uring_clean_tctx(tctx);
9481 /* for exec all current's requests should be gone, kill tctx */
9482 __io_uring_free(current);
9486 void __io_uring_cancel(bool cancel_all)
9488 io_uring_cancel_generic(cancel_all, NULL);
9491 static void *io_uring_validate_mmap_request(struct file *file,
9492 loff_t pgoff, size_t sz)
9494 struct io_ring_ctx *ctx = file->private_data;
9495 loff_t offset = pgoff << PAGE_SHIFT;
9500 case IORING_OFF_SQ_RING:
9501 case IORING_OFF_CQ_RING:
9504 case IORING_OFF_SQES:
9508 return ERR_PTR(-EINVAL);
9511 page = virt_to_head_page(ptr);
9512 if (sz > page_size(page))
9513 return ERR_PTR(-EINVAL);
9520 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9522 size_t sz = vma->vm_end - vma->vm_start;
9526 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9528 return PTR_ERR(ptr);
9530 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9531 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9534 #else /* !CONFIG_MMU */
9536 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9538 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9541 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9543 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9546 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9547 unsigned long addr, unsigned long len,
9548 unsigned long pgoff, unsigned long flags)
9552 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9554 return PTR_ERR(ptr);
9556 return (unsigned long) ptr;
9559 #endif /* !CONFIG_MMU */
9561 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9566 if (!io_sqring_full(ctx))
9568 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9570 if (!io_sqring_full(ctx))
9573 } while (!signal_pending(current));
9575 finish_wait(&ctx->sqo_sq_wait, &wait);
9579 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9580 struct __kernel_timespec __user **ts,
9581 const sigset_t __user **sig)
9583 struct io_uring_getevents_arg arg;
9586 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9587 * is just a pointer to the sigset_t.
9589 if (!(flags & IORING_ENTER_EXT_ARG)) {
9590 *sig = (const sigset_t __user *) argp;
9596 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9597 * timespec and sigset_t pointers if good.
9599 if (*argsz != sizeof(arg))
9601 if (copy_from_user(&arg, argp, sizeof(arg)))
9603 *sig = u64_to_user_ptr(arg.sigmask);
9604 *argsz = arg.sigmask_sz;
9605 *ts = u64_to_user_ptr(arg.ts);
9609 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9610 u32, min_complete, u32, flags, const void __user *, argp,
9613 struct io_ring_ctx *ctx;
9620 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9621 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9625 if (unlikely(!f.file))
9629 if (unlikely(f.file->f_op != &io_uring_fops))
9633 ctx = f.file->private_data;
9634 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9638 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9642 * For SQ polling, the thread will do all submissions and completions.
9643 * Just return the requested submit count, and wake the thread if
9647 if (ctx->flags & IORING_SETUP_SQPOLL) {
9648 io_cqring_overflow_flush(ctx);
9650 if (unlikely(ctx->sq_data->thread == NULL)) {
9654 if (flags & IORING_ENTER_SQ_WAKEUP)
9655 wake_up(&ctx->sq_data->wait);
9656 if (flags & IORING_ENTER_SQ_WAIT) {
9657 ret = io_sqpoll_wait_sq(ctx);
9661 submitted = to_submit;
9662 } else if (to_submit) {
9663 ret = io_uring_add_tctx_node(ctx);
9666 mutex_lock(&ctx->uring_lock);
9667 submitted = io_submit_sqes(ctx, to_submit);
9668 mutex_unlock(&ctx->uring_lock);
9670 if (submitted != to_submit)
9673 if (flags & IORING_ENTER_GETEVENTS) {
9674 const sigset_t __user *sig;
9675 struct __kernel_timespec __user *ts;
9677 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9681 min_complete = min(min_complete, ctx->cq_entries);
9684 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9685 * space applications don't need to do io completion events
9686 * polling again, they can rely on io_sq_thread to do polling
9687 * work, which can reduce cpu usage and uring_lock contention.
9689 if (ctx->flags & IORING_SETUP_IOPOLL &&
9690 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9691 ret = io_iopoll_check(ctx, min_complete);
9693 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9698 percpu_ref_put(&ctx->refs);
9701 return submitted ? submitted : ret;
9704 #ifdef CONFIG_PROC_FS
9705 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9706 const struct cred *cred)
9708 struct user_namespace *uns = seq_user_ns(m);
9709 struct group_info *gi;
9714 seq_printf(m, "%5d\n", id);
9715 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9716 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9717 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9718 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9719 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9720 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9721 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9722 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9723 seq_puts(m, "\n\tGroups:\t");
9724 gi = cred->group_info;
9725 for (g = 0; g < gi->ngroups; g++) {
9726 seq_put_decimal_ull(m, g ? " " : "",
9727 from_kgid_munged(uns, gi->gid[g]));
9729 seq_puts(m, "\n\tCapEff:\t");
9730 cap = cred->cap_effective;
9731 CAP_FOR_EACH_U32(__capi)
9732 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9737 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9739 struct io_sq_data *sq = NULL;
9744 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9745 * since fdinfo case grabs it in the opposite direction of normal use
9746 * cases. If we fail to get the lock, we just don't iterate any
9747 * structures that could be going away outside the io_uring mutex.
9749 has_lock = mutex_trylock(&ctx->uring_lock);
9751 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9757 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9758 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9759 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9760 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9761 struct file *f = io_file_from_index(ctx, i);
9764 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9766 seq_printf(m, "%5u: <none>\n", i);
9768 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9769 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9770 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9771 unsigned int len = buf->ubuf_end - buf->ubuf;
9773 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9775 if (has_lock && !xa_empty(&ctx->personalities)) {
9776 unsigned long index;
9777 const struct cred *cred;
9779 seq_printf(m, "Personalities:\n");
9780 xa_for_each(&ctx->personalities, index, cred)
9781 io_uring_show_cred(m, index, cred);
9783 seq_printf(m, "PollList:\n");
9784 spin_lock(&ctx->completion_lock);
9785 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9786 struct hlist_head *list = &ctx->cancel_hash[i];
9787 struct io_kiocb *req;
9789 hlist_for_each_entry(req, list, hash_node)
9790 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9791 req->task->task_works != NULL);
9793 spin_unlock(&ctx->completion_lock);
9795 mutex_unlock(&ctx->uring_lock);
9798 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9800 struct io_ring_ctx *ctx = f->private_data;
9802 if (percpu_ref_tryget(&ctx->refs)) {
9803 __io_uring_show_fdinfo(ctx, m);
9804 percpu_ref_put(&ctx->refs);
9809 static const struct file_operations io_uring_fops = {
9810 .release = io_uring_release,
9811 .mmap = io_uring_mmap,
9813 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9814 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9816 .poll = io_uring_poll,
9817 .fasync = io_uring_fasync,
9818 #ifdef CONFIG_PROC_FS
9819 .show_fdinfo = io_uring_show_fdinfo,
9823 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9824 struct io_uring_params *p)
9826 struct io_rings *rings;
9827 size_t size, sq_array_offset;
9829 /* make sure these are sane, as we already accounted them */
9830 ctx->sq_entries = p->sq_entries;
9831 ctx->cq_entries = p->cq_entries;
9833 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9834 if (size == SIZE_MAX)
9837 rings = io_mem_alloc(size);
9842 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9843 rings->sq_ring_mask = p->sq_entries - 1;
9844 rings->cq_ring_mask = p->cq_entries - 1;
9845 rings->sq_ring_entries = p->sq_entries;
9846 rings->cq_ring_entries = p->cq_entries;
9848 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9849 if (size == SIZE_MAX) {
9850 io_mem_free(ctx->rings);
9855 ctx->sq_sqes = io_mem_alloc(size);
9856 if (!ctx->sq_sqes) {
9857 io_mem_free(ctx->rings);
9865 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9869 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9873 ret = io_uring_add_tctx_node(ctx);
9878 fd_install(fd, file);
9883 * Allocate an anonymous fd, this is what constitutes the application
9884 * visible backing of an io_uring instance. The application mmaps this
9885 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9886 * we have to tie this fd to a socket for file garbage collection purposes.
9888 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9891 #if defined(CONFIG_UNIX)
9894 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9897 return ERR_PTR(ret);
9900 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9901 O_RDWR | O_CLOEXEC);
9902 #if defined(CONFIG_UNIX)
9904 sock_release(ctx->ring_sock);
9905 ctx->ring_sock = NULL;
9907 ctx->ring_sock->file = file;
9913 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9914 struct io_uring_params __user *params)
9916 struct io_ring_ctx *ctx;
9922 if (entries > IORING_MAX_ENTRIES) {
9923 if (!(p->flags & IORING_SETUP_CLAMP))
9925 entries = IORING_MAX_ENTRIES;
9929 * Use twice as many entries for the CQ ring. It's possible for the
9930 * application to drive a higher depth than the size of the SQ ring,
9931 * since the sqes are only used at submission time. This allows for
9932 * some flexibility in overcommitting a bit. If the application has
9933 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9934 * of CQ ring entries manually.
9936 p->sq_entries = roundup_pow_of_two(entries);
9937 if (p->flags & IORING_SETUP_CQSIZE) {
9939 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9940 * to a power-of-two, if it isn't already. We do NOT impose
9941 * any cq vs sq ring sizing.
9945 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9946 if (!(p->flags & IORING_SETUP_CLAMP))
9948 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9950 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9951 if (p->cq_entries < p->sq_entries)
9954 p->cq_entries = 2 * p->sq_entries;
9957 ctx = io_ring_ctx_alloc(p);
9960 ctx->compat = in_compat_syscall();
9961 if (!capable(CAP_IPC_LOCK))
9962 ctx->user = get_uid(current_user());
9965 * This is just grabbed for accounting purposes. When a process exits,
9966 * the mm is exited and dropped before the files, hence we need to hang
9967 * on to this mm purely for the purposes of being able to unaccount
9968 * memory (locked/pinned vm). It's not used for anything else.
9970 mmgrab(current->mm);
9971 ctx->mm_account = current->mm;
9973 ret = io_allocate_scq_urings(ctx, p);
9977 ret = io_sq_offload_create(ctx, p);
9980 /* always set a rsrc node */
9981 ret = io_rsrc_node_switch_start(ctx);
9984 io_rsrc_node_switch(ctx, NULL);
9986 memset(&p->sq_off, 0, sizeof(p->sq_off));
9987 p->sq_off.head = offsetof(struct io_rings, sq.head);
9988 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9989 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9990 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9991 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9992 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9993 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9995 memset(&p->cq_off, 0, sizeof(p->cq_off));
9996 p->cq_off.head = offsetof(struct io_rings, cq.head);
9997 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9998 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9999 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10000 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10001 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10002 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10004 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10005 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10006 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10007 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10008 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10009 IORING_FEAT_RSRC_TAGS;
10011 if (copy_to_user(params, p, sizeof(*p))) {
10016 file = io_uring_get_file(ctx);
10017 if (IS_ERR(file)) {
10018 ret = PTR_ERR(file);
10023 * Install ring fd as the very last thing, so we don't risk someone
10024 * having closed it before we finish setup
10026 ret = io_uring_install_fd(ctx, file);
10028 /* fput will clean it up */
10033 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10036 io_ring_ctx_wait_and_kill(ctx);
10041 * Sets up an aio uring context, and returns the fd. Applications asks for a
10042 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10043 * params structure passed in.
10045 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10047 struct io_uring_params p;
10050 if (copy_from_user(&p, params, sizeof(p)))
10052 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10057 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10058 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10059 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10060 IORING_SETUP_R_DISABLED))
10063 return io_uring_create(entries, &p, params);
10066 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10067 struct io_uring_params __user *, params)
10069 return io_uring_setup(entries, params);
10072 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10074 struct io_uring_probe *p;
10078 size = struct_size(p, ops, nr_args);
10079 if (size == SIZE_MAX)
10081 p = kzalloc(size, GFP_KERNEL);
10086 if (copy_from_user(p, arg, size))
10089 if (memchr_inv(p, 0, size))
10092 p->last_op = IORING_OP_LAST - 1;
10093 if (nr_args > IORING_OP_LAST)
10094 nr_args = IORING_OP_LAST;
10096 for (i = 0; i < nr_args; i++) {
10098 if (!io_op_defs[i].not_supported)
10099 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10104 if (copy_to_user(arg, p, size))
10111 static int io_register_personality(struct io_ring_ctx *ctx)
10113 const struct cred *creds;
10117 creds = get_current_cred();
10119 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10120 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10128 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10129 unsigned int nr_args)
10131 struct io_uring_restriction *res;
10135 /* Restrictions allowed only if rings started disabled */
10136 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10139 /* We allow only a single restrictions registration */
10140 if (ctx->restrictions.registered)
10143 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10146 size = array_size(nr_args, sizeof(*res));
10147 if (size == SIZE_MAX)
10150 res = memdup_user(arg, size);
10152 return PTR_ERR(res);
10156 for (i = 0; i < nr_args; i++) {
10157 switch (res[i].opcode) {
10158 case IORING_RESTRICTION_REGISTER_OP:
10159 if (res[i].register_op >= IORING_REGISTER_LAST) {
10164 __set_bit(res[i].register_op,
10165 ctx->restrictions.register_op);
10167 case IORING_RESTRICTION_SQE_OP:
10168 if (res[i].sqe_op >= IORING_OP_LAST) {
10173 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10175 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10176 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10178 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10179 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10188 /* Reset all restrictions if an error happened */
10190 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10192 ctx->restrictions.registered = true;
10198 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10200 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10203 if (ctx->restrictions.registered)
10204 ctx->restricted = 1;
10206 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10207 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10208 wake_up(&ctx->sq_data->wait);
10212 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10213 struct io_uring_rsrc_update2 *up,
10221 if (check_add_overflow(up->offset, nr_args, &tmp))
10223 err = io_rsrc_node_switch_start(ctx);
10228 case IORING_RSRC_FILE:
10229 return __io_sqe_files_update(ctx, up, nr_args);
10230 case IORING_RSRC_BUFFER:
10231 return __io_sqe_buffers_update(ctx, up, nr_args);
10236 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10239 struct io_uring_rsrc_update2 up;
10243 memset(&up, 0, sizeof(up));
10244 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10246 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10249 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10250 unsigned size, unsigned type)
10252 struct io_uring_rsrc_update2 up;
10254 if (size != sizeof(up))
10256 if (copy_from_user(&up, arg, sizeof(up)))
10258 if (!up.nr || up.resv)
10260 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10263 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10264 unsigned int size, unsigned int type)
10266 struct io_uring_rsrc_register rr;
10268 /* keep it extendible */
10269 if (size != sizeof(rr))
10272 memset(&rr, 0, sizeof(rr));
10273 if (copy_from_user(&rr, arg, size))
10275 if (!rr.nr || rr.resv || rr.resv2)
10279 case IORING_RSRC_FILE:
10280 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10281 rr.nr, u64_to_user_ptr(rr.tags));
10282 case IORING_RSRC_BUFFER:
10283 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10284 rr.nr, u64_to_user_ptr(rr.tags));
10289 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10292 struct io_uring_task *tctx = current->io_uring;
10293 cpumask_var_t new_mask;
10296 if (!tctx || !tctx->io_wq)
10299 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10302 cpumask_clear(new_mask);
10303 if (len > cpumask_size())
10304 len = cpumask_size();
10306 if (copy_from_user(new_mask, arg, len)) {
10307 free_cpumask_var(new_mask);
10311 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10312 free_cpumask_var(new_mask);
10316 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10318 struct io_uring_task *tctx = current->io_uring;
10320 if (!tctx || !tctx->io_wq)
10323 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10326 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10329 struct io_uring_task *tctx = NULL;
10330 struct io_sq_data *sqd = NULL;
10331 __u32 new_count[2];
10334 if (copy_from_user(new_count, arg, sizeof(new_count)))
10336 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10337 if (new_count[i] > INT_MAX)
10340 if (ctx->flags & IORING_SETUP_SQPOLL) {
10341 sqd = ctx->sq_data;
10343 mutex_lock(&sqd->lock);
10344 tctx = sqd->thread->io_uring;
10347 tctx = current->io_uring;
10351 if (!tctx || !tctx->io_wq)
10354 ret = io_wq_max_workers(tctx->io_wq, new_count);
10359 mutex_unlock(&sqd->lock);
10361 if (copy_to_user(arg, new_count, sizeof(new_count)))
10367 mutex_unlock(&sqd->lock);
10371 static bool io_register_op_must_quiesce(int op)
10374 case IORING_REGISTER_BUFFERS:
10375 case IORING_UNREGISTER_BUFFERS:
10376 case IORING_REGISTER_FILES:
10377 case IORING_UNREGISTER_FILES:
10378 case IORING_REGISTER_FILES_UPDATE:
10379 case IORING_REGISTER_PROBE:
10380 case IORING_REGISTER_PERSONALITY:
10381 case IORING_UNREGISTER_PERSONALITY:
10382 case IORING_REGISTER_FILES2:
10383 case IORING_REGISTER_FILES_UPDATE2:
10384 case IORING_REGISTER_BUFFERS2:
10385 case IORING_REGISTER_BUFFERS_UPDATE:
10386 case IORING_REGISTER_IOWQ_AFF:
10387 case IORING_UNREGISTER_IOWQ_AFF:
10388 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10395 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10399 percpu_ref_kill(&ctx->refs);
10402 * Drop uring mutex before waiting for references to exit. If another
10403 * thread is currently inside io_uring_enter() it might need to grab the
10404 * uring_lock to make progress. If we hold it here across the drain
10405 * wait, then we can deadlock. It's safe to drop the mutex here, since
10406 * no new references will come in after we've killed the percpu ref.
10408 mutex_unlock(&ctx->uring_lock);
10410 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10413 ret = io_run_task_work_sig();
10414 } while (ret >= 0);
10415 mutex_lock(&ctx->uring_lock);
10418 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10422 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10423 void __user *arg, unsigned nr_args)
10424 __releases(ctx->uring_lock)
10425 __acquires(ctx->uring_lock)
10430 * We're inside the ring mutex, if the ref is already dying, then
10431 * someone else killed the ctx or is already going through
10432 * io_uring_register().
10434 if (percpu_ref_is_dying(&ctx->refs))
10437 if (ctx->restricted) {
10438 if (opcode >= IORING_REGISTER_LAST)
10440 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10441 if (!test_bit(opcode, ctx->restrictions.register_op))
10445 if (io_register_op_must_quiesce(opcode)) {
10446 ret = io_ctx_quiesce(ctx);
10452 case IORING_REGISTER_BUFFERS:
10453 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10455 case IORING_UNREGISTER_BUFFERS:
10457 if (arg || nr_args)
10459 ret = io_sqe_buffers_unregister(ctx);
10461 case IORING_REGISTER_FILES:
10462 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10464 case IORING_UNREGISTER_FILES:
10466 if (arg || nr_args)
10468 ret = io_sqe_files_unregister(ctx);
10470 case IORING_REGISTER_FILES_UPDATE:
10471 ret = io_register_files_update(ctx, arg, nr_args);
10473 case IORING_REGISTER_EVENTFD:
10474 case IORING_REGISTER_EVENTFD_ASYNC:
10478 ret = io_eventfd_register(ctx, arg);
10481 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10482 ctx->eventfd_async = 1;
10484 ctx->eventfd_async = 0;
10486 case IORING_UNREGISTER_EVENTFD:
10488 if (arg || nr_args)
10490 ret = io_eventfd_unregister(ctx);
10492 case IORING_REGISTER_PROBE:
10494 if (!arg || nr_args > 256)
10496 ret = io_probe(ctx, arg, nr_args);
10498 case IORING_REGISTER_PERSONALITY:
10500 if (arg || nr_args)
10502 ret = io_register_personality(ctx);
10504 case IORING_UNREGISTER_PERSONALITY:
10508 ret = io_unregister_personality(ctx, nr_args);
10510 case IORING_REGISTER_ENABLE_RINGS:
10512 if (arg || nr_args)
10514 ret = io_register_enable_rings(ctx);
10516 case IORING_REGISTER_RESTRICTIONS:
10517 ret = io_register_restrictions(ctx, arg, nr_args);
10519 case IORING_REGISTER_FILES2:
10520 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10522 case IORING_REGISTER_FILES_UPDATE2:
10523 ret = io_register_rsrc_update(ctx, arg, nr_args,
10526 case IORING_REGISTER_BUFFERS2:
10527 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10529 case IORING_REGISTER_BUFFERS_UPDATE:
10530 ret = io_register_rsrc_update(ctx, arg, nr_args,
10531 IORING_RSRC_BUFFER);
10533 case IORING_REGISTER_IOWQ_AFF:
10535 if (!arg || !nr_args)
10537 ret = io_register_iowq_aff(ctx, arg, nr_args);
10539 case IORING_UNREGISTER_IOWQ_AFF:
10541 if (arg || nr_args)
10543 ret = io_unregister_iowq_aff(ctx);
10545 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10547 if (!arg || nr_args != 2)
10549 ret = io_register_iowq_max_workers(ctx, arg);
10556 if (io_register_op_must_quiesce(opcode)) {
10557 /* bring the ctx back to life */
10558 percpu_ref_reinit(&ctx->refs);
10559 reinit_completion(&ctx->ref_comp);
10564 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10565 void __user *, arg, unsigned int, nr_args)
10567 struct io_ring_ctx *ctx;
10576 if (f.file->f_op != &io_uring_fops)
10579 ctx = f.file->private_data;
10581 io_run_task_work();
10583 mutex_lock(&ctx->uring_lock);
10584 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10585 mutex_unlock(&ctx->uring_lock);
10586 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10587 ctx->cq_ev_fd != NULL, ret);
10593 static int __init io_uring_init(void)
10595 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10596 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10597 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10600 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10601 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10602 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10603 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10604 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10605 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10606 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10607 BUILD_BUG_SQE_ELEM(8, __u64, off);
10608 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10609 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10610 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10611 BUILD_BUG_SQE_ELEM(24, __u32, len);
10612 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10613 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10614 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10615 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10616 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10617 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10618 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10619 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10620 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10621 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10622 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10623 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10624 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10625 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10626 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10627 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10628 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10629 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10630 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10631 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10632 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10634 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10635 sizeof(struct io_uring_rsrc_update));
10636 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10637 sizeof(struct io_uring_rsrc_update2));
10639 /* ->buf_index is u16 */
10640 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10642 /* should fit into one byte */
10643 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10645 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10646 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10648 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10652 __initcall(io_uring_init);