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);
1827 * Don't initialise the fields below on every allocation, but do that in
1828 * advance and keep them valid across allocations.
1830 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1834 req->async_data = NULL;
1835 /* not necessary, but safer to zero */
1839 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1840 struct io_submit_state *state)
1842 spin_lock(&ctx->completion_lock);
1843 list_splice_init(&ctx->locked_free_list, &state->free_list);
1844 ctx->locked_free_nr = 0;
1845 spin_unlock(&ctx->completion_lock);
1848 /* Returns true IFF there are requests in the cache */
1849 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1851 struct io_submit_state *state = &ctx->submit_state;
1855 * If we have more than a batch's worth of requests in our IRQ side
1856 * locked cache, grab the lock and move them over to our submission
1859 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1860 io_flush_cached_locked_reqs(ctx, state);
1862 nr = state->free_reqs;
1863 while (!list_empty(&state->free_list)) {
1864 struct io_kiocb *req = list_first_entry(&state->free_list,
1865 struct io_kiocb, inflight_entry);
1867 list_del(&req->inflight_entry);
1868 state->reqs[nr++] = req;
1869 if (nr == ARRAY_SIZE(state->reqs))
1873 state->free_reqs = nr;
1878 * A request might get retired back into the request caches even before opcode
1879 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1880 * Because of that, io_alloc_req() should be called only under ->uring_lock
1881 * and with extra caution to not get a request that is still worked on.
1883 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1884 __must_hold(&ctx->uring_lock)
1886 struct io_submit_state *state = &ctx->submit_state;
1887 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1890 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1892 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1895 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1899 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1900 * retry single alloc to be on the safe side.
1902 if (unlikely(ret <= 0)) {
1903 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1904 if (!state->reqs[0])
1909 for (i = 0; i < ret; i++)
1910 io_preinit_req(state->reqs[i], ctx);
1911 state->free_reqs = ret;
1914 return state->reqs[state->free_reqs];
1917 static inline void io_put_file(struct file *file)
1923 static void io_dismantle_req(struct io_kiocb *req)
1925 unsigned int flags = req->flags;
1927 if (io_req_needs_clean(req))
1929 if (!(flags & REQ_F_FIXED_FILE))
1930 io_put_file(req->file);
1931 if (req->fixed_rsrc_refs)
1932 percpu_ref_put(req->fixed_rsrc_refs);
1933 if (req->async_data) {
1934 kfree(req->async_data);
1935 req->async_data = NULL;
1939 static void __io_free_req(struct io_kiocb *req)
1941 struct io_ring_ctx *ctx = req->ctx;
1943 io_dismantle_req(req);
1944 io_put_task(req->task, 1);
1946 spin_lock(&ctx->completion_lock);
1947 list_add(&req->inflight_entry, &ctx->locked_free_list);
1948 ctx->locked_free_nr++;
1949 spin_unlock(&ctx->completion_lock);
1951 percpu_ref_put(&ctx->refs);
1954 static inline void io_remove_next_linked(struct io_kiocb *req)
1956 struct io_kiocb *nxt = req->link;
1958 req->link = nxt->link;
1962 static bool io_kill_linked_timeout(struct io_kiocb *req)
1963 __must_hold(&req->ctx->completion_lock)
1964 __must_hold(&req->ctx->timeout_lock)
1966 struct io_kiocb *link = req->link;
1968 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1969 struct io_timeout_data *io = link->async_data;
1971 io_remove_next_linked(req);
1972 link->timeout.head = NULL;
1973 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1974 list_del(&link->timeout.list);
1975 io_cqring_fill_event(link->ctx, link->user_data,
1977 io_put_req_deferred(link);
1984 static void io_fail_links(struct io_kiocb *req)
1985 __must_hold(&req->ctx->completion_lock)
1987 struct io_kiocb *nxt, *link = req->link;
1991 long res = -ECANCELED;
1993 if (link->flags & REQ_F_FAIL)
1999 trace_io_uring_fail_link(req, link);
2000 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2001 io_put_req_deferred(link);
2006 static bool io_disarm_next(struct io_kiocb *req)
2007 __must_hold(&req->ctx->completion_lock)
2009 bool posted = false;
2011 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2012 struct io_kiocb *link = req->link;
2014 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2015 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2016 io_remove_next_linked(req);
2017 io_cqring_fill_event(link->ctx, link->user_data,
2019 io_put_req_deferred(link);
2022 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2023 struct io_ring_ctx *ctx = req->ctx;
2025 spin_lock_irq(&ctx->timeout_lock);
2026 posted = io_kill_linked_timeout(req);
2027 spin_unlock_irq(&ctx->timeout_lock);
2029 if (unlikely((req->flags & REQ_F_FAIL) &&
2030 !(req->flags & REQ_F_HARDLINK))) {
2031 posted |= (req->link != NULL);
2037 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2039 struct io_kiocb *nxt;
2042 * If LINK is set, we have dependent requests in this chain. If we
2043 * didn't fail this request, queue the first one up, moving any other
2044 * dependencies to the next request. In case of failure, fail the rest
2047 if (req->flags & IO_DISARM_MASK) {
2048 struct io_ring_ctx *ctx = req->ctx;
2051 spin_lock(&ctx->completion_lock);
2052 posted = io_disarm_next(req);
2054 io_commit_cqring(req->ctx);
2055 spin_unlock(&ctx->completion_lock);
2057 io_cqring_ev_posted(ctx);
2064 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2066 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2068 return __io_req_find_next(req);
2071 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2076 if (ctx->submit_state.compl_nr)
2077 io_submit_flush_completions(ctx);
2078 mutex_unlock(&ctx->uring_lock);
2081 percpu_ref_put(&ctx->refs);
2084 static void tctx_task_work(struct callback_head *cb)
2086 bool locked = false;
2087 struct io_ring_ctx *ctx = NULL;
2088 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2092 struct io_wq_work_node *node;
2094 spin_lock_irq(&tctx->task_lock);
2095 node = tctx->task_list.first;
2096 INIT_WQ_LIST(&tctx->task_list);
2098 tctx->task_running = false;
2099 spin_unlock_irq(&tctx->task_lock);
2104 struct io_wq_work_node *next = node->next;
2105 struct io_kiocb *req = container_of(node, struct io_kiocb,
2108 if (req->ctx != ctx) {
2109 ctx_flush_and_put(ctx, &locked);
2111 /* if not contended, grab and improve batching */
2112 locked = mutex_trylock(&ctx->uring_lock);
2113 percpu_ref_get(&ctx->refs);
2115 req->io_task_work.func(req, &locked);
2122 ctx_flush_and_put(ctx, &locked);
2125 static void io_req_task_work_add(struct io_kiocb *req)
2127 struct task_struct *tsk = req->task;
2128 struct io_uring_task *tctx = tsk->io_uring;
2129 enum task_work_notify_mode notify;
2130 struct io_wq_work_node *node;
2131 unsigned long flags;
2134 WARN_ON_ONCE(!tctx);
2136 spin_lock_irqsave(&tctx->task_lock, flags);
2137 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2138 running = tctx->task_running;
2140 tctx->task_running = true;
2141 spin_unlock_irqrestore(&tctx->task_lock, flags);
2143 /* task_work already pending, we're done */
2148 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2149 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2150 * processing task_work. There's no reliable way to tell if TWA_RESUME
2153 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2154 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2155 wake_up_process(tsk);
2159 spin_lock_irqsave(&tctx->task_lock, flags);
2160 tctx->task_running = false;
2161 node = tctx->task_list.first;
2162 INIT_WQ_LIST(&tctx->task_list);
2163 spin_unlock_irqrestore(&tctx->task_lock, flags);
2166 req = container_of(node, struct io_kiocb, io_task_work.node);
2168 if (llist_add(&req->io_task_work.fallback_node,
2169 &req->ctx->fallback_llist))
2170 schedule_delayed_work(&req->ctx->fallback_work, 1);
2174 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2176 struct io_ring_ctx *ctx = req->ctx;
2178 /* not needed for normal modes, but SQPOLL depends on it */
2179 io_tw_lock(ctx, locked);
2180 io_req_complete_failed(req, req->result);
2183 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2185 struct io_ring_ctx *ctx = req->ctx;
2187 io_tw_lock(ctx, locked);
2188 /* req->task == current here, checking PF_EXITING is safe */
2189 if (likely(!(req->task->flags & PF_EXITING)))
2190 __io_queue_sqe(req);
2192 io_req_complete_failed(req, -EFAULT);
2195 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2198 req->io_task_work.func = io_req_task_cancel;
2199 io_req_task_work_add(req);
2202 static void io_req_task_queue(struct io_kiocb *req)
2204 req->io_task_work.func = io_req_task_submit;
2205 io_req_task_work_add(req);
2208 static void io_req_task_queue_reissue(struct io_kiocb *req)
2210 req->io_task_work.func = io_queue_async_work;
2211 io_req_task_work_add(req);
2214 static inline void io_queue_next(struct io_kiocb *req)
2216 struct io_kiocb *nxt = io_req_find_next(req);
2219 io_req_task_queue(nxt);
2222 static void io_free_req(struct io_kiocb *req)
2228 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2234 struct task_struct *task;
2239 static inline void io_init_req_batch(struct req_batch *rb)
2246 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2247 struct req_batch *rb)
2250 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2252 io_put_task(rb->task, rb->task_refs);
2255 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2256 struct io_submit_state *state)
2259 io_dismantle_req(req);
2261 if (req->task != rb->task) {
2263 io_put_task(rb->task, rb->task_refs);
2264 rb->task = req->task;
2270 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2271 state->reqs[state->free_reqs++] = req;
2273 list_add(&req->inflight_entry, &state->free_list);
2276 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2277 __must_hold(&ctx->uring_lock)
2279 struct io_submit_state *state = &ctx->submit_state;
2280 int i, nr = state->compl_nr;
2281 struct req_batch rb;
2283 spin_lock(&ctx->completion_lock);
2284 for (i = 0; i < nr; i++) {
2285 struct io_kiocb *req = state->compl_reqs[i];
2287 __io_cqring_fill_event(ctx, req->user_data, req->result,
2290 io_commit_cqring(ctx);
2291 spin_unlock(&ctx->completion_lock);
2292 io_cqring_ev_posted(ctx);
2294 io_init_req_batch(&rb);
2295 for (i = 0; i < nr; i++) {
2296 struct io_kiocb *req = state->compl_reqs[i];
2298 if (req_ref_put_and_test(req))
2299 io_req_free_batch(&rb, req, &ctx->submit_state);
2302 io_req_free_batch_finish(ctx, &rb);
2303 state->compl_nr = 0;
2307 * Drop reference to request, return next in chain (if there is one) if this
2308 * was the last reference to this request.
2310 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2312 struct io_kiocb *nxt = NULL;
2314 if (req_ref_put_and_test(req)) {
2315 nxt = io_req_find_next(req);
2321 static inline void io_put_req(struct io_kiocb *req)
2323 if (req_ref_put_and_test(req))
2327 static inline void io_put_req_deferred(struct io_kiocb *req)
2329 if (req_ref_put_and_test(req)) {
2330 req->io_task_work.func = io_free_req_work;
2331 io_req_task_work_add(req);
2335 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2337 /* See comment at the top of this file */
2339 return __io_cqring_events(ctx);
2342 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2344 struct io_rings *rings = ctx->rings;
2346 /* make sure SQ entry isn't read before tail */
2347 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2350 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2352 unsigned int cflags;
2354 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2355 cflags |= IORING_CQE_F_BUFFER;
2356 req->flags &= ~REQ_F_BUFFER_SELECTED;
2361 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2363 struct io_buffer *kbuf;
2365 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2367 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2368 return io_put_kbuf(req, kbuf);
2371 static inline bool io_run_task_work(void)
2373 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2374 __set_current_state(TASK_RUNNING);
2375 tracehook_notify_signal();
2383 * Find and free completed poll iocbs
2385 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2386 struct list_head *done)
2388 struct req_batch rb;
2389 struct io_kiocb *req;
2391 /* order with ->result store in io_complete_rw_iopoll() */
2394 io_init_req_batch(&rb);
2395 while (!list_empty(done)) {
2396 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2397 list_del(&req->inflight_entry);
2399 if (READ_ONCE(req->result) == -EAGAIN &&
2400 !(req->flags & REQ_F_DONT_REISSUE)) {
2401 req->iopoll_completed = 0;
2402 io_req_task_queue_reissue(req);
2406 __io_cqring_fill_event(ctx, req->user_data, req->result,
2407 io_put_rw_kbuf(req));
2410 if (req_ref_put_and_test(req))
2411 io_req_free_batch(&rb, req, &ctx->submit_state);
2414 io_commit_cqring(ctx);
2415 io_cqring_ev_posted_iopoll(ctx);
2416 io_req_free_batch_finish(ctx, &rb);
2419 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2422 struct io_kiocb *req, *tmp;
2427 * Only spin for completions if we don't have multiple devices hanging
2428 * off our complete list, and we're under the requested amount.
2430 spin = !ctx->poll_multi_queue && *nr_events < min;
2432 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2433 struct kiocb *kiocb = &req->rw.kiocb;
2437 * Move completed and retryable entries to our local lists.
2438 * If we find a request that requires polling, break out
2439 * and complete those lists first, if we have entries there.
2441 if (READ_ONCE(req->iopoll_completed)) {
2442 list_move_tail(&req->inflight_entry, &done);
2445 if (!list_empty(&done))
2448 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2449 if (unlikely(ret < 0))
2454 /* iopoll may have completed current req */
2455 if (READ_ONCE(req->iopoll_completed))
2456 list_move_tail(&req->inflight_entry, &done);
2459 if (!list_empty(&done))
2460 io_iopoll_complete(ctx, nr_events, &done);
2466 * We can't just wait for polled events to come to us, we have to actively
2467 * find and complete them.
2469 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2471 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2474 mutex_lock(&ctx->uring_lock);
2475 while (!list_empty(&ctx->iopoll_list)) {
2476 unsigned int nr_events = 0;
2478 io_do_iopoll(ctx, &nr_events, 0);
2480 /* let it sleep and repeat later if can't complete a request */
2484 * Ensure we allow local-to-the-cpu processing to take place,
2485 * in this case we need to ensure that we reap all events.
2486 * Also let task_work, etc. to progress by releasing the mutex
2488 if (need_resched()) {
2489 mutex_unlock(&ctx->uring_lock);
2491 mutex_lock(&ctx->uring_lock);
2494 mutex_unlock(&ctx->uring_lock);
2497 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2499 unsigned int nr_events = 0;
2503 * We disallow the app entering submit/complete with polling, but we
2504 * still need to lock the ring to prevent racing with polled issue
2505 * that got punted to a workqueue.
2507 mutex_lock(&ctx->uring_lock);
2509 * Don't enter poll loop if we already have events pending.
2510 * If we do, we can potentially be spinning for commands that
2511 * already triggered a CQE (eg in error).
2513 if (test_bit(0, &ctx->check_cq_overflow))
2514 __io_cqring_overflow_flush(ctx, false);
2515 if (io_cqring_events(ctx))
2519 * If a submit got punted to a workqueue, we can have the
2520 * application entering polling for a command before it gets
2521 * issued. That app will hold the uring_lock for the duration
2522 * of the poll right here, so we need to take a breather every
2523 * now and then to ensure that the issue has a chance to add
2524 * the poll to the issued list. Otherwise we can spin here
2525 * forever, while the workqueue is stuck trying to acquire the
2528 if (list_empty(&ctx->iopoll_list)) {
2529 u32 tail = ctx->cached_cq_tail;
2531 mutex_unlock(&ctx->uring_lock);
2533 mutex_lock(&ctx->uring_lock);
2535 /* some requests don't go through iopoll_list */
2536 if (tail != ctx->cached_cq_tail ||
2537 list_empty(&ctx->iopoll_list))
2540 ret = io_do_iopoll(ctx, &nr_events, min);
2541 } while (!ret && nr_events < min && !need_resched());
2543 mutex_unlock(&ctx->uring_lock);
2547 static void kiocb_end_write(struct io_kiocb *req)
2550 * Tell lockdep we inherited freeze protection from submission
2553 if (req->flags & REQ_F_ISREG) {
2554 struct super_block *sb = file_inode(req->file)->i_sb;
2556 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2562 static bool io_resubmit_prep(struct io_kiocb *req)
2564 struct io_async_rw *rw = req->async_data;
2567 return !io_req_prep_async(req);
2568 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2569 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2573 static bool io_rw_should_reissue(struct io_kiocb *req)
2575 umode_t mode = file_inode(req->file)->i_mode;
2576 struct io_ring_ctx *ctx = req->ctx;
2578 if (!S_ISBLK(mode) && !S_ISREG(mode))
2580 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2581 !(ctx->flags & IORING_SETUP_IOPOLL)))
2584 * If ref is dying, we might be running poll reap from the exit work.
2585 * Don't attempt to reissue from that path, just let it fail with
2588 if (percpu_ref_is_dying(&ctx->refs))
2591 * Play it safe and assume not safe to re-import and reissue if we're
2592 * not in the original thread group (or in task context).
2594 if (!same_thread_group(req->task, current) || !in_task())
2599 static bool io_resubmit_prep(struct io_kiocb *req)
2603 static bool io_rw_should_reissue(struct io_kiocb *req)
2609 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2611 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2612 kiocb_end_write(req);
2613 if (res != req->result) {
2614 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2615 io_rw_should_reissue(req)) {
2616 req->flags |= REQ_F_REISSUE;
2625 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2627 unsigned int cflags = io_put_rw_kbuf(req);
2628 long res = req->result;
2631 struct io_ring_ctx *ctx = req->ctx;
2632 struct io_submit_state *state = &ctx->submit_state;
2634 io_req_complete_state(req, res, cflags);
2635 state->compl_reqs[state->compl_nr++] = req;
2636 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2637 io_submit_flush_completions(ctx);
2639 io_req_complete_post(req, res, cflags);
2643 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2644 unsigned int issue_flags)
2646 if (__io_complete_rw_common(req, res))
2648 __io_req_complete(req, 0, req->result, io_put_rw_kbuf(req));
2651 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2653 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2655 if (__io_complete_rw_common(req, res))
2658 req->io_task_work.func = io_req_task_complete;
2659 io_req_task_work_add(req);
2662 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2664 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2666 if (kiocb->ki_flags & IOCB_WRITE)
2667 kiocb_end_write(req);
2668 if (unlikely(res != req->result)) {
2669 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2670 io_resubmit_prep(req))) {
2672 req->flags |= REQ_F_DONT_REISSUE;
2676 WRITE_ONCE(req->result, res);
2677 /* order with io_iopoll_complete() checking ->result */
2679 WRITE_ONCE(req->iopoll_completed, 1);
2683 * After the iocb has been issued, it's safe to be found on the poll list.
2684 * Adding the kiocb to the list AFTER submission ensures that we don't
2685 * find it from a io_do_iopoll() thread before the issuer is done
2686 * accessing the kiocb cookie.
2688 static void io_iopoll_req_issued(struct io_kiocb *req)
2690 struct io_ring_ctx *ctx = req->ctx;
2691 const bool in_async = io_wq_current_is_worker();
2693 /* workqueue context doesn't hold uring_lock, grab it now */
2694 if (unlikely(in_async))
2695 mutex_lock(&ctx->uring_lock);
2698 * Track whether we have multiple files in our lists. This will impact
2699 * how we do polling eventually, not spinning if we're on potentially
2700 * different devices.
2702 if (list_empty(&ctx->iopoll_list)) {
2703 ctx->poll_multi_queue = false;
2704 } else if (!ctx->poll_multi_queue) {
2705 struct io_kiocb *list_req;
2706 unsigned int queue_num0, queue_num1;
2708 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2711 if (list_req->file != req->file) {
2712 ctx->poll_multi_queue = true;
2714 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2715 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2716 if (queue_num0 != queue_num1)
2717 ctx->poll_multi_queue = true;
2722 * For fast devices, IO may have already completed. If it has, add
2723 * it to the front so we find it first.
2725 if (READ_ONCE(req->iopoll_completed))
2726 list_add(&req->inflight_entry, &ctx->iopoll_list);
2728 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2730 if (unlikely(in_async)) {
2732 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2733 * in sq thread task context or in io worker task context. If
2734 * current task context is sq thread, we don't need to check
2735 * whether should wake up sq thread.
2737 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2738 wq_has_sleeper(&ctx->sq_data->wait))
2739 wake_up(&ctx->sq_data->wait);
2741 mutex_unlock(&ctx->uring_lock);
2745 static bool io_bdev_nowait(struct block_device *bdev)
2747 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2751 * If we tracked the file through the SCM inflight mechanism, we could support
2752 * any file. For now, just ensure that anything potentially problematic is done
2755 static bool __io_file_supports_nowait(struct file *file, int rw)
2757 umode_t mode = file_inode(file)->i_mode;
2759 if (S_ISBLK(mode)) {
2760 if (IS_ENABLED(CONFIG_BLOCK) &&
2761 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2767 if (S_ISREG(mode)) {
2768 if (IS_ENABLED(CONFIG_BLOCK) &&
2769 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2770 file->f_op != &io_uring_fops)
2775 /* any ->read/write should understand O_NONBLOCK */
2776 if (file->f_flags & O_NONBLOCK)
2779 if (!(file->f_mode & FMODE_NOWAIT))
2783 return file->f_op->read_iter != NULL;
2785 return file->f_op->write_iter != NULL;
2788 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2790 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2792 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2795 return __io_file_supports_nowait(req->file, rw);
2798 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2800 struct io_ring_ctx *ctx = req->ctx;
2801 struct kiocb *kiocb = &req->rw.kiocb;
2802 struct file *file = req->file;
2806 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2807 req->flags |= REQ_F_ISREG;
2809 kiocb->ki_pos = READ_ONCE(sqe->off);
2810 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2811 req->flags |= REQ_F_CUR_POS;
2812 kiocb->ki_pos = file->f_pos;
2814 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2815 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2816 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2820 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2821 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2822 req->flags |= REQ_F_NOWAIT;
2824 ioprio = READ_ONCE(sqe->ioprio);
2826 ret = ioprio_check_cap(ioprio);
2830 kiocb->ki_ioprio = ioprio;
2832 kiocb->ki_ioprio = get_current_ioprio();
2834 if (ctx->flags & IORING_SETUP_IOPOLL) {
2835 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2836 !kiocb->ki_filp->f_op->iopoll)
2839 kiocb->ki_flags |= IOCB_HIPRI;
2840 kiocb->ki_complete = io_complete_rw_iopoll;
2841 req->iopoll_completed = 0;
2843 if (kiocb->ki_flags & IOCB_HIPRI)
2845 kiocb->ki_complete = io_complete_rw;
2848 if (req->opcode == IORING_OP_READ_FIXED ||
2849 req->opcode == IORING_OP_WRITE_FIXED) {
2851 io_req_set_rsrc_node(req);
2854 req->rw.addr = READ_ONCE(sqe->addr);
2855 req->rw.len = READ_ONCE(sqe->len);
2856 req->buf_index = READ_ONCE(sqe->buf_index);
2860 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2866 case -ERESTARTNOINTR:
2867 case -ERESTARTNOHAND:
2868 case -ERESTART_RESTARTBLOCK:
2870 * We can't just restart the syscall, since previously
2871 * submitted sqes may already be in progress. Just fail this
2877 kiocb->ki_complete(kiocb, ret, 0);
2881 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2882 unsigned int issue_flags)
2884 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2885 struct io_async_rw *io = req->async_data;
2886 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2888 /* add previously done IO, if any */
2889 if (io && io->bytes_done > 0) {
2891 ret = io->bytes_done;
2893 ret += io->bytes_done;
2896 if (req->flags & REQ_F_CUR_POS)
2897 req->file->f_pos = kiocb->ki_pos;
2898 if (ret >= 0 && check_reissue)
2899 __io_complete_rw(req, ret, 0, issue_flags);
2901 io_rw_done(kiocb, ret);
2903 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2904 req->flags &= ~REQ_F_REISSUE;
2905 if (io_resubmit_prep(req)) {
2906 io_req_task_queue_reissue(req);
2909 __io_req_complete(req, issue_flags, ret,
2910 io_put_rw_kbuf(req));
2915 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2916 struct io_mapped_ubuf *imu)
2918 size_t len = req->rw.len;
2919 u64 buf_end, buf_addr = req->rw.addr;
2922 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2924 /* not inside the mapped region */
2925 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2929 * May not be a start of buffer, set size appropriately
2930 * and advance us to the beginning.
2932 offset = buf_addr - imu->ubuf;
2933 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2937 * Don't use iov_iter_advance() here, as it's really slow for
2938 * using the latter parts of a big fixed buffer - it iterates
2939 * over each segment manually. We can cheat a bit here, because
2942 * 1) it's a BVEC iter, we set it up
2943 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2944 * first and last bvec
2946 * So just find our index, and adjust the iterator afterwards.
2947 * If the offset is within the first bvec (or the whole first
2948 * bvec, just use iov_iter_advance(). This makes it easier
2949 * since we can just skip the first segment, which may not
2950 * be PAGE_SIZE aligned.
2952 const struct bio_vec *bvec = imu->bvec;
2954 if (offset <= bvec->bv_len) {
2955 iov_iter_advance(iter, offset);
2957 unsigned long seg_skip;
2959 /* skip first vec */
2960 offset -= bvec->bv_len;
2961 seg_skip = 1 + (offset >> PAGE_SHIFT);
2963 iter->bvec = bvec + seg_skip;
2964 iter->nr_segs -= seg_skip;
2965 iter->count -= bvec->bv_len + offset;
2966 iter->iov_offset = offset & ~PAGE_MASK;
2973 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2975 struct io_ring_ctx *ctx = req->ctx;
2976 struct io_mapped_ubuf *imu = req->imu;
2977 u16 index, buf_index = req->buf_index;
2980 if (unlikely(buf_index >= ctx->nr_user_bufs))
2982 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2983 imu = READ_ONCE(ctx->user_bufs[index]);
2986 return __io_import_fixed(req, rw, iter, imu);
2989 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2992 mutex_unlock(&ctx->uring_lock);
2995 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2998 * "Normal" inline submissions always hold the uring_lock, since we
2999 * grab it from the system call. Same is true for the SQPOLL offload.
3000 * The only exception is when we've detached the request and issue it
3001 * from an async worker thread, grab the lock for that case.
3004 mutex_lock(&ctx->uring_lock);
3007 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3008 int bgid, struct io_buffer *kbuf,
3011 struct io_buffer *head;
3013 if (req->flags & REQ_F_BUFFER_SELECTED)
3016 io_ring_submit_lock(req->ctx, needs_lock);
3018 lockdep_assert_held(&req->ctx->uring_lock);
3020 head = xa_load(&req->ctx->io_buffers, bgid);
3022 if (!list_empty(&head->list)) {
3023 kbuf = list_last_entry(&head->list, struct io_buffer,
3025 list_del(&kbuf->list);
3028 xa_erase(&req->ctx->io_buffers, bgid);
3030 if (*len > kbuf->len)
3033 kbuf = ERR_PTR(-ENOBUFS);
3036 io_ring_submit_unlock(req->ctx, needs_lock);
3041 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3044 struct io_buffer *kbuf;
3047 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3048 bgid = req->buf_index;
3049 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3052 req->rw.addr = (u64) (unsigned long) kbuf;
3053 req->flags |= REQ_F_BUFFER_SELECTED;
3054 return u64_to_user_ptr(kbuf->addr);
3057 #ifdef CONFIG_COMPAT
3058 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3061 struct compat_iovec __user *uiov;
3062 compat_ssize_t clen;
3066 uiov = u64_to_user_ptr(req->rw.addr);
3067 if (!access_ok(uiov, sizeof(*uiov)))
3069 if (__get_user(clen, &uiov->iov_len))
3075 buf = io_rw_buffer_select(req, &len, needs_lock);
3077 return PTR_ERR(buf);
3078 iov[0].iov_base = buf;
3079 iov[0].iov_len = (compat_size_t) len;
3084 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3087 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3091 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3094 len = iov[0].iov_len;
3097 buf = io_rw_buffer_select(req, &len, needs_lock);
3099 return PTR_ERR(buf);
3100 iov[0].iov_base = buf;
3101 iov[0].iov_len = len;
3105 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3108 if (req->flags & REQ_F_BUFFER_SELECTED) {
3109 struct io_buffer *kbuf;
3111 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3112 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3113 iov[0].iov_len = kbuf->len;
3116 if (req->rw.len != 1)
3119 #ifdef CONFIG_COMPAT
3120 if (req->ctx->compat)
3121 return io_compat_import(req, iov, needs_lock);
3124 return __io_iov_buffer_select(req, iov, needs_lock);
3127 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3128 struct iov_iter *iter, bool needs_lock)
3130 void __user *buf = u64_to_user_ptr(req->rw.addr);
3131 size_t sqe_len = req->rw.len;
3132 u8 opcode = req->opcode;
3135 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3137 return io_import_fixed(req, rw, iter);
3140 /* buffer index only valid with fixed read/write, or buffer select */
3141 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3144 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3145 if (req->flags & REQ_F_BUFFER_SELECT) {
3146 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3148 return PTR_ERR(buf);
3149 req->rw.len = sqe_len;
3152 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3157 if (req->flags & REQ_F_BUFFER_SELECT) {
3158 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3160 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3165 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3169 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3171 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3175 * For files that don't have ->read_iter() and ->write_iter(), handle them
3176 * by looping over ->read() or ->write() manually.
3178 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3180 struct kiocb *kiocb = &req->rw.kiocb;
3181 struct file *file = req->file;
3185 * Don't support polled IO through this interface, and we can't
3186 * support non-blocking either. For the latter, this just causes
3187 * the kiocb to be handled from an async context.
3189 if (kiocb->ki_flags & IOCB_HIPRI)
3191 if (kiocb->ki_flags & IOCB_NOWAIT)
3194 while (iov_iter_count(iter)) {
3198 if (!iov_iter_is_bvec(iter)) {
3199 iovec = iov_iter_iovec(iter);
3201 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3202 iovec.iov_len = req->rw.len;
3206 nr = file->f_op->read(file, iovec.iov_base,
3207 iovec.iov_len, io_kiocb_ppos(kiocb));
3209 nr = file->f_op->write(file, iovec.iov_base,
3210 iovec.iov_len, io_kiocb_ppos(kiocb));
3219 if (nr != iovec.iov_len)
3223 iov_iter_advance(iter, nr);
3229 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3230 const struct iovec *fast_iov, struct iov_iter *iter)
3232 struct io_async_rw *rw = req->async_data;
3234 memcpy(&rw->iter, iter, sizeof(*iter));
3235 rw->free_iovec = iovec;
3237 /* can only be fixed buffers, no need to do anything */
3238 if (iov_iter_is_bvec(iter))
3241 unsigned iov_off = 0;
3243 rw->iter.iov = rw->fast_iov;
3244 if (iter->iov != fast_iov) {
3245 iov_off = iter->iov - fast_iov;
3246 rw->iter.iov += iov_off;
3248 if (rw->fast_iov != fast_iov)
3249 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3250 sizeof(struct iovec) * iter->nr_segs);
3252 req->flags |= REQ_F_NEED_CLEANUP;
3256 static inline int io_alloc_async_data(struct io_kiocb *req)
3258 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3259 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3260 return req->async_data == NULL;
3263 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3264 const struct iovec *fast_iov,
3265 struct iov_iter *iter, bool force)
3267 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3269 if (!req->async_data) {
3270 if (io_alloc_async_data(req)) {
3275 io_req_map_rw(req, iovec, fast_iov, iter);
3280 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3282 struct io_async_rw *iorw = req->async_data;
3283 struct iovec *iov = iorw->fast_iov;
3286 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3287 if (unlikely(ret < 0))
3290 iorw->bytes_done = 0;
3291 iorw->free_iovec = iov;
3293 req->flags |= REQ_F_NEED_CLEANUP;
3297 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3299 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3301 return io_prep_rw(req, sqe);
3305 * This is our waitqueue callback handler, registered through lock_page_async()
3306 * when we initially tried to do the IO with the iocb armed our waitqueue.
3307 * This gets called when the page is unlocked, and we generally expect that to
3308 * happen when the page IO is completed and the page is now uptodate. This will
3309 * queue a task_work based retry of the operation, attempting to copy the data
3310 * again. If the latter fails because the page was NOT uptodate, then we will
3311 * do a thread based blocking retry of the operation. That's the unexpected
3314 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3315 int sync, void *arg)
3317 struct wait_page_queue *wpq;
3318 struct io_kiocb *req = wait->private;
3319 struct wait_page_key *key = arg;
3321 wpq = container_of(wait, struct wait_page_queue, wait);
3323 if (!wake_page_match(wpq, key))
3326 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3327 list_del_init(&wait->entry);
3328 io_req_task_queue(req);
3333 * This controls whether a given IO request should be armed for async page
3334 * based retry. If we return false here, the request is handed to the async
3335 * worker threads for retry. If we're doing buffered reads on a regular file,
3336 * we prepare a private wait_page_queue entry and retry the operation. This
3337 * will either succeed because the page is now uptodate and unlocked, or it
3338 * will register a callback when the page is unlocked at IO completion. Through
3339 * that callback, io_uring uses task_work to setup a retry of the operation.
3340 * That retry will attempt the buffered read again. The retry will generally
3341 * succeed, or in rare cases where it fails, we then fall back to using the
3342 * async worker threads for a blocking retry.
3344 static bool io_rw_should_retry(struct io_kiocb *req)
3346 struct io_async_rw *rw = req->async_data;
3347 struct wait_page_queue *wait = &rw->wpq;
3348 struct kiocb *kiocb = &req->rw.kiocb;
3350 /* never retry for NOWAIT, we just complete with -EAGAIN */
3351 if (req->flags & REQ_F_NOWAIT)
3354 /* Only for buffered IO */
3355 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3359 * just use poll if we can, and don't attempt if the fs doesn't
3360 * support callback based unlocks
3362 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3365 wait->wait.func = io_async_buf_func;
3366 wait->wait.private = req;
3367 wait->wait.flags = 0;
3368 INIT_LIST_HEAD(&wait->wait.entry);
3369 kiocb->ki_flags |= IOCB_WAITQ;
3370 kiocb->ki_flags &= ~IOCB_NOWAIT;
3371 kiocb->ki_waitq = wait;
3375 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3377 if (req->file->f_op->read_iter)
3378 return call_read_iter(req->file, &req->rw.kiocb, iter);
3379 else if (req->file->f_op->read)
3380 return loop_rw_iter(READ, req, iter);
3385 static bool need_read_all(struct io_kiocb *req)
3387 return req->flags & REQ_F_ISREG ||
3388 S_ISBLK(file_inode(req->file)->i_mode);
3391 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3393 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3394 struct kiocb *kiocb = &req->rw.kiocb;
3395 struct iov_iter __iter, *iter = &__iter;
3396 struct io_async_rw *rw = req->async_data;
3397 ssize_t io_size, ret, ret2;
3398 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3404 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3408 io_size = iov_iter_count(iter);
3409 req->result = io_size;
3411 /* Ensure we clear previously set non-block flag */
3412 if (!force_nonblock)
3413 kiocb->ki_flags &= ~IOCB_NOWAIT;
3415 kiocb->ki_flags |= IOCB_NOWAIT;
3417 /* If the file doesn't support async, just async punt */
3418 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3419 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3420 return ret ?: -EAGAIN;
3423 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3424 if (unlikely(ret)) {
3429 ret = io_iter_do_read(req, iter);
3431 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3432 req->flags &= ~REQ_F_REISSUE;
3433 /* IOPOLL retry should happen for io-wq threads */
3434 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3436 /* no retry on NONBLOCK nor RWF_NOWAIT */
3437 if (req->flags & REQ_F_NOWAIT)
3439 /* some cases will consume bytes even on error returns */
3440 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3442 } else if (ret == -EIOCBQUEUED) {
3444 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3445 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3446 /* read all, failed, already did sync or don't want to retry */
3450 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3455 rw = req->async_data;
3456 /* now use our persistent iterator, if we aren't already */
3461 rw->bytes_done += ret;
3462 /* if we can retry, do so with the callbacks armed */
3463 if (!io_rw_should_retry(req)) {
3464 kiocb->ki_flags &= ~IOCB_WAITQ;
3469 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3470 * we get -EIOCBQUEUED, then we'll get a notification when the
3471 * desired page gets unlocked. We can also get a partial read
3472 * here, and if we do, then just retry at the new offset.
3474 ret = io_iter_do_read(req, iter);
3475 if (ret == -EIOCBQUEUED)
3477 /* we got some bytes, but not all. retry. */
3478 kiocb->ki_flags &= ~IOCB_WAITQ;
3479 } while (ret > 0 && ret < io_size);
3481 kiocb_done(kiocb, ret, issue_flags);
3483 /* it's faster to check here then delegate to kfree */
3489 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3491 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3493 return io_prep_rw(req, sqe);
3496 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3498 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3499 struct kiocb *kiocb = &req->rw.kiocb;
3500 struct iov_iter __iter, *iter = &__iter;
3501 struct io_async_rw *rw = req->async_data;
3502 ssize_t ret, ret2, io_size;
3503 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3509 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3513 io_size = iov_iter_count(iter);
3514 req->result = io_size;
3516 /* Ensure we clear previously set non-block flag */
3517 if (!force_nonblock)
3518 kiocb->ki_flags &= ~IOCB_NOWAIT;
3520 kiocb->ki_flags |= IOCB_NOWAIT;
3522 /* If the file doesn't support async, just async punt */
3523 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3526 /* file path doesn't support NOWAIT for non-direct_IO */
3527 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3528 (req->flags & REQ_F_ISREG))
3531 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3536 * Open-code file_start_write here to grab freeze protection,
3537 * which will be released by another thread in
3538 * io_complete_rw(). Fool lockdep by telling it the lock got
3539 * released so that it doesn't complain about the held lock when
3540 * we return to userspace.
3542 if (req->flags & REQ_F_ISREG) {
3543 sb_start_write(file_inode(req->file)->i_sb);
3544 __sb_writers_release(file_inode(req->file)->i_sb,
3547 kiocb->ki_flags |= IOCB_WRITE;
3549 if (req->file->f_op->write_iter)
3550 ret2 = call_write_iter(req->file, kiocb, iter);
3551 else if (req->file->f_op->write)
3552 ret2 = loop_rw_iter(WRITE, req, iter);
3556 if (req->flags & REQ_F_REISSUE) {
3557 req->flags &= ~REQ_F_REISSUE;
3562 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3563 * retry them without IOCB_NOWAIT.
3565 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3567 /* no retry on NONBLOCK nor RWF_NOWAIT */
3568 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3570 if (!force_nonblock || ret2 != -EAGAIN) {
3571 /* IOPOLL retry should happen for io-wq threads */
3572 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3575 kiocb_done(kiocb, ret2, issue_flags);
3578 /* some cases will consume bytes even on error returns */
3579 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3580 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3581 return ret ?: -EAGAIN;
3584 /* it's reportedly faster than delegating the null check to kfree() */
3590 static int io_renameat_prep(struct io_kiocb *req,
3591 const struct io_uring_sqe *sqe)
3593 struct io_rename *ren = &req->rename;
3594 const char __user *oldf, *newf;
3596 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3598 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3600 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3603 ren->old_dfd = READ_ONCE(sqe->fd);
3604 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3605 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3606 ren->new_dfd = READ_ONCE(sqe->len);
3607 ren->flags = READ_ONCE(sqe->rename_flags);
3609 ren->oldpath = getname(oldf);
3610 if (IS_ERR(ren->oldpath))
3611 return PTR_ERR(ren->oldpath);
3613 ren->newpath = getname(newf);
3614 if (IS_ERR(ren->newpath)) {
3615 putname(ren->oldpath);
3616 return PTR_ERR(ren->newpath);
3619 req->flags |= REQ_F_NEED_CLEANUP;
3623 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3625 struct io_rename *ren = &req->rename;
3628 if (issue_flags & IO_URING_F_NONBLOCK)
3631 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3632 ren->newpath, ren->flags);
3634 req->flags &= ~REQ_F_NEED_CLEANUP;
3637 io_req_complete(req, ret);
3641 static int io_unlinkat_prep(struct io_kiocb *req,
3642 const struct io_uring_sqe *sqe)
3644 struct io_unlink *un = &req->unlink;
3645 const char __user *fname;
3647 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3649 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3652 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3655 un->dfd = READ_ONCE(sqe->fd);
3657 un->flags = READ_ONCE(sqe->unlink_flags);
3658 if (un->flags & ~AT_REMOVEDIR)
3661 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3662 un->filename = getname(fname);
3663 if (IS_ERR(un->filename))
3664 return PTR_ERR(un->filename);
3666 req->flags |= REQ_F_NEED_CLEANUP;
3670 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3672 struct io_unlink *un = &req->unlink;
3675 if (issue_flags & IO_URING_F_NONBLOCK)
3678 if (un->flags & AT_REMOVEDIR)
3679 ret = do_rmdir(un->dfd, un->filename);
3681 ret = do_unlinkat(un->dfd, un->filename);
3683 req->flags &= ~REQ_F_NEED_CLEANUP;
3686 io_req_complete(req, ret);
3690 static int io_shutdown_prep(struct io_kiocb *req,
3691 const struct io_uring_sqe *sqe)
3693 #if defined(CONFIG_NET)
3694 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3696 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3697 sqe->buf_index || sqe->splice_fd_in))
3700 req->shutdown.how = READ_ONCE(sqe->len);
3707 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3709 #if defined(CONFIG_NET)
3710 struct socket *sock;
3713 if (issue_flags & IO_URING_F_NONBLOCK)
3716 sock = sock_from_file(req->file);
3717 if (unlikely(!sock))
3720 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3723 io_req_complete(req, ret);
3730 static int __io_splice_prep(struct io_kiocb *req,
3731 const struct io_uring_sqe *sqe)
3733 struct io_splice *sp = &req->splice;
3734 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3736 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3740 sp->len = READ_ONCE(sqe->len);
3741 sp->flags = READ_ONCE(sqe->splice_flags);
3743 if (unlikely(sp->flags & ~valid_flags))
3746 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3747 (sp->flags & SPLICE_F_FD_IN_FIXED));
3750 req->flags |= REQ_F_NEED_CLEANUP;
3754 static int io_tee_prep(struct io_kiocb *req,
3755 const struct io_uring_sqe *sqe)
3757 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3759 return __io_splice_prep(req, sqe);
3762 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3764 struct io_splice *sp = &req->splice;
3765 struct file *in = sp->file_in;
3766 struct file *out = sp->file_out;
3767 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3770 if (issue_flags & IO_URING_F_NONBLOCK)
3773 ret = do_tee(in, out, sp->len, flags);
3775 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3777 req->flags &= ~REQ_F_NEED_CLEANUP;
3781 io_req_complete(req, ret);
3785 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3787 struct io_splice *sp = &req->splice;
3789 sp->off_in = READ_ONCE(sqe->splice_off_in);
3790 sp->off_out = READ_ONCE(sqe->off);
3791 return __io_splice_prep(req, sqe);
3794 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3796 struct io_splice *sp = &req->splice;
3797 struct file *in = sp->file_in;
3798 struct file *out = sp->file_out;
3799 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3800 loff_t *poff_in, *poff_out;
3803 if (issue_flags & IO_URING_F_NONBLOCK)
3806 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3807 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3810 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3812 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3814 req->flags &= ~REQ_F_NEED_CLEANUP;
3818 io_req_complete(req, ret);
3823 * IORING_OP_NOP just posts a completion event, nothing else.
3825 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3827 struct io_ring_ctx *ctx = req->ctx;
3829 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3832 __io_req_complete(req, issue_flags, 0, 0);
3836 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3838 struct io_ring_ctx *ctx = req->ctx;
3843 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3845 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
3849 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3850 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3853 req->sync.off = READ_ONCE(sqe->off);
3854 req->sync.len = READ_ONCE(sqe->len);
3858 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3860 loff_t end = req->sync.off + req->sync.len;
3863 /* fsync always requires a blocking context */
3864 if (issue_flags & IO_URING_F_NONBLOCK)
3867 ret = vfs_fsync_range(req->file, req->sync.off,
3868 end > 0 ? end : LLONG_MAX,
3869 req->sync.flags & IORING_FSYNC_DATASYNC);
3872 io_req_complete(req, ret);
3876 static int io_fallocate_prep(struct io_kiocb *req,
3877 const struct io_uring_sqe *sqe)
3879 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
3882 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3885 req->sync.off = READ_ONCE(sqe->off);
3886 req->sync.len = READ_ONCE(sqe->addr);
3887 req->sync.mode = READ_ONCE(sqe->len);
3891 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3895 /* fallocate always requiring blocking context */
3896 if (issue_flags & IO_URING_F_NONBLOCK)
3898 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3902 io_req_complete(req, ret);
3906 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3908 const char __user *fname;
3911 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3913 if (unlikely(sqe->ioprio || sqe->buf_index))
3915 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3918 /* open.how should be already initialised */
3919 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3920 req->open.how.flags |= O_LARGEFILE;
3922 req->open.dfd = READ_ONCE(sqe->fd);
3923 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3924 req->open.filename = getname(fname);
3925 if (IS_ERR(req->open.filename)) {
3926 ret = PTR_ERR(req->open.filename);
3927 req->open.filename = NULL;
3931 req->open.file_slot = READ_ONCE(sqe->file_index);
3932 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
3935 req->open.nofile = rlimit(RLIMIT_NOFILE);
3936 req->flags |= REQ_F_NEED_CLEANUP;
3940 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3942 u64 mode = READ_ONCE(sqe->len);
3943 u64 flags = READ_ONCE(sqe->open_flags);
3945 req->open.how = build_open_how(flags, mode);
3946 return __io_openat_prep(req, sqe);
3949 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3951 struct open_how __user *how;
3955 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3956 len = READ_ONCE(sqe->len);
3957 if (len < OPEN_HOW_SIZE_VER0)
3960 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3965 return __io_openat_prep(req, sqe);
3968 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3970 struct open_flags op;
3972 bool resolve_nonblock, nonblock_set;
3973 bool fixed = !!req->open.file_slot;
3976 ret = build_open_flags(&req->open.how, &op);
3979 nonblock_set = op.open_flag & O_NONBLOCK;
3980 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3981 if (issue_flags & IO_URING_F_NONBLOCK) {
3983 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3984 * it'll always -EAGAIN
3986 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3988 op.lookup_flags |= LOOKUP_CACHED;
3989 op.open_flag |= O_NONBLOCK;
3993 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3998 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4001 * We could hang on to this 'fd' on retrying, but seems like
4002 * marginal gain for something that is now known to be a slower
4003 * path. So just put it, and we'll get a new one when we retry.
4008 ret = PTR_ERR(file);
4009 /* only retry if RESOLVE_CACHED wasn't already set by application */
4010 if (ret == -EAGAIN &&
4011 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4016 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4017 file->f_flags &= ~O_NONBLOCK;
4018 fsnotify_open(file);
4021 fd_install(ret, file);
4023 ret = io_install_fixed_file(req, file, issue_flags,
4024 req->open.file_slot - 1);
4026 putname(req->open.filename);
4027 req->flags &= ~REQ_F_NEED_CLEANUP;
4030 __io_req_complete(req, issue_flags, ret, 0);
4034 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4036 return io_openat2(req, issue_flags);
4039 static int io_remove_buffers_prep(struct io_kiocb *req,
4040 const struct io_uring_sqe *sqe)
4042 struct io_provide_buf *p = &req->pbuf;
4045 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4049 tmp = READ_ONCE(sqe->fd);
4050 if (!tmp || tmp > USHRT_MAX)
4053 memset(p, 0, sizeof(*p));
4055 p->bgid = READ_ONCE(sqe->buf_group);
4059 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4060 int bgid, unsigned nbufs)
4064 /* shouldn't happen */
4068 /* the head kbuf is the list itself */
4069 while (!list_empty(&buf->list)) {
4070 struct io_buffer *nxt;
4072 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4073 list_del(&nxt->list);
4080 xa_erase(&ctx->io_buffers, bgid);
4085 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4087 struct io_provide_buf *p = &req->pbuf;
4088 struct io_ring_ctx *ctx = req->ctx;
4089 struct io_buffer *head;
4091 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4093 io_ring_submit_lock(ctx, !force_nonblock);
4095 lockdep_assert_held(&ctx->uring_lock);
4098 head = xa_load(&ctx->io_buffers, p->bgid);
4100 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4104 /* complete before unlock, IOPOLL may need the lock */
4105 __io_req_complete(req, issue_flags, ret, 0);
4106 io_ring_submit_unlock(ctx, !force_nonblock);
4110 static int io_provide_buffers_prep(struct io_kiocb *req,
4111 const struct io_uring_sqe *sqe)
4113 unsigned long size, tmp_check;
4114 struct io_provide_buf *p = &req->pbuf;
4117 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4120 tmp = READ_ONCE(sqe->fd);
4121 if (!tmp || tmp > USHRT_MAX)
4124 p->addr = READ_ONCE(sqe->addr);
4125 p->len = READ_ONCE(sqe->len);
4127 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4130 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4133 size = (unsigned long)p->len * p->nbufs;
4134 if (!access_ok(u64_to_user_ptr(p->addr), size))
4137 p->bgid = READ_ONCE(sqe->buf_group);
4138 tmp = READ_ONCE(sqe->off);
4139 if (tmp > USHRT_MAX)
4145 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4147 struct io_buffer *buf;
4148 u64 addr = pbuf->addr;
4149 int i, bid = pbuf->bid;
4151 for (i = 0; i < pbuf->nbufs; i++) {
4152 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4157 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4162 INIT_LIST_HEAD(&buf->list);
4165 list_add_tail(&buf->list, &(*head)->list);
4169 return i ? i : -ENOMEM;
4172 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4174 struct io_provide_buf *p = &req->pbuf;
4175 struct io_ring_ctx *ctx = req->ctx;
4176 struct io_buffer *head, *list;
4178 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4180 io_ring_submit_lock(ctx, !force_nonblock);
4182 lockdep_assert_held(&ctx->uring_lock);
4184 list = head = xa_load(&ctx->io_buffers, p->bgid);
4186 ret = io_add_buffers(p, &head);
4187 if (ret >= 0 && !list) {
4188 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4190 __io_remove_buffers(ctx, head, p->bgid, -1U);
4194 /* complete before unlock, IOPOLL may need the lock */
4195 __io_req_complete(req, issue_flags, ret, 0);
4196 io_ring_submit_unlock(ctx, !force_nonblock);
4200 static int io_epoll_ctl_prep(struct io_kiocb *req,
4201 const struct io_uring_sqe *sqe)
4203 #if defined(CONFIG_EPOLL)
4204 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4206 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4209 req->epoll.epfd = READ_ONCE(sqe->fd);
4210 req->epoll.op = READ_ONCE(sqe->len);
4211 req->epoll.fd = READ_ONCE(sqe->off);
4213 if (ep_op_has_event(req->epoll.op)) {
4214 struct epoll_event __user *ev;
4216 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4217 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4227 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4229 #if defined(CONFIG_EPOLL)
4230 struct io_epoll *ie = &req->epoll;
4232 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4234 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4235 if (force_nonblock && ret == -EAGAIN)
4240 __io_req_complete(req, issue_flags, ret, 0);
4247 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4249 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4250 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4252 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4255 req->madvise.addr = READ_ONCE(sqe->addr);
4256 req->madvise.len = READ_ONCE(sqe->len);
4257 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4264 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4266 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4267 struct io_madvise *ma = &req->madvise;
4270 if (issue_flags & IO_URING_F_NONBLOCK)
4273 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4276 io_req_complete(req, ret);
4283 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4285 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4287 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4290 req->fadvise.offset = READ_ONCE(sqe->off);
4291 req->fadvise.len = READ_ONCE(sqe->len);
4292 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4296 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4298 struct io_fadvise *fa = &req->fadvise;
4301 if (issue_flags & IO_URING_F_NONBLOCK) {
4302 switch (fa->advice) {
4303 case POSIX_FADV_NORMAL:
4304 case POSIX_FADV_RANDOM:
4305 case POSIX_FADV_SEQUENTIAL:
4312 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4315 __io_req_complete(req, issue_flags, ret, 0);
4319 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4321 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4323 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4325 if (req->flags & REQ_F_FIXED_FILE)
4328 req->statx.dfd = READ_ONCE(sqe->fd);
4329 req->statx.mask = READ_ONCE(sqe->len);
4330 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4331 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4332 req->statx.flags = READ_ONCE(sqe->statx_flags);
4337 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4339 struct io_statx *ctx = &req->statx;
4342 if (issue_flags & IO_URING_F_NONBLOCK)
4345 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4350 io_req_complete(req, ret);
4354 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4356 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4358 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4359 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4361 if (req->flags & REQ_F_FIXED_FILE)
4364 req->close.fd = READ_ONCE(sqe->fd);
4368 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4370 struct files_struct *files = current->files;
4371 struct io_close *close = &req->close;
4372 struct fdtable *fdt;
4373 struct file *file = NULL;
4376 spin_lock(&files->file_lock);
4377 fdt = files_fdtable(files);
4378 if (close->fd >= fdt->max_fds) {
4379 spin_unlock(&files->file_lock);
4382 file = fdt->fd[close->fd];
4383 if (!file || file->f_op == &io_uring_fops) {
4384 spin_unlock(&files->file_lock);
4389 /* if the file has a flush method, be safe and punt to async */
4390 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4391 spin_unlock(&files->file_lock);
4395 ret = __close_fd_get_file(close->fd, &file);
4396 spin_unlock(&files->file_lock);
4403 /* No ->flush() or already async, safely close from here */
4404 ret = filp_close(file, current->files);
4410 __io_req_complete(req, issue_flags, ret, 0);
4414 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4416 struct io_ring_ctx *ctx = req->ctx;
4418 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4420 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4424 req->sync.off = READ_ONCE(sqe->off);
4425 req->sync.len = READ_ONCE(sqe->len);
4426 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4430 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4434 /* sync_file_range always requires a blocking context */
4435 if (issue_flags & IO_URING_F_NONBLOCK)
4438 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4442 io_req_complete(req, ret);
4446 #if defined(CONFIG_NET)
4447 static int io_setup_async_msg(struct io_kiocb *req,
4448 struct io_async_msghdr *kmsg)
4450 struct io_async_msghdr *async_msg = req->async_data;
4454 if (io_alloc_async_data(req)) {
4455 kfree(kmsg->free_iov);
4458 async_msg = req->async_data;
4459 req->flags |= REQ_F_NEED_CLEANUP;
4460 memcpy(async_msg, kmsg, sizeof(*kmsg));
4461 async_msg->msg.msg_name = &async_msg->addr;
4462 /* if were using fast_iov, set it to the new one */
4463 if (!async_msg->free_iov)
4464 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4469 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4470 struct io_async_msghdr *iomsg)
4472 iomsg->msg.msg_name = &iomsg->addr;
4473 iomsg->free_iov = iomsg->fast_iov;
4474 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4475 req->sr_msg.msg_flags, &iomsg->free_iov);
4478 static int io_sendmsg_prep_async(struct io_kiocb *req)
4482 ret = io_sendmsg_copy_hdr(req, req->async_data);
4484 req->flags |= REQ_F_NEED_CLEANUP;
4488 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4490 struct io_sr_msg *sr = &req->sr_msg;
4492 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4495 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4496 sr->len = READ_ONCE(sqe->len);
4497 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4498 if (sr->msg_flags & MSG_DONTWAIT)
4499 req->flags |= REQ_F_NOWAIT;
4501 #ifdef CONFIG_COMPAT
4502 if (req->ctx->compat)
4503 sr->msg_flags |= MSG_CMSG_COMPAT;
4508 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4510 struct io_async_msghdr iomsg, *kmsg;
4511 struct socket *sock;
4516 sock = sock_from_file(req->file);
4517 if (unlikely(!sock))
4520 kmsg = req->async_data;
4522 ret = io_sendmsg_copy_hdr(req, &iomsg);
4528 flags = req->sr_msg.msg_flags;
4529 if (issue_flags & IO_URING_F_NONBLOCK)
4530 flags |= MSG_DONTWAIT;
4531 if (flags & MSG_WAITALL)
4532 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4534 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4535 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4536 return io_setup_async_msg(req, kmsg);
4537 if (ret == -ERESTARTSYS)
4540 /* fast path, check for non-NULL to avoid function call */
4542 kfree(kmsg->free_iov);
4543 req->flags &= ~REQ_F_NEED_CLEANUP;
4546 __io_req_complete(req, issue_flags, ret, 0);
4550 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4552 struct io_sr_msg *sr = &req->sr_msg;
4555 struct socket *sock;
4560 sock = sock_from_file(req->file);
4561 if (unlikely(!sock))
4564 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4568 msg.msg_name = NULL;
4569 msg.msg_control = NULL;
4570 msg.msg_controllen = 0;
4571 msg.msg_namelen = 0;
4573 flags = req->sr_msg.msg_flags;
4574 if (issue_flags & IO_URING_F_NONBLOCK)
4575 flags |= MSG_DONTWAIT;
4576 if (flags & MSG_WAITALL)
4577 min_ret = iov_iter_count(&msg.msg_iter);
4579 msg.msg_flags = flags;
4580 ret = sock_sendmsg(sock, &msg);
4581 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4583 if (ret == -ERESTARTSYS)
4588 __io_req_complete(req, issue_flags, ret, 0);
4592 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4593 struct io_async_msghdr *iomsg)
4595 struct io_sr_msg *sr = &req->sr_msg;
4596 struct iovec __user *uiov;
4600 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4601 &iomsg->uaddr, &uiov, &iov_len);
4605 if (req->flags & REQ_F_BUFFER_SELECT) {
4608 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4610 sr->len = iomsg->fast_iov[0].iov_len;
4611 iomsg->free_iov = NULL;
4613 iomsg->free_iov = iomsg->fast_iov;
4614 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4615 &iomsg->free_iov, &iomsg->msg.msg_iter,
4624 #ifdef CONFIG_COMPAT
4625 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4626 struct io_async_msghdr *iomsg)
4628 struct io_sr_msg *sr = &req->sr_msg;
4629 struct compat_iovec __user *uiov;
4634 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4639 uiov = compat_ptr(ptr);
4640 if (req->flags & REQ_F_BUFFER_SELECT) {
4641 compat_ssize_t clen;
4645 if (!access_ok(uiov, sizeof(*uiov)))
4647 if (__get_user(clen, &uiov->iov_len))
4652 iomsg->free_iov = NULL;
4654 iomsg->free_iov = iomsg->fast_iov;
4655 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4656 UIO_FASTIOV, &iomsg->free_iov,
4657 &iomsg->msg.msg_iter, true);
4666 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4667 struct io_async_msghdr *iomsg)
4669 iomsg->msg.msg_name = &iomsg->addr;
4671 #ifdef CONFIG_COMPAT
4672 if (req->ctx->compat)
4673 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4676 return __io_recvmsg_copy_hdr(req, iomsg);
4679 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4682 struct io_sr_msg *sr = &req->sr_msg;
4683 struct io_buffer *kbuf;
4685 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4690 req->flags |= REQ_F_BUFFER_SELECTED;
4694 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4696 return io_put_kbuf(req, req->sr_msg.kbuf);
4699 static int io_recvmsg_prep_async(struct io_kiocb *req)
4703 ret = io_recvmsg_copy_hdr(req, req->async_data);
4705 req->flags |= REQ_F_NEED_CLEANUP;
4709 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4711 struct io_sr_msg *sr = &req->sr_msg;
4713 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4716 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4717 sr->len = READ_ONCE(sqe->len);
4718 sr->bgid = READ_ONCE(sqe->buf_group);
4719 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4720 if (sr->msg_flags & MSG_DONTWAIT)
4721 req->flags |= REQ_F_NOWAIT;
4723 #ifdef CONFIG_COMPAT
4724 if (req->ctx->compat)
4725 sr->msg_flags |= MSG_CMSG_COMPAT;
4730 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4732 struct io_async_msghdr iomsg, *kmsg;
4733 struct socket *sock;
4734 struct io_buffer *kbuf;
4737 int ret, cflags = 0;
4738 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4740 sock = sock_from_file(req->file);
4741 if (unlikely(!sock))
4744 kmsg = req->async_data;
4746 ret = io_recvmsg_copy_hdr(req, &iomsg);
4752 if (req->flags & REQ_F_BUFFER_SELECT) {
4753 kbuf = io_recv_buffer_select(req, !force_nonblock);
4755 return PTR_ERR(kbuf);
4756 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4757 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4758 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4759 1, req->sr_msg.len);
4762 flags = req->sr_msg.msg_flags;
4764 flags |= MSG_DONTWAIT;
4765 if (flags & MSG_WAITALL)
4766 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4768 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4769 kmsg->uaddr, flags);
4770 if (force_nonblock && ret == -EAGAIN)
4771 return io_setup_async_msg(req, kmsg);
4772 if (ret == -ERESTARTSYS)
4775 if (req->flags & REQ_F_BUFFER_SELECTED)
4776 cflags = io_put_recv_kbuf(req);
4777 /* fast path, check for non-NULL to avoid function call */
4779 kfree(kmsg->free_iov);
4780 req->flags &= ~REQ_F_NEED_CLEANUP;
4781 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4783 __io_req_complete(req, issue_flags, ret, cflags);
4787 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4789 struct io_buffer *kbuf;
4790 struct io_sr_msg *sr = &req->sr_msg;
4792 void __user *buf = sr->buf;
4793 struct socket *sock;
4797 int ret, cflags = 0;
4798 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4800 sock = sock_from_file(req->file);
4801 if (unlikely(!sock))
4804 if (req->flags & REQ_F_BUFFER_SELECT) {
4805 kbuf = io_recv_buffer_select(req, !force_nonblock);
4807 return PTR_ERR(kbuf);
4808 buf = u64_to_user_ptr(kbuf->addr);
4811 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4815 msg.msg_name = NULL;
4816 msg.msg_control = NULL;
4817 msg.msg_controllen = 0;
4818 msg.msg_namelen = 0;
4819 msg.msg_iocb = NULL;
4822 flags = req->sr_msg.msg_flags;
4824 flags |= MSG_DONTWAIT;
4825 if (flags & MSG_WAITALL)
4826 min_ret = iov_iter_count(&msg.msg_iter);
4828 ret = sock_recvmsg(sock, &msg, flags);
4829 if (force_nonblock && ret == -EAGAIN)
4831 if (ret == -ERESTARTSYS)
4834 if (req->flags & REQ_F_BUFFER_SELECTED)
4835 cflags = io_put_recv_kbuf(req);
4836 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4838 __io_req_complete(req, issue_flags, ret, cflags);
4842 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4844 struct io_accept *accept = &req->accept;
4846 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4848 if (sqe->ioprio || sqe->len || sqe->buf_index)
4851 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4852 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4853 accept->flags = READ_ONCE(sqe->accept_flags);
4854 accept->nofile = rlimit(RLIMIT_NOFILE);
4856 accept->file_slot = READ_ONCE(sqe->file_index);
4857 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
4858 (accept->flags & SOCK_CLOEXEC)))
4860 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4862 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4863 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4867 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4869 struct io_accept *accept = &req->accept;
4870 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4871 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4872 bool fixed = !!accept->file_slot;
4876 if (req->file->f_flags & O_NONBLOCK)
4877 req->flags |= REQ_F_NOWAIT;
4880 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4881 if (unlikely(fd < 0))
4884 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4889 ret = PTR_ERR(file);
4890 if (ret == -EAGAIN && force_nonblock)
4892 if (ret == -ERESTARTSYS)
4895 } else if (!fixed) {
4896 fd_install(fd, file);
4899 ret = io_install_fixed_file(req, file, issue_flags,
4900 accept->file_slot - 1);
4902 __io_req_complete(req, issue_flags, ret, 0);
4906 static int io_connect_prep_async(struct io_kiocb *req)
4908 struct io_async_connect *io = req->async_data;
4909 struct io_connect *conn = &req->connect;
4911 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4914 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4916 struct io_connect *conn = &req->connect;
4918 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4920 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
4924 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4925 conn->addr_len = READ_ONCE(sqe->addr2);
4929 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4931 struct io_async_connect __io, *io;
4932 unsigned file_flags;
4934 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4936 if (req->async_data) {
4937 io = req->async_data;
4939 ret = move_addr_to_kernel(req->connect.addr,
4940 req->connect.addr_len,
4947 file_flags = force_nonblock ? O_NONBLOCK : 0;
4949 ret = __sys_connect_file(req->file, &io->address,
4950 req->connect.addr_len, file_flags);
4951 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4952 if (req->async_data)
4954 if (io_alloc_async_data(req)) {
4958 memcpy(req->async_data, &__io, sizeof(__io));
4961 if (ret == -ERESTARTSYS)
4966 __io_req_complete(req, issue_flags, ret, 0);
4969 #else /* !CONFIG_NET */
4970 #define IO_NETOP_FN(op) \
4971 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4973 return -EOPNOTSUPP; \
4976 #define IO_NETOP_PREP(op) \
4978 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4980 return -EOPNOTSUPP; \
4983 #define IO_NETOP_PREP_ASYNC(op) \
4985 static int io_##op##_prep_async(struct io_kiocb *req) \
4987 return -EOPNOTSUPP; \
4990 IO_NETOP_PREP_ASYNC(sendmsg);
4991 IO_NETOP_PREP_ASYNC(recvmsg);
4992 IO_NETOP_PREP_ASYNC(connect);
4993 IO_NETOP_PREP(accept);
4996 #endif /* CONFIG_NET */
4998 struct io_poll_table {
4999 struct poll_table_struct pt;
5000 struct io_kiocb *req;
5005 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5006 __poll_t mask, io_req_tw_func_t func)
5008 /* for instances that support it check for an event match first: */
5009 if (mask && !(mask & poll->events))
5012 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5014 list_del_init(&poll->wait.entry);
5017 req->io_task_work.func = func;
5020 * If this fails, then the task is exiting. When a task exits, the
5021 * work gets canceled, so just cancel this request as well instead
5022 * of executing it. We can't safely execute it anyway, as we may not
5023 * have the needed state needed for it anyway.
5025 io_req_task_work_add(req);
5029 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5030 __acquires(&req->ctx->completion_lock)
5032 struct io_ring_ctx *ctx = req->ctx;
5034 /* req->task == current here, checking PF_EXITING is safe */
5035 if (unlikely(req->task->flags & PF_EXITING))
5036 WRITE_ONCE(poll->canceled, true);
5038 if (!req->result && !READ_ONCE(poll->canceled)) {
5039 struct poll_table_struct pt = { ._key = poll->events };
5041 req->result = vfs_poll(req->file, &pt) & poll->events;
5044 spin_lock(&ctx->completion_lock);
5045 if (!req->result && !READ_ONCE(poll->canceled)) {
5046 add_wait_queue(poll->head, &poll->wait);
5053 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5055 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5056 if (req->opcode == IORING_OP_POLL_ADD)
5057 return req->async_data;
5058 return req->apoll->double_poll;
5061 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5063 if (req->opcode == IORING_OP_POLL_ADD)
5065 return &req->apoll->poll;
5068 static void io_poll_remove_double(struct io_kiocb *req)
5069 __must_hold(&req->ctx->completion_lock)
5071 struct io_poll_iocb *poll = io_poll_get_double(req);
5073 lockdep_assert_held(&req->ctx->completion_lock);
5075 if (poll && poll->head) {
5076 struct wait_queue_head *head = poll->head;
5078 spin_lock_irq(&head->lock);
5079 list_del_init(&poll->wait.entry);
5080 if (poll->wait.private)
5083 spin_unlock_irq(&head->lock);
5087 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5088 __must_hold(&req->ctx->completion_lock)
5090 struct io_ring_ctx *ctx = req->ctx;
5091 unsigned flags = IORING_CQE_F_MORE;
5094 if (READ_ONCE(req->poll.canceled)) {
5096 req->poll.events |= EPOLLONESHOT;
5098 error = mangle_poll(mask);
5100 if (req->poll.events & EPOLLONESHOT)
5102 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5103 req->poll.done = true;
5106 if (flags & IORING_CQE_F_MORE)
5109 io_commit_cqring(ctx);
5110 return !(flags & IORING_CQE_F_MORE);
5113 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5115 struct io_ring_ctx *ctx = req->ctx;
5116 struct io_kiocb *nxt;
5118 if (io_poll_rewait(req, &req->poll)) {
5119 spin_unlock(&ctx->completion_lock);
5123 done = io_poll_complete(req, req->result);
5125 io_poll_remove_double(req);
5126 hash_del(&req->hash_node);
5129 add_wait_queue(req->poll.head, &req->poll.wait);
5131 spin_unlock(&ctx->completion_lock);
5132 io_cqring_ev_posted(ctx);
5135 nxt = io_put_req_find_next(req);
5137 io_req_task_submit(nxt, locked);
5142 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5143 int sync, void *key)
5145 struct io_kiocb *req = wait->private;
5146 struct io_poll_iocb *poll = io_poll_get_single(req);
5147 __poll_t mask = key_to_poll(key);
5148 unsigned long flags;
5150 /* for instances that support it check for an event match first: */
5151 if (mask && !(mask & poll->events))
5153 if (!(poll->events & EPOLLONESHOT))
5154 return poll->wait.func(&poll->wait, mode, sync, key);
5156 list_del_init(&wait->entry);
5161 spin_lock_irqsave(&poll->head->lock, flags);
5162 done = list_empty(&poll->wait.entry);
5164 list_del_init(&poll->wait.entry);
5165 /* make sure double remove sees this as being gone */
5166 wait->private = NULL;
5167 spin_unlock_irqrestore(&poll->head->lock, flags);
5169 /* use wait func handler, so it matches the rq type */
5170 poll->wait.func(&poll->wait, mode, sync, key);
5177 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5178 wait_queue_func_t wake_func)
5182 poll->canceled = false;
5183 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5184 /* mask in events that we always want/need */
5185 poll->events = events | IO_POLL_UNMASK;
5186 INIT_LIST_HEAD(&poll->wait.entry);
5187 init_waitqueue_func_entry(&poll->wait, wake_func);
5190 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5191 struct wait_queue_head *head,
5192 struct io_poll_iocb **poll_ptr)
5194 struct io_kiocb *req = pt->req;
5197 * The file being polled uses multiple waitqueues for poll handling
5198 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5201 if (unlikely(pt->nr_entries)) {
5202 struct io_poll_iocb *poll_one = poll;
5204 /* double add on the same waitqueue head, ignore */
5205 if (poll_one->head == head)
5207 /* already have a 2nd entry, fail a third attempt */
5209 if ((*poll_ptr)->head == head)
5211 pt->error = -EINVAL;
5215 * Can't handle multishot for double wait for now, turn it
5216 * into one-shot mode.
5218 if (!(poll_one->events & EPOLLONESHOT))
5219 poll_one->events |= EPOLLONESHOT;
5220 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5222 pt->error = -ENOMEM;
5225 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5227 poll->wait.private = req;
5234 if (poll->events & EPOLLEXCLUSIVE)
5235 add_wait_queue_exclusive(head, &poll->wait);
5237 add_wait_queue(head, &poll->wait);
5240 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5241 struct poll_table_struct *p)
5243 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5244 struct async_poll *apoll = pt->req->apoll;
5246 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5249 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5251 struct async_poll *apoll = req->apoll;
5252 struct io_ring_ctx *ctx = req->ctx;
5254 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5256 if (io_poll_rewait(req, &apoll->poll)) {
5257 spin_unlock(&ctx->completion_lock);
5261 hash_del(&req->hash_node);
5262 io_poll_remove_double(req);
5263 spin_unlock(&ctx->completion_lock);
5265 if (!READ_ONCE(apoll->poll.canceled))
5266 io_req_task_submit(req, locked);
5268 io_req_complete_failed(req, -ECANCELED);
5271 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5274 struct io_kiocb *req = wait->private;
5275 struct io_poll_iocb *poll = &req->apoll->poll;
5277 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5280 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5283 static void io_poll_req_insert(struct io_kiocb *req)
5285 struct io_ring_ctx *ctx = req->ctx;
5286 struct hlist_head *list;
5288 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5289 hlist_add_head(&req->hash_node, list);
5292 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5293 struct io_poll_iocb *poll,
5294 struct io_poll_table *ipt, __poll_t mask,
5295 wait_queue_func_t wake_func)
5296 __acquires(&ctx->completion_lock)
5298 struct io_ring_ctx *ctx = req->ctx;
5299 bool cancel = false;
5301 INIT_HLIST_NODE(&req->hash_node);
5302 io_init_poll_iocb(poll, mask, wake_func);
5303 poll->file = req->file;
5304 poll->wait.private = req;
5306 ipt->pt._key = mask;
5309 ipt->nr_entries = 0;
5311 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5312 if (unlikely(!ipt->nr_entries) && !ipt->error)
5313 ipt->error = -EINVAL;
5315 spin_lock(&ctx->completion_lock);
5316 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5317 io_poll_remove_double(req);
5318 if (likely(poll->head)) {
5319 spin_lock_irq(&poll->head->lock);
5320 if (unlikely(list_empty(&poll->wait.entry))) {
5326 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5327 list_del_init(&poll->wait.entry);
5329 WRITE_ONCE(poll->canceled, true);
5330 else if (!poll->done) /* actually waiting for an event */
5331 io_poll_req_insert(req);
5332 spin_unlock_irq(&poll->head->lock);
5344 static int io_arm_poll_handler(struct io_kiocb *req)
5346 const struct io_op_def *def = &io_op_defs[req->opcode];
5347 struct io_ring_ctx *ctx = req->ctx;
5348 struct async_poll *apoll;
5349 struct io_poll_table ipt;
5350 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5353 if (!req->file || !file_can_poll(req->file))
5354 return IO_APOLL_ABORTED;
5355 if (req->flags & REQ_F_POLLED)
5356 return IO_APOLL_ABORTED;
5357 if (!def->pollin && !def->pollout)
5358 return IO_APOLL_ABORTED;
5362 mask |= POLLIN | POLLRDNORM;
5364 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5365 if ((req->opcode == IORING_OP_RECVMSG) &&
5366 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5370 mask |= POLLOUT | POLLWRNORM;
5373 /* if we can't nonblock try, then no point in arming a poll handler */
5374 if (!io_file_supports_nowait(req, rw))
5375 return IO_APOLL_ABORTED;
5377 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5378 if (unlikely(!apoll))
5379 return IO_APOLL_ABORTED;
5380 apoll->double_poll = NULL;
5382 req->flags |= REQ_F_POLLED;
5383 ipt.pt._qproc = io_async_queue_proc;
5384 io_req_set_refcount(req);
5386 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5388 spin_unlock(&ctx->completion_lock);
5389 if (ret || ipt.error)
5390 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5392 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5393 mask, apoll->poll.events);
5397 static bool __io_poll_remove_one(struct io_kiocb *req,
5398 struct io_poll_iocb *poll, bool do_cancel)
5399 __must_hold(&req->ctx->completion_lock)
5401 bool do_complete = false;
5405 spin_lock_irq(&poll->head->lock);
5407 WRITE_ONCE(poll->canceled, true);
5408 if (!list_empty(&poll->wait.entry)) {
5409 list_del_init(&poll->wait.entry);
5412 spin_unlock_irq(&poll->head->lock);
5413 hash_del(&req->hash_node);
5417 static bool io_poll_remove_one(struct io_kiocb *req)
5418 __must_hold(&req->ctx->completion_lock)
5422 io_poll_remove_double(req);
5423 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5426 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5427 io_commit_cqring(req->ctx);
5429 io_put_req_deferred(req);
5435 * Returns true if we found and killed one or more poll requests
5437 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5440 struct hlist_node *tmp;
5441 struct io_kiocb *req;
5444 spin_lock(&ctx->completion_lock);
5445 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5446 struct hlist_head *list;
5448 list = &ctx->cancel_hash[i];
5449 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5450 if (io_match_task(req, tsk, cancel_all))
5451 posted += io_poll_remove_one(req);
5454 spin_unlock(&ctx->completion_lock);
5457 io_cqring_ev_posted(ctx);
5462 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5464 __must_hold(&ctx->completion_lock)
5466 struct hlist_head *list;
5467 struct io_kiocb *req;
5469 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5470 hlist_for_each_entry(req, list, hash_node) {
5471 if (sqe_addr != req->user_data)
5473 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5480 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5482 __must_hold(&ctx->completion_lock)
5484 struct io_kiocb *req;
5486 req = io_poll_find(ctx, sqe_addr, poll_only);
5489 if (io_poll_remove_one(req))
5495 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5500 events = READ_ONCE(sqe->poll32_events);
5502 events = swahw32(events);
5504 if (!(flags & IORING_POLL_ADD_MULTI))
5505 events |= EPOLLONESHOT;
5506 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5509 static int io_poll_update_prep(struct io_kiocb *req,
5510 const struct io_uring_sqe *sqe)
5512 struct io_poll_update *upd = &req->poll_update;
5515 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5517 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5519 flags = READ_ONCE(sqe->len);
5520 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5521 IORING_POLL_ADD_MULTI))
5523 /* meaningless without update */
5524 if (flags == IORING_POLL_ADD_MULTI)
5527 upd->old_user_data = READ_ONCE(sqe->addr);
5528 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5529 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5531 upd->new_user_data = READ_ONCE(sqe->off);
5532 if (!upd->update_user_data && upd->new_user_data)
5534 if (upd->update_events)
5535 upd->events = io_poll_parse_events(sqe, flags);
5536 else if (sqe->poll32_events)
5542 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5545 struct io_kiocb *req = wait->private;
5546 struct io_poll_iocb *poll = &req->poll;
5548 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5551 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5552 struct poll_table_struct *p)
5554 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5556 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5559 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5561 struct io_poll_iocb *poll = &req->poll;
5564 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5566 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5568 flags = READ_ONCE(sqe->len);
5569 if (flags & ~IORING_POLL_ADD_MULTI)
5572 io_req_set_refcount(req);
5573 poll->events = io_poll_parse_events(sqe, flags);
5577 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5579 struct io_poll_iocb *poll = &req->poll;
5580 struct io_ring_ctx *ctx = req->ctx;
5581 struct io_poll_table ipt;
5584 ipt.pt._qproc = io_poll_queue_proc;
5586 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5589 if (mask) { /* no async, we'd stolen it */
5591 io_poll_complete(req, mask);
5593 spin_unlock(&ctx->completion_lock);
5596 io_cqring_ev_posted(ctx);
5597 if (poll->events & EPOLLONESHOT)
5603 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5605 struct io_ring_ctx *ctx = req->ctx;
5606 struct io_kiocb *preq;
5610 spin_lock(&ctx->completion_lock);
5611 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5617 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5619 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5624 * Don't allow racy completion with singleshot, as we cannot safely
5625 * update those. For multishot, if we're racing with completion, just
5626 * let completion re-add it.
5628 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5629 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5633 /* we now have a detached poll request. reissue. */
5637 spin_unlock(&ctx->completion_lock);
5639 io_req_complete(req, ret);
5642 /* only mask one event flags, keep behavior flags */
5643 if (req->poll_update.update_events) {
5644 preq->poll.events &= ~0xffff;
5645 preq->poll.events |= req->poll_update.events & 0xffff;
5646 preq->poll.events |= IO_POLL_UNMASK;
5648 if (req->poll_update.update_user_data)
5649 preq->user_data = req->poll_update.new_user_data;
5650 spin_unlock(&ctx->completion_lock);
5652 /* complete update request, we're done with it */
5653 io_req_complete(req, ret);
5656 ret = io_poll_add(preq, issue_flags);
5659 io_req_complete(preq, ret);
5665 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5668 io_req_complete_post(req, -ETIME, 0);
5671 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5673 struct io_timeout_data *data = container_of(timer,
5674 struct io_timeout_data, timer);
5675 struct io_kiocb *req = data->req;
5676 struct io_ring_ctx *ctx = req->ctx;
5677 unsigned long flags;
5679 spin_lock_irqsave(&ctx->timeout_lock, flags);
5680 list_del_init(&req->timeout.list);
5681 atomic_set(&req->ctx->cq_timeouts,
5682 atomic_read(&req->ctx->cq_timeouts) + 1);
5683 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5685 req->io_task_work.func = io_req_task_timeout;
5686 io_req_task_work_add(req);
5687 return HRTIMER_NORESTART;
5690 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5692 __must_hold(&ctx->timeout_lock)
5694 struct io_timeout_data *io;
5695 struct io_kiocb *req;
5698 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5699 found = user_data == req->user_data;
5704 return ERR_PTR(-ENOENT);
5706 io = req->async_data;
5707 if (hrtimer_try_to_cancel(&io->timer) == -1)
5708 return ERR_PTR(-EALREADY);
5709 list_del_init(&req->timeout.list);
5713 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5714 __must_hold(&ctx->completion_lock)
5715 __must_hold(&ctx->timeout_lock)
5717 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5720 return PTR_ERR(req);
5723 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5724 io_put_req_deferred(req);
5728 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5730 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5731 case IORING_TIMEOUT_BOOTTIME:
5732 return CLOCK_BOOTTIME;
5733 case IORING_TIMEOUT_REALTIME:
5734 return CLOCK_REALTIME;
5736 /* can't happen, vetted at prep time */
5740 return CLOCK_MONOTONIC;
5744 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5745 struct timespec64 *ts, enum hrtimer_mode mode)
5746 __must_hold(&ctx->timeout_lock)
5748 struct io_timeout_data *io;
5749 struct io_kiocb *req;
5752 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5753 found = user_data == req->user_data;
5760 io = req->async_data;
5761 if (hrtimer_try_to_cancel(&io->timer) == -1)
5763 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5764 io->timer.function = io_link_timeout_fn;
5765 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5769 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5770 struct timespec64 *ts, enum hrtimer_mode mode)
5771 __must_hold(&ctx->timeout_lock)
5773 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5774 struct io_timeout_data *data;
5777 return PTR_ERR(req);
5779 req->timeout.off = 0; /* noseq */
5780 data = req->async_data;
5781 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5782 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5783 data->timer.function = io_timeout_fn;
5784 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5788 static int io_timeout_remove_prep(struct io_kiocb *req,
5789 const struct io_uring_sqe *sqe)
5791 struct io_timeout_rem *tr = &req->timeout_rem;
5793 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5795 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5797 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5800 tr->ltimeout = false;
5801 tr->addr = READ_ONCE(sqe->addr);
5802 tr->flags = READ_ONCE(sqe->timeout_flags);
5803 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5804 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5806 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5807 tr->ltimeout = true;
5808 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5810 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5812 } else if (tr->flags) {
5813 /* timeout removal doesn't support flags */
5820 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5822 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5827 * Remove or update an existing timeout command
5829 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5831 struct io_timeout_rem *tr = &req->timeout_rem;
5832 struct io_ring_ctx *ctx = req->ctx;
5835 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5836 spin_lock(&ctx->completion_lock);
5837 spin_lock_irq(&ctx->timeout_lock);
5838 ret = io_timeout_cancel(ctx, tr->addr);
5839 spin_unlock_irq(&ctx->timeout_lock);
5840 spin_unlock(&ctx->completion_lock);
5842 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5844 spin_lock_irq(&ctx->timeout_lock);
5846 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5848 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5849 spin_unlock_irq(&ctx->timeout_lock);
5854 io_req_complete_post(req, ret, 0);
5858 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5859 bool is_timeout_link)
5861 struct io_timeout_data *data;
5863 u32 off = READ_ONCE(sqe->off);
5865 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5867 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5870 if (off && is_timeout_link)
5872 flags = READ_ONCE(sqe->timeout_flags);
5873 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
5875 /* more than one clock specified is invalid, obviously */
5876 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5879 INIT_LIST_HEAD(&req->timeout.list);
5880 req->timeout.off = off;
5881 if (unlikely(off && !req->ctx->off_timeout_used))
5882 req->ctx->off_timeout_used = true;
5884 if (!req->async_data && io_alloc_async_data(req))
5887 data = req->async_data;
5889 data->flags = flags;
5891 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5894 data->mode = io_translate_timeout_mode(flags);
5895 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5897 if (is_timeout_link) {
5898 struct io_submit_link *link = &req->ctx->submit_state.link;
5902 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5904 req->timeout.head = link->last;
5905 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5910 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5912 struct io_ring_ctx *ctx = req->ctx;
5913 struct io_timeout_data *data = req->async_data;
5914 struct list_head *entry;
5915 u32 tail, off = req->timeout.off;
5917 spin_lock_irq(&ctx->timeout_lock);
5920 * sqe->off holds how many events that need to occur for this
5921 * timeout event to be satisfied. If it isn't set, then this is
5922 * a pure timeout request, sequence isn't used.
5924 if (io_is_timeout_noseq(req)) {
5925 entry = ctx->timeout_list.prev;
5929 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5930 req->timeout.target_seq = tail + off;
5932 /* Update the last seq here in case io_flush_timeouts() hasn't.
5933 * This is safe because ->completion_lock is held, and submissions
5934 * and completions are never mixed in the same ->completion_lock section.
5936 ctx->cq_last_tm_flush = tail;
5939 * Insertion sort, ensuring the first entry in the list is always
5940 * the one we need first.
5942 list_for_each_prev(entry, &ctx->timeout_list) {
5943 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5946 if (io_is_timeout_noseq(nxt))
5948 /* nxt.seq is behind @tail, otherwise would've been completed */
5949 if (off >= nxt->timeout.target_seq - tail)
5953 list_add(&req->timeout.list, entry);
5954 data->timer.function = io_timeout_fn;
5955 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5956 spin_unlock_irq(&ctx->timeout_lock);
5960 struct io_cancel_data {
5961 struct io_ring_ctx *ctx;
5965 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5967 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5968 struct io_cancel_data *cd = data;
5970 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5973 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5974 struct io_ring_ctx *ctx)
5976 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5977 enum io_wq_cancel cancel_ret;
5980 if (!tctx || !tctx->io_wq)
5983 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5984 switch (cancel_ret) {
5985 case IO_WQ_CANCEL_OK:
5988 case IO_WQ_CANCEL_RUNNING:
5991 case IO_WQ_CANCEL_NOTFOUND:
5999 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6001 struct io_ring_ctx *ctx = req->ctx;
6004 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6006 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6010 spin_lock(&ctx->completion_lock);
6011 spin_lock_irq(&ctx->timeout_lock);
6012 ret = io_timeout_cancel(ctx, sqe_addr);
6013 spin_unlock_irq(&ctx->timeout_lock);
6016 ret = io_poll_cancel(ctx, sqe_addr, false);
6018 spin_unlock(&ctx->completion_lock);
6022 static int io_async_cancel_prep(struct io_kiocb *req,
6023 const struct io_uring_sqe *sqe)
6025 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6027 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6029 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6033 req->cancel.addr = READ_ONCE(sqe->addr);
6037 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6039 struct io_ring_ctx *ctx = req->ctx;
6040 u64 sqe_addr = req->cancel.addr;
6041 struct io_tctx_node *node;
6044 ret = io_try_cancel_userdata(req, sqe_addr);
6048 /* slow path, try all io-wq's */
6049 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6051 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6052 struct io_uring_task *tctx = node->task->io_uring;
6054 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6058 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6062 io_req_complete_post(req, ret, 0);
6066 static int io_rsrc_update_prep(struct io_kiocb *req,
6067 const struct io_uring_sqe *sqe)
6069 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6071 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6074 req->rsrc_update.offset = READ_ONCE(sqe->off);
6075 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6076 if (!req->rsrc_update.nr_args)
6078 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6082 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6084 struct io_ring_ctx *ctx = req->ctx;
6085 struct io_uring_rsrc_update2 up;
6088 if (issue_flags & IO_URING_F_NONBLOCK)
6091 up.offset = req->rsrc_update.offset;
6092 up.data = req->rsrc_update.arg;
6097 mutex_lock(&ctx->uring_lock);
6098 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6099 &up, req->rsrc_update.nr_args);
6100 mutex_unlock(&ctx->uring_lock);
6104 __io_req_complete(req, issue_flags, ret, 0);
6108 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6110 switch (req->opcode) {
6113 case IORING_OP_READV:
6114 case IORING_OP_READ_FIXED:
6115 case IORING_OP_READ:
6116 return io_read_prep(req, sqe);
6117 case IORING_OP_WRITEV:
6118 case IORING_OP_WRITE_FIXED:
6119 case IORING_OP_WRITE:
6120 return io_write_prep(req, sqe);
6121 case IORING_OP_POLL_ADD:
6122 return io_poll_add_prep(req, sqe);
6123 case IORING_OP_POLL_REMOVE:
6124 return io_poll_update_prep(req, sqe);
6125 case IORING_OP_FSYNC:
6126 return io_fsync_prep(req, sqe);
6127 case IORING_OP_SYNC_FILE_RANGE:
6128 return io_sfr_prep(req, sqe);
6129 case IORING_OP_SENDMSG:
6130 case IORING_OP_SEND:
6131 return io_sendmsg_prep(req, sqe);
6132 case IORING_OP_RECVMSG:
6133 case IORING_OP_RECV:
6134 return io_recvmsg_prep(req, sqe);
6135 case IORING_OP_CONNECT:
6136 return io_connect_prep(req, sqe);
6137 case IORING_OP_TIMEOUT:
6138 return io_timeout_prep(req, sqe, false);
6139 case IORING_OP_TIMEOUT_REMOVE:
6140 return io_timeout_remove_prep(req, sqe);
6141 case IORING_OP_ASYNC_CANCEL:
6142 return io_async_cancel_prep(req, sqe);
6143 case IORING_OP_LINK_TIMEOUT:
6144 return io_timeout_prep(req, sqe, true);
6145 case IORING_OP_ACCEPT:
6146 return io_accept_prep(req, sqe);
6147 case IORING_OP_FALLOCATE:
6148 return io_fallocate_prep(req, sqe);
6149 case IORING_OP_OPENAT:
6150 return io_openat_prep(req, sqe);
6151 case IORING_OP_CLOSE:
6152 return io_close_prep(req, sqe);
6153 case IORING_OP_FILES_UPDATE:
6154 return io_rsrc_update_prep(req, sqe);
6155 case IORING_OP_STATX:
6156 return io_statx_prep(req, sqe);
6157 case IORING_OP_FADVISE:
6158 return io_fadvise_prep(req, sqe);
6159 case IORING_OP_MADVISE:
6160 return io_madvise_prep(req, sqe);
6161 case IORING_OP_OPENAT2:
6162 return io_openat2_prep(req, sqe);
6163 case IORING_OP_EPOLL_CTL:
6164 return io_epoll_ctl_prep(req, sqe);
6165 case IORING_OP_SPLICE:
6166 return io_splice_prep(req, sqe);
6167 case IORING_OP_PROVIDE_BUFFERS:
6168 return io_provide_buffers_prep(req, sqe);
6169 case IORING_OP_REMOVE_BUFFERS:
6170 return io_remove_buffers_prep(req, sqe);
6172 return io_tee_prep(req, sqe);
6173 case IORING_OP_SHUTDOWN:
6174 return io_shutdown_prep(req, sqe);
6175 case IORING_OP_RENAMEAT:
6176 return io_renameat_prep(req, sqe);
6177 case IORING_OP_UNLINKAT:
6178 return io_unlinkat_prep(req, sqe);
6181 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6186 static int io_req_prep_async(struct io_kiocb *req)
6188 if (!io_op_defs[req->opcode].needs_async_setup)
6190 if (WARN_ON_ONCE(req->async_data))
6192 if (io_alloc_async_data(req))
6195 switch (req->opcode) {
6196 case IORING_OP_READV:
6197 return io_rw_prep_async(req, READ);
6198 case IORING_OP_WRITEV:
6199 return io_rw_prep_async(req, WRITE);
6200 case IORING_OP_SENDMSG:
6201 return io_sendmsg_prep_async(req);
6202 case IORING_OP_RECVMSG:
6203 return io_recvmsg_prep_async(req);
6204 case IORING_OP_CONNECT:
6205 return io_connect_prep_async(req);
6207 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6212 static u32 io_get_sequence(struct io_kiocb *req)
6214 u32 seq = req->ctx->cached_sq_head;
6216 /* need original cached_sq_head, but it was increased for each req */
6217 io_for_each_link(req, req)
6222 static bool io_drain_req(struct io_kiocb *req)
6224 struct io_kiocb *pos;
6225 struct io_ring_ctx *ctx = req->ctx;
6226 struct io_defer_entry *de;
6231 * If we need to drain a request in the middle of a link, drain the
6232 * head request and the next request/link after the current link.
6233 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6234 * maintained for every request of our link.
6236 if (ctx->drain_next) {
6237 req->flags |= REQ_F_IO_DRAIN;
6238 ctx->drain_next = false;
6240 /* not interested in head, start from the first linked */
6241 io_for_each_link(pos, req->link) {
6242 if (pos->flags & REQ_F_IO_DRAIN) {
6243 ctx->drain_next = true;
6244 req->flags |= REQ_F_IO_DRAIN;
6249 /* Still need defer if there is pending req in defer list. */
6250 if (likely(list_empty_careful(&ctx->defer_list) &&
6251 !(req->flags & REQ_F_IO_DRAIN))) {
6252 ctx->drain_active = false;
6256 seq = io_get_sequence(req);
6257 /* Still a chance to pass the sequence check */
6258 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6261 ret = io_req_prep_async(req);
6264 io_prep_async_link(req);
6265 de = kmalloc(sizeof(*de), GFP_KERNEL);
6269 io_req_complete_failed(req, ret);
6273 spin_lock(&ctx->completion_lock);
6274 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6275 spin_unlock(&ctx->completion_lock);
6277 io_queue_async_work(req, NULL);
6281 trace_io_uring_defer(ctx, req, req->user_data);
6284 list_add_tail(&de->list, &ctx->defer_list);
6285 spin_unlock(&ctx->completion_lock);
6289 static void io_clean_op(struct io_kiocb *req)
6291 if (req->flags & REQ_F_BUFFER_SELECTED) {
6292 switch (req->opcode) {
6293 case IORING_OP_READV:
6294 case IORING_OP_READ_FIXED:
6295 case IORING_OP_READ:
6296 kfree((void *)(unsigned long)req->rw.addr);
6298 case IORING_OP_RECVMSG:
6299 case IORING_OP_RECV:
6300 kfree(req->sr_msg.kbuf);
6305 if (req->flags & REQ_F_NEED_CLEANUP) {
6306 switch (req->opcode) {
6307 case IORING_OP_READV:
6308 case IORING_OP_READ_FIXED:
6309 case IORING_OP_READ:
6310 case IORING_OP_WRITEV:
6311 case IORING_OP_WRITE_FIXED:
6312 case IORING_OP_WRITE: {
6313 struct io_async_rw *io = req->async_data;
6315 kfree(io->free_iovec);
6318 case IORING_OP_RECVMSG:
6319 case IORING_OP_SENDMSG: {
6320 struct io_async_msghdr *io = req->async_data;
6322 kfree(io->free_iov);
6325 case IORING_OP_SPLICE:
6327 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6328 io_put_file(req->splice.file_in);
6330 case IORING_OP_OPENAT:
6331 case IORING_OP_OPENAT2:
6332 if (req->open.filename)
6333 putname(req->open.filename);
6335 case IORING_OP_RENAMEAT:
6336 putname(req->rename.oldpath);
6337 putname(req->rename.newpath);
6339 case IORING_OP_UNLINKAT:
6340 putname(req->unlink.filename);
6344 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6345 kfree(req->apoll->double_poll);
6349 if (req->flags & REQ_F_INFLIGHT) {
6350 struct io_uring_task *tctx = req->task->io_uring;
6352 atomic_dec(&tctx->inflight_tracked);
6354 if (req->flags & REQ_F_CREDS)
6355 put_cred(req->creds);
6357 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6360 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6362 struct io_ring_ctx *ctx = req->ctx;
6363 const struct cred *creds = NULL;
6366 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6367 creds = override_creds(req->creds);
6369 switch (req->opcode) {
6371 ret = io_nop(req, issue_flags);
6373 case IORING_OP_READV:
6374 case IORING_OP_READ_FIXED:
6375 case IORING_OP_READ:
6376 ret = io_read(req, issue_flags);
6378 case IORING_OP_WRITEV:
6379 case IORING_OP_WRITE_FIXED:
6380 case IORING_OP_WRITE:
6381 ret = io_write(req, issue_flags);
6383 case IORING_OP_FSYNC:
6384 ret = io_fsync(req, issue_flags);
6386 case IORING_OP_POLL_ADD:
6387 ret = io_poll_add(req, issue_flags);
6389 case IORING_OP_POLL_REMOVE:
6390 ret = io_poll_update(req, issue_flags);
6392 case IORING_OP_SYNC_FILE_RANGE:
6393 ret = io_sync_file_range(req, issue_flags);
6395 case IORING_OP_SENDMSG:
6396 ret = io_sendmsg(req, issue_flags);
6398 case IORING_OP_SEND:
6399 ret = io_send(req, issue_flags);
6401 case IORING_OP_RECVMSG:
6402 ret = io_recvmsg(req, issue_flags);
6404 case IORING_OP_RECV:
6405 ret = io_recv(req, issue_flags);
6407 case IORING_OP_TIMEOUT:
6408 ret = io_timeout(req, issue_flags);
6410 case IORING_OP_TIMEOUT_REMOVE:
6411 ret = io_timeout_remove(req, issue_flags);
6413 case IORING_OP_ACCEPT:
6414 ret = io_accept(req, issue_flags);
6416 case IORING_OP_CONNECT:
6417 ret = io_connect(req, issue_flags);
6419 case IORING_OP_ASYNC_CANCEL:
6420 ret = io_async_cancel(req, issue_flags);
6422 case IORING_OP_FALLOCATE:
6423 ret = io_fallocate(req, issue_flags);
6425 case IORING_OP_OPENAT:
6426 ret = io_openat(req, issue_flags);
6428 case IORING_OP_CLOSE:
6429 ret = io_close(req, issue_flags);
6431 case IORING_OP_FILES_UPDATE:
6432 ret = io_files_update(req, issue_flags);
6434 case IORING_OP_STATX:
6435 ret = io_statx(req, issue_flags);
6437 case IORING_OP_FADVISE:
6438 ret = io_fadvise(req, issue_flags);
6440 case IORING_OP_MADVISE:
6441 ret = io_madvise(req, issue_flags);
6443 case IORING_OP_OPENAT2:
6444 ret = io_openat2(req, issue_flags);
6446 case IORING_OP_EPOLL_CTL:
6447 ret = io_epoll_ctl(req, issue_flags);
6449 case IORING_OP_SPLICE:
6450 ret = io_splice(req, issue_flags);
6452 case IORING_OP_PROVIDE_BUFFERS:
6453 ret = io_provide_buffers(req, issue_flags);
6455 case IORING_OP_REMOVE_BUFFERS:
6456 ret = io_remove_buffers(req, issue_flags);
6459 ret = io_tee(req, issue_flags);
6461 case IORING_OP_SHUTDOWN:
6462 ret = io_shutdown(req, issue_flags);
6464 case IORING_OP_RENAMEAT:
6465 ret = io_renameat(req, issue_flags);
6467 case IORING_OP_UNLINKAT:
6468 ret = io_unlinkat(req, issue_flags);
6476 revert_creds(creds);
6479 /* If the op doesn't have a file, we're not polling for it */
6480 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6481 io_iopoll_req_issued(req);
6486 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6488 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6490 req = io_put_req_find_next(req);
6491 return req ? &req->work : NULL;
6494 static void io_wq_submit_work(struct io_wq_work *work)
6496 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6497 struct io_kiocb *timeout;
6500 /* one will be dropped by ->io_free_work() after returning to io-wq */
6501 if (!(req->flags & REQ_F_REFCOUNT))
6502 __io_req_set_refcount(req, 2);
6506 timeout = io_prep_linked_timeout(req);
6508 io_queue_linked_timeout(timeout);
6510 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6511 if (work->flags & IO_WQ_WORK_CANCEL)
6516 ret = io_issue_sqe(req, 0);
6518 * We can get EAGAIN for polled IO even though we're
6519 * forcing a sync submission from here, since we can't
6520 * wait for request slots on the block side.
6528 /* avoid locking problems by failing it from a clean context */
6530 io_req_task_queue_fail(req, ret);
6533 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6536 return &table->files[i];
6539 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6542 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6544 return (struct file *) (slot->file_ptr & FFS_MASK);
6547 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6549 unsigned long file_ptr = (unsigned long) file;
6551 if (__io_file_supports_nowait(file, READ))
6552 file_ptr |= FFS_ASYNC_READ;
6553 if (__io_file_supports_nowait(file, WRITE))
6554 file_ptr |= FFS_ASYNC_WRITE;
6555 if (S_ISREG(file_inode(file)->i_mode))
6556 file_ptr |= FFS_ISREG;
6557 file_slot->file_ptr = file_ptr;
6560 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6561 struct io_kiocb *req, int fd)
6564 unsigned long file_ptr;
6566 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6568 fd = array_index_nospec(fd, ctx->nr_user_files);
6569 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6570 file = (struct file *) (file_ptr & FFS_MASK);
6571 file_ptr &= ~FFS_MASK;
6572 /* mask in overlapping REQ_F and FFS bits */
6573 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6574 io_req_set_rsrc_node(req);
6578 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6579 struct io_kiocb *req, int fd)
6581 struct file *file = fget(fd);
6583 trace_io_uring_file_get(ctx, fd);
6585 /* we don't allow fixed io_uring files */
6586 if (file && unlikely(file->f_op == &io_uring_fops))
6587 io_req_track_inflight(req);
6591 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6592 struct io_kiocb *req, int fd, bool fixed)
6595 return io_file_get_fixed(ctx, req, fd);
6597 return io_file_get_normal(ctx, req, fd);
6600 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6602 struct io_kiocb *prev = req->timeout.prev;
6606 ret = io_try_cancel_userdata(req, prev->user_data);
6607 io_req_complete_post(req, ret ?: -ETIME, 0);
6610 io_req_complete_post(req, -ETIME, 0);
6614 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6616 struct io_timeout_data *data = container_of(timer,
6617 struct io_timeout_data, timer);
6618 struct io_kiocb *prev, *req = data->req;
6619 struct io_ring_ctx *ctx = req->ctx;
6620 unsigned long flags;
6622 spin_lock_irqsave(&ctx->timeout_lock, flags);
6623 prev = req->timeout.head;
6624 req->timeout.head = NULL;
6627 * We don't expect the list to be empty, that will only happen if we
6628 * race with the completion of the linked work.
6631 io_remove_next_linked(prev);
6632 if (!req_ref_inc_not_zero(prev))
6635 list_del(&req->timeout.list);
6636 req->timeout.prev = prev;
6637 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6639 req->io_task_work.func = io_req_task_link_timeout;
6640 io_req_task_work_add(req);
6641 return HRTIMER_NORESTART;
6644 static void io_queue_linked_timeout(struct io_kiocb *req)
6646 struct io_ring_ctx *ctx = req->ctx;
6648 spin_lock_irq(&ctx->timeout_lock);
6650 * If the back reference is NULL, then our linked request finished
6651 * before we got a chance to setup the timer
6653 if (req->timeout.head) {
6654 struct io_timeout_data *data = req->async_data;
6656 data->timer.function = io_link_timeout_fn;
6657 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6659 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6661 spin_unlock_irq(&ctx->timeout_lock);
6662 /* drop submission reference */
6666 static void __io_queue_sqe(struct io_kiocb *req)
6667 __must_hold(&req->ctx->uring_lock)
6669 struct io_kiocb *linked_timeout;
6673 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6676 * We async punt it if the file wasn't marked NOWAIT, or if the file
6677 * doesn't support non-blocking read/write attempts
6680 if (req->flags & REQ_F_COMPLETE_INLINE) {
6681 struct io_ring_ctx *ctx = req->ctx;
6682 struct io_submit_state *state = &ctx->submit_state;
6684 state->compl_reqs[state->compl_nr++] = req;
6685 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6686 io_submit_flush_completions(ctx);
6690 linked_timeout = io_prep_linked_timeout(req);
6692 io_queue_linked_timeout(linked_timeout);
6693 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6694 linked_timeout = io_prep_linked_timeout(req);
6696 switch (io_arm_poll_handler(req)) {
6697 case IO_APOLL_READY:
6699 io_unprep_linked_timeout(req);
6701 case IO_APOLL_ABORTED:
6703 * Queued up for async execution, worker will release
6704 * submit reference when the iocb is actually submitted.
6706 io_queue_async_work(req, NULL);
6711 io_queue_linked_timeout(linked_timeout);
6713 io_req_complete_failed(req, ret);
6717 static inline void io_queue_sqe(struct io_kiocb *req)
6718 __must_hold(&req->ctx->uring_lock)
6720 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6723 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6724 __io_queue_sqe(req);
6725 } else if (req->flags & REQ_F_FAIL) {
6726 io_req_complete_failed(req, req->result);
6728 int ret = io_req_prep_async(req);
6731 io_req_complete_failed(req, ret);
6733 io_queue_async_work(req, NULL);
6738 * Check SQE restrictions (opcode and flags).
6740 * Returns 'true' if SQE is allowed, 'false' otherwise.
6742 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6743 struct io_kiocb *req,
6744 unsigned int sqe_flags)
6746 if (likely(!ctx->restricted))
6749 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6752 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6753 ctx->restrictions.sqe_flags_required)
6756 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6757 ctx->restrictions.sqe_flags_required))
6763 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6764 const struct io_uring_sqe *sqe)
6765 __must_hold(&ctx->uring_lock)
6767 struct io_submit_state *state;
6768 unsigned int sqe_flags;
6769 int personality, ret = 0;
6771 /* req is partially pre-initialised, see io_preinit_req() */
6772 req->opcode = READ_ONCE(sqe->opcode);
6773 /* same numerical values with corresponding REQ_F_*, safe to copy */
6774 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6775 req->user_data = READ_ONCE(sqe->user_data);
6777 req->fixed_rsrc_refs = NULL;
6778 req->task = current;
6780 /* enforce forwards compatibility on users */
6781 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6783 if (unlikely(req->opcode >= IORING_OP_LAST))
6785 if (!io_check_restriction(ctx, req, sqe_flags))
6788 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6789 !io_op_defs[req->opcode].buffer_select)
6791 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6792 ctx->drain_active = true;
6794 personality = READ_ONCE(sqe->personality);
6796 req->creds = xa_load(&ctx->personalities, personality);
6799 get_cred(req->creds);
6800 req->flags |= REQ_F_CREDS;
6802 state = &ctx->submit_state;
6805 * Plug now if we have more than 1 IO left after this, and the target
6806 * is potentially a read/write to block based storage.
6808 if (!state->plug_started && state->ios_left > 1 &&
6809 io_op_defs[req->opcode].plug) {
6810 blk_start_plug(&state->plug);
6811 state->plug_started = true;
6814 if (io_op_defs[req->opcode].needs_file) {
6815 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6816 (sqe_flags & IOSQE_FIXED_FILE));
6817 if (unlikely(!req->file))
6825 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6826 const struct io_uring_sqe *sqe)
6827 __must_hold(&ctx->uring_lock)
6829 struct io_submit_link *link = &ctx->submit_state.link;
6832 ret = io_init_req(ctx, req, sqe);
6833 if (unlikely(ret)) {
6835 /* fail even hard links since we don't submit */
6838 * we can judge a link req is failed or cancelled by if
6839 * REQ_F_FAIL is set, but the head is an exception since
6840 * it may be set REQ_F_FAIL because of other req's failure
6841 * so let's leverage req->result to distinguish if a head
6842 * is set REQ_F_FAIL because of its failure or other req's
6843 * failure so that we can set the correct ret code for it.
6844 * init result here to avoid affecting the normal path.
6846 if (!(link->head->flags & REQ_F_FAIL))
6847 req_fail_link_node(link->head, -ECANCELED);
6848 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6850 * the current req is a normal req, we should return
6851 * error and thus break the submittion loop.
6853 io_req_complete_failed(req, ret);
6856 req_fail_link_node(req, ret);
6858 ret = io_req_prep(req, sqe);
6863 /* don't need @sqe from now on */
6864 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6866 ctx->flags & IORING_SETUP_SQPOLL);
6869 * If we already have a head request, queue this one for async
6870 * submittal once the head completes. If we don't have a head but
6871 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6872 * submitted sync once the chain is complete. If none of those
6873 * conditions are true (normal request), then just queue it.
6876 struct io_kiocb *head = link->head;
6878 if (!(req->flags & REQ_F_FAIL)) {
6879 ret = io_req_prep_async(req);
6880 if (unlikely(ret)) {
6881 req_fail_link_node(req, ret);
6882 if (!(head->flags & REQ_F_FAIL))
6883 req_fail_link_node(head, -ECANCELED);
6886 trace_io_uring_link(ctx, req, head);
6887 link->last->link = req;
6890 /* last request of a link, enqueue the link */
6891 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6896 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6908 * Batched submission is done, ensure local IO is flushed out.
6910 static void io_submit_state_end(struct io_submit_state *state,
6911 struct io_ring_ctx *ctx)
6913 if (state->link.head)
6914 io_queue_sqe(state->link.head);
6915 if (state->compl_nr)
6916 io_submit_flush_completions(ctx);
6917 if (state->plug_started)
6918 blk_finish_plug(&state->plug);
6922 * Start submission side cache.
6924 static void io_submit_state_start(struct io_submit_state *state,
6925 unsigned int max_ios)
6927 state->plug_started = false;
6928 state->ios_left = max_ios;
6929 /* set only head, no need to init link_last in advance */
6930 state->link.head = NULL;
6933 static void io_commit_sqring(struct io_ring_ctx *ctx)
6935 struct io_rings *rings = ctx->rings;
6938 * Ensure any loads from the SQEs are done at this point,
6939 * since once we write the new head, the application could
6940 * write new data to them.
6942 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6946 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6947 * that is mapped by userspace. This means that care needs to be taken to
6948 * ensure that reads are stable, as we cannot rely on userspace always
6949 * being a good citizen. If members of the sqe are validated and then later
6950 * used, it's important that those reads are done through READ_ONCE() to
6951 * prevent a re-load down the line.
6953 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6955 unsigned head, mask = ctx->sq_entries - 1;
6956 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6959 * The cached sq head (or cq tail) serves two purposes:
6961 * 1) allows us to batch the cost of updating the user visible
6963 * 2) allows the kernel side to track the head on its own, even
6964 * though the application is the one updating it.
6966 head = READ_ONCE(ctx->sq_array[sq_idx]);
6967 if (likely(head < ctx->sq_entries))
6968 return &ctx->sq_sqes[head];
6970 /* drop invalid entries */
6972 WRITE_ONCE(ctx->rings->sq_dropped,
6973 READ_ONCE(ctx->rings->sq_dropped) + 1);
6977 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6978 __must_hold(&ctx->uring_lock)
6982 /* make sure SQ entry isn't read before tail */
6983 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6984 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6986 io_get_task_refs(nr);
6988 io_submit_state_start(&ctx->submit_state, nr);
6989 while (submitted < nr) {
6990 const struct io_uring_sqe *sqe;
6991 struct io_kiocb *req;
6993 req = io_alloc_req(ctx);
6994 if (unlikely(!req)) {
6996 submitted = -EAGAIN;
6999 sqe = io_get_sqe(ctx);
7000 if (unlikely(!sqe)) {
7001 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7004 /* will complete beyond this point, count as submitted */
7006 if (io_submit_sqe(ctx, req, sqe))
7010 if (unlikely(submitted != nr)) {
7011 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7012 int unused = nr - ref_used;
7014 current->io_uring->cached_refs += unused;
7015 percpu_ref_put_many(&ctx->refs, unused);
7018 io_submit_state_end(&ctx->submit_state, ctx);
7019 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7020 io_commit_sqring(ctx);
7025 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7027 return READ_ONCE(sqd->state);
7030 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7032 /* Tell userspace we may need a wakeup call */
7033 spin_lock(&ctx->completion_lock);
7034 WRITE_ONCE(ctx->rings->sq_flags,
7035 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7036 spin_unlock(&ctx->completion_lock);
7039 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7041 spin_lock(&ctx->completion_lock);
7042 WRITE_ONCE(ctx->rings->sq_flags,
7043 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7044 spin_unlock(&ctx->completion_lock);
7047 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7049 unsigned int to_submit;
7052 to_submit = io_sqring_entries(ctx);
7053 /* if we're handling multiple rings, cap submit size for fairness */
7054 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7055 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7057 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7058 unsigned nr_events = 0;
7059 const struct cred *creds = NULL;
7061 if (ctx->sq_creds != current_cred())
7062 creds = override_creds(ctx->sq_creds);
7064 mutex_lock(&ctx->uring_lock);
7065 if (!list_empty(&ctx->iopoll_list))
7066 io_do_iopoll(ctx, &nr_events, 0);
7069 * Don't submit if refs are dying, good for io_uring_register(),
7070 * but also it is relied upon by io_ring_exit_work()
7072 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7073 !(ctx->flags & IORING_SETUP_R_DISABLED))
7074 ret = io_submit_sqes(ctx, to_submit);
7075 mutex_unlock(&ctx->uring_lock);
7077 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7078 wake_up(&ctx->sqo_sq_wait);
7080 revert_creds(creds);
7086 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7088 struct io_ring_ctx *ctx;
7089 unsigned sq_thread_idle = 0;
7091 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7092 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7093 sqd->sq_thread_idle = sq_thread_idle;
7096 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7098 bool did_sig = false;
7099 struct ksignal ksig;
7101 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7102 signal_pending(current)) {
7103 mutex_unlock(&sqd->lock);
7104 if (signal_pending(current))
7105 did_sig = get_signal(&ksig);
7107 mutex_lock(&sqd->lock);
7109 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7112 static int io_sq_thread(void *data)
7114 struct io_sq_data *sqd = data;
7115 struct io_ring_ctx *ctx;
7116 unsigned long timeout = 0;
7117 char buf[TASK_COMM_LEN];
7120 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7121 set_task_comm(current, buf);
7123 if (sqd->sq_cpu != -1)
7124 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7126 set_cpus_allowed_ptr(current, cpu_online_mask);
7127 current->flags |= PF_NO_SETAFFINITY;
7129 mutex_lock(&sqd->lock);
7131 bool cap_entries, sqt_spin = false;
7133 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7134 if (io_sqd_handle_event(sqd))
7136 timeout = jiffies + sqd->sq_thread_idle;
7139 cap_entries = !list_is_singular(&sqd->ctx_list);
7140 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7141 int ret = __io_sq_thread(ctx, cap_entries);
7143 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7146 if (io_run_task_work())
7149 if (sqt_spin || !time_after(jiffies, timeout)) {
7152 timeout = jiffies + sqd->sq_thread_idle;
7156 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7157 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7158 bool needs_sched = true;
7160 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7161 io_ring_set_wakeup_flag(ctx);
7163 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7164 !list_empty_careful(&ctx->iopoll_list)) {
7165 needs_sched = false;
7168 if (io_sqring_entries(ctx)) {
7169 needs_sched = false;
7175 mutex_unlock(&sqd->lock);
7177 mutex_lock(&sqd->lock);
7179 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7180 io_ring_clear_wakeup_flag(ctx);
7183 finish_wait(&sqd->wait, &wait);
7184 timeout = jiffies + sqd->sq_thread_idle;
7187 io_uring_cancel_generic(true, sqd);
7189 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7190 io_ring_set_wakeup_flag(ctx);
7192 mutex_unlock(&sqd->lock);
7194 complete(&sqd->exited);
7198 struct io_wait_queue {
7199 struct wait_queue_entry wq;
7200 struct io_ring_ctx *ctx;
7202 unsigned nr_timeouts;
7205 static inline bool io_should_wake(struct io_wait_queue *iowq)
7207 struct io_ring_ctx *ctx = iowq->ctx;
7208 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7211 * Wake up if we have enough events, or if a timeout occurred since we
7212 * started waiting. For timeouts, we always want to return to userspace,
7213 * regardless of event count.
7215 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7218 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7219 int wake_flags, void *key)
7221 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7225 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7226 * the task, and the next invocation will do it.
7228 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7229 return autoremove_wake_function(curr, mode, wake_flags, key);
7233 static int io_run_task_work_sig(void)
7235 if (io_run_task_work())
7237 if (!signal_pending(current))
7239 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7240 return -ERESTARTSYS;
7244 /* when returns >0, the caller should retry */
7245 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7246 struct io_wait_queue *iowq,
7247 signed long *timeout)
7251 /* make sure we run task_work before checking for signals */
7252 ret = io_run_task_work_sig();
7253 if (ret || io_should_wake(iowq))
7255 /* let the caller flush overflows, retry */
7256 if (test_bit(0, &ctx->check_cq_overflow))
7259 *timeout = schedule_timeout(*timeout);
7260 return !*timeout ? -ETIME : 1;
7264 * Wait until events become available, if we don't already have some. The
7265 * application must reap them itself, as they reside on the shared cq ring.
7267 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7268 const sigset_t __user *sig, size_t sigsz,
7269 struct __kernel_timespec __user *uts)
7271 struct io_wait_queue iowq;
7272 struct io_rings *rings = ctx->rings;
7273 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7277 io_cqring_overflow_flush(ctx);
7278 if (io_cqring_events(ctx) >= min_events)
7280 if (!io_run_task_work())
7285 #ifdef CONFIG_COMPAT
7286 if (in_compat_syscall())
7287 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7291 ret = set_user_sigmask(sig, sigsz);
7298 struct timespec64 ts;
7300 if (get_timespec64(&ts, uts))
7302 timeout = timespec64_to_jiffies(&ts);
7305 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7306 iowq.wq.private = current;
7307 INIT_LIST_HEAD(&iowq.wq.entry);
7309 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7310 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7312 trace_io_uring_cqring_wait(ctx, min_events);
7314 /* if we can't even flush overflow, don't wait for more */
7315 if (!io_cqring_overflow_flush(ctx)) {
7319 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7320 TASK_INTERRUPTIBLE);
7321 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7322 finish_wait(&ctx->cq_wait, &iowq.wq);
7326 restore_saved_sigmask_unless(ret == -EINTR);
7328 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7331 static void io_free_page_table(void **table, size_t size)
7333 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7335 for (i = 0; i < nr_tables; i++)
7340 static void **io_alloc_page_table(size_t size)
7342 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7343 size_t init_size = size;
7346 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7350 for (i = 0; i < nr_tables; i++) {
7351 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7353 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7355 io_free_page_table(table, init_size);
7363 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7365 percpu_ref_exit(&ref_node->refs);
7369 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7371 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7372 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7373 unsigned long flags;
7374 bool first_add = false;
7376 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7379 while (!list_empty(&ctx->rsrc_ref_list)) {
7380 node = list_first_entry(&ctx->rsrc_ref_list,
7381 struct io_rsrc_node, node);
7382 /* recycle ref nodes in order */
7385 list_del(&node->node);
7386 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7388 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7391 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7394 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7396 struct io_rsrc_node *ref_node;
7398 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7402 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7407 INIT_LIST_HEAD(&ref_node->node);
7408 INIT_LIST_HEAD(&ref_node->rsrc_list);
7409 ref_node->done = false;
7413 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7414 struct io_rsrc_data *data_to_kill)
7416 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7417 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7420 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7422 rsrc_node->rsrc_data = data_to_kill;
7423 spin_lock_irq(&ctx->rsrc_ref_lock);
7424 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7425 spin_unlock_irq(&ctx->rsrc_ref_lock);
7427 atomic_inc(&data_to_kill->refs);
7428 percpu_ref_kill(&rsrc_node->refs);
7429 ctx->rsrc_node = NULL;
7432 if (!ctx->rsrc_node) {
7433 ctx->rsrc_node = ctx->rsrc_backup_node;
7434 ctx->rsrc_backup_node = NULL;
7438 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7440 if (ctx->rsrc_backup_node)
7442 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7443 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7446 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7450 /* As we may drop ->uring_lock, other task may have started quiesce */
7454 data->quiesce = true;
7456 ret = io_rsrc_node_switch_start(ctx);
7459 io_rsrc_node_switch(ctx, data);
7461 /* kill initial ref, already quiesced if zero */
7462 if (atomic_dec_and_test(&data->refs))
7464 mutex_unlock(&ctx->uring_lock);
7465 flush_delayed_work(&ctx->rsrc_put_work);
7466 ret = wait_for_completion_interruptible(&data->done);
7468 mutex_lock(&ctx->uring_lock);
7472 atomic_inc(&data->refs);
7473 /* wait for all works potentially completing data->done */
7474 flush_delayed_work(&ctx->rsrc_put_work);
7475 reinit_completion(&data->done);
7477 ret = io_run_task_work_sig();
7478 mutex_lock(&ctx->uring_lock);
7480 data->quiesce = false;
7485 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7487 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7488 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7490 return &data->tags[table_idx][off];
7493 static void io_rsrc_data_free(struct io_rsrc_data *data)
7495 size_t size = data->nr * sizeof(data->tags[0][0]);
7498 io_free_page_table((void **)data->tags, size);
7502 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7503 u64 __user *utags, unsigned nr,
7504 struct io_rsrc_data **pdata)
7506 struct io_rsrc_data *data;
7510 data = kzalloc(sizeof(*data), GFP_KERNEL);
7513 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7521 data->do_put = do_put;
7524 for (i = 0; i < nr; i++) {
7525 u64 *tag_slot = io_get_tag_slot(data, i);
7527 if (copy_from_user(tag_slot, &utags[i],
7533 atomic_set(&data->refs, 1);
7534 init_completion(&data->done);
7538 io_rsrc_data_free(data);
7542 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7544 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7545 GFP_KERNEL_ACCOUNT);
7546 return !!table->files;
7549 static void io_free_file_tables(struct io_file_table *table)
7551 kvfree(table->files);
7552 table->files = NULL;
7555 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7557 #if defined(CONFIG_UNIX)
7558 if (ctx->ring_sock) {
7559 struct sock *sock = ctx->ring_sock->sk;
7560 struct sk_buff *skb;
7562 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7568 for (i = 0; i < ctx->nr_user_files; i++) {
7571 file = io_file_from_index(ctx, i);
7576 io_free_file_tables(&ctx->file_table);
7577 io_rsrc_data_free(ctx->file_data);
7578 ctx->file_data = NULL;
7579 ctx->nr_user_files = 0;
7582 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7586 if (!ctx->file_data)
7588 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7590 __io_sqe_files_unregister(ctx);
7594 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7595 __releases(&sqd->lock)
7597 WARN_ON_ONCE(sqd->thread == current);
7600 * Do the dance but not conditional clear_bit() because it'd race with
7601 * other threads incrementing park_pending and setting the bit.
7603 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7604 if (atomic_dec_return(&sqd->park_pending))
7605 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7606 mutex_unlock(&sqd->lock);
7609 static void io_sq_thread_park(struct io_sq_data *sqd)
7610 __acquires(&sqd->lock)
7612 WARN_ON_ONCE(sqd->thread == current);
7614 atomic_inc(&sqd->park_pending);
7615 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7616 mutex_lock(&sqd->lock);
7618 wake_up_process(sqd->thread);
7621 static void io_sq_thread_stop(struct io_sq_data *sqd)
7623 WARN_ON_ONCE(sqd->thread == current);
7624 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7626 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7627 mutex_lock(&sqd->lock);
7629 wake_up_process(sqd->thread);
7630 mutex_unlock(&sqd->lock);
7631 wait_for_completion(&sqd->exited);
7634 static void io_put_sq_data(struct io_sq_data *sqd)
7636 if (refcount_dec_and_test(&sqd->refs)) {
7637 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7639 io_sq_thread_stop(sqd);
7644 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7646 struct io_sq_data *sqd = ctx->sq_data;
7649 io_sq_thread_park(sqd);
7650 list_del_init(&ctx->sqd_list);
7651 io_sqd_update_thread_idle(sqd);
7652 io_sq_thread_unpark(sqd);
7654 io_put_sq_data(sqd);
7655 ctx->sq_data = NULL;
7659 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7661 struct io_ring_ctx *ctx_attach;
7662 struct io_sq_data *sqd;
7665 f = fdget(p->wq_fd);
7667 return ERR_PTR(-ENXIO);
7668 if (f.file->f_op != &io_uring_fops) {
7670 return ERR_PTR(-EINVAL);
7673 ctx_attach = f.file->private_data;
7674 sqd = ctx_attach->sq_data;
7677 return ERR_PTR(-EINVAL);
7679 if (sqd->task_tgid != current->tgid) {
7681 return ERR_PTR(-EPERM);
7684 refcount_inc(&sqd->refs);
7689 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7692 struct io_sq_data *sqd;
7695 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7696 sqd = io_attach_sq_data(p);
7701 /* fall through for EPERM case, setup new sqd/task */
7702 if (PTR_ERR(sqd) != -EPERM)
7706 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7708 return ERR_PTR(-ENOMEM);
7710 atomic_set(&sqd->park_pending, 0);
7711 refcount_set(&sqd->refs, 1);
7712 INIT_LIST_HEAD(&sqd->ctx_list);
7713 mutex_init(&sqd->lock);
7714 init_waitqueue_head(&sqd->wait);
7715 init_completion(&sqd->exited);
7719 #if defined(CONFIG_UNIX)
7721 * Ensure the UNIX gc is aware of our file set, so we are certain that
7722 * the io_uring can be safely unregistered on process exit, even if we have
7723 * loops in the file referencing.
7725 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7727 struct sock *sk = ctx->ring_sock->sk;
7728 struct scm_fp_list *fpl;
7729 struct sk_buff *skb;
7732 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7736 skb = alloc_skb(0, GFP_KERNEL);
7745 fpl->user = get_uid(current_user());
7746 for (i = 0; i < nr; i++) {
7747 struct file *file = io_file_from_index(ctx, i + offset);
7751 fpl->fp[nr_files] = get_file(file);
7752 unix_inflight(fpl->user, fpl->fp[nr_files]);
7757 fpl->max = SCM_MAX_FD;
7758 fpl->count = nr_files;
7759 UNIXCB(skb).fp = fpl;
7760 skb->destructor = unix_destruct_scm;
7761 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7762 skb_queue_head(&sk->sk_receive_queue, skb);
7764 for (i = 0; i < nr_files; i++)
7775 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7776 * causes regular reference counting to break down. We rely on the UNIX
7777 * garbage collection to take care of this problem for us.
7779 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7781 unsigned left, total;
7785 left = ctx->nr_user_files;
7787 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7789 ret = __io_sqe_files_scm(ctx, this_files, total);
7793 total += this_files;
7799 while (total < ctx->nr_user_files) {
7800 struct file *file = io_file_from_index(ctx, total);
7810 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7816 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7818 struct file *file = prsrc->file;
7819 #if defined(CONFIG_UNIX)
7820 struct sock *sock = ctx->ring_sock->sk;
7821 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7822 struct sk_buff *skb;
7825 __skb_queue_head_init(&list);
7828 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7829 * remove this entry and rearrange the file array.
7831 skb = skb_dequeue(head);
7833 struct scm_fp_list *fp;
7835 fp = UNIXCB(skb).fp;
7836 for (i = 0; i < fp->count; i++) {
7839 if (fp->fp[i] != file)
7842 unix_notinflight(fp->user, fp->fp[i]);
7843 left = fp->count - 1 - i;
7845 memmove(&fp->fp[i], &fp->fp[i + 1],
7846 left * sizeof(struct file *));
7853 __skb_queue_tail(&list, skb);
7863 __skb_queue_tail(&list, skb);
7865 skb = skb_dequeue(head);
7868 if (skb_peek(&list)) {
7869 spin_lock_irq(&head->lock);
7870 while ((skb = __skb_dequeue(&list)) != NULL)
7871 __skb_queue_tail(head, skb);
7872 spin_unlock_irq(&head->lock);
7879 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7881 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7882 struct io_ring_ctx *ctx = rsrc_data->ctx;
7883 struct io_rsrc_put *prsrc, *tmp;
7885 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7886 list_del(&prsrc->list);
7889 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7891 io_ring_submit_lock(ctx, lock_ring);
7892 spin_lock(&ctx->completion_lock);
7893 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7895 io_commit_cqring(ctx);
7896 spin_unlock(&ctx->completion_lock);
7897 io_cqring_ev_posted(ctx);
7898 io_ring_submit_unlock(ctx, lock_ring);
7901 rsrc_data->do_put(ctx, prsrc);
7905 io_rsrc_node_destroy(ref_node);
7906 if (atomic_dec_and_test(&rsrc_data->refs))
7907 complete(&rsrc_data->done);
7910 static void io_rsrc_put_work(struct work_struct *work)
7912 struct io_ring_ctx *ctx;
7913 struct llist_node *node;
7915 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7916 node = llist_del_all(&ctx->rsrc_put_llist);
7919 struct io_rsrc_node *ref_node;
7920 struct llist_node *next = node->next;
7922 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7923 __io_rsrc_put_work(ref_node);
7928 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7929 unsigned nr_args, u64 __user *tags)
7931 __s32 __user *fds = (__s32 __user *) arg;
7940 if (nr_args > IORING_MAX_FIXED_FILES)
7942 if (nr_args > rlimit(RLIMIT_NOFILE))
7944 ret = io_rsrc_node_switch_start(ctx);
7947 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7953 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7956 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7957 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7961 /* allow sparse sets */
7964 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7971 if (unlikely(!file))
7975 * Don't allow io_uring instances to be registered. If UNIX
7976 * isn't enabled, then this causes a reference cycle and this
7977 * instance can never get freed. If UNIX is enabled we'll
7978 * handle it just fine, but there's still no point in allowing
7979 * a ring fd as it doesn't support regular read/write anyway.
7981 if (file->f_op == &io_uring_fops) {
7985 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7988 ret = io_sqe_files_scm(ctx);
7990 __io_sqe_files_unregister(ctx);
7994 io_rsrc_node_switch(ctx, NULL);
7997 for (i = 0; i < ctx->nr_user_files; i++) {
7998 file = io_file_from_index(ctx, i);
8002 io_free_file_tables(&ctx->file_table);
8003 ctx->nr_user_files = 0;
8005 io_rsrc_data_free(ctx->file_data);
8006 ctx->file_data = NULL;
8010 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8013 #if defined(CONFIG_UNIX)
8014 struct sock *sock = ctx->ring_sock->sk;
8015 struct sk_buff_head *head = &sock->sk_receive_queue;
8016 struct sk_buff *skb;
8019 * See if we can merge this file into an existing skb SCM_RIGHTS
8020 * file set. If there's no room, fall back to allocating a new skb
8021 * and filling it in.
8023 spin_lock_irq(&head->lock);
8024 skb = skb_peek(head);
8026 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8028 if (fpl->count < SCM_MAX_FD) {
8029 __skb_unlink(skb, head);
8030 spin_unlock_irq(&head->lock);
8031 fpl->fp[fpl->count] = get_file(file);
8032 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8034 spin_lock_irq(&head->lock);
8035 __skb_queue_head(head, skb);
8040 spin_unlock_irq(&head->lock);
8047 return __io_sqe_files_scm(ctx, 1, index);
8053 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8054 unsigned int issue_flags, u32 slot_index)
8056 struct io_ring_ctx *ctx = req->ctx;
8057 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8058 struct io_fixed_file *file_slot;
8061 io_ring_submit_lock(ctx, !force_nonblock);
8062 if (file->f_op == &io_uring_fops)
8065 if (!ctx->file_data)
8068 if (slot_index >= ctx->nr_user_files)
8071 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8072 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8074 if (file_slot->file_ptr)
8077 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8078 io_fixed_file_set(file_slot, file);
8079 ret = io_sqe_file_register(ctx, file, slot_index);
8081 file_slot->file_ptr = 0;
8087 io_ring_submit_unlock(ctx, !force_nonblock);
8093 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8094 struct io_rsrc_node *node, void *rsrc)
8096 struct io_rsrc_put *prsrc;
8098 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8102 prsrc->tag = *io_get_tag_slot(data, idx);
8104 list_add(&prsrc->list, &node->rsrc_list);
8108 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8109 struct io_uring_rsrc_update2 *up,
8112 u64 __user *tags = u64_to_user_ptr(up->tags);
8113 __s32 __user *fds = u64_to_user_ptr(up->data);
8114 struct io_rsrc_data *data = ctx->file_data;
8115 struct io_fixed_file *file_slot;
8119 bool needs_switch = false;
8121 if (!ctx->file_data)
8123 if (up->offset + nr_args > ctx->nr_user_files)
8126 for (done = 0; done < nr_args; done++) {
8129 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8130 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8134 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8138 if (fd == IORING_REGISTER_FILES_SKIP)
8141 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8142 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8144 if (file_slot->file_ptr) {
8145 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8146 err = io_queue_rsrc_removal(data, up->offset + done,
8147 ctx->rsrc_node, file);
8150 file_slot->file_ptr = 0;
8151 needs_switch = true;
8160 * Don't allow io_uring instances to be registered. If
8161 * UNIX isn't enabled, then this causes a reference
8162 * cycle and this instance can never get freed. If UNIX
8163 * is enabled we'll handle it just fine, but there's
8164 * still no point in allowing a ring fd as it doesn't
8165 * support regular read/write anyway.
8167 if (file->f_op == &io_uring_fops) {
8172 *io_get_tag_slot(data, up->offset + done) = tag;
8173 io_fixed_file_set(file_slot, file);
8174 err = io_sqe_file_register(ctx, file, i);
8176 file_slot->file_ptr = 0;
8184 io_rsrc_node_switch(ctx, data);
8185 return done ? done : err;
8188 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8189 struct task_struct *task)
8191 struct io_wq_hash *hash;
8192 struct io_wq_data data;
8193 unsigned int concurrency;
8195 mutex_lock(&ctx->uring_lock);
8196 hash = ctx->hash_map;
8198 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8200 mutex_unlock(&ctx->uring_lock);
8201 return ERR_PTR(-ENOMEM);
8203 refcount_set(&hash->refs, 1);
8204 init_waitqueue_head(&hash->wait);
8205 ctx->hash_map = hash;
8207 mutex_unlock(&ctx->uring_lock);
8211 data.free_work = io_wq_free_work;
8212 data.do_work = io_wq_submit_work;
8214 /* Do QD, or 4 * CPUS, whatever is smallest */
8215 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8217 return io_wq_create(concurrency, &data);
8220 static int io_uring_alloc_task_context(struct task_struct *task,
8221 struct io_ring_ctx *ctx)
8223 struct io_uring_task *tctx;
8226 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8227 if (unlikely(!tctx))
8230 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8231 if (unlikely(ret)) {
8236 tctx->io_wq = io_init_wq_offload(ctx, task);
8237 if (IS_ERR(tctx->io_wq)) {
8238 ret = PTR_ERR(tctx->io_wq);
8239 percpu_counter_destroy(&tctx->inflight);
8245 init_waitqueue_head(&tctx->wait);
8246 atomic_set(&tctx->in_idle, 0);
8247 atomic_set(&tctx->inflight_tracked, 0);
8248 task->io_uring = tctx;
8249 spin_lock_init(&tctx->task_lock);
8250 INIT_WQ_LIST(&tctx->task_list);
8251 init_task_work(&tctx->task_work, tctx_task_work);
8255 void __io_uring_free(struct task_struct *tsk)
8257 struct io_uring_task *tctx = tsk->io_uring;
8259 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8260 WARN_ON_ONCE(tctx->io_wq);
8261 WARN_ON_ONCE(tctx->cached_refs);
8263 percpu_counter_destroy(&tctx->inflight);
8265 tsk->io_uring = NULL;
8268 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8269 struct io_uring_params *p)
8273 /* Retain compatibility with failing for an invalid attach attempt */
8274 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8275 IORING_SETUP_ATTACH_WQ) {
8278 f = fdget(p->wq_fd);
8281 if (f.file->f_op != &io_uring_fops) {
8287 if (ctx->flags & IORING_SETUP_SQPOLL) {
8288 struct task_struct *tsk;
8289 struct io_sq_data *sqd;
8292 sqd = io_get_sq_data(p, &attached);
8298 ctx->sq_creds = get_current_cred();
8300 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8301 if (!ctx->sq_thread_idle)
8302 ctx->sq_thread_idle = HZ;
8304 io_sq_thread_park(sqd);
8305 list_add(&ctx->sqd_list, &sqd->ctx_list);
8306 io_sqd_update_thread_idle(sqd);
8307 /* don't attach to a dying SQPOLL thread, would be racy */
8308 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8309 io_sq_thread_unpark(sqd);
8316 if (p->flags & IORING_SETUP_SQ_AFF) {
8317 int cpu = p->sq_thread_cpu;
8320 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8327 sqd->task_pid = current->pid;
8328 sqd->task_tgid = current->tgid;
8329 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8336 ret = io_uring_alloc_task_context(tsk, ctx);
8337 wake_up_new_task(tsk);
8340 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8341 /* Can't have SQ_AFF without SQPOLL */
8348 complete(&ctx->sq_data->exited);
8350 io_sq_thread_finish(ctx);
8354 static inline void __io_unaccount_mem(struct user_struct *user,
8355 unsigned long nr_pages)
8357 atomic_long_sub(nr_pages, &user->locked_vm);
8360 static inline int __io_account_mem(struct user_struct *user,
8361 unsigned long nr_pages)
8363 unsigned long page_limit, cur_pages, new_pages;
8365 /* Don't allow more pages than we can safely lock */
8366 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8369 cur_pages = atomic_long_read(&user->locked_vm);
8370 new_pages = cur_pages + nr_pages;
8371 if (new_pages > page_limit)
8373 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8374 new_pages) != cur_pages);
8379 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8382 __io_unaccount_mem(ctx->user, nr_pages);
8384 if (ctx->mm_account)
8385 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8388 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8393 ret = __io_account_mem(ctx->user, nr_pages);
8398 if (ctx->mm_account)
8399 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8404 static void io_mem_free(void *ptr)
8411 page = virt_to_head_page(ptr);
8412 if (put_page_testzero(page))
8413 free_compound_page(page);
8416 static void *io_mem_alloc(size_t size)
8418 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8419 __GFP_NORETRY | __GFP_ACCOUNT;
8421 return (void *) __get_free_pages(gfp_flags, get_order(size));
8424 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8427 struct io_rings *rings;
8428 size_t off, sq_array_size;
8430 off = struct_size(rings, cqes, cq_entries);
8431 if (off == SIZE_MAX)
8435 off = ALIGN(off, SMP_CACHE_BYTES);
8443 sq_array_size = array_size(sizeof(u32), sq_entries);
8444 if (sq_array_size == SIZE_MAX)
8447 if (check_add_overflow(off, sq_array_size, &off))
8453 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8455 struct io_mapped_ubuf *imu = *slot;
8458 if (imu != ctx->dummy_ubuf) {
8459 for (i = 0; i < imu->nr_bvecs; i++)
8460 unpin_user_page(imu->bvec[i].bv_page);
8461 if (imu->acct_pages)
8462 io_unaccount_mem(ctx, imu->acct_pages);
8468 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8470 io_buffer_unmap(ctx, &prsrc->buf);
8474 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8478 for (i = 0; i < ctx->nr_user_bufs; i++)
8479 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8480 kfree(ctx->user_bufs);
8481 io_rsrc_data_free(ctx->buf_data);
8482 ctx->user_bufs = NULL;
8483 ctx->buf_data = NULL;
8484 ctx->nr_user_bufs = 0;
8487 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8494 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8496 __io_sqe_buffers_unregister(ctx);
8500 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8501 void __user *arg, unsigned index)
8503 struct iovec __user *src;
8505 #ifdef CONFIG_COMPAT
8507 struct compat_iovec __user *ciovs;
8508 struct compat_iovec ciov;
8510 ciovs = (struct compat_iovec __user *) arg;
8511 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8514 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8515 dst->iov_len = ciov.iov_len;
8519 src = (struct iovec __user *) arg;
8520 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8526 * Not super efficient, but this is just a registration time. And we do cache
8527 * the last compound head, so generally we'll only do a full search if we don't
8530 * We check if the given compound head page has already been accounted, to
8531 * avoid double accounting it. This allows us to account the full size of the
8532 * page, not just the constituent pages of a huge page.
8534 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8535 int nr_pages, struct page *hpage)
8539 /* check current page array */
8540 for (i = 0; i < nr_pages; i++) {
8541 if (!PageCompound(pages[i]))
8543 if (compound_head(pages[i]) == hpage)
8547 /* check previously registered pages */
8548 for (i = 0; i < ctx->nr_user_bufs; i++) {
8549 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8551 for (j = 0; j < imu->nr_bvecs; j++) {
8552 if (!PageCompound(imu->bvec[j].bv_page))
8554 if (compound_head(imu->bvec[j].bv_page) == hpage)
8562 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8563 int nr_pages, struct io_mapped_ubuf *imu,
8564 struct page **last_hpage)
8568 imu->acct_pages = 0;
8569 for (i = 0; i < nr_pages; i++) {
8570 if (!PageCompound(pages[i])) {
8575 hpage = compound_head(pages[i]);
8576 if (hpage == *last_hpage)
8578 *last_hpage = hpage;
8579 if (headpage_already_acct(ctx, pages, i, hpage))
8581 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8585 if (!imu->acct_pages)
8588 ret = io_account_mem(ctx, imu->acct_pages);
8590 imu->acct_pages = 0;
8594 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8595 struct io_mapped_ubuf **pimu,
8596 struct page **last_hpage)
8598 struct io_mapped_ubuf *imu = NULL;
8599 struct vm_area_struct **vmas = NULL;
8600 struct page **pages = NULL;
8601 unsigned long off, start, end, ubuf;
8603 int ret, pret, nr_pages, i;
8605 if (!iov->iov_base) {
8606 *pimu = ctx->dummy_ubuf;
8610 ubuf = (unsigned long) iov->iov_base;
8611 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8612 start = ubuf >> PAGE_SHIFT;
8613 nr_pages = end - start;
8618 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8622 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8627 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8632 mmap_read_lock(current->mm);
8633 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8635 if (pret == nr_pages) {
8636 /* don't support file backed memory */
8637 for (i = 0; i < nr_pages; i++) {
8638 struct vm_area_struct *vma = vmas[i];
8640 if (vma_is_shmem(vma))
8643 !is_file_hugepages(vma->vm_file)) {
8649 ret = pret < 0 ? pret : -EFAULT;
8651 mmap_read_unlock(current->mm);
8654 * if we did partial map, or found file backed vmas,
8655 * release any pages we did get
8658 unpin_user_pages(pages, pret);
8662 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8664 unpin_user_pages(pages, pret);
8668 off = ubuf & ~PAGE_MASK;
8669 size = iov->iov_len;
8670 for (i = 0; i < nr_pages; i++) {
8673 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8674 imu->bvec[i].bv_page = pages[i];
8675 imu->bvec[i].bv_len = vec_len;
8676 imu->bvec[i].bv_offset = off;
8680 /* store original address for later verification */
8682 imu->ubuf_end = ubuf + iov->iov_len;
8683 imu->nr_bvecs = nr_pages;
8694 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8696 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8697 return ctx->user_bufs ? 0 : -ENOMEM;
8700 static int io_buffer_validate(struct iovec *iov)
8702 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8705 * Don't impose further limits on the size and buffer
8706 * constraints here, we'll -EINVAL later when IO is
8707 * submitted if they are wrong.
8710 return iov->iov_len ? -EFAULT : 0;
8714 /* arbitrary limit, but we need something */
8715 if (iov->iov_len > SZ_1G)
8718 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8724 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8725 unsigned int nr_args, u64 __user *tags)
8727 struct page *last_hpage = NULL;
8728 struct io_rsrc_data *data;
8734 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8736 ret = io_rsrc_node_switch_start(ctx);
8739 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8742 ret = io_buffers_map_alloc(ctx, nr_args);
8744 io_rsrc_data_free(data);
8748 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8749 ret = io_copy_iov(ctx, &iov, arg, i);
8752 ret = io_buffer_validate(&iov);
8755 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8760 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8766 WARN_ON_ONCE(ctx->buf_data);
8768 ctx->buf_data = data;
8770 __io_sqe_buffers_unregister(ctx);
8772 io_rsrc_node_switch(ctx, NULL);
8776 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8777 struct io_uring_rsrc_update2 *up,
8778 unsigned int nr_args)
8780 u64 __user *tags = u64_to_user_ptr(up->tags);
8781 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8782 struct page *last_hpage = NULL;
8783 bool needs_switch = false;
8789 if (up->offset + nr_args > ctx->nr_user_bufs)
8792 for (done = 0; done < nr_args; done++) {
8793 struct io_mapped_ubuf *imu;
8794 int offset = up->offset + done;
8797 err = io_copy_iov(ctx, &iov, iovs, done);
8800 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8804 err = io_buffer_validate(&iov);
8807 if (!iov.iov_base && tag) {
8811 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8815 i = array_index_nospec(offset, ctx->nr_user_bufs);
8816 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8817 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8818 ctx->rsrc_node, ctx->user_bufs[i]);
8819 if (unlikely(err)) {
8820 io_buffer_unmap(ctx, &imu);
8823 ctx->user_bufs[i] = NULL;
8824 needs_switch = true;
8827 ctx->user_bufs[i] = imu;
8828 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8832 io_rsrc_node_switch(ctx, ctx->buf_data);
8833 return done ? done : err;
8836 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8838 __s32 __user *fds = arg;
8844 if (copy_from_user(&fd, fds, sizeof(*fds)))
8847 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8848 if (IS_ERR(ctx->cq_ev_fd)) {
8849 int ret = PTR_ERR(ctx->cq_ev_fd);
8851 ctx->cq_ev_fd = NULL;
8858 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8860 if (ctx->cq_ev_fd) {
8861 eventfd_ctx_put(ctx->cq_ev_fd);
8862 ctx->cq_ev_fd = NULL;
8869 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8871 struct io_buffer *buf;
8872 unsigned long index;
8874 xa_for_each(&ctx->io_buffers, index, buf)
8875 __io_remove_buffers(ctx, buf, index, -1U);
8878 static void io_req_cache_free(struct list_head *list)
8880 struct io_kiocb *req, *nxt;
8882 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8883 list_del(&req->inflight_entry);
8884 kmem_cache_free(req_cachep, req);
8888 static void io_req_caches_free(struct io_ring_ctx *ctx)
8890 struct io_submit_state *state = &ctx->submit_state;
8892 mutex_lock(&ctx->uring_lock);
8894 if (state->free_reqs) {
8895 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8896 state->free_reqs = 0;
8899 io_flush_cached_locked_reqs(ctx, state);
8900 io_req_cache_free(&state->free_list);
8901 mutex_unlock(&ctx->uring_lock);
8904 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8906 if (data && !atomic_dec_and_test(&data->refs))
8907 wait_for_completion(&data->done);
8910 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8912 io_sq_thread_finish(ctx);
8914 if (ctx->mm_account) {
8915 mmdrop(ctx->mm_account);
8916 ctx->mm_account = NULL;
8919 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8920 io_wait_rsrc_data(ctx->buf_data);
8921 io_wait_rsrc_data(ctx->file_data);
8923 mutex_lock(&ctx->uring_lock);
8925 __io_sqe_buffers_unregister(ctx);
8927 __io_sqe_files_unregister(ctx);
8929 __io_cqring_overflow_flush(ctx, true);
8930 mutex_unlock(&ctx->uring_lock);
8931 io_eventfd_unregister(ctx);
8932 io_destroy_buffers(ctx);
8934 put_cred(ctx->sq_creds);
8936 /* there are no registered resources left, nobody uses it */
8938 io_rsrc_node_destroy(ctx->rsrc_node);
8939 if (ctx->rsrc_backup_node)
8940 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8941 flush_delayed_work(&ctx->rsrc_put_work);
8943 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8944 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8946 #if defined(CONFIG_UNIX)
8947 if (ctx->ring_sock) {
8948 ctx->ring_sock->file = NULL; /* so that iput() is called */
8949 sock_release(ctx->ring_sock);
8952 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8954 io_mem_free(ctx->rings);
8955 io_mem_free(ctx->sq_sqes);
8957 percpu_ref_exit(&ctx->refs);
8958 free_uid(ctx->user);
8959 io_req_caches_free(ctx);
8961 io_wq_put_hash(ctx->hash_map);
8962 kfree(ctx->cancel_hash);
8963 kfree(ctx->dummy_ubuf);
8967 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8969 struct io_ring_ctx *ctx = file->private_data;
8972 poll_wait(file, &ctx->poll_wait, wait);
8974 * synchronizes with barrier from wq_has_sleeper call in
8978 if (!io_sqring_full(ctx))
8979 mask |= EPOLLOUT | EPOLLWRNORM;
8982 * Don't flush cqring overflow list here, just do a simple check.
8983 * Otherwise there could possible be ABBA deadlock:
8986 * lock(&ctx->uring_lock);
8988 * lock(&ctx->uring_lock);
8991 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8992 * pushs them to do the flush.
8994 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8995 mask |= EPOLLIN | EPOLLRDNORM;
9000 static int io_uring_fasync(int fd, struct file *file, int on)
9002 struct io_ring_ctx *ctx = file->private_data;
9004 return fasync_helper(fd, file, on, &ctx->cq_fasync);
9007 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9009 const struct cred *creds;
9011 creds = xa_erase(&ctx->personalities, id);
9020 struct io_tctx_exit {
9021 struct callback_head task_work;
9022 struct completion completion;
9023 struct io_ring_ctx *ctx;
9026 static void io_tctx_exit_cb(struct callback_head *cb)
9028 struct io_uring_task *tctx = current->io_uring;
9029 struct io_tctx_exit *work;
9031 work = container_of(cb, struct io_tctx_exit, task_work);
9033 * When @in_idle, we're in cancellation and it's racy to remove the
9034 * node. It'll be removed by the end of cancellation, just ignore it.
9036 if (!atomic_read(&tctx->in_idle))
9037 io_uring_del_tctx_node((unsigned long)work->ctx);
9038 complete(&work->completion);
9041 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9043 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9045 return req->ctx == data;
9048 static void io_ring_exit_work(struct work_struct *work)
9050 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9051 unsigned long timeout = jiffies + HZ * 60 * 5;
9052 unsigned long interval = HZ / 20;
9053 struct io_tctx_exit exit;
9054 struct io_tctx_node *node;
9058 * If we're doing polled IO and end up having requests being
9059 * submitted async (out-of-line), then completions can come in while
9060 * we're waiting for refs to drop. We need to reap these manually,
9061 * as nobody else will be looking for them.
9064 io_uring_try_cancel_requests(ctx, NULL, true);
9066 struct io_sq_data *sqd = ctx->sq_data;
9067 struct task_struct *tsk;
9069 io_sq_thread_park(sqd);
9071 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9072 io_wq_cancel_cb(tsk->io_uring->io_wq,
9073 io_cancel_ctx_cb, ctx, true);
9074 io_sq_thread_unpark(sqd);
9077 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9078 /* there is little hope left, don't run it too often */
9081 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9083 init_completion(&exit.completion);
9084 init_task_work(&exit.task_work, io_tctx_exit_cb);
9087 * Some may use context even when all refs and requests have been put,
9088 * and they are free to do so while still holding uring_lock or
9089 * completion_lock, see io_req_task_submit(). Apart from other work,
9090 * this lock/unlock section also waits them to finish.
9092 mutex_lock(&ctx->uring_lock);
9093 while (!list_empty(&ctx->tctx_list)) {
9094 WARN_ON_ONCE(time_after(jiffies, timeout));
9096 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9098 /* don't spin on a single task if cancellation failed */
9099 list_rotate_left(&ctx->tctx_list);
9100 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9101 if (WARN_ON_ONCE(ret))
9103 wake_up_process(node->task);
9105 mutex_unlock(&ctx->uring_lock);
9106 wait_for_completion(&exit.completion);
9107 mutex_lock(&ctx->uring_lock);
9109 mutex_unlock(&ctx->uring_lock);
9110 spin_lock(&ctx->completion_lock);
9111 spin_unlock(&ctx->completion_lock);
9113 io_ring_ctx_free(ctx);
9116 /* Returns true if we found and killed one or more timeouts */
9117 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9120 struct io_kiocb *req, *tmp;
9123 spin_lock(&ctx->completion_lock);
9124 spin_lock_irq(&ctx->timeout_lock);
9125 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9126 if (io_match_task(req, tsk, cancel_all)) {
9127 io_kill_timeout(req, -ECANCELED);
9131 spin_unlock_irq(&ctx->timeout_lock);
9133 io_commit_cqring(ctx);
9134 spin_unlock(&ctx->completion_lock);
9136 io_cqring_ev_posted(ctx);
9137 return canceled != 0;
9140 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9142 unsigned long index;
9143 struct creds *creds;
9145 mutex_lock(&ctx->uring_lock);
9146 percpu_ref_kill(&ctx->refs);
9148 __io_cqring_overflow_flush(ctx, true);
9149 xa_for_each(&ctx->personalities, index, creds)
9150 io_unregister_personality(ctx, index);
9151 mutex_unlock(&ctx->uring_lock);
9153 io_kill_timeouts(ctx, NULL, true);
9154 io_poll_remove_all(ctx, NULL, true);
9156 /* if we failed setting up the ctx, we might not have any rings */
9157 io_iopoll_try_reap_events(ctx);
9159 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9161 * Use system_unbound_wq to avoid spawning tons of event kworkers
9162 * if we're exiting a ton of rings at the same time. It just adds
9163 * noise and overhead, there's no discernable change in runtime
9164 * over using system_wq.
9166 queue_work(system_unbound_wq, &ctx->exit_work);
9169 static int io_uring_release(struct inode *inode, struct file *file)
9171 struct io_ring_ctx *ctx = file->private_data;
9173 file->private_data = NULL;
9174 io_ring_ctx_wait_and_kill(ctx);
9178 struct io_task_cancel {
9179 struct task_struct *task;
9183 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9185 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9186 struct io_task_cancel *cancel = data;
9189 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9190 struct io_ring_ctx *ctx = req->ctx;
9192 /* protect against races with linked timeouts */
9193 spin_lock(&ctx->completion_lock);
9194 ret = io_match_task(req, cancel->task, cancel->all);
9195 spin_unlock(&ctx->completion_lock);
9197 ret = io_match_task(req, cancel->task, cancel->all);
9202 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9203 struct task_struct *task, bool cancel_all)
9205 struct io_defer_entry *de;
9208 spin_lock(&ctx->completion_lock);
9209 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9210 if (io_match_task(de->req, task, cancel_all)) {
9211 list_cut_position(&list, &ctx->defer_list, &de->list);
9215 spin_unlock(&ctx->completion_lock);
9216 if (list_empty(&list))
9219 while (!list_empty(&list)) {
9220 de = list_first_entry(&list, struct io_defer_entry, list);
9221 list_del_init(&de->list);
9222 io_req_complete_failed(de->req, -ECANCELED);
9228 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9230 struct io_tctx_node *node;
9231 enum io_wq_cancel cret;
9234 mutex_lock(&ctx->uring_lock);
9235 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9236 struct io_uring_task *tctx = node->task->io_uring;
9239 * io_wq will stay alive while we hold uring_lock, because it's
9240 * killed after ctx nodes, which requires to take the lock.
9242 if (!tctx || !tctx->io_wq)
9244 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9245 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9247 mutex_unlock(&ctx->uring_lock);
9252 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9253 struct task_struct *task,
9256 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9257 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9260 enum io_wq_cancel cret;
9264 ret |= io_uring_try_cancel_iowq(ctx);
9265 } else if (tctx && tctx->io_wq) {
9267 * Cancels requests of all rings, not only @ctx, but
9268 * it's fine as the task is in exit/exec.
9270 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9272 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9275 /* SQPOLL thread does its own polling */
9276 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9277 (ctx->sq_data && ctx->sq_data->thread == current)) {
9278 while (!list_empty_careful(&ctx->iopoll_list)) {
9279 io_iopoll_try_reap_events(ctx);
9284 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9285 ret |= io_poll_remove_all(ctx, task, cancel_all);
9286 ret |= io_kill_timeouts(ctx, task, cancel_all);
9288 ret |= io_run_task_work();
9295 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9297 struct io_uring_task *tctx = current->io_uring;
9298 struct io_tctx_node *node;
9301 if (unlikely(!tctx)) {
9302 ret = io_uring_alloc_task_context(current, ctx);
9305 tctx = current->io_uring;
9307 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9308 node = kmalloc(sizeof(*node), GFP_KERNEL);
9312 node->task = current;
9314 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9321 mutex_lock(&ctx->uring_lock);
9322 list_add(&node->ctx_node, &ctx->tctx_list);
9323 mutex_unlock(&ctx->uring_lock);
9330 * Note that this task has used io_uring. We use it for cancelation purposes.
9332 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9334 struct io_uring_task *tctx = current->io_uring;
9336 if (likely(tctx && tctx->last == ctx))
9338 return __io_uring_add_tctx_node(ctx);
9342 * Remove this io_uring_file -> task mapping.
9344 static void io_uring_del_tctx_node(unsigned long index)
9346 struct io_uring_task *tctx = current->io_uring;
9347 struct io_tctx_node *node;
9351 node = xa_erase(&tctx->xa, index);
9355 WARN_ON_ONCE(current != node->task);
9356 WARN_ON_ONCE(list_empty(&node->ctx_node));
9358 mutex_lock(&node->ctx->uring_lock);
9359 list_del(&node->ctx_node);
9360 mutex_unlock(&node->ctx->uring_lock);
9362 if (tctx->last == node->ctx)
9367 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9369 struct io_wq *wq = tctx->io_wq;
9370 struct io_tctx_node *node;
9371 unsigned long index;
9373 xa_for_each(&tctx->xa, index, node)
9374 io_uring_del_tctx_node(index);
9377 * Must be after io_uring_del_task_file() (removes nodes under
9378 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9380 io_wq_put_and_exit(wq);
9385 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9388 return atomic_read(&tctx->inflight_tracked);
9389 return percpu_counter_sum(&tctx->inflight);
9392 static void io_uring_drop_tctx_refs(struct task_struct *task)
9394 struct io_uring_task *tctx = task->io_uring;
9395 unsigned int refs = tctx->cached_refs;
9398 tctx->cached_refs = 0;
9399 percpu_counter_sub(&tctx->inflight, refs);
9400 put_task_struct_many(task, refs);
9405 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9406 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9408 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9410 struct io_uring_task *tctx = current->io_uring;
9411 struct io_ring_ctx *ctx;
9415 WARN_ON_ONCE(sqd && sqd->thread != current);
9417 if (!current->io_uring)
9420 io_wq_exit_start(tctx->io_wq);
9422 atomic_inc(&tctx->in_idle);
9424 io_uring_drop_tctx_refs(current);
9425 /* read completions before cancelations */
9426 inflight = tctx_inflight(tctx, !cancel_all);
9431 struct io_tctx_node *node;
9432 unsigned long index;
9434 xa_for_each(&tctx->xa, index, node) {
9435 /* sqpoll task will cancel all its requests */
9436 if (node->ctx->sq_data)
9438 io_uring_try_cancel_requests(node->ctx, current,
9442 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9443 io_uring_try_cancel_requests(ctx, current,
9447 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9448 io_uring_drop_tctx_refs(current);
9450 * If we've seen completions, retry without waiting. This
9451 * avoids a race where a completion comes in before we did
9452 * prepare_to_wait().
9454 if (inflight == tctx_inflight(tctx, !cancel_all))
9456 finish_wait(&tctx->wait, &wait);
9458 atomic_dec(&tctx->in_idle);
9460 io_uring_clean_tctx(tctx);
9462 /* for exec all current's requests should be gone, kill tctx */
9463 __io_uring_free(current);
9467 void __io_uring_cancel(bool cancel_all)
9469 io_uring_cancel_generic(cancel_all, NULL);
9472 static void *io_uring_validate_mmap_request(struct file *file,
9473 loff_t pgoff, size_t sz)
9475 struct io_ring_ctx *ctx = file->private_data;
9476 loff_t offset = pgoff << PAGE_SHIFT;
9481 case IORING_OFF_SQ_RING:
9482 case IORING_OFF_CQ_RING:
9485 case IORING_OFF_SQES:
9489 return ERR_PTR(-EINVAL);
9492 page = virt_to_head_page(ptr);
9493 if (sz > page_size(page))
9494 return ERR_PTR(-EINVAL);
9501 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9503 size_t sz = vma->vm_end - vma->vm_start;
9507 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9509 return PTR_ERR(ptr);
9511 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9512 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9515 #else /* !CONFIG_MMU */
9517 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9519 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9522 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9524 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9527 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9528 unsigned long addr, unsigned long len,
9529 unsigned long pgoff, unsigned long flags)
9533 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9535 return PTR_ERR(ptr);
9537 return (unsigned long) ptr;
9540 #endif /* !CONFIG_MMU */
9542 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9547 if (!io_sqring_full(ctx))
9549 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9551 if (!io_sqring_full(ctx))
9554 } while (!signal_pending(current));
9556 finish_wait(&ctx->sqo_sq_wait, &wait);
9560 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9561 struct __kernel_timespec __user **ts,
9562 const sigset_t __user **sig)
9564 struct io_uring_getevents_arg arg;
9567 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9568 * is just a pointer to the sigset_t.
9570 if (!(flags & IORING_ENTER_EXT_ARG)) {
9571 *sig = (const sigset_t __user *) argp;
9577 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9578 * timespec and sigset_t pointers if good.
9580 if (*argsz != sizeof(arg))
9582 if (copy_from_user(&arg, argp, sizeof(arg)))
9584 *sig = u64_to_user_ptr(arg.sigmask);
9585 *argsz = arg.sigmask_sz;
9586 *ts = u64_to_user_ptr(arg.ts);
9590 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9591 u32, min_complete, u32, flags, const void __user *, argp,
9594 struct io_ring_ctx *ctx;
9601 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9602 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9606 if (unlikely(!f.file))
9610 if (unlikely(f.file->f_op != &io_uring_fops))
9614 ctx = f.file->private_data;
9615 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9619 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9623 * For SQ polling, the thread will do all submissions and completions.
9624 * Just return the requested submit count, and wake the thread if
9628 if (ctx->flags & IORING_SETUP_SQPOLL) {
9629 io_cqring_overflow_flush(ctx);
9631 if (unlikely(ctx->sq_data->thread == NULL)) {
9635 if (flags & IORING_ENTER_SQ_WAKEUP)
9636 wake_up(&ctx->sq_data->wait);
9637 if (flags & IORING_ENTER_SQ_WAIT) {
9638 ret = io_sqpoll_wait_sq(ctx);
9642 submitted = to_submit;
9643 } else if (to_submit) {
9644 ret = io_uring_add_tctx_node(ctx);
9647 mutex_lock(&ctx->uring_lock);
9648 submitted = io_submit_sqes(ctx, to_submit);
9649 mutex_unlock(&ctx->uring_lock);
9651 if (submitted != to_submit)
9654 if (flags & IORING_ENTER_GETEVENTS) {
9655 const sigset_t __user *sig;
9656 struct __kernel_timespec __user *ts;
9658 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9662 min_complete = min(min_complete, ctx->cq_entries);
9665 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9666 * space applications don't need to do io completion events
9667 * polling again, they can rely on io_sq_thread to do polling
9668 * work, which can reduce cpu usage and uring_lock contention.
9670 if (ctx->flags & IORING_SETUP_IOPOLL &&
9671 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9672 ret = io_iopoll_check(ctx, min_complete);
9674 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9679 percpu_ref_put(&ctx->refs);
9682 return submitted ? submitted : ret;
9685 #ifdef CONFIG_PROC_FS
9686 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9687 const struct cred *cred)
9689 struct user_namespace *uns = seq_user_ns(m);
9690 struct group_info *gi;
9695 seq_printf(m, "%5d\n", id);
9696 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9697 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9698 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9699 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9700 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9701 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9702 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9703 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9704 seq_puts(m, "\n\tGroups:\t");
9705 gi = cred->group_info;
9706 for (g = 0; g < gi->ngroups; g++) {
9707 seq_put_decimal_ull(m, g ? " " : "",
9708 from_kgid_munged(uns, gi->gid[g]));
9710 seq_puts(m, "\n\tCapEff:\t");
9711 cap = cred->cap_effective;
9712 CAP_FOR_EACH_U32(__capi)
9713 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9718 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9720 struct io_sq_data *sq = NULL;
9725 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9726 * since fdinfo case grabs it in the opposite direction of normal use
9727 * cases. If we fail to get the lock, we just don't iterate any
9728 * structures that could be going away outside the io_uring mutex.
9730 has_lock = mutex_trylock(&ctx->uring_lock);
9732 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9738 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9739 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9740 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9741 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9742 struct file *f = io_file_from_index(ctx, i);
9745 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9747 seq_printf(m, "%5u: <none>\n", i);
9749 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9750 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9751 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9752 unsigned int len = buf->ubuf_end - buf->ubuf;
9754 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9756 if (has_lock && !xa_empty(&ctx->personalities)) {
9757 unsigned long index;
9758 const struct cred *cred;
9760 seq_printf(m, "Personalities:\n");
9761 xa_for_each(&ctx->personalities, index, cred)
9762 io_uring_show_cred(m, index, cred);
9764 seq_printf(m, "PollList:\n");
9765 spin_lock(&ctx->completion_lock);
9766 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9767 struct hlist_head *list = &ctx->cancel_hash[i];
9768 struct io_kiocb *req;
9770 hlist_for_each_entry(req, list, hash_node)
9771 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9772 req->task->task_works != NULL);
9774 spin_unlock(&ctx->completion_lock);
9776 mutex_unlock(&ctx->uring_lock);
9779 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9781 struct io_ring_ctx *ctx = f->private_data;
9783 if (percpu_ref_tryget(&ctx->refs)) {
9784 __io_uring_show_fdinfo(ctx, m);
9785 percpu_ref_put(&ctx->refs);
9790 static const struct file_operations io_uring_fops = {
9791 .release = io_uring_release,
9792 .mmap = io_uring_mmap,
9794 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9795 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9797 .poll = io_uring_poll,
9798 .fasync = io_uring_fasync,
9799 #ifdef CONFIG_PROC_FS
9800 .show_fdinfo = io_uring_show_fdinfo,
9804 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9805 struct io_uring_params *p)
9807 struct io_rings *rings;
9808 size_t size, sq_array_offset;
9810 /* make sure these are sane, as we already accounted them */
9811 ctx->sq_entries = p->sq_entries;
9812 ctx->cq_entries = p->cq_entries;
9814 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9815 if (size == SIZE_MAX)
9818 rings = io_mem_alloc(size);
9823 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9824 rings->sq_ring_mask = p->sq_entries - 1;
9825 rings->cq_ring_mask = p->cq_entries - 1;
9826 rings->sq_ring_entries = p->sq_entries;
9827 rings->cq_ring_entries = p->cq_entries;
9829 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9830 if (size == SIZE_MAX) {
9831 io_mem_free(ctx->rings);
9836 ctx->sq_sqes = io_mem_alloc(size);
9837 if (!ctx->sq_sqes) {
9838 io_mem_free(ctx->rings);
9846 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9850 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9854 ret = io_uring_add_tctx_node(ctx);
9859 fd_install(fd, file);
9864 * Allocate an anonymous fd, this is what constitutes the application
9865 * visible backing of an io_uring instance. The application mmaps this
9866 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9867 * we have to tie this fd to a socket for file garbage collection purposes.
9869 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9872 #if defined(CONFIG_UNIX)
9875 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9878 return ERR_PTR(ret);
9881 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9882 O_RDWR | O_CLOEXEC);
9883 #if defined(CONFIG_UNIX)
9885 sock_release(ctx->ring_sock);
9886 ctx->ring_sock = NULL;
9888 ctx->ring_sock->file = file;
9894 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9895 struct io_uring_params __user *params)
9897 struct io_ring_ctx *ctx;
9903 if (entries > IORING_MAX_ENTRIES) {
9904 if (!(p->flags & IORING_SETUP_CLAMP))
9906 entries = IORING_MAX_ENTRIES;
9910 * Use twice as many entries for the CQ ring. It's possible for the
9911 * application to drive a higher depth than the size of the SQ ring,
9912 * since the sqes are only used at submission time. This allows for
9913 * some flexibility in overcommitting a bit. If the application has
9914 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9915 * of CQ ring entries manually.
9917 p->sq_entries = roundup_pow_of_two(entries);
9918 if (p->flags & IORING_SETUP_CQSIZE) {
9920 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9921 * to a power-of-two, if it isn't already. We do NOT impose
9922 * any cq vs sq ring sizing.
9926 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9927 if (!(p->flags & IORING_SETUP_CLAMP))
9929 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9931 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9932 if (p->cq_entries < p->sq_entries)
9935 p->cq_entries = 2 * p->sq_entries;
9938 ctx = io_ring_ctx_alloc(p);
9941 ctx->compat = in_compat_syscall();
9942 if (!capable(CAP_IPC_LOCK))
9943 ctx->user = get_uid(current_user());
9946 * This is just grabbed for accounting purposes. When a process exits,
9947 * the mm is exited and dropped before the files, hence we need to hang
9948 * on to this mm purely for the purposes of being able to unaccount
9949 * memory (locked/pinned vm). It's not used for anything else.
9951 mmgrab(current->mm);
9952 ctx->mm_account = current->mm;
9954 ret = io_allocate_scq_urings(ctx, p);
9958 ret = io_sq_offload_create(ctx, p);
9961 /* always set a rsrc node */
9962 ret = io_rsrc_node_switch_start(ctx);
9965 io_rsrc_node_switch(ctx, NULL);
9967 memset(&p->sq_off, 0, sizeof(p->sq_off));
9968 p->sq_off.head = offsetof(struct io_rings, sq.head);
9969 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9970 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9971 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9972 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9973 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9974 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9976 memset(&p->cq_off, 0, sizeof(p->cq_off));
9977 p->cq_off.head = offsetof(struct io_rings, cq.head);
9978 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9979 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9980 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9981 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9982 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9983 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9985 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9986 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9987 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9988 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9989 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9990 IORING_FEAT_RSRC_TAGS;
9992 if (copy_to_user(params, p, sizeof(*p))) {
9997 file = io_uring_get_file(ctx);
9999 ret = PTR_ERR(file);
10004 * Install ring fd as the very last thing, so we don't risk someone
10005 * having closed it before we finish setup
10007 ret = io_uring_install_fd(ctx, file);
10009 /* fput will clean it up */
10014 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10017 io_ring_ctx_wait_and_kill(ctx);
10022 * Sets up an aio uring context, and returns the fd. Applications asks for a
10023 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10024 * params structure passed in.
10026 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10028 struct io_uring_params p;
10031 if (copy_from_user(&p, params, sizeof(p)))
10033 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10038 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10039 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10040 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10041 IORING_SETUP_R_DISABLED))
10044 return io_uring_create(entries, &p, params);
10047 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10048 struct io_uring_params __user *, params)
10050 return io_uring_setup(entries, params);
10053 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10055 struct io_uring_probe *p;
10059 size = struct_size(p, ops, nr_args);
10060 if (size == SIZE_MAX)
10062 p = kzalloc(size, GFP_KERNEL);
10067 if (copy_from_user(p, arg, size))
10070 if (memchr_inv(p, 0, size))
10073 p->last_op = IORING_OP_LAST - 1;
10074 if (nr_args > IORING_OP_LAST)
10075 nr_args = IORING_OP_LAST;
10077 for (i = 0; i < nr_args; i++) {
10079 if (!io_op_defs[i].not_supported)
10080 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10085 if (copy_to_user(arg, p, size))
10092 static int io_register_personality(struct io_ring_ctx *ctx)
10094 const struct cred *creds;
10098 creds = get_current_cred();
10100 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10101 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10109 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10110 unsigned int nr_args)
10112 struct io_uring_restriction *res;
10116 /* Restrictions allowed only if rings started disabled */
10117 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10120 /* We allow only a single restrictions registration */
10121 if (ctx->restrictions.registered)
10124 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10127 size = array_size(nr_args, sizeof(*res));
10128 if (size == SIZE_MAX)
10131 res = memdup_user(arg, size);
10133 return PTR_ERR(res);
10137 for (i = 0; i < nr_args; i++) {
10138 switch (res[i].opcode) {
10139 case IORING_RESTRICTION_REGISTER_OP:
10140 if (res[i].register_op >= IORING_REGISTER_LAST) {
10145 __set_bit(res[i].register_op,
10146 ctx->restrictions.register_op);
10148 case IORING_RESTRICTION_SQE_OP:
10149 if (res[i].sqe_op >= IORING_OP_LAST) {
10154 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10156 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10157 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10159 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10160 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10169 /* Reset all restrictions if an error happened */
10171 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10173 ctx->restrictions.registered = true;
10179 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10181 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10184 if (ctx->restrictions.registered)
10185 ctx->restricted = 1;
10187 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10188 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10189 wake_up(&ctx->sq_data->wait);
10193 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10194 struct io_uring_rsrc_update2 *up,
10202 if (check_add_overflow(up->offset, nr_args, &tmp))
10204 err = io_rsrc_node_switch_start(ctx);
10209 case IORING_RSRC_FILE:
10210 return __io_sqe_files_update(ctx, up, nr_args);
10211 case IORING_RSRC_BUFFER:
10212 return __io_sqe_buffers_update(ctx, up, nr_args);
10217 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10220 struct io_uring_rsrc_update2 up;
10224 memset(&up, 0, sizeof(up));
10225 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10227 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10230 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10231 unsigned size, unsigned type)
10233 struct io_uring_rsrc_update2 up;
10235 if (size != sizeof(up))
10237 if (copy_from_user(&up, arg, sizeof(up)))
10239 if (!up.nr || up.resv)
10241 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10244 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10245 unsigned int size, unsigned int type)
10247 struct io_uring_rsrc_register rr;
10249 /* keep it extendible */
10250 if (size != sizeof(rr))
10253 memset(&rr, 0, sizeof(rr));
10254 if (copy_from_user(&rr, arg, size))
10256 if (!rr.nr || rr.resv || rr.resv2)
10260 case IORING_RSRC_FILE:
10261 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10262 rr.nr, u64_to_user_ptr(rr.tags));
10263 case IORING_RSRC_BUFFER:
10264 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10265 rr.nr, u64_to_user_ptr(rr.tags));
10270 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10273 struct io_uring_task *tctx = current->io_uring;
10274 cpumask_var_t new_mask;
10277 if (!tctx || !tctx->io_wq)
10280 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10283 cpumask_clear(new_mask);
10284 if (len > cpumask_size())
10285 len = cpumask_size();
10287 if (copy_from_user(new_mask, arg, len)) {
10288 free_cpumask_var(new_mask);
10292 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10293 free_cpumask_var(new_mask);
10297 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10299 struct io_uring_task *tctx = current->io_uring;
10301 if (!tctx || !tctx->io_wq)
10304 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10307 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10310 struct io_uring_task *tctx = current->io_uring;
10311 __u32 new_count[2];
10314 if (!tctx || !tctx->io_wq)
10316 if (copy_from_user(new_count, arg, sizeof(new_count)))
10318 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10319 if (new_count[i] > INT_MAX)
10322 ret = io_wq_max_workers(tctx->io_wq, new_count);
10326 if (copy_to_user(arg, new_count, sizeof(new_count)))
10332 static bool io_register_op_must_quiesce(int op)
10335 case IORING_REGISTER_BUFFERS:
10336 case IORING_UNREGISTER_BUFFERS:
10337 case IORING_REGISTER_FILES:
10338 case IORING_UNREGISTER_FILES:
10339 case IORING_REGISTER_FILES_UPDATE:
10340 case IORING_REGISTER_PROBE:
10341 case IORING_REGISTER_PERSONALITY:
10342 case IORING_UNREGISTER_PERSONALITY:
10343 case IORING_REGISTER_FILES2:
10344 case IORING_REGISTER_FILES_UPDATE2:
10345 case IORING_REGISTER_BUFFERS2:
10346 case IORING_REGISTER_BUFFERS_UPDATE:
10347 case IORING_REGISTER_IOWQ_AFF:
10348 case IORING_UNREGISTER_IOWQ_AFF:
10349 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10356 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10360 percpu_ref_kill(&ctx->refs);
10363 * Drop uring mutex before waiting for references to exit. If another
10364 * thread is currently inside io_uring_enter() it might need to grab the
10365 * uring_lock to make progress. If we hold it here across the drain
10366 * wait, then we can deadlock. It's safe to drop the mutex here, since
10367 * no new references will come in after we've killed the percpu ref.
10369 mutex_unlock(&ctx->uring_lock);
10371 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10374 ret = io_run_task_work_sig();
10375 } while (ret >= 0);
10376 mutex_lock(&ctx->uring_lock);
10379 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10383 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10384 void __user *arg, unsigned nr_args)
10385 __releases(ctx->uring_lock)
10386 __acquires(ctx->uring_lock)
10391 * We're inside the ring mutex, if the ref is already dying, then
10392 * someone else killed the ctx or is already going through
10393 * io_uring_register().
10395 if (percpu_ref_is_dying(&ctx->refs))
10398 if (ctx->restricted) {
10399 if (opcode >= IORING_REGISTER_LAST)
10401 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10402 if (!test_bit(opcode, ctx->restrictions.register_op))
10406 if (io_register_op_must_quiesce(opcode)) {
10407 ret = io_ctx_quiesce(ctx);
10413 case IORING_REGISTER_BUFFERS:
10414 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10416 case IORING_UNREGISTER_BUFFERS:
10418 if (arg || nr_args)
10420 ret = io_sqe_buffers_unregister(ctx);
10422 case IORING_REGISTER_FILES:
10423 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10425 case IORING_UNREGISTER_FILES:
10427 if (arg || nr_args)
10429 ret = io_sqe_files_unregister(ctx);
10431 case IORING_REGISTER_FILES_UPDATE:
10432 ret = io_register_files_update(ctx, arg, nr_args);
10434 case IORING_REGISTER_EVENTFD:
10435 case IORING_REGISTER_EVENTFD_ASYNC:
10439 ret = io_eventfd_register(ctx, arg);
10442 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10443 ctx->eventfd_async = 1;
10445 ctx->eventfd_async = 0;
10447 case IORING_UNREGISTER_EVENTFD:
10449 if (arg || nr_args)
10451 ret = io_eventfd_unregister(ctx);
10453 case IORING_REGISTER_PROBE:
10455 if (!arg || nr_args > 256)
10457 ret = io_probe(ctx, arg, nr_args);
10459 case IORING_REGISTER_PERSONALITY:
10461 if (arg || nr_args)
10463 ret = io_register_personality(ctx);
10465 case IORING_UNREGISTER_PERSONALITY:
10469 ret = io_unregister_personality(ctx, nr_args);
10471 case IORING_REGISTER_ENABLE_RINGS:
10473 if (arg || nr_args)
10475 ret = io_register_enable_rings(ctx);
10477 case IORING_REGISTER_RESTRICTIONS:
10478 ret = io_register_restrictions(ctx, arg, nr_args);
10480 case IORING_REGISTER_FILES2:
10481 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10483 case IORING_REGISTER_FILES_UPDATE2:
10484 ret = io_register_rsrc_update(ctx, arg, nr_args,
10487 case IORING_REGISTER_BUFFERS2:
10488 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10490 case IORING_REGISTER_BUFFERS_UPDATE:
10491 ret = io_register_rsrc_update(ctx, arg, nr_args,
10492 IORING_RSRC_BUFFER);
10494 case IORING_REGISTER_IOWQ_AFF:
10496 if (!arg || !nr_args)
10498 ret = io_register_iowq_aff(ctx, arg, nr_args);
10500 case IORING_UNREGISTER_IOWQ_AFF:
10502 if (arg || nr_args)
10504 ret = io_unregister_iowq_aff(ctx);
10506 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10508 if (!arg || nr_args != 2)
10510 ret = io_register_iowq_max_workers(ctx, arg);
10517 if (io_register_op_must_quiesce(opcode)) {
10518 /* bring the ctx back to life */
10519 percpu_ref_reinit(&ctx->refs);
10520 reinit_completion(&ctx->ref_comp);
10525 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10526 void __user *, arg, unsigned int, nr_args)
10528 struct io_ring_ctx *ctx;
10537 if (f.file->f_op != &io_uring_fops)
10540 ctx = f.file->private_data;
10542 io_run_task_work();
10544 mutex_lock(&ctx->uring_lock);
10545 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10546 mutex_unlock(&ctx->uring_lock);
10547 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10548 ctx->cq_ev_fd != NULL, ret);
10554 static int __init io_uring_init(void)
10556 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10557 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10558 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10561 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10562 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10563 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10564 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10565 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10566 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10567 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10568 BUILD_BUG_SQE_ELEM(8, __u64, off);
10569 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10570 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10571 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10572 BUILD_BUG_SQE_ELEM(24, __u32, len);
10573 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10574 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10575 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10576 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10577 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10578 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10579 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10580 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10581 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10582 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10583 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10584 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10585 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10586 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10587 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10588 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10589 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10590 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10591 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10592 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10593 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10595 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10596 sizeof(struct io_uring_rsrc_update));
10597 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10598 sizeof(struct io_uring_rsrc_update2));
10600 /* ->buf_index is u16 */
10601 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10603 /* should fit into one byte */
10604 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10606 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10607 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10609 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10613 __initcall(io_uring_init);