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] = {
998 .unbound_nonreg_file = 1,
1001 .async_size = sizeof(struct io_async_rw),
1003 [IORING_OP_FADVISE] = {
1006 [IORING_OP_MADVISE] = {},
1007 [IORING_OP_SEND] = {
1009 .unbound_nonreg_file = 1,
1012 [IORING_OP_RECV] = {
1014 .unbound_nonreg_file = 1,
1018 [IORING_OP_OPENAT2] = {
1020 [IORING_OP_EPOLL_CTL] = {
1021 .unbound_nonreg_file = 1,
1023 [IORING_OP_SPLICE] = {
1026 .unbound_nonreg_file = 1,
1028 [IORING_OP_PROVIDE_BUFFERS] = {},
1029 [IORING_OP_REMOVE_BUFFERS] = {},
1033 .unbound_nonreg_file = 1,
1035 [IORING_OP_SHUTDOWN] = {
1038 [IORING_OP_RENAMEAT] = {},
1039 [IORING_OP_UNLINKAT] = {},
1042 /* requests with any of those set should undergo io_disarm_next() */
1043 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1045 static bool io_disarm_next(struct io_kiocb *req);
1046 static void io_uring_del_tctx_node(unsigned long index);
1047 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1048 struct task_struct *task,
1050 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1052 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1053 long res, unsigned int cflags);
1054 static void io_put_req(struct io_kiocb *req);
1055 static void io_put_req_deferred(struct io_kiocb *req);
1056 static void io_dismantle_req(struct io_kiocb *req);
1057 static void io_queue_linked_timeout(struct io_kiocb *req);
1058 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1059 struct io_uring_rsrc_update2 *up,
1061 static void io_clean_op(struct io_kiocb *req);
1062 static struct file *io_file_get(struct io_ring_ctx *ctx,
1063 struct io_kiocb *req, int fd, bool fixed);
1064 static void __io_queue_sqe(struct io_kiocb *req);
1065 static void io_rsrc_put_work(struct work_struct *work);
1067 static void io_req_task_queue(struct io_kiocb *req);
1068 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1069 static int io_req_prep_async(struct io_kiocb *req);
1071 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1072 unsigned int issue_flags, u32 slot_index);
1073 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1075 static struct kmem_cache *req_cachep;
1077 static const struct file_operations io_uring_fops;
1079 struct sock *io_uring_get_socket(struct file *file)
1081 #if defined(CONFIG_UNIX)
1082 if (file->f_op == &io_uring_fops) {
1083 struct io_ring_ctx *ctx = file->private_data;
1085 return ctx->ring_sock->sk;
1090 EXPORT_SYMBOL(io_uring_get_socket);
1092 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1095 mutex_lock(&ctx->uring_lock);
1100 #define io_for_each_link(pos, head) \
1101 for (pos = (head); pos; pos = pos->link)
1104 * Shamelessly stolen from the mm implementation of page reference checking,
1105 * see commit f958d7b528b1 for details.
1107 #define req_ref_zero_or_close_to_overflow(req) \
1108 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1110 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1112 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1113 return atomic_inc_not_zero(&req->refs);
1116 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1118 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1121 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1122 return atomic_dec_and_test(&req->refs);
1125 static inline void req_ref_put(struct io_kiocb *req)
1127 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1128 WARN_ON_ONCE(req_ref_put_and_test(req));
1131 static inline void req_ref_get(struct io_kiocb *req)
1133 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1134 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1135 atomic_inc(&req->refs);
1138 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1140 if (!(req->flags & REQ_F_REFCOUNT)) {
1141 req->flags |= REQ_F_REFCOUNT;
1142 atomic_set(&req->refs, nr);
1146 static inline void io_req_set_refcount(struct io_kiocb *req)
1148 __io_req_set_refcount(req, 1);
1151 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1153 struct io_ring_ctx *ctx = req->ctx;
1155 if (!req->fixed_rsrc_refs) {
1156 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1157 percpu_ref_get(req->fixed_rsrc_refs);
1161 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1163 bool got = percpu_ref_tryget(ref);
1165 /* already at zero, wait for ->release() */
1167 wait_for_completion(compl);
1168 percpu_ref_resurrect(ref);
1170 percpu_ref_put(ref);
1173 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1176 struct io_kiocb *req;
1178 if (task && head->task != task)
1183 io_for_each_link(req, head) {
1184 if (req->flags & REQ_F_INFLIGHT)
1190 static inline void req_set_fail(struct io_kiocb *req)
1192 req->flags |= REQ_F_FAIL;
1195 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1201 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1203 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1205 complete(&ctx->ref_comp);
1208 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1210 return !req->timeout.off;
1213 static void io_fallback_req_func(struct work_struct *work)
1215 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1216 fallback_work.work);
1217 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1218 struct io_kiocb *req, *tmp;
1219 bool locked = false;
1221 percpu_ref_get(&ctx->refs);
1222 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1223 req->io_task_work.func(req, &locked);
1226 if (ctx->submit_state.compl_nr)
1227 io_submit_flush_completions(ctx);
1228 mutex_unlock(&ctx->uring_lock);
1230 percpu_ref_put(&ctx->refs);
1234 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1236 struct io_ring_ctx *ctx;
1239 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1244 * Use 5 bits less than the max cq entries, that should give us around
1245 * 32 entries per hash list if totally full and uniformly spread.
1247 hash_bits = ilog2(p->cq_entries);
1251 ctx->cancel_hash_bits = hash_bits;
1252 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1254 if (!ctx->cancel_hash)
1256 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1258 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1259 if (!ctx->dummy_ubuf)
1261 /* set invalid range, so io_import_fixed() fails meeting it */
1262 ctx->dummy_ubuf->ubuf = -1UL;
1264 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1265 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1268 ctx->flags = p->flags;
1269 init_waitqueue_head(&ctx->sqo_sq_wait);
1270 INIT_LIST_HEAD(&ctx->sqd_list);
1271 init_waitqueue_head(&ctx->poll_wait);
1272 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1273 init_completion(&ctx->ref_comp);
1274 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1275 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1276 mutex_init(&ctx->uring_lock);
1277 init_waitqueue_head(&ctx->cq_wait);
1278 spin_lock_init(&ctx->completion_lock);
1279 spin_lock_init(&ctx->timeout_lock);
1280 INIT_LIST_HEAD(&ctx->iopoll_list);
1281 INIT_LIST_HEAD(&ctx->defer_list);
1282 INIT_LIST_HEAD(&ctx->timeout_list);
1283 INIT_LIST_HEAD(&ctx->ltimeout_list);
1284 spin_lock_init(&ctx->rsrc_ref_lock);
1285 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1286 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1287 init_llist_head(&ctx->rsrc_put_llist);
1288 INIT_LIST_HEAD(&ctx->tctx_list);
1289 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1290 INIT_LIST_HEAD(&ctx->locked_free_list);
1291 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1294 kfree(ctx->dummy_ubuf);
1295 kfree(ctx->cancel_hash);
1300 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1302 struct io_rings *r = ctx->rings;
1304 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1308 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1310 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1311 struct io_ring_ctx *ctx = req->ctx;
1313 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1319 #define FFS_ASYNC_READ 0x1UL
1320 #define FFS_ASYNC_WRITE 0x2UL
1322 #define FFS_ISREG 0x4UL
1324 #define FFS_ISREG 0x0UL
1326 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1328 static inline bool io_req_ffs_set(struct io_kiocb *req)
1330 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1333 static void io_req_track_inflight(struct io_kiocb *req)
1335 if (!(req->flags & REQ_F_INFLIGHT)) {
1336 req->flags |= REQ_F_INFLIGHT;
1337 atomic_inc(¤t->io_uring->inflight_tracked);
1341 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1343 req->flags &= ~REQ_F_LINK_TIMEOUT;
1346 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1348 if (WARN_ON_ONCE(!req->link))
1351 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1352 req->flags |= REQ_F_LINK_TIMEOUT;
1354 /* linked timeouts should have two refs once prep'ed */
1355 io_req_set_refcount(req);
1356 __io_req_set_refcount(req->link, 2);
1360 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1362 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1364 return __io_prep_linked_timeout(req);
1367 static void io_prep_async_work(struct io_kiocb *req)
1369 const struct io_op_def *def = &io_op_defs[req->opcode];
1370 struct io_ring_ctx *ctx = req->ctx;
1372 if (!(req->flags & REQ_F_CREDS)) {
1373 req->flags |= REQ_F_CREDS;
1374 req->creds = get_current_cred();
1377 req->work.list.next = NULL;
1378 req->work.flags = 0;
1379 if (req->flags & REQ_F_FORCE_ASYNC)
1380 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1382 if (req->flags & REQ_F_ISREG) {
1383 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1384 io_wq_hash_work(&req->work, file_inode(req->file));
1385 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1386 if (def->unbound_nonreg_file)
1387 req->work.flags |= IO_WQ_WORK_UNBOUND;
1390 switch (req->opcode) {
1391 case IORING_OP_SPLICE:
1393 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1394 req->work.flags |= IO_WQ_WORK_UNBOUND;
1399 static void io_prep_async_link(struct io_kiocb *req)
1401 struct io_kiocb *cur;
1403 if (req->flags & REQ_F_LINK_TIMEOUT) {
1404 struct io_ring_ctx *ctx = req->ctx;
1406 spin_lock(&ctx->completion_lock);
1407 io_for_each_link(cur, req)
1408 io_prep_async_work(cur);
1409 spin_unlock(&ctx->completion_lock);
1411 io_for_each_link(cur, req)
1412 io_prep_async_work(cur);
1416 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1418 struct io_ring_ctx *ctx = req->ctx;
1419 struct io_kiocb *link = io_prep_linked_timeout(req);
1420 struct io_uring_task *tctx = req->task->io_uring;
1422 /* must not take the lock, NULL it as a precaution */
1426 BUG_ON(!tctx->io_wq);
1428 /* init ->work of the whole link before punting */
1429 io_prep_async_link(req);
1432 * Not expected to happen, but if we do have a bug where this _can_
1433 * happen, catch it here and ensure the request is marked as
1434 * canceled. That will make io-wq go through the usual work cancel
1435 * procedure rather than attempt to run this request (or create a new
1438 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1439 req->work.flags |= IO_WQ_WORK_CANCEL;
1441 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1442 &req->work, req->flags);
1443 io_wq_enqueue(tctx->io_wq, &req->work);
1445 io_queue_linked_timeout(link);
1448 static void io_kill_timeout(struct io_kiocb *req, int status)
1449 __must_hold(&req->ctx->completion_lock)
1450 __must_hold(&req->ctx->timeout_lock)
1452 struct io_timeout_data *io = req->async_data;
1454 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1455 atomic_set(&req->ctx->cq_timeouts,
1456 atomic_read(&req->ctx->cq_timeouts) + 1);
1457 list_del_init(&req->timeout.list);
1458 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1459 io_put_req_deferred(req);
1463 static void io_queue_deferred(struct io_ring_ctx *ctx)
1465 while (!list_empty(&ctx->defer_list)) {
1466 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1467 struct io_defer_entry, list);
1469 if (req_need_defer(de->req, de->seq))
1471 list_del_init(&de->list);
1472 io_req_task_queue(de->req);
1477 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1478 __must_hold(&ctx->completion_lock)
1480 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1482 spin_lock_irq(&ctx->timeout_lock);
1483 while (!list_empty(&ctx->timeout_list)) {
1484 u32 events_needed, events_got;
1485 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1486 struct io_kiocb, timeout.list);
1488 if (io_is_timeout_noseq(req))
1492 * Since seq can easily wrap around over time, subtract
1493 * the last seq at which timeouts were flushed before comparing.
1494 * Assuming not more than 2^31-1 events have happened since,
1495 * these subtractions won't have wrapped, so we can check if
1496 * target is in [last_seq, current_seq] by comparing the two.
1498 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1499 events_got = seq - ctx->cq_last_tm_flush;
1500 if (events_got < events_needed)
1503 list_del_init(&req->timeout.list);
1504 io_kill_timeout(req, 0);
1506 ctx->cq_last_tm_flush = seq;
1507 spin_unlock_irq(&ctx->timeout_lock);
1510 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1512 if (ctx->off_timeout_used)
1513 io_flush_timeouts(ctx);
1514 if (ctx->drain_active)
1515 io_queue_deferred(ctx);
1518 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1520 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1521 __io_commit_cqring_flush(ctx);
1522 /* order cqe stores with ring update */
1523 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1526 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1528 struct io_rings *r = ctx->rings;
1530 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1533 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1535 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1538 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1540 struct io_rings *rings = ctx->rings;
1541 unsigned tail, mask = ctx->cq_entries - 1;
1544 * writes to the cq entry need to come after reading head; the
1545 * control dependency is enough as we're using WRITE_ONCE to
1548 if (__io_cqring_events(ctx) == ctx->cq_entries)
1551 tail = ctx->cached_cq_tail++;
1552 return &rings->cqes[tail & mask];
1555 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1557 if (likely(!ctx->cq_ev_fd))
1559 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1561 return !ctx->eventfd_async || io_wq_current_is_worker();
1565 * This should only get called when at least one event has been posted.
1566 * Some applications rely on the eventfd notification count only changing
1567 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1568 * 1:1 relationship between how many times this function is called (and
1569 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1571 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1574 * wake_up_all() may seem excessive, but io_wake_function() and
1575 * io_should_wake() handle the termination of the loop and only
1576 * wake as many waiters as we need to.
1578 if (wq_has_sleeper(&ctx->cq_wait))
1579 wake_up_all(&ctx->cq_wait);
1580 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1581 wake_up(&ctx->sq_data->wait);
1582 if (io_should_trigger_evfd(ctx))
1583 eventfd_signal(ctx->cq_ev_fd, 1);
1584 if (waitqueue_active(&ctx->poll_wait)) {
1585 wake_up_interruptible(&ctx->poll_wait);
1586 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1590 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1592 if (ctx->flags & IORING_SETUP_SQPOLL) {
1593 if (wq_has_sleeper(&ctx->cq_wait))
1594 wake_up_all(&ctx->cq_wait);
1596 if (io_should_trigger_evfd(ctx))
1597 eventfd_signal(ctx->cq_ev_fd, 1);
1598 if (waitqueue_active(&ctx->poll_wait)) {
1599 wake_up_interruptible(&ctx->poll_wait);
1600 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1604 /* Returns true if there are no backlogged entries after the flush */
1605 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1607 bool all_flushed, posted;
1609 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1613 spin_lock(&ctx->completion_lock);
1614 while (!list_empty(&ctx->cq_overflow_list)) {
1615 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1616 struct io_overflow_cqe *ocqe;
1620 ocqe = list_first_entry(&ctx->cq_overflow_list,
1621 struct io_overflow_cqe, list);
1623 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1625 io_account_cq_overflow(ctx);
1628 list_del(&ocqe->list);
1632 all_flushed = list_empty(&ctx->cq_overflow_list);
1634 clear_bit(0, &ctx->check_cq_overflow);
1635 WRITE_ONCE(ctx->rings->sq_flags,
1636 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1640 io_commit_cqring(ctx);
1641 spin_unlock(&ctx->completion_lock);
1643 io_cqring_ev_posted(ctx);
1647 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1651 if (test_bit(0, &ctx->check_cq_overflow)) {
1652 /* iopoll syncs against uring_lock, not completion_lock */
1653 if (ctx->flags & IORING_SETUP_IOPOLL)
1654 mutex_lock(&ctx->uring_lock);
1655 ret = __io_cqring_overflow_flush(ctx, false);
1656 if (ctx->flags & IORING_SETUP_IOPOLL)
1657 mutex_unlock(&ctx->uring_lock);
1663 /* must to be called somewhat shortly after putting a request */
1664 static inline void io_put_task(struct task_struct *task, int nr)
1666 struct io_uring_task *tctx = task->io_uring;
1668 if (likely(task == current)) {
1669 tctx->cached_refs += nr;
1671 percpu_counter_sub(&tctx->inflight, nr);
1672 if (unlikely(atomic_read(&tctx->in_idle)))
1673 wake_up(&tctx->wait);
1674 put_task_struct_many(task, nr);
1678 static void io_task_refs_refill(struct io_uring_task *tctx)
1680 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1682 percpu_counter_add(&tctx->inflight, refill);
1683 refcount_add(refill, ¤t->usage);
1684 tctx->cached_refs += refill;
1687 static inline void io_get_task_refs(int nr)
1689 struct io_uring_task *tctx = current->io_uring;
1691 tctx->cached_refs -= nr;
1692 if (unlikely(tctx->cached_refs < 0))
1693 io_task_refs_refill(tctx);
1696 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1697 long res, unsigned int cflags)
1699 struct io_overflow_cqe *ocqe;
1701 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1704 * If we're in ring overflow flush mode, or in task cancel mode,
1705 * or cannot allocate an overflow entry, then we need to drop it
1708 io_account_cq_overflow(ctx);
1711 if (list_empty(&ctx->cq_overflow_list)) {
1712 set_bit(0, &ctx->check_cq_overflow);
1713 WRITE_ONCE(ctx->rings->sq_flags,
1714 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1717 ocqe->cqe.user_data = user_data;
1718 ocqe->cqe.res = res;
1719 ocqe->cqe.flags = cflags;
1720 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1724 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1725 long res, unsigned int cflags)
1727 struct io_uring_cqe *cqe;
1729 trace_io_uring_complete(ctx, user_data, res, cflags);
1732 * If we can't get a cq entry, userspace overflowed the
1733 * submission (by quite a lot). Increment the overflow count in
1736 cqe = io_get_cqe(ctx);
1738 WRITE_ONCE(cqe->user_data, user_data);
1739 WRITE_ONCE(cqe->res, res);
1740 WRITE_ONCE(cqe->flags, cflags);
1743 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1746 /* not as hot to bloat with inlining */
1747 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1748 long res, unsigned int cflags)
1750 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1753 static void io_req_complete_post(struct io_kiocb *req, long res,
1754 unsigned int cflags)
1756 struct io_ring_ctx *ctx = req->ctx;
1758 spin_lock(&ctx->completion_lock);
1759 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1761 * If we're the last reference to this request, add to our locked
1764 if (req_ref_put_and_test(req)) {
1765 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1766 if (req->flags & IO_DISARM_MASK)
1767 io_disarm_next(req);
1769 io_req_task_queue(req->link);
1773 io_dismantle_req(req);
1774 io_put_task(req->task, 1);
1775 list_add(&req->inflight_entry, &ctx->locked_free_list);
1776 ctx->locked_free_nr++;
1778 if (!percpu_ref_tryget(&ctx->refs))
1781 io_commit_cqring(ctx);
1782 spin_unlock(&ctx->completion_lock);
1785 io_cqring_ev_posted(ctx);
1786 percpu_ref_put(&ctx->refs);
1790 static inline bool io_req_needs_clean(struct io_kiocb *req)
1792 return req->flags & IO_REQ_CLEAN_FLAGS;
1795 static void io_req_complete_state(struct io_kiocb *req, long res,
1796 unsigned int cflags)
1798 if (io_req_needs_clean(req))
1801 req->compl.cflags = cflags;
1802 req->flags |= REQ_F_COMPLETE_INLINE;
1805 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1806 long res, unsigned cflags)
1808 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1809 io_req_complete_state(req, res, cflags);
1811 io_req_complete_post(req, res, cflags);
1814 static inline void io_req_complete(struct io_kiocb *req, long res)
1816 __io_req_complete(req, 0, res, 0);
1819 static void io_req_complete_failed(struct io_kiocb *req, long res)
1822 io_req_complete_post(req, res, 0);
1826 * Don't initialise the fields below on every allocation, but do that in
1827 * advance and keep them valid across allocations.
1829 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1833 req->async_data = NULL;
1834 /* not necessary, but safer to zero */
1838 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1839 struct io_submit_state *state)
1841 spin_lock(&ctx->completion_lock);
1842 list_splice_init(&ctx->locked_free_list, &state->free_list);
1843 ctx->locked_free_nr = 0;
1844 spin_unlock(&ctx->completion_lock);
1847 /* Returns true IFF there are requests in the cache */
1848 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1850 struct io_submit_state *state = &ctx->submit_state;
1854 * If we have more than a batch's worth of requests in our IRQ side
1855 * locked cache, grab the lock and move them over to our submission
1858 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1859 io_flush_cached_locked_reqs(ctx, state);
1861 nr = state->free_reqs;
1862 while (!list_empty(&state->free_list)) {
1863 struct io_kiocb *req = list_first_entry(&state->free_list,
1864 struct io_kiocb, inflight_entry);
1866 list_del(&req->inflight_entry);
1867 state->reqs[nr++] = req;
1868 if (nr == ARRAY_SIZE(state->reqs))
1872 state->free_reqs = nr;
1877 * A request might get retired back into the request caches even before opcode
1878 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1879 * Because of that, io_alloc_req() should be called only under ->uring_lock
1880 * and with extra caution to not get a request that is still worked on.
1882 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1883 __must_hold(&ctx->uring_lock)
1885 struct io_submit_state *state = &ctx->submit_state;
1886 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1889 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1891 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1894 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1898 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1899 * retry single alloc to be on the safe side.
1901 if (unlikely(ret <= 0)) {
1902 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1903 if (!state->reqs[0])
1908 for (i = 0; i < ret; i++)
1909 io_preinit_req(state->reqs[i], ctx);
1910 state->free_reqs = ret;
1913 return state->reqs[state->free_reqs];
1916 static inline void io_put_file(struct file *file)
1922 static void io_dismantle_req(struct io_kiocb *req)
1924 unsigned int flags = req->flags;
1926 if (io_req_needs_clean(req))
1928 if (!(flags & REQ_F_FIXED_FILE))
1929 io_put_file(req->file);
1930 if (req->fixed_rsrc_refs)
1931 percpu_ref_put(req->fixed_rsrc_refs);
1932 if (req->async_data) {
1933 kfree(req->async_data);
1934 req->async_data = NULL;
1938 static void __io_free_req(struct io_kiocb *req)
1940 struct io_ring_ctx *ctx = req->ctx;
1942 io_dismantle_req(req);
1943 io_put_task(req->task, 1);
1945 spin_lock(&ctx->completion_lock);
1946 list_add(&req->inflight_entry, &ctx->locked_free_list);
1947 ctx->locked_free_nr++;
1948 spin_unlock(&ctx->completion_lock);
1950 percpu_ref_put(&ctx->refs);
1953 static inline void io_remove_next_linked(struct io_kiocb *req)
1955 struct io_kiocb *nxt = req->link;
1957 req->link = nxt->link;
1961 static bool io_kill_linked_timeout(struct io_kiocb *req)
1962 __must_hold(&req->ctx->completion_lock)
1963 __must_hold(&req->ctx->timeout_lock)
1965 struct io_kiocb *link = req->link;
1967 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1968 struct io_timeout_data *io = link->async_data;
1970 io_remove_next_linked(req);
1971 link->timeout.head = NULL;
1972 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1973 list_del(&link->timeout.list);
1974 io_cqring_fill_event(link->ctx, link->user_data,
1976 io_put_req_deferred(link);
1983 static void io_fail_links(struct io_kiocb *req)
1984 __must_hold(&req->ctx->completion_lock)
1986 struct io_kiocb *nxt, *link = req->link;
1990 long res = -ECANCELED;
1992 if (link->flags & REQ_F_FAIL)
1998 trace_io_uring_fail_link(req, link);
1999 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2000 io_put_req_deferred(link);
2005 static bool io_disarm_next(struct io_kiocb *req)
2006 __must_hold(&req->ctx->completion_lock)
2008 bool posted = false;
2010 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2011 struct io_kiocb *link = req->link;
2013 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2014 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2015 io_remove_next_linked(req);
2016 io_cqring_fill_event(link->ctx, link->user_data,
2018 io_put_req_deferred(link);
2021 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2022 struct io_ring_ctx *ctx = req->ctx;
2024 spin_lock_irq(&ctx->timeout_lock);
2025 posted = io_kill_linked_timeout(req);
2026 spin_unlock_irq(&ctx->timeout_lock);
2028 if (unlikely((req->flags & REQ_F_FAIL) &&
2029 !(req->flags & REQ_F_HARDLINK))) {
2030 posted |= (req->link != NULL);
2036 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2038 struct io_kiocb *nxt;
2041 * If LINK is set, we have dependent requests in this chain. If we
2042 * didn't fail this request, queue the first one up, moving any other
2043 * dependencies to the next request. In case of failure, fail the rest
2046 if (req->flags & IO_DISARM_MASK) {
2047 struct io_ring_ctx *ctx = req->ctx;
2050 spin_lock(&ctx->completion_lock);
2051 posted = io_disarm_next(req);
2053 io_commit_cqring(req->ctx);
2054 spin_unlock(&ctx->completion_lock);
2056 io_cqring_ev_posted(ctx);
2063 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2065 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2067 return __io_req_find_next(req);
2070 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2075 if (ctx->submit_state.compl_nr)
2076 io_submit_flush_completions(ctx);
2077 mutex_unlock(&ctx->uring_lock);
2080 percpu_ref_put(&ctx->refs);
2083 static void tctx_task_work(struct callback_head *cb)
2085 bool locked = false;
2086 struct io_ring_ctx *ctx = NULL;
2087 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2091 struct io_wq_work_node *node;
2093 spin_lock_irq(&tctx->task_lock);
2094 node = tctx->task_list.first;
2095 INIT_WQ_LIST(&tctx->task_list);
2097 tctx->task_running = false;
2098 spin_unlock_irq(&tctx->task_lock);
2103 struct io_wq_work_node *next = node->next;
2104 struct io_kiocb *req = container_of(node, struct io_kiocb,
2107 if (req->ctx != ctx) {
2108 ctx_flush_and_put(ctx, &locked);
2110 /* if not contended, grab and improve batching */
2111 locked = mutex_trylock(&ctx->uring_lock);
2112 percpu_ref_get(&ctx->refs);
2114 req->io_task_work.func(req, &locked);
2121 ctx_flush_and_put(ctx, &locked);
2124 static void io_req_task_work_add(struct io_kiocb *req)
2126 struct task_struct *tsk = req->task;
2127 struct io_uring_task *tctx = tsk->io_uring;
2128 enum task_work_notify_mode notify;
2129 struct io_wq_work_node *node;
2130 unsigned long flags;
2133 WARN_ON_ONCE(!tctx);
2135 spin_lock_irqsave(&tctx->task_lock, flags);
2136 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2137 running = tctx->task_running;
2139 tctx->task_running = true;
2140 spin_unlock_irqrestore(&tctx->task_lock, flags);
2142 /* task_work already pending, we're done */
2147 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2148 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2149 * processing task_work. There's no reliable way to tell if TWA_RESUME
2152 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2153 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2154 wake_up_process(tsk);
2158 spin_lock_irqsave(&tctx->task_lock, flags);
2159 tctx->task_running = false;
2160 node = tctx->task_list.first;
2161 INIT_WQ_LIST(&tctx->task_list);
2162 spin_unlock_irqrestore(&tctx->task_lock, flags);
2165 req = container_of(node, struct io_kiocb, io_task_work.node);
2167 if (llist_add(&req->io_task_work.fallback_node,
2168 &req->ctx->fallback_llist))
2169 schedule_delayed_work(&req->ctx->fallback_work, 1);
2173 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2175 struct io_ring_ctx *ctx = req->ctx;
2177 /* not needed for normal modes, but SQPOLL depends on it */
2178 io_tw_lock(ctx, locked);
2179 io_req_complete_failed(req, req->result);
2182 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2184 struct io_ring_ctx *ctx = req->ctx;
2186 io_tw_lock(ctx, locked);
2187 /* req->task == current here, checking PF_EXITING is safe */
2188 if (likely(!(req->task->flags & PF_EXITING)))
2189 __io_queue_sqe(req);
2191 io_req_complete_failed(req, -EFAULT);
2194 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2197 req->io_task_work.func = io_req_task_cancel;
2198 io_req_task_work_add(req);
2201 static void io_req_task_queue(struct io_kiocb *req)
2203 req->io_task_work.func = io_req_task_submit;
2204 io_req_task_work_add(req);
2207 static void io_req_task_queue_reissue(struct io_kiocb *req)
2209 req->io_task_work.func = io_queue_async_work;
2210 io_req_task_work_add(req);
2213 static inline void io_queue_next(struct io_kiocb *req)
2215 struct io_kiocb *nxt = io_req_find_next(req);
2218 io_req_task_queue(nxt);
2221 static void io_free_req(struct io_kiocb *req)
2227 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2233 struct task_struct *task;
2238 static inline void io_init_req_batch(struct req_batch *rb)
2245 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2246 struct req_batch *rb)
2249 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2251 io_put_task(rb->task, rb->task_refs);
2254 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2255 struct io_submit_state *state)
2258 io_dismantle_req(req);
2260 if (req->task != rb->task) {
2262 io_put_task(rb->task, rb->task_refs);
2263 rb->task = req->task;
2269 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2270 state->reqs[state->free_reqs++] = req;
2272 list_add(&req->inflight_entry, &state->free_list);
2275 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2276 __must_hold(&ctx->uring_lock)
2278 struct io_submit_state *state = &ctx->submit_state;
2279 int i, nr = state->compl_nr;
2280 struct req_batch rb;
2282 spin_lock(&ctx->completion_lock);
2283 for (i = 0; i < nr; i++) {
2284 struct io_kiocb *req = state->compl_reqs[i];
2286 __io_cqring_fill_event(ctx, req->user_data, req->result,
2289 io_commit_cqring(ctx);
2290 spin_unlock(&ctx->completion_lock);
2291 io_cqring_ev_posted(ctx);
2293 io_init_req_batch(&rb);
2294 for (i = 0; i < nr; i++) {
2295 struct io_kiocb *req = state->compl_reqs[i];
2297 if (req_ref_put_and_test(req))
2298 io_req_free_batch(&rb, req, &ctx->submit_state);
2301 io_req_free_batch_finish(ctx, &rb);
2302 state->compl_nr = 0;
2306 * Drop reference to request, return next in chain (if there is one) if this
2307 * was the last reference to this request.
2309 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2311 struct io_kiocb *nxt = NULL;
2313 if (req_ref_put_and_test(req)) {
2314 nxt = io_req_find_next(req);
2320 static inline void io_put_req(struct io_kiocb *req)
2322 if (req_ref_put_and_test(req))
2326 static inline void io_put_req_deferred(struct io_kiocb *req)
2328 if (req_ref_put_and_test(req)) {
2329 req->io_task_work.func = io_free_req_work;
2330 io_req_task_work_add(req);
2334 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2336 /* See comment at the top of this file */
2338 return __io_cqring_events(ctx);
2341 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2343 struct io_rings *rings = ctx->rings;
2345 /* make sure SQ entry isn't read before tail */
2346 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2349 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2351 unsigned int cflags;
2353 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2354 cflags |= IORING_CQE_F_BUFFER;
2355 req->flags &= ~REQ_F_BUFFER_SELECTED;
2360 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2362 struct io_buffer *kbuf;
2364 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2366 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2367 return io_put_kbuf(req, kbuf);
2370 static inline bool io_run_task_work(void)
2372 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2373 __set_current_state(TASK_RUNNING);
2374 tracehook_notify_signal();
2382 * Find and free completed poll iocbs
2384 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2385 struct list_head *done)
2387 struct req_batch rb;
2388 struct io_kiocb *req;
2390 /* order with ->result store in io_complete_rw_iopoll() */
2393 io_init_req_batch(&rb);
2394 while (!list_empty(done)) {
2395 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2396 list_del(&req->inflight_entry);
2398 if (READ_ONCE(req->result) == -EAGAIN &&
2399 !(req->flags & REQ_F_DONT_REISSUE)) {
2400 req->iopoll_completed = 0;
2401 io_req_task_queue_reissue(req);
2405 __io_cqring_fill_event(ctx, req->user_data, req->result,
2406 io_put_rw_kbuf(req));
2409 if (req_ref_put_and_test(req))
2410 io_req_free_batch(&rb, req, &ctx->submit_state);
2413 io_commit_cqring(ctx);
2414 io_cqring_ev_posted_iopoll(ctx);
2415 io_req_free_batch_finish(ctx, &rb);
2418 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2421 struct io_kiocb *req, *tmp;
2426 * Only spin for completions if we don't have multiple devices hanging
2427 * off our complete list, and we're under the requested amount.
2429 spin = !ctx->poll_multi_queue && *nr_events < min;
2431 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2432 struct kiocb *kiocb = &req->rw.kiocb;
2436 * Move completed and retryable entries to our local lists.
2437 * If we find a request that requires polling, break out
2438 * and complete those lists first, if we have entries there.
2440 if (READ_ONCE(req->iopoll_completed)) {
2441 list_move_tail(&req->inflight_entry, &done);
2444 if (!list_empty(&done))
2447 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2448 if (unlikely(ret < 0))
2453 /* iopoll may have completed current req */
2454 if (READ_ONCE(req->iopoll_completed))
2455 list_move_tail(&req->inflight_entry, &done);
2458 if (!list_empty(&done))
2459 io_iopoll_complete(ctx, nr_events, &done);
2465 * We can't just wait for polled events to come to us, we have to actively
2466 * find and complete them.
2468 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2470 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2473 mutex_lock(&ctx->uring_lock);
2474 while (!list_empty(&ctx->iopoll_list)) {
2475 unsigned int nr_events = 0;
2477 io_do_iopoll(ctx, &nr_events, 0);
2479 /* let it sleep and repeat later if can't complete a request */
2483 * Ensure we allow local-to-the-cpu processing to take place,
2484 * in this case we need to ensure that we reap all events.
2485 * Also let task_work, etc. to progress by releasing the mutex
2487 if (need_resched()) {
2488 mutex_unlock(&ctx->uring_lock);
2490 mutex_lock(&ctx->uring_lock);
2493 mutex_unlock(&ctx->uring_lock);
2496 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2498 unsigned int nr_events = 0;
2502 * We disallow the app entering submit/complete with polling, but we
2503 * still need to lock the ring to prevent racing with polled issue
2504 * that got punted to a workqueue.
2506 mutex_lock(&ctx->uring_lock);
2508 * Don't enter poll loop if we already have events pending.
2509 * If we do, we can potentially be spinning for commands that
2510 * already triggered a CQE (eg in error).
2512 if (test_bit(0, &ctx->check_cq_overflow))
2513 __io_cqring_overflow_flush(ctx, false);
2514 if (io_cqring_events(ctx))
2518 * If a submit got punted to a workqueue, we can have the
2519 * application entering polling for a command before it gets
2520 * issued. That app will hold the uring_lock for the duration
2521 * of the poll right here, so we need to take a breather every
2522 * now and then to ensure that the issue has a chance to add
2523 * the poll to the issued list. Otherwise we can spin here
2524 * forever, while the workqueue is stuck trying to acquire the
2527 if (list_empty(&ctx->iopoll_list)) {
2528 u32 tail = ctx->cached_cq_tail;
2530 mutex_unlock(&ctx->uring_lock);
2532 mutex_lock(&ctx->uring_lock);
2534 /* some requests don't go through iopoll_list */
2535 if (tail != ctx->cached_cq_tail ||
2536 list_empty(&ctx->iopoll_list))
2539 ret = io_do_iopoll(ctx, &nr_events, min);
2540 } while (!ret && nr_events < min && !need_resched());
2542 mutex_unlock(&ctx->uring_lock);
2546 static void kiocb_end_write(struct io_kiocb *req)
2549 * Tell lockdep we inherited freeze protection from submission
2552 if (req->flags & REQ_F_ISREG) {
2553 struct super_block *sb = file_inode(req->file)->i_sb;
2555 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2561 static bool io_resubmit_prep(struct io_kiocb *req)
2563 struct io_async_rw *rw = req->async_data;
2566 return !io_req_prep_async(req);
2567 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2568 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2572 static bool io_rw_should_reissue(struct io_kiocb *req)
2574 umode_t mode = file_inode(req->file)->i_mode;
2575 struct io_ring_ctx *ctx = req->ctx;
2577 if (!S_ISBLK(mode) && !S_ISREG(mode))
2579 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2580 !(ctx->flags & IORING_SETUP_IOPOLL)))
2583 * If ref is dying, we might be running poll reap from the exit work.
2584 * Don't attempt to reissue from that path, just let it fail with
2587 if (percpu_ref_is_dying(&ctx->refs))
2590 * Play it safe and assume not safe to re-import and reissue if we're
2591 * not in the original thread group (or in task context).
2593 if (!same_thread_group(req->task, current) || !in_task())
2598 static bool io_resubmit_prep(struct io_kiocb *req)
2602 static bool io_rw_should_reissue(struct io_kiocb *req)
2608 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2610 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2611 kiocb_end_write(req);
2612 if (res != req->result) {
2613 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2614 io_rw_should_reissue(req)) {
2615 req->flags |= REQ_F_REISSUE;
2624 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2626 unsigned int cflags = io_put_rw_kbuf(req);
2627 long res = req->result;
2630 struct io_ring_ctx *ctx = req->ctx;
2631 struct io_submit_state *state = &ctx->submit_state;
2633 io_req_complete_state(req, res, cflags);
2634 state->compl_reqs[state->compl_nr++] = req;
2635 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2636 io_submit_flush_completions(ctx);
2638 io_req_complete_post(req, res, cflags);
2642 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2643 unsigned int issue_flags)
2645 if (__io_complete_rw_common(req, res))
2647 __io_req_complete(req, 0, req->result, io_put_rw_kbuf(req));
2650 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2652 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2654 if (__io_complete_rw_common(req, res))
2657 req->io_task_work.func = io_req_task_complete;
2658 io_req_task_work_add(req);
2661 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2663 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2665 if (kiocb->ki_flags & IOCB_WRITE)
2666 kiocb_end_write(req);
2667 if (unlikely(res != req->result)) {
2668 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2669 io_resubmit_prep(req))) {
2671 req->flags |= REQ_F_DONT_REISSUE;
2675 WRITE_ONCE(req->result, res);
2676 /* order with io_iopoll_complete() checking ->result */
2678 WRITE_ONCE(req->iopoll_completed, 1);
2682 * After the iocb has been issued, it's safe to be found on the poll list.
2683 * Adding the kiocb to the list AFTER submission ensures that we don't
2684 * find it from a io_do_iopoll() thread before the issuer is done
2685 * accessing the kiocb cookie.
2687 static void io_iopoll_req_issued(struct io_kiocb *req)
2689 struct io_ring_ctx *ctx = req->ctx;
2690 const bool in_async = io_wq_current_is_worker();
2692 /* workqueue context doesn't hold uring_lock, grab it now */
2693 if (unlikely(in_async))
2694 mutex_lock(&ctx->uring_lock);
2697 * Track whether we have multiple files in our lists. This will impact
2698 * how we do polling eventually, not spinning if we're on potentially
2699 * different devices.
2701 if (list_empty(&ctx->iopoll_list)) {
2702 ctx->poll_multi_queue = false;
2703 } else if (!ctx->poll_multi_queue) {
2704 struct io_kiocb *list_req;
2705 unsigned int queue_num0, queue_num1;
2707 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2710 if (list_req->file != req->file) {
2711 ctx->poll_multi_queue = true;
2713 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2714 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2715 if (queue_num0 != queue_num1)
2716 ctx->poll_multi_queue = true;
2721 * For fast devices, IO may have already completed. If it has, add
2722 * it to the front so we find it first.
2724 if (READ_ONCE(req->iopoll_completed))
2725 list_add(&req->inflight_entry, &ctx->iopoll_list);
2727 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2729 if (unlikely(in_async)) {
2731 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2732 * in sq thread task context or in io worker task context. If
2733 * current task context is sq thread, we don't need to check
2734 * whether should wake up sq thread.
2736 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2737 wq_has_sleeper(&ctx->sq_data->wait))
2738 wake_up(&ctx->sq_data->wait);
2740 mutex_unlock(&ctx->uring_lock);
2744 static bool io_bdev_nowait(struct block_device *bdev)
2746 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2750 * If we tracked the file through the SCM inflight mechanism, we could support
2751 * any file. For now, just ensure that anything potentially problematic is done
2754 static bool __io_file_supports_nowait(struct file *file, int rw)
2756 umode_t mode = file_inode(file)->i_mode;
2758 if (S_ISBLK(mode)) {
2759 if (IS_ENABLED(CONFIG_BLOCK) &&
2760 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2766 if (S_ISREG(mode)) {
2767 if (IS_ENABLED(CONFIG_BLOCK) &&
2768 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2769 file->f_op != &io_uring_fops)
2774 /* any ->read/write should understand O_NONBLOCK */
2775 if (file->f_flags & O_NONBLOCK)
2778 if (!(file->f_mode & FMODE_NOWAIT))
2782 return file->f_op->read_iter != NULL;
2784 return file->f_op->write_iter != NULL;
2787 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2789 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2791 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2794 return __io_file_supports_nowait(req->file, rw);
2797 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2799 struct io_ring_ctx *ctx = req->ctx;
2800 struct kiocb *kiocb = &req->rw.kiocb;
2801 struct file *file = req->file;
2805 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2806 req->flags |= REQ_F_ISREG;
2808 kiocb->ki_pos = READ_ONCE(sqe->off);
2809 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2810 req->flags |= REQ_F_CUR_POS;
2811 kiocb->ki_pos = file->f_pos;
2813 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2814 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2815 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2819 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2820 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2821 req->flags |= REQ_F_NOWAIT;
2823 ioprio = READ_ONCE(sqe->ioprio);
2825 ret = ioprio_check_cap(ioprio);
2829 kiocb->ki_ioprio = ioprio;
2831 kiocb->ki_ioprio = get_current_ioprio();
2833 if (ctx->flags & IORING_SETUP_IOPOLL) {
2834 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2835 !kiocb->ki_filp->f_op->iopoll)
2838 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2839 kiocb->ki_complete = io_complete_rw_iopoll;
2840 req->iopoll_completed = 0;
2842 if (kiocb->ki_flags & IOCB_HIPRI)
2844 kiocb->ki_complete = io_complete_rw;
2847 if (req->opcode == IORING_OP_READ_FIXED ||
2848 req->opcode == IORING_OP_WRITE_FIXED) {
2850 io_req_set_rsrc_node(req);
2853 req->rw.addr = READ_ONCE(sqe->addr);
2854 req->rw.len = READ_ONCE(sqe->len);
2855 req->buf_index = READ_ONCE(sqe->buf_index);
2859 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2865 case -ERESTARTNOINTR:
2866 case -ERESTARTNOHAND:
2867 case -ERESTART_RESTARTBLOCK:
2869 * We can't just restart the syscall, since previously
2870 * submitted sqes may already be in progress. Just fail this
2876 kiocb->ki_complete(kiocb, ret, 0);
2880 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2881 unsigned int issue_flags)
2883 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2884 struct io_async_rw *io = req->async_data;
2885 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2887 /* add previously done IO, if any */
2888 if (io && io->bytes_done > 0) {
2890 ret = io->bytes_done;
2892 ret += io->bytes_done;
2895 if (req->flags & REQ_F_CUR_POS)
2896 req->file->f_pos = kiocb->ki_pos;
2897 if (ret >= 0 && check_reissue)
2898 __io_complete_rw(req, ret, 0, issue_flags);
2900 io_rw_done(kiocb, ret);
2902 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2903 req->flags &= ~REQ_F_REISSUE;
2904 if (io_resubmit_prep(req)) {
2905 io_req_task_queue_reissue(req);
2908 __io_req_complete(req, issue_flags, ret,
2909 io_put_rw_kbuf(req));
2914 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2915 struct io_mapped_ubuf *imu)
2917 size_t len = req->rw.len;
2918 u64 buf_end, buf_addr = req->rw.addr;
2921 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2923 /* not inside the mapped region */
2924 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2928 * May not be a start of buffer, set size appropriately
2929 * and advance us to the beginning.
2931 offset = buf_addr - imu->ubuf;
2932 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2936 * Don't use iov_iter_advance() here, as it's really slow for
2937 * using the latter parts of a big fixed buffer - it iterates
2938 * over each segment manually. We can cheat a bit here, because
2941 * 1) it's a BVEC iter, we set it up
2942 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2943 * first and last bvec
2945 * So just find our index, and adjust the iterator afterwards.
2946 * If the offset is within the first bvec (or the whole first
2947 * bvec, just use iov_iter_advance(). This makes it easier
2948 * since we can just skip the first segment, which may not
2949 * be PAGE_SIZE aligned.
2951 const struct bio_vec *bvec = imu->bvec;
2953 if (offset <= bvec->bv_len) {
2954 iov_iter_advance(iter, offset);
2956 unsigned long seg_skip;
2958 /* skip first vec */
2959 offset -= bvec->bv_len;
2960 seg_skip = 1 + (offset >> PAGE_SHIFT);
2962 iter->bvec = bvec + seg_skip;
2963 iter->nr_segs -= seg_skip;
2964 iter->count -= bvec->bv_len + offset;
2965 iter->iov_offset = offset & ~PAGE_MASK;
2972 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2974 struct io_ring_ctx *ctx = req->ctx;
2975 struct io_mapped_ubuf *imu = req->imu;
2976 u16 index, buf_index = req->buf_index;
2979 if (unlikely(buf_index >= ctx->nr_user_bufs))
2981 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2982 imu = READ_ONCE(ctx->user_bufs[index]);
2985 return __io_import_fixed(req, rw, iter, imu);
2988 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2991 mutex_unlock(&ctx->uring_lock);
2994 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2997 * "Normal" inline submissions always hold the uring_lock, since we
2998 * grab it from the system call. Same is true for the SQPOLL offload.
2999 * The only exception is when we've detached the request and issue it
3000 * from an async worker thread, grab the lock for that case.
3003 mutex_lock(&ctx->uring_lock);
3006 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3007 int bgid, struct io_buffer *kbuf,
3010 struct io_buffer *head;
3012 if (req->flags & REQ_F_BUFFER_SELECTED)
3015 io_ring_submit_lock(req->ctx, needs_lock);
3017 lockdep_assert_held(&req->ctx->uring_lock);
3019 head = xa_load(&req->ctx->io_buffers, bgid);
3021 if (!list_empty(&head->list)) {
3022 kbuf = list_last_entry(&head->list, struct io_buffer,
3024 list_del(&kbuf->list);
3027 xa_erase(&req->ctx->io_buffers, bgid);
3029 if (*len > kbuf->len)
3032 kbuf = ERR_PTR(-ENOBUFS);
3035 io_ring_submit_unlock(req->ctx, needs_lock);
3040 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3043 struct io_buffer *kbuf;
3046 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3047 bgid = req->buf_index;
3048 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3051 req->rw.addr = (u64) (unsigned long) kbuf;
3052 req->flags |= REQ_F_BUFFER_SELECTED;
3053 return u64_to_user_ptr(kbuf->addr);
3056 #ifdef CONFIG_COMPAT
3057 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3060 struct compat_iovec __user *uiov;
3061 compat_ssize_t clen;
3065 uiov = u64_to_user_ptr(req->rw.addr);
3066 if (!access_ok(uiov, sizeof(*uiov)))
3068 if (__get_user(clen, &uiov->iov_len))
3074 buf = io_rw_buffer_select(req, &len, needs_lock);
3076 return PTR_ERR(buf);
3077 iov[0].iov_base = buf;
3078 iov[0].iov_len = (compat_size_t) len;
3083 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3086 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3090 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3093 len = iov[0].iov_len;
3096 buf = io_rw_buffer_select(req, &len, needs_lock);
3098 return PTR_ERR(buf);
3099 iov[0].iov_base = buf;
3100 iov[0].iov_len = len;
3104 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3107 if (req->flags & REQ_F_BUFFER_SELECTED) {
3108 struct io_buffer *kbuf;
3110 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3111 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3112 iov[0].iov_len = kbuf->len;
3115 if (req->rw.len != 1)
3118 #ifdef CONFIG_COMPAT
3119 if (req->ctx->compat)
3120 return io_compat_import(req, iov, needs_lock);
3123 return __io_iov_buffer_select(req, iov, needs_lock);
3126 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3127 struct iov_iter *iter, bool needs_lock)
3129 void __user *buf = u64_to_user_ptr(req->rw.addr);
3130 size_t sqe_len = req->rw.len;
3131 u8 opcode = req->opcode;
3134 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3136 return io_import_fixed(req, rw, iter);
3139 /* buffer index only valid with fixed read/write, or buffer select */
3140 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3143 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3144 if (req->flags & REQ_F_BUFFER_SELECT) {
3145 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3147 return PTR_ERR(buf);
3148 req->rw.len = sqe_len;
3151 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3156 if (req->flags & REQ_F_BUFFER_SELECT) {
3157 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3159 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3164 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3168 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3170 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3174 * For files that don't have ->read_iter() and ->write_iter(), handle them
3175 * by looping over ->read() or ->write() manually.
3177 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3179 struct kiocb *kiocb = &req->rw.kiocb;
3180 struct file *file = req->file;
3184 * Don't support polled IO through this interface, and we can't
3185 * support non-blocking either. For the latter, this just causes
3186 * the kiocb to be handled from an async context.
3188 if (kiocb->ki_flags & IOCB_HIPRI)
3190 if (kiocb->ki_flags & IOCB_NOWAIT)
3193 while (iov_iter_count(iter)) {
3197 if (!iov_iter_is_bvec(iter)) {
3198 iovec = iov_iter_iovec(iter);
3200 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3201 iovec.iov_len = req->rw.len;
3205 nr = file->f_op->read(file, iovec.iov_base,
3206 iovec.iov_len, io_kiocb_ppos(kiocb));
3208 nr = file->f_op->write(file, iovec.iov_base,
3209 iovec.iov_len, io_kiocb_ppos(kiocb));
3218 if (nr != iovec.iov_len)
3222 iov_iter_advance(iter, nr);
3228 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3229 const struct iovec *fast_iov, struct iov_iter *iter)
3231 struct io_async_rw *rw = req->async_data;
3233 memcpy(&rw->iter, iter, sizeof(*iter));
3234 rw->free_iovec = iovec;
3236 /* can only be fixed buffers, no need to do anything */
3237 if (iov_iter_is_bvec(iter))
3240 unsigned iov_off = 0;
3242 rw->iter.iov = rw->fast_iov;
3243 if (iter->iov != fast_iov) {
3244 iov_off = iter->iov - fast_iov;
3245 rw->iter.iov += iov_off;
3247 if (rw->fast_iov != fast_iov)
3248 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3249 sizeof(struct iovec) * iter->nr_segs);
3251 req->flags |= REQ_F_NEED_CLEANUP;
3255 static inline int io_alloc_async_data(struct io_kiocb *req)
3257 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3258 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3259 return req->async_data == NULL;
3262 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3263 const struct iovec *fast_iov,
3264 struct iov_iter *iter, bool force)
3266 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3268 if (!req->async_data) {
3269 if (io_alloc_async_data(req)) {
3274 io_req_map_rw(req, iovec, fast_iov, iter);
3279 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3281 struct io_async_rw *iorw = req->async_data;
3282 struct iovec *iov = iorw->fast_iov;
3285 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3286 if (unlikely(ret < 0))
3289 iorw->bytes_done = 0;
3290 iorw->free_iovec = iov;
3292 req->flags |= REQ_F_NEED_CLEANUP;
3296 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3298 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3300 return io_prep_rw(req, sqe);
3304 * This is our waitqueue callback handler, registered through lock_page_async()
3305 * when we initially tried to do the IO with the iocb armed our waitqueue.
3306 * This gets called when the page is unlocked, and we generally expect that to
3307 * happen when the page IO is completed and the page is now uptodate. This will
3308 * queue a task_work based retry of the operation, attempting to copy the data
3309 * again. If the latter fails because the page was NOT uptodate, then we will
3310 * do a thread based blocking retry of the operation. That's the unexpected
3313 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3314 int sync, void *arg)
3316 struct wait_page_queue *wpq;
3317 struct io_kiocb *req = wait->private;
3318 struct wait_page_key *key = arg;
3320 wpq = container_of(wait, struct wait_page_queue, wait);
3322 if (!wake_page_match(wpq, key))
3325 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3326 list_del_init(&wait->entry);
3327 io_req_task_queue(req);
3332 * This controls whether a given IO request should be armed for async page
3333 * based retry. If we return false here, the request is handed to the async
3334 * worker threads for retry. If we're doing buffered reads on a regular file,
3335 * we prepare a private wait_page_queue entry and retry the operation. This
3336 * will either succeed because the page is now uptodate and unlocked, or it
3337 * will register a callback when the page is unlocked at IO completion. Through
3338 * that callback, io_uring uses task_work to setup a retry of the operation.
3339 * That retry will attempt the buffered read again. The retry will generally
3340 * succeed, or in rare cases where it fails, we then fall back to using the
3341 * async worker threads for a blocking retry.
3343 static bool io_rw_should_retry(struct io_kiocb *req)
3345 struct io_async_rw *rw = req->async_data;
3346 struct wait_page_queue *wait = &rw->wpq;
3347 struct kiocb *kiocb = &req->rw.kiocb;
3349 /* never retry for NOWAIT, we just complete with -EAGAIN */
3350 if (req->flags & REQ_F_NOWAIT)
3353 /* Only for buffered IO */
3354 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3358 * just use poll if we can, and don't attempt if the fs doesn't
3359 * support callback based unlocks
3361 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3364 wait->wait.func = io_async_buf_func;
3365 wait->wait.private = req;
3366 wait->wait.flags = 0;
3367 INIT_LIST_HEAD(&wait->wait.entry);
3368 kiocb->ki_flags |= IOCB_WAITQ;
3369 kiocb->ki_flags &= ~IOCB_NOWAIT;
3370 kiocb->ki_waitq = wait;
3374 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3376 if (req->file->f_op->read_iter)
3377 return call_read_iter(req->file, &req->rw.kiocb, iter);
3378 else if (req->file->f_op->read)
3379 return loop_rw_iter(READ, req, iter);
3384 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3386 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3387 struct kiocb *kiocb = &req->rw.kiocb;
3388 struct iov_iter __iter, *iter = &__iter;
3389 struct io_async_rw *rw = req->async_data;
3390 ssize_t io_size, ret, ret2;
3391 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3397 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3401 io_size = iov_iter_count(iter);
3402 req->result = io_size;
3404 /* Ensure we clear previously set non-block flag */
3405 if (!force_nonblock)
3406 kiocb->ki_flags &= ~IOCB_NOWAIT;
3408 kiocb->ki_flags |= IOCB_NOWAIT;
3410 /* If the file doesn't support async, just async punt */
3411 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3412 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3413 return ret ?: -EAGAIN;
3416 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3417 if (unlikely(ret)) {
3422 ret = io_iter_do_read(req, iter);
3424 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3425 req->flags &= ~REQ_F_REISSUE;
3426 /* IOPOLL retry should happen for io-wq threads */
3427 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3429 /* no retry on NONBLOCK nor RWF_NOWAIT */
3430 if (req->flags & REQ_F_NOWAIT)
3432 /* some cases will consume bytes even on error returns */
3433 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3435 } else if (ret == -EIOCBQUEUED) {
3437 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3438 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3439 /* read all, failed, already did sync or don't want to retry */
3443 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3448 rw = req->async_data;
3449 /* now use our persistent iterator, if we aren't already */
3454 rw->bytes_done += ret;
3455 /* if we can retry, do so with the callbacks armed */
3456 if (!io_rw_should_retry(req)) {
3457 kiocb->ki_flags &= ~IOCB_WAITQ;
3462 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3463 * we get -EIOCBQUEUED, then we'll get a notification when the
3464 * desired page gets unlocked. We can also get a partial read
3465 * here, and if we do, then just retry at the new offset.
3467 ret = io_iter_do_read(req, iter);
3468 if (ret == -EIOCBQUEUED)
3470 /* we got some bytes, but not all. retry. */
3471 kiocb->ki_flags &= ~IOCB_WAITQ;
3472 } while (ret > 0 && ret < io_size);
3474 kiocb_done(kiocb, ret, issue_flags);
3476 /* it's faster to check here then delegate to kfree */
3482 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3484 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3486 return io_prep_rw(req, sqe);
3489 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3491 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3492 struct kiocb *kiocb = &req->rw.kiocb;
3493 struct iov_iter __iter, *iter = &__iter;
3494 struct io_async_rw *rw = req->async_data;
3495 ssize_t ret, ret2, io_size;
3496 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3502 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3506 io_size = iov_iter_count(iter);
3507 req->result = io_size;
3509 /* Ensure we clear previously set non-block flag */
3510 if (!force_nonblock)
3511 kiocb->ki_flags &= ~IOCB_NOWAIT;
3513 kiocb->ki_flags |= IOCB_NOWAIT;
3515 /* If the file doesn't support async, just async punt */
3516 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3519 /* file path doesn't support NOWAIT for non-direct_IO */
3520 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3521 (req->flags & REQ_F_ISREG))
3524 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3529 * Open-code file_start_write here to grab freeze protection,
3530 * which will be released by another thread in
3531 * io_complete_rw(). Fool lockdep by telling it the lock got
3532 * released so that it doesn't complain about the held lock when
3533 * we return to userspace.
3535 if (req->flags & REQ_F_ISREG) {
3536 sb_start_write(file_inode(req->file)->i_sb);
3537 __sb_writers_release(file_inode(req->file)->i_sb,
3540 kiocb->ki_flags |= IOCB_WRITE;
3542 if (req->file->f_op->write_iter)
3543 ret2 = call_write_iter(req->file, kiocb, iter);
3544 else if (req->file->f_op->write)
3545 ret2 = loop_rw_iter(WRITE, req, iter);
3549 if (req->flags & REQ_F_REISSUE) {
3550 req->flags &= ~REQ_F_REISSUE;
3555 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3556 * retry them without IOCB_NOWAIT.
3558 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3560 /* no retry on NONBLOCK nor RWF_NOWAIT */
3561 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3563 if (!force_nonblock || ret2 != -EAGAIN) {
3564 /* IOPOLL retry should happen for io-wq threads */
3565 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3568 kiocb_done(kiocb, ret2, issue_flags);
3571 /* some cases will consume bytes even on error returns */
3572 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3573 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3574 return ret ?: -EAGAIN;
3577 /* it's reportedly faster than delegating the null check to kfree() */
3583 static int io_renameat_prep(struct io_kiocb *req,
3584 const struct io_uring_sqe *sqe)
3586 struct io_rename *ren = &req->rename;
3587 const char __user *oldf, *newf;
3589 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3591 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3593 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3596 ren->old_dfd = READ_ONCE(sqe->fd);
3597 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3598 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3599 ren->new_dfd = READ_ONCE(sqe->len);
3600 ren->flags = READ_ONCE(sqe->rename_flags);
3602 ren->oldpath = getname(oldf);
3603 if (IS_ERR(ren->oldpath))
3604 return PTR_ERR(ren->oldpath);
3606 ren->newpath = getname(newf);
3607 if (IS_ERR(ren->newpath)) {
3608 putname(ren->oldpath);
3609 return PTR_ERR(ren->newpath);
3612 req->flags |= REQ_F_NEED_CLEANUP;
3616 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3618 struct io_rename *ren = &req->rename;
3621 if (issue_flags & IO_URING_F_NONBLOCK)
3624 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3625 ren->newpath, ren->flags);
3627 req->flags &= ~REQ_F_NEED_CLEANUP;
3630 io_req_complete(req, ret);
3634 static int io_unlinkat_prep(struct io_kiocb *req,
3635 const struct io_uring_sqe *sqe)
3637 struct io_unlink *un = &req->unlink;
3638 const char __user *fname;
3640 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3642 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3645 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3648 un->dfd = READ_ONCE(sqe->fd);
3650 un->flags = READ_ONCE(sqe->unlink_flags);
3651 if (un->flags & ~AT_REMOVEDIR)
3654 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3655 un->filename = getname(fname);
3656 if (IS_ERR(un->filename))
3657 return PTR_ERR(un->filename);
3659 req->flags |= REQ_F_NEED_CLEANUP;
3663 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3665 struct io_unlink *un = &req->unlink;
3668 if (issue_flags & IO_URING_F_NONBLOCK)
3671 if (un->flags & AT_REMOVEDIR)
3672 ret = do_rmdir(un->dfd, un->filename);
3674 ret = do_unlinkat(un->dfd, un->filename);
3676 req->flags &= ~REQ_F_NEED_CLEANUP;
3679 io_req_complete(req, ret);
3683 static int io_shutdown_prep(struct io_kiocb *req,
3684 const struct io_uring_sqe *sqe)
3686 #if defined(CONFIG_NET)
3687 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3689 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3690 sqe->buf_index || sqe->splice_fd_in))
3693 req->shutdown.how = READ_ONCE(sqe->len);
3700 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3702 #if defined(CONFIG_NET)
3703 struct socket *sock;
3706 if (issue_flags & IO_URING_F_NONBLOCK)
3709 sock = sock_from_file(req->file);
3710 if (unlikely(!sock))
3713 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3716 io_req_complete(req, ret);
3723 static int __io_splice_prep(struct io_kiocb *req,
3724 const struct io_uring_sqe *sqe)
3726 struct io_splice *sp = &req->splice;
3727 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3729 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3733 sp->len = READ_ONCE(sqe->len);
3734 sp->flags = READ_ONCE(sqe->splice_flags);
3736 if (unlikely(sp->flags & ~valid_flags))
3739 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3740 (sp->flags & SPLICE_F_FD_IN_FIXED));
3743 req->flags |= REQ_F_NEED_CLEANUP;
3747 static int io_tee_prep(struct io_kiocb *req,
3748 const struct io_uring_sqe *sqe)
3750 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3752 return __io_splice_prep(req, sqe);
3755 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3757 struct io_splice *sp = &req->splice;
3758 struct file *in = sp->file_in;
3759 struct file *out = sp->file_out;
3760 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3763 if (issue_flags & IO_URING_F_NONBLOCK)
3766 ret = do_tee(in, out, sp->len, flags);
3768 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3770 req->flags &= ~REQ_F_NEED_CLEANUP;
3774 io_req_complete(req, ret);
3778 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3780 struct io_splice *sp = &req->splice;
3782 sp->off_in = READ_ONCE(sqe->splice_off_in);
3783 sp->off_out = READ_ONCE(sqe->off);
3784 return __io_splice_prep(req, sqe);
3787 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3789 struct io_splice *sp = &req->splice;
3790 struct file *in = sp->file_in;
3791 struct file *out = sp->file_out;
3792 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3793 loff_t *poff_in, *poff_out;
3796 if (issue_flags & IO_URING_F_NONBLOCK)
3799 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3800 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3803 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3805 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3807 req->flags &= ~REQ_F_NEED_CLEANUP;
3811 io_req_complete(req, ret);
3816 * IORING_OP_NOP just posts a completion event, nothing else.
3818 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3820 struct io_ring_ctx *ctx = req->ctx;
3822 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3825 __io_req_complete(req, issue_flags, 0, 0);
3829 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3831 struct io_ring_ctx *ctx = req->ctx;
3836 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3838 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
3842 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3843 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3846 req->sync.off = READ_ONCE(sqe->off);
3847 req->sync.len = READ_ONCE(sqe->len);
3851 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3853 loff_t end = req->sync.off + req->sync.len;
3856 /* fsync always requires a blocking context */
3857 if (issue_flags & IO_URING_F_NONBLOCK)
3860 ret = vfs_fsync_range(req->file, req->sync.off,
3861 end > 0 ? end : LLONG_MAX,
3862 req->sync.flags & IORING_FSYNC_DATASYNC);
3865 io_req_complete(req, ret);
3869 static int io_fallocate_prep(struct io_kiocb *req,
3870 const struct io_uring_sqe *sqe)
3872 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
3875 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3878 req->sync.off = READ_ONCE(sqe->off);
3879 req->sync.len = READ_ONCE(sqe->addr);
3880 req->sync.mode = READ_ONCE(sqe->len);
3884 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3888 /* fallocate always requiring blocking context */
3889 if (issue_flags & IO_URING_F_NONBLOCK)
3891 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3895 io_req_complete(req, ret);
3899 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3901 const char __user *fname;
3904 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3906 if (unlikely(sqe->ioprio || sqe->buf_index))
3908 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3911 /* open.how should be already initialised */
3912 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3913 req->open.how.flags |= O_LARGEFILE;
3915 req->open.dfd = READ_ONCE(sqe->fd);
3916 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3917 req->open.filename = getname(fname);
3918 if (IS_ERR(req->open.filename)) {
3919 ret = PTR_ERR(req->open.filename);
3920 req->open.filename = NULL;
3924 req->open.file_slot = READ_ONCE(sqe->file_index);
3925 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
3928 req->open.nofile = rlimit(RLIMIT_NOFILE);
3929 req->flags |= REQ_F_NEED_CLEANUP;
3933 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3935 u64 mode = READ_ONCE(sqe->len);
3936 u64 flags = READ_ONCE(sqe->open_flags);
3938 req->open.how = build_open_how(flags, mode);
3939 return __io_openat_prep(req, sqe);
3942 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3944 struct open_how __user *how;
3948 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3949 len = READ_ONCE(sqe->len);
3950 if (len < OPEN_HOW_SIZE_VER0)
3953 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3958 return __io_openat_prep(req, sqe);
3961 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3963 struct open_flags op;
3965 bool resolve_nonblock, nonblock_set;
3966 bool fixed = !!req->open.file_slot;
3969 ret = build_open_flags(&req->open.how, &op);
3972 nonblock_set = op.open_flag & O_NONBLOCK;
3973 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3974 if (issue_flags & IO_URING_F_NONBLOCK) {
3976 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3977 * it'll always -EAGAIN
3979 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3981 op.lookup_flags |= LOOKUP_CACHED;
3982 op.open_flag |= O_NONBLOCK;
3986 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3991 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3994 * We could hang on to this 'fd' on retrying, but seems like
3995 * marginal gain for something that is now known to be a slower
3996 * path. So just put it, and we'll get a new one when we retry.
4001 ret = PTR_ERR(file);
4002 /* only retry if RESOLVE_CACHED wasn't already set by application */
4003 if (ret == -EAGAIN &&
4004 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4009 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4010 file->f_flags &= ~O_NONBLOCK;
4011 fsnotify_open(file);
4014 fd_install(ret, file);
4016 ret = io_install_fixed_file(req, file, issue_flags,
4017 req->open.file_slot - 1);
4019 putname(req->open.filename);
4020 req->flags &= ~REQ_F_NEED_CLEANUP;
4023 __io_req_complete(req, issue_flags, ret, 0);
4027 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4029 return io_openat2(req, issue_flags);
4032 static int io_remove_buffers_prep(struct io_kiocb *req,
4033 const struct io_uring_sqe *sqe)
4035 struct io_provide_buf *p = &req->pbuf;
4038 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4042 tmp = READ_ONCE(sqe->fd);
4043 if (!tmp || tmp > USHRT_MAX)
4046 memset(p, 0, sizeof(*p));
4048 p->bgid = READ_ONCE(sqe->buf_group);
4052 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4053 int bgid, unsigned nbufs)
4057 /* shouldn't happen */
4061 /* the head kbuf is the list itself */
4062 while (!list_empty(&buf->list)) {
4063 struct io_buffer *nxt;
4065 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4066 list_del(&nxt->list);
4073 xa_erase(&ctx->io_buffers, bgid);
4078 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4080 struct io_provide_buf *p = &req->pbuf;
4081 struct io_ring_ctx *ctx = req->ctx;
4082 struct io_buffer *head;
4084 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4086 io_ring_submit_lock(ctx, !force_nonblock);
4088 lockdep_assert_held(&ctx->uring_lock);
4091 head = xa_load(&ctx->io_buffers, p->bgid);
4093 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4097 /* complete before unlock, IOPOLL may need the lock */
4098 __io_req_complete(req, issue_flags, ret, 0);
4099 io_ring_submit_unlock(ctx, !force_nonblock);
4103 static int io_provide_buffers_prep(struct io_kiocb *req,
4104 const struct io_uring_sqe *sqe)
4106 unsigned long size, tmp_check;
4107 struct io_provide_buf *p = &req->pbuf;
4110 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4113 tmp = READ_ONCE(sqe->fd);
4114 if (!tmp || tmp > USHRT_MAX)
4117 p->addr = READ_ONCE(sqe->addr);
4118 p->len = READ_ONCE(sqe->len);
4120 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4123 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4126 size = (unsigned long)p->len * p->nbufs;
4127 if (!access_ok(u64_to_user_ptr(p->addr), size))
4130 p->bgid = READ_ONCE(sqe->buf_group);
4131 tmp = READ_ONCE(sqe->off);
4132 if (tmp > USHRT_MAX)
4138 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4140 struct io_buffer *buf;
4141 u64 addr = pbuf->addr;
4142 int i, bid = pbuf->bid;
4144 for (i = 0; i < pbuf->nbufs; i++) {
4145 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4150 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4155 INIT_LIST_HEAD(&buf->list);
4158 list_add_tail(&buf->list, &(*head)->list);
4162 return i ? i : -ENOMEM;
4165 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4167 struct io_provide_buf *p = &req->pbuf;
4168 struct io_ring_ctx *ctx = req->ctx;
4169 struct io_buffer *head, *list;
4171 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4173 io_ring_submit_lock(ctx, !force_nonblock);
4175 lockdep_assert_held(&ctx->uring_lock);
4177 list = head = xa_load(&ctx->io_buffers, p->bgid);
4179 ret = io_add_buffers(p, &head);
4180 if (ret >= 0 && !list) {
4181 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4183 __io_remove_buffers(ctx, head, p->bgid, -1U);
4187 /* complete before unlock, IOPOLL may need the lock */
4188 __io_req_complete(req, issue_flags, ret, 0);
4189 io_ring_submit_unlock(ctx, !force_nonblock);
4193 static int io_epoll_ctl_prep(struct io_kiocb *req,
4194 const struct io_uring_sqe *sqe)
4196 #if defined(CONFIG_EPOLL)
4197 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4199 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4202 req->epoll.epfd = READ_ONCE(sqe->fd);
4203 req->epoll.op = READ_ONCE(sqe->len);
4204 req->epoll.fd = READ_ONCE(sqe->off);
4206 if (ep_op_has_event(req->epoll.op)) {
4207 struct epoll_event __user *ev;
4209 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4210 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4220 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4222 #if defined(CONFIG_EPOLL)
4223 struct io_epoll *ie = &req->epoll;
4225 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4227 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4228 if (force_nonblock && ret == -EAGAIN)
4233 __io_req_complete(req, issue_flags, ret, 0);
4240 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4242 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4243 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4245 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4248 req->madvise.addr = READ_ONCE(sqe->addr);
4249 req->madvise.len = READ_ONCE(sqe->len);
4250 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4257 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4259 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4260 struct io_madvise *ma = &req->madvise;
4263 if (issue_flags & IO_URING_F_NONBLOCK)
4266 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4269 io_req_complete(req, ret);
4276 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4278 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4280 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4283 req->fadvise.offset = READ_ONCE(sqe->off);
4284 req->fadvise.len = READ_ONCE(sqe->len);
4285 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4289 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4291 struct io_fadvise *fa = &req->fadvise;
4294 if (issue_flags & IO_URING_F_NONBLOCK) {
4295 switch (fa->advice) {
4296 case POSIX_FADV_NORMAL:
4297 case POSIX_FADV_RANDOM:
4298 case POSIX_FADV_SEQUENTIAL:
4305 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4308 __io_req_complete(req, issue_flags, ret, 0);
4312 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4314 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4316 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4318 if (req->flags & REQ_F_FIXED_FILE)
4321 req->statx.dfd = READ_ONCE(sqe->fd);
4322 req->statx.mask = READ_ONCE(sqe->len);
4323 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4324 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4325 req->statx.flags = READ_ONCE(sqe->statx_flags);
4330 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4332 struct io_statx *ctx = &req->statx;
4335 if (issue_flags & IO_URING_F_NONBLOCK)
4338 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4343 io_req_complete(req, ret);
4347 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4349 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4351 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4352 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4354 if (req->flags & REQ_F_FIXED_FILE)
4357 req->close.fd = READ_ONCE(sqe->fd);
4361 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4363 struct files_struct *files = current->files;
4364 struct io_close *close = &req->close;
4365 struct fdtable *fdt;
4366 struct file *file = NULL;
4369 spin_lock(&files->file_lock);
4370 fdt = files_fdtable(files);
4371 if (close->fd >= fdt->max_fds) {
4372 spin_unlock(&files->file_lock);
4375 file = fdt->fd[close->fd];
4376 if (!file || file->f_op == &io_uring_fops) {
4377 spin_unlock(&files->file_lock);
4382 /* if the file has a flush method, be safe and punt to async */
4383 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4384 spin_unlock(&files->file_lock);
4388 ret = __close_fd_get_file(close->fd, &file);
4389 spin_unlock(&files->file_lock);
4396 /* No ->flush() or already async, safely close from here */
4397 ret = filp_close(file, current->files);
4403 __io_req_complete(req, issue_flags, ret, 0);
4407 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4409 struct io_ring_ctx *ctx = req->ctx;
4411 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4413 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4417 req->sync.off = READ_ONCE(sqe->off);
4418 req->sync.len = READ_ONCE(sqe->len);
4419 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4423 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4427 /* sync_file_range always requires a blocking context */
4428 if (issue_flags & IO_URING_F_NONBLOCK)
4431 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4435 io_req_complete(req, ret);
4439 #if defined(CONFIG_NET)
4440 static int io_setup_async_msg(struct io_kiocb *req,
4441 struct io_async_msghdr *kmsg)
4443 struct io_async_msghdr *async_msg = req->async_data;
4447 if (io_alloc_async_data(req)) {
4448 kfree(kmsg->free_iov);
4451 async_msg = req->async_data;
4452 req->flags |= REQ_F_NEED_CLEANUP;
4453 memcpy(async_msg, kmsg, sizeof(*kmsg));
4454 async_msg->msg.msg_name = &async_msg->addr;
4455 /* if were using fast_iov, set it to the new one */
4456 if (!async_msg->free_iov)
4457 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4462 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4463 struct io_async_msghdr *iomsg)
4465 iomsg->msg.msg_name = &iomsg->addr;
4466 iomsg->free_iov = iomsg->fast_iov;
4467 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4468 req->sr_msg.msg_flags, &iomsg->free_iov);
4471 static int io_sendmsg_prep_async(struct io_kiocb *req)
4475 ret = io_sendmsg_copy_hdr(req, req->async_data);
4477 req->flags |= REQ_F_NEED_CLEANUP;
4481 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4483 struct io_sr_msg *sr = &req->sr_msg;
4485 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4488 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4489 sr->len = READ_ONCE(sqe->len);
4490 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4491 if (sr->msg_flags & MSG_DONTWAIT)
4492 req->flags |= REQ_F_NOWAIT;
4494 #ifdef CONFIG_COMPAT
4495 if (req->ctx->compat)
4496 sr->msg_flags |= MSG_CMSG_COMPAT;
4501 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4503 struct io_async_msghdr iomsg, *kmsg;
4504 struct socket *sock;
4509 sock = sock_from_file(req->file);
4510 if (unlikely(!sock))
4513 kmsg = req->async_data;
4515 ret = io_sendmsg_copy_hdr(req, &iomsg);
4521 flags = req->sr_msg.msg_flags;
4522 if (issue_flags & IO_URING_F_NONBLOCK)
4523 flags |= MSG_DONTWAIT;
4524 if (flags & MSG_WAITALL)
4525 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4527 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4528 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4529 return io_setup_async_msg(req, kmsg);
4530 if (ret == -ERESTARTSYS)
4533 /* fast path, check for non-NULL to avoid function call */
4535 kfree(kmsg->free_iov);
4536 req->flags &= ~REQ_F_NEED_CLEANUP;
4539 __io_req_complete(req, issue_flags, ret, 0);
4543 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4545 struct io_sr_msg *sr = &req->sr_msg;
4548 struct socket *sock;
4553 sock = sock_from_file(req->file);
4554 if (unlikely(!sock))
4557 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4561 msg.msg_name = NULL;
4562 msg.msg_control = NULL;
4563 msg.msg_controllen = 0;
4564 msg.msg_namelen = 0;
4566 flags = req->sr_msg.msg_flags;
4567 if (issue_flags & IO_URING_F_NONBLOCK)
4568 flags |= MSG_DONTWAIT;
4569 if (flags & MSG_WAITALL)
4570 min_ret = iov_iter_count(&msg.msg_iter);
4572 msg.msg_flags = flags;
4573 ret = sock_sendmsg(sock, &msg);
4574 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4576 if (ret == -ERESTARTSYS)
4581 __io_req_complete(req, issue_flags, ret, 0);
4585 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4586 struct io_async_msghdr *iomsg)
4588 struct io_sr_msg *sr = &req->sr_msg;
4589 struct iovec __user *uiov;
4593 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4594 &iomsg->uaddr, &uiov, &iov_len);
4598 if (req->flags & REQ_F_BUFFER_SELECT) {
4601 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4603 sr->len = iomsg->fast_iov[0].iov_len;
4604 iomsg->free_iov = NULL;
4606 iomsg->free_iov = iomsg->fast_iov;
4607 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4608 &iomsg->free_iov, &iomsg->msg.msg_iter,
4617 #ifdef CONFIG_COMPAT
4618 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4619 struct io_async_msghdr *iomsg)
4621 struct io_sr_msg *sr = &req->sr_msg;
4622 struct compat_iovec __user *uiov;
4627 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4632 uiov = compat_ptr(ptr);
4633 if (req->flags & REQ_F_BUFFER_SELECT) {
4634 compat_ssize_t clen;
4638 if (!access_ok(uiov, sizeof(*uiov)))
4640 if (__get_user(clen, &uiov->iov_len))
4645 iomsg->free_iov = NULL;
4647 iomsg->free_iov = iomsg->fast_iov;
4648 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4649 UIO_FASTIOV, &iomsg->free_iov,
4650 &iomsg->msg.msg_iter, true);
4659 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4660 struct io_async_msghdr *iomsg)
4662 iomsg->msg.msg_name = &iomsg->addr;
4664 #ifdef CONFIG_COMPAT
4665 if (req->ctx->compat)
4666 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4669 return __io_recvmsg_copy_hdr(req, iomsg);
4672 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4675 struct io_sr_msg *sr = &req->sr_msg;
4676 struct io_buffer *kbuf;
4678 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4683 req->flags |= REQ_F_BUFFER_SELECTED;
4687 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4689 return io_put_kbuf(req, req->sr_msg.kbuf);
4692 static int io_recvmsg_prep_async(struct io_kiocb *req)
4696 ret = io_recvmsg_copy_hdr(req, req->async_data);
4698 req->flags |= REQ_F_NEED_CLEANUP;
4702 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4704 struct io_sr_msg *sr = &req->sr_msg;
4706 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4709 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4710 sr->len = READ_ONCE(sqe->len);
4711 sr->bgid = READ_ONCE(sqe->buf_group);
4712 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4713 if (sr->msg_flags & MSG_DONTWAIT)
4714 req->flags |= REQ_F_NOWAIT;
4716 #ifdef CONFIG_COMPAT
4717 if (req->ctx->compat)
4718 sr->msg_flags |= MSG_CMSG_COMPAT;
4723 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4725 struct io_async_msghdr iomsg, *kmsg;
4726 struct socket *sock;
4727 struct io_buffer *kbuf;
4730 int ret, cflags = 0;
4731 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4733 sock = sock_from_file(req->file);
4734 if (unlikely(!sock))
4737 kmsg = req->async_data;
4739 ret = io_recvmsg_copy_hdr(req, &iomsg);
4745 if (req->flags & REQ_F_BUFFER_SELECT) {
4746 kbuf = io_recv_buffer_select(req, !force_nonblock);
4748 return PTR_ERR(kbuf);
4749 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4750 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4751 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4752 1, req->sr_msg.len);
4755 flags = req->sr_msg.msg_flags;
4757 flags |= MSG_DONTWAIT;
4758 if (flags & MSG_WAITALL)
4759 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4761 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4762 kmsg->uaddr, flags);
4763 if (force_nonblock && ret == -EAGAIN)
4764 return io_setup_async_msg(req, kmsg);
4765 if (ret == -ERESTARTSYS)
4768 if (req->flags & REQ_F_BUFFER_SELECTED)
4769 cflags = io_put_recv_kbuf(req);
4770 /* fast path, check for non-NULL to avoid function call */
4772 kfree(kmsg->free_iov);
4773 req->flags &= ~REQ_F_NEED_CLEANUP;
4774 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4776 __io_req_complete(req, issue_flags, ret, cflags);
4780 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4782 struct io_buffer *kbuf;
4783 struct io_sr_msg *sr = &req->sr_msg;
4785 void __user *buf = sr->buf;
4786 struct socket *sock;
4790 int ret, cflags = 0;
4791 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4793 sock = sock_from_file(req->file);
4794 if (unlikely(!sock))
4797 if (req->flags & REQ_F_BUFFER_SELECT) {
4798 kbuf = io_recv_buffer_select(req, !force_nonblock);
4800 return PTR_ERR(kbuf);
4801 buf = u64_to_user_ptr(kbuf->addr);
4804 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4808 msg.msg_name = NULL;
4809 msg.msg_control = NULL;
4810 msg.msg_controllen = 0;
4811 msg.msg_namelen = 0;
4812 msg.msg_iocb = NULL;
4815 flags = req->sr_msg.msg_flags;
4817 flags |= MSG_DONTWAIT;
4818 if (flags & MSG_WAITALL)
4819 min_ret = iov_iter_count(&msg.msg_iter);
4821 ret = sock_recvmsg(sock, &msg, flags);
4822 if (force_nonblock && ret == -EAGAIN)
4824 if (ret == -ERESTARTSYS)
4827 if (req->flags & REQ_F_BUFFER_SELECTED)
4828 cflags = io_put_recv_kbuf(req);
4829 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4831 __io_req_complete(req, issue_flags, ret, cflags);
4835 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4837 struct io_accept *accept = &req->accept;
4839 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4841 if (sqe->ioprio || sqe->len || sqe->buf_index)
4844 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4845 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4846 accept->flags = READ_ONCE(sqe->accept_flags);
4847 accept->nofile = rlimit(RLIMIT_NOFILE);
4849 accept->file_slot = READ_ONCE(sqe->file_index);
4850 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
4851 (accept->flags & SOCK_CLOEXEC)))
4853 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4855 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4856 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4860 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4862 struct io_accept *accept = &req->accept;
4863 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4864 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4865 bool fixed = !!accept->file_slot;
4869 if (req->file->f_flags & O_NONBLOCK)
4870 req->flags |= REQ_F_NOWAIT;
4873 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4874 if (unlikely(fd < 0))
4877 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4882 ret = PTR_ERR(file);
4883 if (ret == -EAGAIN && force_nonblock)
4885 if (ret == -ERESTARTSYS)
4888 } else if (!fixed) {
4889 fd_install(fd, file);
4892 ret = io_install_fixed_file(req, file, issue_flags,
4893 accept->file_slot - 1);
4895 __io_req_complete(req, issue_flags, ret, 0);
4899 static int io_connect_prep_async(struct io_kiocb *req)
4901 struct io_async_connect *io = req->async_data;
4902 struct io_connect *conn = &req->connect;
4904 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4907 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4909 struct io_connect *conn = &req->connect;
4911 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4913 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
4917 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4918 conn->addr_len = READ_ONCE(sqe->addr2);
4922 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4924 struct io_async_connect __io, *io;
4925 unsigned file_flags;
4927 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4929 if (req->async_data) {
4930 io = req->async_data;
4932 ret = move_addr_to_kernel(req->connect.addr,
4933 req->connect.addr_len,
4940 file_flags = force_nonblock ? O_NONBLOCK : 0;
4942 ret = __sys_connect_file(req->file, &io->address,
4943 req->connect.addr_len, file_flags);
4944 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4945 if (req->async_data)
4947 if (io_alloc_async_data(req)) {
4951 memcpy(req->async_data, &__io, sizeof(__io));
4954 if (ret == -ERESTARTSYS)
4959 __io_req_complete(req, issue_flags, ret, 0);
4962 #else /* !CONFIG_NET */
4963 #define IO_NETOP_FN(op) \
4964 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4966 return -EOPNOTSUPP; \
4969 #define IO_NETOP_PREP(op) \
4971 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4973 return -EOPNOTSUPP; \
4976 #define IO_NETOP_PREP_ASYNC(op) \
4978 static int io_##op##_prep_async(struct io_kiocb *req) \
4980 return -EOPNOTSUPP; \
4983 IO_NETOP_PREP_ASYNC(sendmsg);
4984 IO_NETOP_PREP_ASYNC(recvmsg);
4985 IO_NETOP_PREP_ASYNC(connect);
4986 IO_NETOP_PREP(accept);
4989 #endif /* CONFIG_NET */
4991 struct io_poll_table {
4992 struct poll_table_struct pt;
4993 struct io_kiocb *req;
4998 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4999 __poll_t mask, io_req_tw_func_t func)
5001 /* for instances that support it check for an event match first: */
5002 if (mask && !(mask & poll->events))
5005 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5007 list_del_init(&poll->wait.entry);
5010 req->io_task_work.func = func;
5013 * If this fails, then the task is exiting. When a task exits, the
5014 * work gets canceled, so just cancel this request as well instead
5015 * of executing it. We can't safely execute it anyway, as we may not
5016 * have the needed state needed for it anyway.
5018 io_req_task_work_add(req);
5022 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5023 __acquires(&req->ctx->completion_lock)
5025 struct io_ring_ctx *ctx = req->ctx;
5027 /* req->task == current here, checking PF_EXITING is safe */
5028 if (unlikely(req->task->flags & PF_EXITING))
5029 WRITE_ONCE(poll->canceled, true);
5031 if (!req->result && !READ_ONCE(poll->canceled)) {
5032 struct poll_table_struct pt = { ._key = poll->events };
5034 req->result = vfs_poll(req->file, &pt) & poll->events;
5037 spin_lock(&ctx->completion_lock);
5038 if (!req->result && !READ_ONCE(poll->canceled)) {
5039 add_wait_queue(poll->head, &poll->wait);
5046 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5048 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5049 if (req->opcode == IORING_OP_POLL_ADD)
5050 return req->async_data;
5051 return req->apoll->double_poll;
5054 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5056 if (req->opcode == IORING_OP_POLL_ADD)
5058 return &req->apoll->poll;
5061 static void io_poll_remove_double(struct io_kiocb *req)
5062 __must_hold(&req->ctx->completion_lock)
5064 struct io_poll_iocb *poll = io_poll_get_double(req);
5066 lockdep_assert_held(&req->ctx->completion_lock);
5068 if (poll && poll->head) {
5069 struct wait_queue_head *head = poll->head;
5071 spin_lock_irq(&head->lock);
5072 list_del_init(&poll->wait.entry);
5073 if (poll->wait.private)
5076 spin_unlock_irq(&head->lock);
5080 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5081 __must_hold(&req->ctx->completion_lock)
5083 struct io_ring_ctx *ctx = req->ctx;
5084 unsigned flags = IORING_CQE_F_MORE;
5087 if (READ_ONCE(req->poll.canceled)) {
5089 req->poll.events |= EPOLLONESHOT;
5091 error = mangle_poll(mask);
5093 if (req->poll.events & EPOLLONESHOT)
5095 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5096 req->poll.done = true;
5099 if (flags & IORING_CQE_F_MORE)
5102 io_commit_cqring(ctx);
5103 return !(flags & IORING_CQE_F_MORE);
5106 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5108 struct io_ring_ctx *ctx = req->ctx;
5109 struct io_kiocb *nxt;
5111 if (io_poll_rewait(req, &req->poll)) {
5112 spin_unlock(&ctx->completion_lock);
5116 done = io_poll_complete(req, req->result);
5118 io_poll_remove_double(req);
5119 hash_del(&req->hash_node);
5122 add_wait_queue(req->poll.head, &req->poll.wait);
5124 spin_unlock(&ctx->completion_lock);
5125 io_cqring_ev_posted(ctx);
5128 nxt = io_put_req_find_next(req);
5130 io_req_task_submit(nxt, locked);
5135 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5136 int sync, void *key)
5138 struct io_kiocb *req = wait->private;
5139 struct io_poll_iocb *poll = io_poll_get_single(req);
5140 __poll_t mask = key_to_poll(key);
5141 unsigned long flags;
5143 /* for instances that support it check for an event match first: */
5144 if (mask && !(mask & poll->events))
5146 if (!(poll->events & EPOLLONESHOT))
5147 return poll->wait.func(&poll->wait, mode, sync, key);
5149 list_del_init(&wait->entry);
5154 spin_lock_irqsave(&poll->head->lock, flags);
5155 done = list_empty(&poll->wait.entry);
5157 list_del_init(&poll->wait.entry);
5158 /* make sure double remove sees this as being gone */
5159 wait->private = NULL;
5160 spin_unlock_irqrestore(&poll->head->lock, flags);
5162 /* use wait func handler, so it matches the rq type */
5163 poll->wait.func(&poll->wait, mode, sync, key);
5170 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5171 wait_queue_func_t wake_func)
5175 poll->canceled = false;
5176 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5177 /* mask in events that we always want/need */
5178 poll->events = events | IO_POLL_UNMASK;
5179 INIT_LIST_HEAD(&poll->wait.entry);
5180 init_waitqueue_func_entry(&poll->wait, wake_func);
5183 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5184 struct wait_queue_head *head,
5185 struct io_poll_iocb **poll_ptr)
5187 struct io_kiocb *req = pt->req;
5190 * The file being polled uses multiple waitqueues for poll handling
5191 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5194 if (unlikely(pt->nr_entries)) {
5195 struct io_poll_iocb *poll_one = poll;
5197 /* double add on the same waitqueue head, ignore */
5198 if (poll_one->head == head)
5200 /* already have a 2nd entry, fail a third attempt */
5202 if ((*poll_ptr)->head == head)
5204 pt->error = -EINVAL;
5208 * Can't handle multishot for double wait for now, turn it
5209 * into one-shot mode.
5211 if (!(poll_one->events & EPOLLONESHOT))
5212 poll_one->events |= EPOLLONESHOT;
5213 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5215 pt->error = -ENOMEM;
5218 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5220 poll->wait.private = req;
5227 if (poll->events & EPOLLEXCLUSIVE)
5228 add_wait_queue_exclusive(head, &poll->wait);
5230 add_wait_queue(head, &poll->wait);
5233 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5234 struct poll_table_struct *p)
5236 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5237 struct async_poll *apoll = pt->req->apoll;
5239 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5242 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5244 struct async_poll *apoll = req->apoll;
5245 struct io_ring_ctx *ctx = req->ctx;
5247 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5249 if (io_poll_rewait(req, &apoll->poll)) {
5250 spin_unlock(&ctx->completion_lock);
5254 hash_del(&req->hash_node);
5255 io_poll_remove_double(req);
5256 spin_unlock(&ctx->completion_lock);
5258 if (!READ_ONCE(apoll->poll.canceled))
5259 io_req_task_submit(req, locked);
5261 io_req_complete_failed(req, -ECANCELED);
5264 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5267 struct io_kiocb *req = wait->private;
5268 struct io_poll_iocb *poll = &req->apoll->poll;
5270 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5273 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5276 static void io_poll_req_insert(struct io_kiocb *req)
5278 struct io_ring_ctx *ctx = req->ctx;
5279 struct hlist_head *list;
5281 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5282 hlist_add_head(&req->hash_node, list);
5285 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5286 struct io_poll_iocb *poll,
5287 struct io_poll_table *ipt, __poll_t mask,
5288 wait_queue_func_t wake_func)
5289 __acquires(&ctx->completion_lock)
5291 struct io_ring_ctx *ctx = req->ctx;
5292 bool cancel = false;
5294 INIT_HLIST_NODE(&req->hash_node);
5295 io_init_poll_iocb(poll, mask, wake_func);
5296 poll->file = req->file;
5297 poll->wait.private = req;
5299 ipt->pt._key = mask;
5302 ipt->nr_entries = 0;
5304 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5305 if (unlikely(!ipt->nr_entries) && !ipt->error)
5306 ipt->error = -EINVAL;
5308 spin_lock(&ctx->completion_lock);
5309 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5310 io_poll_remove_double(req);
5311 if (likely(poll->head)) {
5312 spin_lock_irq(&poll->head->lock);
5313 if (unlikely(list_empty(&poll->wait.entry))) {
5319 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5320 list_del_init(&poll->wait.entry);
5322 WRITE_ONCE(poll->canceled, true);
5323 else if (!poll->done) /* actually waiting for an event */
5324 io_poll_req_insert(req);
5325 spin_unlock_irq(&poll->head->lock);
5337 static int io_arm_poll_handler(struct io_kiocb *req)
5339 const struct io_op_def *def = &io_op_defs[req->opcode];
5340 struct io_ring_ctx *ctx = req->ctx;
5341 struct async_poll *apoll;
5342 struct io_poll_table ipt;
5343 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5346 if (!req->file || !file_can_poll(req->file))
5347 return IO_APOLL_ABORTED;
5348 if (req->flags & REQ_F_POLLED)
5349 return IO_APOLL_ABORTED;
5350 if (!def->pollin && !def->pollout)
5351 return IO_APOLL_ABORTED;
5355 mask |= POLLIN | POLLRDNORM;
5357 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5358 if ((req->opcode == IORING_OP_RECVMSG) &&
5359 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5363 mask |= POLLOUT | POLLWRNORM;
5366 /* if we can't nonblock try, then no point in arming a poll handler */
5367 if (!io_file_supports_nowait(req, rw))
5368 return IO_APOLL_ABORTED;
5370 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5371 if (unlikely(!apoll))
5372 return IO_APOLL_ABORTED;
5373 apoll->double_poll = NULL;
5375 req->flags |= REQ_F_POLLED;
5376 ipt.pt._qproc = io_async_queue_proc;
5377 io_req_set_refcount(req);
5379 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5381 spin_unlock(&ctx->completion_lock);
5382 if (ret || ipt.error)
5383 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5385 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5386 mask, apoll->poll.events);
5390 static bool __io_poll_remove_one(struct io_kiocb *req,
5391 struct io_poll_iocb *poll, bool do_cancel)
5392 __must_hold(&req->ctx->completion_lock)
5394 bool do_complete = false;
5398 spin_lock_irq(&poll->head->lock);
5400 WRITE_ONCE(poll->canceled, true);
5401 if (!list_empty(&poll->wait.entry)) {
5402 list_del_init(&poll->wait.entry);
5405 spin_unlock_irq(&poll->head->lock);
5406 hash_del(&req->hash_node);
5410 static bool io_poll_remove_one(struct io_kiocb *req)
5411 __must_hold(&req->ctx->completion_lock)
5415 io_poll_remove_double(req);
5416 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5419 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5420 io_commit_cqring(req->ctx);
5422 io_put_req_deferred(req);
5428 * Returns true if we found and killed one or more poll requests
5430 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5433 struct hlist_node *tmp;
5434 struct io_kiocb *req;
5437 spin_lock(&ctx->completion_lock);
5438 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5439 struct hlist_head *list;
5441 list = &ctx->cancel_hash[i];
5442 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5443 if (io_match_task(req, tsk, cancel_all))
5444 posted += io_poll_remove_one(req);
5447 spin_unlock(&ctx->completion_lock);
5450 io_cqring_ev_posted(ctx);
5455 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5457 __must_hold(&ctx->completion_lock)
5459 struct hlist_head *list;
5460 struct io_kiocb *req;
5462 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5463 hlist_for_each_entry(req, list, hash_node) {
5464 if (sqe_addr != req->user_data)
5466 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5473 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5475 __must_hold(&ctx->completion_lock)
5477 struct io_kiocb *req;
5479 req = io_poll_find(ctx, sqe_addr, poll_only);
5482 if (io_poll_remove_one(req))
5488 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5493 events = READ_ONCE(sqe->poll32_events);
5495 events = swahw32(events);
5497 if (!(flags & IORING_POLL_ADD_MULTI))
5498 events |= EPOLLONESHOT;
5499 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5502 static int io_poll_update_prep(struct io_kiocb *req,
5503 const struct io_uring_sqe *sqe)
5505 struct io_poll_update *upd = &req->poll_update;
5508 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5510 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5512 flags = READ_ONCE(sqe->len);
5513 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5514 IORING_POLL_ADD_MULTI))
5516 /* meaningless without update */
5517 if (flags == IORING_POLL_ADD_MULTI)
5520 upd->old_user_data = READ_ONCE(sqe->addr);
5521 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5522 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5524 upd->new_user_data = READ_ONCE(sqe->off);
5525 if (!upd->update_user_data && upd->new_user_data)
5527 if (upd->update_events)
5528 upd->events = io_poll_parse_events(sqe, flags);
5529 else if (sqe->poll32_events)
5535 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5538 struct io_kiocb *req = wait->private;
5539 struct io_poll_iocb *poll = &req->poll;
5541 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5544 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5545 struct poll_table_struct *p)
5547 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5549 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5552 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5554 struct io_poll_iocb *poll = &req->poll;
5557 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5559 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5561 flags = READ_ONCE(sqe->len);
5562 if (flags & ~IORING_POLL_ADD_MULTI)
5565 io_req_set_refcount(req);
5566 poll->events = io_poll_parse_events(sqe, flags);
5570 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5572 struct io_poll_iocb *poll = &req->poll;
5573 struct io_ring_ctx *ctx = req->ctx;
5574 struct io_poll_table ipt;
5577 ipt.pt._qproc = io_poll_queue_proc;
5579 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5582 if (mask) { /* no async, we'd stolen it */
5584 io_poll_complete(req, mask);
5586 spin_unlock(&ctx->completion_lock);
5589 io_cqring_ev_posted(ctx);
5590 if (poll->events & EPOLLONESHOT)
5596 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5598 struct io_ring_ctx *ctx = req->ctx;
5599 struct io_kiocb *preq;
5603 spin_lock(&ctx->completion_lock);
5604 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5610 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5612 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5617 * Don't allow racy completion with singleshot, as we cannot safely
5618 * update those. For multishot, if we're racing with completion, just
5619 * let completion re-add it.
5621 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5622 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5626 /* we now have a detached poll request. reissue. */
5630 spin_unlock(&ctx->completion_lock);
5632 io_req_complete(req, ret);
5635 /* only mask one event flags, keep behavior flags */
5636 if (req->poll_update.update_events) {
5637 preq->poll.events &= ~0xffff;
5638 preq->poll.events |= req->poll_update.events & 0xffff;
5639 preq->poll.events |= IO_POLL_UNMASK;
5641 if (req->poll_update.update_user_data)
5642 preq->user_data = req->poll_update.new_user_data;
5643 spin_unlock(&ctx->completion_lock);
5645 /* complete update request, we're done with it */
5646 io_req_complete(req, ret);
5649 ret = io_poll_add(preq, issue_flags);
5652 io_req_complete(preq, ret);
5658 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5661 io_req_complete_post(req, -ETIME, 0);
5664 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5666 struct io_timeout_data *data = container_of(timer,
5667 struct io_timeout_data, timer);
5668 struct io_kiocb *req = data->req;
5669 struct io_ring_ctx *ctx = req->ctx;
5670 unsigned long flags;
5672 spin_lock_irqsave(&ctx->timeout_lock, flags);
5673 list_del_init(&req->timeout.list);
5674 atomic_set(&req->ctx->cq_timeouts,
5675 atomic_read(&req->ctx->cq_timeouts) + 1);
5676 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5678 req->io_task_work.func = io_req_task_timeout;
5679 io_req_task_work_add(req);
5680 return HRTIMER_NORESTART;
5683 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5685 __must_hold(&ctx->timeout_lock)
5687 struct io_timeout_data *io;
5688 struct io_kiocb *req;
5691 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5692 found = user_data == req->user_data;
5697 return ERR_PTR(-ENOENT);
5699 io = req->async_data;
5700 if (hrtimer_try_to_cancel(&io->timer) == -1)
5701 return ERR_PTR(-EALREADY);
5702 list_del_init(&req->timeout.list);
5706 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5707 __must_hold(&ctx->completion_lock)
5708 __must_hold(&ctx->timeout_lock)
5710 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5713 return PTR_ERR(req);
5716 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5717 io_put_req_deferred(req);
5721 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5723 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5724 case IORING_TIMEOUT_BOOTTIME:
5725 return CLOCK_BOOTTIME;
5726 case IORING_TIMEOUT_REALTIME:
5727 return CLOCK_REALTIME;
5729 /* can't happen, vetted at prep time */
5733 return CLOCK_MONOTONIC;
5737 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5738 struct timespec64 *ts, enum hrtimer_mode mode)
5739 __must_hold(&ctx->timeout_lock)
5741 struct io_timeout_data *io;
5742 struct io_kiocb *req;
5745 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5746 found = user_data == req->user_data;
5753 io = req->async_data;
5754 if (hrtimer_try_to_cancel(&io->timer) == -1)
5756 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5757 io->timer.function = io_link_timeout_fn;
5758 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5762 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5763 struct timespec64 *ts, enum hrtimer_mode mode)
5764 __must_hold(&ctx->timeout_lock)
5766 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5767 struct io_timeout_data *data;
5770 return PTR_ERR(req);
5772 req->timeout.off = 0; /* noseq */
5773 data = req->async_data;
5774 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5775 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5776 data->timer.function = io_timeout_fn;
5777 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5781 static int io_timeout_remove_prep(struct io_kiocb *req,
5782 const struct io_uring_sqe *sqe)
5784 struct io_timeout_rem *tr = &req->timeout_rem;
5786 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5788 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5790 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5793 tr->ltimeout = false;
5794 tr->addr = READ_ONCE(sqe->addr);
5795 tr->flags = READ_ONCE(sqe->timeout_flags);
5796 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5797 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5799 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5800 tr->ltimeout = true;
5801 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5803 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5805 } else if (tr->flags) {
5806 /* timeout removal doesn't support flags */
5813 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5815 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5820 * Remove or update an existing timeout command
5822 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5824 struct io_timeout_rem *tr = &req->timeout_rem;
5825 struct io_ring_ctx *ctx = req->ctx;
5828 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5829 spin_lock(&ctx->completion_lock);
5830 spin_lock_irq(&ctx->timeout_lock);
5831 ret = io_timeout_cancel(ctx, tr->addr);
5832 spin_unlock_irq(&ctx->timeout_lock);
5833 spin_unlock(&ctx->completion_lock);
5835 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5837 spin_lock_irq(&ctx->timeout_lock);
5839 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5841 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5842 spin_unlock_irq(&ctx->timeout_lock);
5847 io_req_complete_post(req, ret, 0);
5851 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5852 bool is_timeout_link)
5854 struct io_timeout_data *data;
5856 u32 off = READ_ONCE(sqe->off);
5858 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5860 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5863 if (off && is_timeout_link)
5865 flags = READ_ONCE(sqe->timeout_flags);
5866 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
5868 /* more than one clock specified is invalid, obviously */
5869 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5872 INIT_LIST_HEAD(&req->timeout.list);
5873 req->timeout.off = off;
5874 if (unlikely(off && !req->ctx->off_timeout_used))
5875 req->ctx->off_timeout_used = true;
5877 if (!req->async_data && io_alloc_async_data(req))
5880 data = req->async_data;
5882 data->flags = flags;
5884 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5887 data->mode = io_translate_timeout_mode(flags);
5888 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5890 if (is_timeout_link) {
5891 struct io_submit_link *link = &req->ctx->submit_state.link;
5895 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5897 req->timeout.head = link->last;
5898 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5903 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5905 struct io_ring_ctx *ctx = req->ctx;
5906 struct io_timeout_data *data = req->async_data;
5907 struct list_head *entry;
5908 u32 tail, off = req->timeout.off;
5910 spin_lock_irq(&ctx->timeout_lock);
5913 * sqe->off holds how many events that need to occur for this
5914 * timeout event to be satisfied. If it isn't set, then this is
5915 * a pure timeout request, sequence isn't used.
5917 if (io_is_timeout_noseq(req)) {
5918 entry = ctx->timeout_list.prev;
5922 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5923 req->timeout.target_seq = tail + off;
5925 /* Update the last seq here in case io_flush_timeouts() hasn't.
5926 * This is safe because ->completion_lock is held, and submissions
5927 * and completions are never mixed in the same ->completion_lock section.
5929 ctx->cq_last_tm_flush = tail;
5932 * Insertion sort, ensuring the first entry in the list is always
5933 * the one we need first.
5935 list_for_each_prev(entry, &ctx->timeout_list) {
5936 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5939 if (io_is_timeout_noseq(nxt))
5941 /* nxt.seq is behind @tail, otherwise would've been completed */
5942 if (off >= nxt->timeout.target_seq - tail)
5946 list_add(&req->timeout.list, entry);
5947 data->timer.function = io_timeout_fn;
5948 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5949 spin_unlock_irq(&ctx->timeout_lock);
5953 struct io_cancel_data {
5954 struct io_ring_ctx *ctx;
5958 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5960 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5961 struct io_cancel_data *cd = data;
5963 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5966 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5967 struct io_ring_ctx *ctx)
5969 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5970 enum io_wq_cancel cancel_ret;
5973 if (!tctx || !tctx->io_wq)
5976 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5977 switch (cancel_ret) {
5978 case IO_WQ_CANCEL_OK:
5981 case IO_WQ_CANCEL_RUNNING:
5984 case IO_WQ_CANCEL_NOTFOUND:
5992 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
5994 struct io_ring_ctx *ctx = req->ctx;
5997 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
5999 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6003 spin_lock(&ctx->completion_lock);
6004 spin_lock_irq(&ctx->timeout_lock);
6005 ret = io_timeout_cancel(ctx, sqe_addr);
6006 spin_unlock_irq(&ctx->timeout_lock);
6009 ret = io_poll_cancel(ctx, sqe_addr, false);
6011 spin_unlock(&ctx->completion_lock);
6015 static int io_async_cancel_prep(struct io_kiocb *req,
6016 const struct io_uring_sqe *sqe)
6018 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6020 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6022 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6026 req->cancel.addr = READ_ONCE(sqe->addr);
6030 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6032 struct io_ring_ctx *ctx = req->ctx;
6033 u64 sqe_addr = req->cancel.addr;
6034 struct io_tctx_node *node;
6037 ret = io_try_cancel_userdata(req, sqe_addr);
6041 /* slow path, try all io-wq's */
6042 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6044 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6045 struct io_uring_task *tctx = node->task->io_uring;
6047 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6051 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6055 io_req_complete_post(req, ret, 0);
6059 static int io_rsrc_update_prep(struct io_kiocb *req,
6060 const struct io_uring_sqe *sqe)
6062 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6064 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6067 req->rsrc_update.offset = READ_ONCE(sqe->off);
6068 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6069 if (!req->rsrc_update.nr_args)
6071 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6075 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6077 struct io_ring_ctx *ctx = req->ctx;
6078 struct io_uring_rsrc_update2 up;
6081 if (issue_flags & IO_URING_F_NONBLOCK)
6084 up.offset = req->rsrc_update.offset;
6085 up.data = req->rsrc_update.arg;
6090 mutex_lock(&ctx->uring_lock);
6091 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6092 &up, req->rsrc_update.nr_args);
6093 mutex_unlock(&ctx->uring_lock);
6097 __io_req_complete(req, issue_flags, ret, 0);
6101 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6103 switch (req->opcode) {
6106 case IORING_OP_READV:
6107 case IORING_OP_READ_FIXED:
6108 case IORING_OP_READ:
6109 return io_read_prep(req, sqe);
6110 case IORING_OP_WRITEV:
6111 case IORING_OP_WRITE_FIXED:
6112 case IORING_OP_WRITE:
6113 return io_write_prep(req, sqe);
6114 case IORING_OP_POLL_ADD:
6115 return io_poll_add_prep(req, sqe);
6116 case IORING_OP_POLL_REMOVE:
6117 return io_poll_update_prep(req, sqe);
6118 case IORING_OP_FSYNC:
6119 return io_fsync_prep(req, sqe);
6120 case IORING_OP_SYNC_FILE_RANGE:
6121 return io_sfr_prep(req, sqe);
6122 case IORING_OP_SENDMSG:
6123 case IORING_OP_SEND:
6124 return io_sendmsg_prep(req, sqe);
6125 case IORING_OP_RECVMSG:
6126 case IORING_OP_RECV:
6127 return io_recvmsg_prep(req, sqe);
6128 case IORING_OP_CONNECT:
6129 return io_connect_prep(req, sqe);
6130 case IORING_OP_TIMEOUT:
6131 return io_timeout_prep(req, sqe, false);
6132 case IORING_OP_TIMEOUT_REMOVE:
6133 return io_timeout_remove_prep(req, sqe);
6134 case IORING_OP_ASYNC_CANCEL:
6135 return io_async_cancel_prep(req, sqe);
6136 case IORING_OP_LINK_TIMEOUT:
6137 return io_timeout_prep(req, sqe, true);
6138 case IORING_OP_ACCEPT:
6139 return io_accept_prep(req, sqe);
6140 case IORING_OP_FALLOCATE:
6141 return io_fallocate_prep(req, sqe);
6142 case IORING_OP_OPENAT:
6143 return io_openat_prep(req, sqe);
6144 case IORING_OP_CLOSE:
6145 return io_close_prep(req, sqe);
6146 case IORING_OP_FILES_UPDATE:
6147 return io_rsrc_update_prep(req, sqe);
6148 case IORING_OP_STATX:
6149 return io_statx_prep(req, sqe);
6150 case IORING_OP_FADVISE:
6151 return io_fadvise_prep(req, sqe);
6152 case IORING_OP_MADVISE:
6153 return io_madvise_prep(req, sqe);
6154 case IORING_OP_OPENAT2:
6155 return io_openat2_prep(req, sqe);
6156 case IORING_OP_EPOLL_CTL:
6157 return io_epoll_ctl_prep(req, sqe);
6158 case IORING_OP_SPLICE:
6159 return io_splice_prep(req, sqe);
6160 case IORING_OP_PROVIDE_BUFFERS:
6161 return io_provide_buffers_prep(req, sqe);
6162 case IORING_OP_REMOVE_BUFFERS:
6163 return io_remove_buffers_prep(req, sqe);
6165 return io_tee_prep(req, sqe);
6166 case IORING_OP_SHUTDOWN:
6167 return io_shutdown_prep(req, sqe);
6168 case IORING_OP_RENAMEAT:
6169 return io_renameat_prep(req, sqe);
6170 case IORING_OP_UNLINKAT:
6171 return io_unlinkat_prep(req, sqe);
6174 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6179 static int io_req_prep_async(struct io_kiocb *req)
6181 if (!io_op_defs[req->opcode].needs_async_setup)
6183 if (WARN_ON_ONCE(req->async_data))
6185 if (io_alloc_async_data(req))
6188 switch (req->opcode) {
6189 case IORING_OP_READV:
6190 return io_rw_prep_async(req, READ);
6191 case IORING_OP_WRITEV:
6192 return io_rw_prep_async(req, WRITE);
6193 case IORING_OP_SENDMSG:
6194 return io_sendmsg_prep_async(req);
6195 case IORING_OP_RECVMSG:
6196 return io_recvmsg_prep_async(req);
6197 case IORING_OP_CONNECT:
6198 return io_connect_prep_async(req);
6200 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6205 static u32 io_get_sequence(struct io_kiocb *req)
6207 u32 seq = req->ctx->cached_sq_head;
6209 /* need original cached_sq_head, but it was increased for each req */
6210 io_for_each_link(req, req)
6215 static bool io_drain_req(struct io_kiocb *req)
6217 struct io_kiocb *pos;
6218 struct io_ring_ctx *ctx = req->ctx;
6219 struct io_defer_entry *de;
6224 * If we need to drain a request in the middle of a link, drain the
6225 * head request and the next request/link after the current link.
6226 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6227 * maintained for every request of our link.
6229 if (ctx->drain_next) {
6230 req->flags |= REQ_F_IO_DRAIN;
6231 ctx->drain_next = false;
6233 /* not interested in head, start from the first linked */
6234 io_for_each_link(pos, req->link) {
6235 if (pos->flags & REQ_F_IO_DRAIN) {
6236 ctx->drain_next = true;
6237 req->flags |= REQ_F_IO_DRAIN;
6242 /* Still need defer if there is pending req in defer list. */
6243 if (likely(list_empty_careful(&ctx->defer_list) &&
6244 !(req->flags & REQ_F_IO_DRAIN))) {
6245 ctx->drain_active = false;
6249 seq = io_get_sequence(req);
6250 /* Still a chance to pass the sequence check */
6251 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6254 ret = io_req_prep_async(req);
6257 io_prep_async_link(req);
6258 de = kmalloc(sizeof(*de), GFP_KERNEL);
6262 io_req_complete_failed(req, ret);
6266 spin_lock(&ctx->completion_lock);
6267 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6268 spin_unlock(&ctx->completion_lock);
6270 io_queue_async_work(req, NULL);
6274 trace_io_uring_defer(ctx, req, req->user_data);
6277 list_add_tail(&de->list, &ctx->defer_list);
6278 spin_unlock(&ctx->completion_lock);
6282 static void io_clean_op(struct io_kiocb *req)
6284 if (req->flags & REQ_F_BUFFER_SELECTED) {
6285 switch (req->opcode) {
6286 case IORING_OP_READV:
6287 case IORING_OP_READ_FIXED:
6288 case IORING_OP_READ:
6289 kfree((void *)(unsigned long)req->rw.addr);
6291 case IORING_OP_RECVMSG:
6292 case IORING_OP_RECV:
6293 kfree(req->sr_msg.kbuf);
6298 if (req->flags & REQ_F_NEED_CLEANUP) {
6299 switch (req->opcode) {
6300 case IORING_OP_READV:
6301 case IORING_OP_READ_FIXED:
6302 case IORING_OP_READ:
6303 case IORING_OP_WRITEV:
6304 case IORING_OP_WRITE_FIXED:
6305 case IORING_OP_WRITE: {
6306 struct io_async_rw *io = req->async_data;
6308 kfree(io->free_iovec);
6311 case IORING_OP_RECVMSG:
6312 case IORING_OP_SENDMSG: {
6313 struct io_async_msghdr *io = req->async_data;
6315 kfree(io->free_iov);
6318 case IORING_OP_SPLICE:
6320 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6321 io_put_file(req->splice.file_in);
6323 case IORING_OP_OPENAT:
6324 case IORING_OP_OPENAT2:
6325 if (req->open.filename)
6326 putname(req->open.filename);
6328 case IORING_OP_RENAMEAT:
6329 putname(req->rename.oldpath);
6330 putname(req->rename.newpath);
6332 case IORING_OP_UNLINKAT:
6333 putname(req->unlink.filename);
6337 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6338 kfree(req->apoll->double_poll);
6342 if (req->flags & REQ_F_INFLIGHT) {
6343 struct io_uring_task *tctx = req->task->io_uring;
6345 atomic_dec(&tctx->inflight_tracked);
6347 if (req->flags & REQ_F_CREDS)
6348 put_cred(req->creds);
6350 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6353 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6355 struct io_ring_ctx *ctx = req->ctx;
6356 const struct cred *creds = NULL;
6359 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6360 creds = override_creds(req->creds);
6362 switch (req->opcode) {
6364 ret = io_nop(req, issue_flags);
6366 case IORING_OP_READV:
6367 case IORING_OP_READ_FIXED:
6368 case IORING_OP_READ:
6369 ret = io_read(req, issue_flags);
6371 case IORING_OP_WRITEV:
6372 case IORING_OP_WRITE_FIXED:
6373 case IORING_OP_WRITE:
6374 ret = io_write(req, issue_flags);
6376 case IORING_OP_FSYNC:
6377 ret = io_fsync(req, issue_flags);
6379 case IORING_OP_POLL_ADD:
6380 ret = io_poll_add(req, issue_flags);
6382 case IORING_OP_POLL_REMOVE:
6383 ret = io_poll_update(req, issue_flags);
6385 case IORING_OP_SYNC_FILE_RANGE:
6386 ret = io_sync_file_range(req, issue_flags);
6388 case IORING_OP_SENDMSG:
6389 ret = io_sendmsg(req, issue_flags);
6391 case IORING_OP_SEND:
6392 ret = io_send(req, issue_flags);
6394 case IORING_OP_RECVMSG:
6395 ret = io_recvmsg(req, issue_flags);
6397 case IORING_OP_RECV:
6398 ret = io_recv(req, issue_flags);
6400 case IORING_OP_TIMEOUT:
6401 ret = io_timeout(req, issue_flags);
6403 case IORING_OP_TIMEOUT_REMOVE:
6404 ret = io_timeout_remove(req, issue_flags);
6406 case IORING_OP_ACCEPT:
6407 ret = io_accept(req, issue_flags);
6409 case IORING_OP_CONNECT:
6410 ret = io_connect(req, issue_flags);
6412 case IORING_OP_ASYNC_CANCEL:
6413 ret = io_async_cancel(req, issue_flags);
6415 case IORING_OP_FALLOCATE:
6416 ret = io_fallocate(req, issue_flags);
6418 case IORING_OP_OPENAT:
6419 ret = io_openat(req, issue_flags);
6421 case IORING_OP_CLOSE:
6422 ret = io_close(req, issue_flags);
6424 case IORING_OP_FILES_UPDATE:
6425 ret = io_files_update(req, issue_flags);
6427 case IORING_OP_STATX:
6428 ret = io_statx(req, issue_flags);
6430 case IORING_OP_FADVISE:
6431 ret = io_fadvise(req, issue_flags);
6433 case IORING_OP_MADVISE:
6434 ret = io_madvise(req, issue_flags);
6436 case IORING_OP_OPENAT2:
6437 ret = io_openat2(req, issue_flags);
6439 case IORING_OP_EPOLL_CTL:
6440 ret = io_epoll_ctl(req, issue_flags);
6442 case IORING_OP_SPLICE:
6443 ret = io_splice(req, issue_flags);
6445 case IORING_OP_PROVIDE_BUFFERS:
6446 ret = io_provide_buffers(req, issue_flags);
6448 case IORING_OP_REMOVE_BUFFERS:
6449 ret = io_remove_buffers(req, issue_flags);
6452 ret = io_tee(req, issue_flags);
6454 case IORING_OP_SHUTDOWN:
6455 ret = io_shutdown(req, issue_flags);
6457 case IORING_OP_RENAMEAT:
6458 ret = io_renameat(req, issue_flags);
6460 case IORING_OP_UNLINKAT:
6461 ret = io_unlinkat(req, issue_flags);
6469 revert_creds(creds);
6472 /* If the op doesn't have a file, we're not polling for it */
6473 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6474 io_iopoll_req_issued(req);
6479 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6481 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6483 req = io_put_req_find_next(req);
6484 return req ? &req->work : NULL;
6487 static void io_wq_submit_work(struct io_wq_work *work)
6489 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6490 struct io_kiocb *timeout;
6493 /* one will be dropped by ->io_free_work() after returning to io-wq */
6494 if (!(req->flags & REQ_F_REFCOUNT))
6495 __io_req_set_refcount(req, 2);
6499 timeout = io_prep_linked_timeout(req);
6501 io_queue_linked_timeout(timeout);
6503 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6504 if (work->flags & IO_WQ_WORK_CANCEL)
6509 ret = io_issue_sqe(req, 0);
6511 * We can get EAGAIN for polled IO even though we're
6512 * forcing a sync submission from here, since we can't
6513 * wait for request slots on the block side.
6521 /* avoid locking problems by failing it from a clean context */
6523 io_req_task_queue_fail(req, ret);
6526 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6529 return &table->files[i];
6532 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6535 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6537 return (struct file *) (slot->file_ptr & FFS_MASK);
6540 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6542 unsigned long file_ptr = (unsigned long) file;
6544 if (__io_file_supports_nowait(file, READ))
6545 file_ptr |= FFS_ASYNC_READ;
6546 if (__io_file_supports_nowait(file, WRITE))
6547 file_ptr |= FFS_ASYNC_WRITE;
6548 if (S_ISREG(file_inode(file)->i_mode))
6549 file_ptr |= FFS_ISREG;
6550 file_slot->file_ptr = file_ptr;
6553 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6554 struct io_kiocb *req, int fd)
6557 unsigned long file_ptr;
6559 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6561 fd = array_index_nospec(fd, ctx->nr_user_files);
6562 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6563 file = (struct file *) (file_ptr & FFS_MASK);
6564 file_ptr &= ~FFS_MASK;
6565 /* mask in overlapping REQ_F and FFS bits */
6566 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6567 io_req_set_rsrc_node(req);
6571 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6572 struct io_kiocb *req, int fd)
6574 struct file *file = fget(fd);
6576 trace_io_uring_file_get(ctx, fd);
6578 /* we don't allow fixed io_uring files */
6579 if (file && unlikely(file->f_op == &io_uring_fops))
6580 io_req_track_inflight(req);
6584 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6585 struct io_kiocb *req, int fd, bool fixed)
6588 return io_file_get_fixed(ctx, req, fd);
6590 return io_file_get_normal(ctx, req, fd);
6593 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6595 struct io_kiocb *prev = req->timeout.prev;
6599 ret = io_try_cancel_userdata(req, prev->user_data);
6600 io_req_complete_post(req, ret ?: -ETIME, 0);
6603 io_req_complete_post(req, -ETIME, 0);
6607 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6609 struct io_timeout_data *data = container_of(timer,
6610 struct io_timeout_data, timer);
6611 struct io_kiocb *prev, *req = data->req;
6612 struct io_ring_ctx *ctx = req->ctx;
6613 unsigned long flags;
6615 spin_lock_irqsave(&ctx->timeout_lock, flags);
6616 prev = req->timeout.head;
6617 req->timeout.head = NULL;
6620 * We don't expect the list to be empty, that will only happen if we
6621 * race with the completion of the linked work.
6624 io_remove_next_linked(prev);
6625 if (!req_ref_inc_not_zero(prev))
6628 list_del(&req->timeout.list);
6629 req->timeout.prev = prev;
6630 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6632 req->io_task_work.func = io_req_task_link_timeout;
6633 io_req_task_work_add(req);
6634 return HRTIMER_NORESTART;
6637 static void io_queue_linked_timeout(struct io_kiocb *req)
6639 struct io_ring_ctx *ctx = req->ctx;
6641 spin_lock_irq(&ctx->timeout_lock);
6643 * If the back reference is NULL, then our linked request finished
6644 * before we got a chance to setup the timer
6646 if (req->timeout.head) {
6647 struct io_timeout_data *data = req->async_data;
6649 data->timer.function = io_link_timeout_fn;
6650 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6652 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6654 spin_unlock_irq(&ctx->timeout_lock);
6655 /* drop submission reference */
6659 static void __io_queue_sqe(struct io_kiocb *req)
6660 __must_hold(&req->ctx->uring_lock)
6662 struct io_kiocb *linked_timeout;
6666 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6669 * We async punt it if the file wasn't marked NOWAIT, or if the file
6670 * doesn't support non-blocking read/write attempts
6673 if (req->flags & REQ_F_COMPLETE_INLINE) {
6674 struct io_ring_ctx *ctx = req->ctx;
6675 struct io_submit_state *state = &ctx->submit_state;
6677 state->compl_reqs[state->compl_nr++] = req;
6678 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6679 io_submit_flush_completions(ctx);
6683 linked_timeout = io_prep_linked_timeout(req);
6685 io_queue_linked_timeout(linked_timeout);
6686 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6687 linked_timeout = io_prep_linked_timeout(req);
6689 switch (io_arm_poll_handler(req)) {
6690 case IO_APOLL_READY:
6692 io_unprep_linked_timeout(req);
6694 case IO_APOLL_ABORTED:
6696 * Queued up for async execution, worker will release
6697 * submit reference when the iocb is actually submitted.
6699 io_queue_async_work(req, NULL);
6704 io_queue_linked_timeout(linked_timeout);
6706 io_req_complete_failed(req, ret);
6710 static inline void io_queue_sqe(struct io_kiocb *req)
6711 __must_hold(&req->ctx->uring_lock)
6713 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6716 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6717 __io_queue_sqe(req);
6718 } else if (req->flags & REQ_F_FAIL) {
6719 io_req_complete_failed(req, req->result);
6721 int ret = io_req_prep_async(req);
6724 io_req_complete_failed(req, ret);
6726 io_queue_async_work(req, NULL);
6731 * Check SQE restrictions (opcode and flags).
6733 * Returns 'true' if SQE is allowed, 'false' otherwise.
6735 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6736 struct io_kiocb *req,
6737 unsigned int sqe_flags)
6739 if (likely(!ctx->restricted))
6742 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6745 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6746 ctx->restrictions.sqe_flags_required)
6749 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6750 ctx->restrictions.sqe_flags_required))
6756 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6757 const struct io_uring_sqe *sqe)
6758 __must_hold(&ctx->uring_lock)
6760 struct io_submit_state *state;
6761 unsigned int sqe_flags;
6762 int personality, ret = 0;
6764 /* req is partially pre-initialised, see io_preinit_req() */
6765 req->opcode = READ_ONCE(sqe->opcode);
6766 /* same numerical values with corresponding REQ_F_*, safe to copy */
6767 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6768 req->user_data = READ_ONCE(sqe->user_data);
6770 req->fixed_rsrc_refs = NULL;
6771 req->task = current;
6773 /* enforce forwards compatibility on users */
6774 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6776 if (unlikely(req->opcode >= IORING_OP_LAST))
6778 if (!io_check_restriction(ctx, req, sqe_flags))
6781 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6782 !io_op_defs[req->opcode].buffer_select)
6784 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6785 ctx->drain_active = true;
6787 personality = READ_ONCE(sqe->personality);
6789 req->creds = xa_load(&ctx->personalities, personality);
6792 get_cred(req->creds);
6793 req->flags |= REQ_F_CREDS;
6795 state = &ctx->submit_state;
6798 * Plug now if we have more than 1 IO left after this, and the target
6799 * is potentially a read/write to block based storage.
6801 if (!state->plug_started && state->ios_left > 1 &&
6802 io_op_defs[req->opcode].plug) {
6803 blk_start_plug(&state->plug);
6804 state->plug_started = true;
6807 if (io_op_defs[req->opcode].needs_file) {
6808 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6809 (sqe_flags & IOSQE_FIXED_FILE));
6810 if (unlikely(!req->file))
6818 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6819 const struct io_uring_sqe *sqe)
6820 __must_hold(&ctx->uring_lock)
6822 struct io_submit_link *link = &ctx->submit_state.link;
6825 ret = io_init_req(ctx, req, sqe);
6826 if (unlikely(ret)) {
6828 /* fail even hard links since we don't submit */
6831 * we can judge a link req is failed or cancelled by if
6832 * REQ_F_FAIL is set, but the head is an exception since
6833 * it may be set REQ_F_FAIL because of other req's failure
6834 * so let's leverage req->result to distinguish if a head
6835 * is set REQ_F_FAIL because of its failure or other req's
6836 * failure so that we can set the correct ret code for it.
6837 * init result here to avoid affecting the normal path.
6839 if (!(link->head->flags & REQ_F_FAIL))
6840 req_fail_link_node(link->head, -ECANCELED);
6841 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6843 * the current req is a normal req, we should return
6844 * error and thus break the submittion loop.
6846 io_req_complete_failed(req, ret);
6849 req_fail_link_node(req, ret);
6851 ret = io_req_prep(req, sqe);
6856 /* don't need @sqe from now on */
6857 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6859 ctx->flags & IORING_SETUP_SQPOLL);
6862 * If we already have a head request, queue this one for async
6863 * submittal once the head completes. If we don't have a head but
6864 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6865 * submitted sync once the chain is complete. If none of those
6866 * conditions are true (normal request), then just queue it.
6869 struct io_kiocb *head = link->head;
6871 if (!(req->flags & REQ_F_FAIL)) {
6872 ret = io_req_prep_async(req);
6873 if (unlikely(ret)) {
6874 req_fail_link_node(req, ret);
6875 if (!(head->flags & REQ_F_FAIL))
6876 req_fail_link_node(head, -ECANCELED);
6879 trace_io_uring_link(ctx, req, head);
6880 link->last->link = req;
6883 /* last request of a link, enqueue the link */
6884 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6889 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6901 * Batched submission is done, ensure local IO is flushed out.
6903 static void io_submit_state_end(struct io_submit_state *state,
6904 struct io_ring_ctx *ctx)
6906 if (state->link.head)
6907 io_queue_sqe(state->link.head);
6908 if (state->compl_nr)
6909 io_submit_flush_completions(ctx);
6910 if (state->plug_started)
6911 blk_finish_plug(&state->plug);
6915 * Start submission side cache.
6917 static void io_submit_state_start(struct io_submit_state *state,
6918 unsigned int max_ios)
6920 state->plug_started = false;
6921 state->ios_left = max_ios;
6922 /* set only head, no need to init link_last in advance */
6923 state->link.head = NULL;
6926 static void io_commit_sqring(struct io_ring_ctx *ctx)
6928 struct io_rings *rings = ctx->rings;
6931 * Ensure any loads from the SQEs are done at this point,
6932 * since once we write the new head, the application could
6933 * write new data to them.
6935 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6939 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6940 * that is mapped by userspace. This means that care needs to be taken to
6941 * ensure that reads are stable, as we cannot rely on userspace always
6942 * being a good citizen. If members of the sqe are validated and then later
6943 * used, it's important that those reads are done through READ_ONCE() to
6944 * prevent a re-load down the line.
6946 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6948 unsigned head, mask = ctx->sq_entries - 1;
6949 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6952 * The cached sq head (or cq tail) serves two purposes:
6954 * 1) allows us to batch the cost of updating the user visible
6956 * 2) allows the kernel side to track the head on its own, even
6957 * though the application is the one updating it.
6959 head = READ_ONCE(ctx->sq_array[sq_idx]);
6960 if (likely(head < ctx->sq_entries))
6961 return &ctx->sq_sqes[head];
6963 /* drop invalid entries */
6965 WRITE_ONCE(ctx->rings->sq_dropped,
6966 READ_ONCE(ctx->rings->sq_dropped) + 1);
6970 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6971 __must_hold(&ctx->uring_lock)
6975 /* make sure SQ entry isn't read before tail */
6976 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6977 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6979 io_get_task_refs(nr);
6981 io_submit_state_start(&ctx->submit_state, nr);
6982 while (submitted < nr) {
6983 const struct io_uring_sqe *sqe;
6984 struct io_kiocb *req;
6986 req = io_alloc_req(ctx);
6987 if (unlikely(!req)) {
6989 submitted = -EAGAIN;
6992 sqe = io_get_sqe(ctx);
6993 if (unlikely(!sqe)) {
6994 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
6997 /* will complete beyond this point, count as submitted */
6999 if (io_submit_sqe(ctx, req, sqe))
7003 if (unlikely(submitted != nr)) {
7004 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7005 int unused = nr - ref_used;
7007 current->io_uring->cached_refs += unused;
7008 percpu_ref_put_many(&ctx->refs, unused);
7011 io_submit_state_end(&ctx->submit_state, ctx);
7012 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7013 io_commit_sqring(ctx);
7018 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7020 return READ_ONCE(sqd->state);
7023 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7025 /* Tell userspace we may need a wakeup call */
7026 spin_lock(&ctx->completion_lock);
7027 WRITE_ONCE(ctx->rings->sq_flags,
7028 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7029 spin_unlock(&ctx->completion_lock);
7032 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7034 spin_lock(&ctx->completion_lock);
7035 WRITE_ONCE(ctx->rings->sq_flags,
7036 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7037 spin_unlock(&ctx->completion_lock);
7040 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7042 unsigned int to_submit;
7045 to_submit = io_sqring_entries(ctx);
7046 /* if we're handling multiple rings, cap submit size for fairness */
7047 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7048 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7050 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7051 unsigned nr_events = 0;
7052 const struct cred *creds = NULL;
7054 if (ctx->sq_creds != current_cred())
7055 creds = override_creds(ctx->sq_creds);
7057 mutex_lock(&ctx->uring_lock);
7058 if (!list_empty(&ctx->iopoll_list))
7059 io_do_iopoll(ctx, &nr_events, 0);
7062 * Don't submit if refs are dying, good for io_uring_register(),
7063 * but also it is relied upon by io_ring_exit_work()
7065 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7066 !(ctx->flags & IORING_SETUP_R_DISABLED))
7067 ret = io_submit_sqes(ctx, to_submit);
7068 mutex_unlock(&ctx->uring_lock);
7070 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7071 wake_up(&ctx->sqo_sq_wait);
7073 revert_creds(creds);
7079 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7081 struct io_ring_ctx *ctx;
7082 unsigned sq_thread_idle = 0;
7084 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7085 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7086 sqd->sq_thread_idle = sq_thread_idle;
7089 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7091 bool did_sig = false;
7092 struct ksignal ksig;
7094 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7095 signal_pending(current)) {
7096 mutex_unlock(&sqd->lock);
7097 if (signal_pending(current))
7098 did_sig = get_signal(&ksig);
7100 mutex_lock(&sqd->lock);
7102 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7105 static int io_sq_thread(void *data)
7107 struct io_sq_data *sqd = data;
7108 struct io_ring_ctx *ctx;
7109 unsigned long timeout = 0;
7110 char buf[TASK_COMM_LEN];
7113 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7114 set_task_comm(current, buf);
7116 if (sqd->sq_cpu != -1)
7117 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7119 set_cpus_allowed_ptr(current, cpu_online_mask);
7120 current->flags |= PF_NO_SETAFFINITY;
7122 mutex_lock(&sqd->lock);
7124 bool cap_entries, sqt_spin = false;
7126 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7127 if (io_sqd_handle_event(sqd))
7129 timeout = jiffies + sqd->sq_thread_idle;
7132 cap_entries = !list_is_singular(&sqd->ctx_list);
7133 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7134 int ret = __io_sq_thread(ctx, cap_entries);
7136 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7139 if (io_run_task_work())
7142 if (sqt_spin || !time_after(jiffies, timeout)) {
7145 timeout = jiffies + sqd->sq_thread_idle;
7149 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7150 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7151 bool needs_sched = true;
7153 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7154 io_ring_set_wakeup_flag(ctx);
7156 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7157 !list_empty_careful(&ctx->iopoll_list)) {
7158 needs_sched = false;
7161 if (io_sqring_entries(ctx)) {
7162 needs_sched = false;
7168 mutex_unlock(&sqd->lock);
7170 mutex_lock(&sqd->lock);
7172 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7173 io_ring_clear_wakeup_flag(ctx);
7176 finish_wait(&sqd->wait, &wait);
7177 timeout = jiffies + sqd->sq_thread_idle;
7180 io_uring_cancel_generic(true, sqd);
7182 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7183 io_ring_set_wakeup_flag(ctx);
7185 mutex_unlock(&sqd->lock);
7187 complete(&sqd->exited);
7191 struct io_wait_queue {
7192 struct wait_queue_entry wq;
7193 struct io_ring_ctx *ctx;
7195 unsigned nr_timeouts;
7198 static inline bool io_should_wake(struct io_wait_queue *iowq)
7200 struct io_ring_ctx *ctx = iowq->ctx;
7201 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7204 * Wake up if we have enough events, or if a timeout occurred since we
7205 * started waiting. For timeouts, we always want to return to userspace,
7206 * regardless of event count.
7208 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7211 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7212 int wake_flags, void *key)
7214 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7218 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7219 * the task, and the next invocation will do it.
7221 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7222 return autoremove_wake_function(curr, mode, wake_flags, key);
7226 static int io_run_task_work_sig(void)
7228 if (io_run_task_work())
7230 if (!signal_pending(current))
7232 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7233 return -ERESTARTSYS;
7237 /* when returns >0, the caller should retry */
7238 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7239 struct io_wait_queue *iowq,
7240 signed long *timeout)
7244 /* make sure we run task_work before checking for signals */
7245 ret = io_run_task_work_sig();
7246 if (ret || io_should_wake(iowq))
7248 /* let the caller flush overflows, retry */
7249 if (test_bit(0, &ctx->check_cq_overflow))
7252 *timeout = schedule_timeout(*timeout);
7253 return !*timeout ? -ETIME : 1;
7257 * Wait until events become available, if we don't already have some. The
7258 * application must reap them itself, as they reside on the shared cq ring.
7260 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7261 const sigset_t __user *sig, size_t sigsz,
7262 struct __kernel_timespec __user *uts)
7264 struct io_wait_queue iowq;
7265 struct io_rings *rings = ctx->rings;
7266 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7270 io_cqring_overflow_flush(ctx);
7271 if (io_cqring_events(ctx) >= min_events)
7273 if (!io_run_task_work())
7278 #ifdef CONFIG_COMPAT
7279 if (in_compat_syscall())
7280 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7284 ret = set_user_sigmask(sig, sigsz);
7291 struct timespec64 ts;
7293 if (get_timespec64(&ts, uts))
7295 timeout = timespec64_to_jiffies(&ts);
7298 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7299 iowq.wq.private = current;
7300 INIT_LIST_HEAD(&iowq.wq.entry);
7302 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7303 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7305 trace_io_uring_cqring_wait(ctx, min_events);
7307 /* if we can't even flush overflow, don't wait for more */
7308 if (!io_cqring_overflow_flush(ctx)) {
7312 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7313 TASK_INTERRUPTIBLE);
7314 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7315 finish_wait(&ctx->cq_wait, &iowq.wq);
7319 restore_saved_sigmask_unless(ret == -EINTR);
7321 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7324 static void io_free_page_table(void **table, size_t size)
7326 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7328 for (i = 0; i < nr_tables; i++)
7333 static void **io_alloc_page_table(size_t size)
7335 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7336 size_t init_size = size;
7339 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7343 for (i = 0; i < nr_tables; i++) {
7344 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7346 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7348 io_free_page_table(table, init_size);
7356 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7358 percpu_ref_exit(&ref_node->refs);
7362 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7364 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7365 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7366 unsigned long flags;
7367 bool first_add = false;
7369 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7372 while (!list_empty(&ctx->rsrc_ref_list)) {
7373 node = list_first_entry(&ctx->rsrc_ref_list,
7374 struct io_rsrc_node, node);
7375 /* recycle ref nodes in order */
7378 list_del(&node->node);
7379 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7381 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7384 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7387 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7389 struct io_rsrc_node *ref_node;
7391 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7395 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7400 INIT_LIST_HEAD(&ref_node->node);
7401 INIT_LIST_HEAD(&ref_node->rsrc_list);
7402 ref_node->done = false;
7406 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7407 struct io_rsrc_data *data_to_kill)
7409 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7410 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7413 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7415 rsrc_node->rsrc_data = data_to_kill;
7416 spin_lock_irq(&ctx->rsrc_ref_lock);
7417 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7418 spin_unlock_irq(&ctx->rsrc_ref_lock);
7420 atomic_inc(&data_to_kill->refs);
7421 percpu_ref_kill(&rsrc_node->refs);
7422 ctx->rsrc_node = NULL;
7425 if (!ctx->rsrc_node) {
7426 ctx->rsrc_node = ctx->rsrc_backup_node;
7427 ctx->rsrc_backup_node = NULL;
7431 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7433 if (ctx->rsrc_backup_node)
7435 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7436 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7439 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7443 /* As we may drop ->uring_lock, other task may have started quiesce */
7447 data->quiesce = true;
7449 ret = io_rsrc_node_switch_start(ctx);
7452 io_rsrc_node_switch(ctx, data);
7454 /* kill initial ref, already quiesced if zero */
7455 if (atomic_dec_and_test(&data->refs))
7457 mutex_unlock(&ctx->uring_lock);
7458 flush_delayed_work(&ctx->rsrc_put_work);
7459 ret = wait_for_completion_interruptible(&data->done);
7461 mutex_lock(&ctx->uring_lock);
7465 atomic_inc(&data->refs);
7466 /* wait for all works potentially completing data->done */
7467 flush_delayed_work(&ctx->rsrc_put_work);
7468 reinit_completion(&data->done);
7470 ret = io_run_task_work_sig();
7471 mutex_lock(&ctx->uring_lock);
7473 data->quiesce = false;
7478 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7480 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7481 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7483 return &data->tags[table_idx][off];
7486 static void io_rsrc_data_free(struct io_rsrc_data *data)
7488 size_t size = data->nr * sizeof(data->tags[0][0]);
7491 io_free_page_table((void **)data->tags, size);
7495 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7496 u64 __user *utags, unsigned nr,
7497 struct io_rsrc_data **pdata)
7499 struct io_rsrc_data *data;
7503 data = kzalloc(sizeof(*data), GFP_KERNEL);
7506 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7514 data->do_put = do_put;
7517 for (i = 0; i < nr; i++) {
7518 u64 *tag_slot = io_get_tag_slot(data, i);
7520 if (copy_from_user(tag_slot, &utags[i],
7526 atomic_set(&data->refs, 1);
7527 init_completion(&data->done);
7531 io_rsrc_data_free(data);
7535 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7537 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7538 GFP_KERNEL_ACCOUNT);
7539 return !!table->files;
7542 static void io_free_file_tables(struct io_file_table *table)
7544 kvfree(table->files);
7545 table->files = NULL;
7548 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7550 #if defined(CONFIG_UNIX)
7551 if (ctx->ring_sock) {
7552 struct sock *sock = ctx->ring_sock->sk;
7553 struct sk_buff *skb;
7555 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7561 for (i = 0; i < ctx->nr_user_files; i++) {
7564 file = io_file_from_index(ctx, i);
7569 io_free_file_tables(&ctx->file_table);
7570 io_rsrc_data_free(ctx->file_data);
7571 ctx->file_data = NULL;
7572 ctx->nr_user_files = 0;
7575 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7579 if (!ctx->file_data)
7581 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7583 __io_sqe_files_unregister(ctx);
7587 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7588 __releases(&sqd->lock)
7590 WARN_ON_ONCE(sqd->thread == current);
7593 * Do the dance but not conditional clear_bit() because it'd race with
7594 * other threads incrementing park_pending and setting the bit.
7596 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7597 if (atomic_dec_return(&sqd->park_pending))
7598 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7599 mutex_unlock(&sqd->lock);
7602 static void io_sq_thread_park(struct io_sq_data *sqd)
7603 __acquires(&sqd->lock)
7605 WARN_ON_ONCE(sqd->thread == current);
7607 atomic_inc(&sqd->park_pending);
7608 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7609 mutex_lock(&sqd->lock);
7611 wake_up_process(sqd->thread);
7614 static void io_sq_thread_stop(struct io_sq_data *sqd)
7616 WARN_ON_ONCE(sqd->thread == current);
7617 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7619 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7620 mutex_lock(&sqd->lock);
7622 wake_up_process(sqd->thread);
7623 mutex_unlock(&sqd->lock);
7624 wait_for_completion(&sqd->exited);
7627 static void io_put_sq_data(struct io_sq_data *sqd)
7629 if (refcount_dec_and_test(&sqd->refs)) {
7630 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7632 io_sq_thread_stop(sqd);
7637 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7639 struct io_sq_data *sqd = ctx->sq_data;
7642 io_sq_thread_park(sqd);
7643 list_del_init(&ctx->sqd_list);
7644 io_sqd_update_thread_idle(sqd);
7645 io_sq_thread_unpark(sqd);
7647 io_put_sq_data(sqd);
7648 ctx->sq_data = NULL;
7652 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7654 struct io_ring_ctx *ctx_attach;
7655 struct io_sq_data *sqd;
7658 f = fdget(p->wq_fd);
7660 return ERR_PTR(-ENXIO);
7661 if (f.file->f_op != &io_uring_fops) {
7663 return ERR_PTR(-EINVAL);
7666 ctx_attach = f.file->private_data;
7667 sqd = ctx_attach->sq_data;
7670 return ERR_PTR(-EINVAL);
7672 if (sqd->task_tgid != current->tgid) {
7674 return ERR_PTR(-EPERM);
7677 refcount_inc(&sqd->refs);
7682 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7685 struct io_sq_data *sqd;
7688 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7689 sqd = io_attach_sq_data(p);
7694 /* fall through for EPERM case, setup new sqd/task */
7695 if (PTR_ERR(sqd) != -EPERM)
7699 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7701 return ERR_PTR(-ENOMEM);
7703 atomic_set(&sqd->park_pending, 0);
7704 refcount_set(&sqd->refs, 1);
7705 INIT_LIST_HEAD(&sqd->ctx_list);
7706 mutex_init(&sqd->lock);
7707 init_waitqueue_head(&sqd->wait);
7708 init_completion(&sqd->exited);
7712 #if defined(CONFIG_UNIX)
7714 * Ensure the UNIX gc is aware of our file set, so we are certain that
7715 * the io_uring can be safely unregistered on process exit, even if we have
7716 * loops in the file referencing.
7718 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7720 struct sock *sk = ctx->ring_sock->sk;
7721 struct scm_fp_list *fpl;
7722 struct sk_buff *skb;
7725 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7729 skb = alloc_skb(0, GFP_KERNEL);
7738 fpl->user = get_uid(current_user());
7739 for (i = 0; i < nr; i++) {
7740 struct file *file = io_file_from_index(ctx, i + offset);
7744 fpl->fp[nr_files] = get_file(file);
7745 unix_inflight(fpl->user, fpl->fp[nr_files]);
7750 fpl->max = SCM_MAX_FD;
7751 fpl->count = nr_files;
7752 UNIXCB(skb).fp = fpl;
7753 skb->destructor = unix_destruct_scm;
7754 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7755 skb_queue_head(&sk->sk_receive_queue, skb);
7757 for (i = 0; i < nr_files; i++)
7768 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7769 * causes regular reference counting to break down. We rely on the UNIX
7770 * garbage collection to take care of this problem for us.
7772 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7774 unsigned left, total;
7778 left = ctx->nr_user_files;
7780 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7782 ret = __io_sqe_files_scm(ctx, this_files, total);
7786 total += this_files;
7792 while (total < ctx->nr_user_files) {
7793 struct file *file = io_file_from_index(ctx, total);
7803 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7809 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7811 struct file *file = prsrc->file;
7812 #if defined(CONFIG_UNIX)
7813 struct sock *sock = ctx->ring_sock->sk;
7814 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7815 struct sk_buff *skb;
7818 __skb_queue_head_init(&list);
7821 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7822 * remove this entry and rearrange the file array.
7824 skb = skb_dequeue(head);
7826 struct scm_fp_list *fp;
7828 fp = UNIXCB(skb).fp;
7829 for (i = 0; i < fp->count; i++) {
7832 if (fp->fp[i] != file)
7835 unix_notinflight(fp->user, fp->fp[i]);
7836 left = fp->count - 1 - i;
7838 memmove(&fp->fp[i], &fp->fp[i + 1],
7839 left * sizeof(struct file *));
7846 __skb_queue_tail(&list, skb);
7856 __skb_queue_tail(&list, skb);
7858 skb = skb_dequeue(head);
7861 if (skb_peek(&list)) {
7862 spin_lock_irq(&head->lock);
7863 while ((skb = __skb_dequeue(&list)) != NULL)
7864 __skb_queue_tail(head, skb);
7865 spin_unlock_irq(&head->lock);
7872 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7874 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7875 struct io_ring_ctx *ctx = rsrc_data->ctx;
7876 struct io_rsrc_put *prsrc, *tmp;
7878 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7879 list_del(&prsrc->list);
7882 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7884 io_ring_submit_lock(ctx, lock_ring);
7885 spin_lock(&ctx->completion_lock);
7886 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7888 io_commit_cqring(ctx);
7889 spin_unlock(&ctx->completion_lock);
7890 io_cqring_ev_posted(ctx);
7891 io_ring_submit_unlock(ctx, lock_ring);
7894 rsrc_data->do_put(ctx, prsrc);
7898 io_rsrc_node_destroy(ref_node);
7899 if (atomic_dec_and_test(&rsrc_data->refs))
7900 complete(&rsrc_data->done);
7903 static void io_rsrc_put_work(struct work_struct *work)
7905 struct io_ring_ctx *ctx;
7906 struct llist_node *node;
7908 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7909 node = llist_del_all(&ctx->rsrc_put_llist);
7912 struct io_rsrc_node *ref_node;
7913 struct llist_node *next = node->next;
7915 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7916 __io_rsrc_put_work(ref_node);
7921 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7922 unsigned nr_args, u64 __user *tags)
7924 __s32 __user *fds = (__s32 __user *) arg;
7933 if (nr_args > IORING_MAX_FIXED_FILES)
7935 if (nr_args > rlimit(RLIMIT_NOFILE))
7937 ret = io_rsrc_node_switch_start(ctx);
7940 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7946 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7949 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7950 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7954 /* allow sparse sets */
7957 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7964 if (unlikely(!file))
7968 * Don't allow io_uring instances to be registered. If UNIX
7969 * isn't enabled, then this causes a reference cycle and this
7970 * instance can never get freed. If UNIX is enabled we'll
7971 * handle it just fine, but there's still no point in allowing
7972 * a ring fd as it doesn't support regular read/write anyway.
7974 if (file->f_op == &io_uring_fops) {
7978 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7981 ret = io_sqe_files_scm(ctx);
7983 __io_sqe_files_unregister(ctx);
7987 io_rsrc_node_switch(ctx, NULL);
7990 for (i = 0; i < ctx->nr_user_files; i++) {
7991 file = io_file_from_index(ctx, i);
7995 io_free_file_tables(&ctx->file_table);
7996 ctx->nr_user_files = 0;
7998 io_rsrc_data_free(ctx->file_data);
7999 ctx->file_data = NULL;
8003 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8006 #if defined(CONFIG_UNIX)
8007 struct sock *sock = ctx->ring_sock->sk;
8008 struct sk_buff_head *head = &sock->sk_receive_queue;
8009 struct sk_buff *skb;
8012 * See if we can merge this file into an existing skb SCM_RIGHTS
8013 * file set. If there's no room, fall back to allocating a new skb
8014 * and filling it in.
8016 spin_lock_irq(&head->lock);
8017 skb = skb_peek(head);
8019 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8021 if (fpl->count < SCM_MAX_FD) {
8022 __skb_unlink(skb, head);
8023 spin_unlock_irq(&head->lock);
8024 fpl->fp[fpl->count] = get_file(file);
8025 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8027 spin_lock_irq(&head->lock);
8028 __skb_queue_head(head, skb);
8033 spin_unlock_irq(&head->lock);
8040 return __io_sqe_files_scm(ctx, 1, index);
8046 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8047 unsigned int issue_flags, u32 slot_index)
8049 struct io_ring_ctx *ctx = req->ctx;
8050 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8051 struct io_fixed_file *file_slot;
8054 io_ring_submit_lock(ctx, !force_nonblock);
8055 if (file->f_op == &io_uring_fops)
8058 if (!ctx->file_data)
8061 if (slot_index >= ctx->nr_user_files)
8064 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8065 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8067 if (file_slot->file_ptr)
8070 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8071 io_fixed_file_set(file_slot, file);
8072 ret = io_sqe_file_register(ctx, file, slot_index);
8074 file_slot->file_ptr = 0;
8080 io_ring_submit_unlock(ctx, !force_nonblock);
8086 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8087 struct io_rsrc_node *node, void *rsrc)
8089 struct io_rsrc_put *prsrc;
8091 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8095 prsrc->tag = *io_get_tag_slot(data, idx);
8097 list_add(&prsrc->list, &node->rsrc_list);
8101 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8102 struct io_uring_rsrc_update2 *up,
8105 u64 __user *tags = u64_to_user_ptr(up->tags);
8106 __s32 __user *fds = u64_to_user_ptr(up->data);
8107 struct io_rsrc_data *data = ctx->file_data;
8108 struct io_fixed_file *file_slot;
8112 bool needs_switch = false;
8114 if (!ctx->file_data)
8116 if (up->offset + nr_args > ctx->nr_user_files)
8119 for (done = 0; done < nr_args; done++) {
8122 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8123 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8127 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8131 if (fd == IORING_REGISTER_FILES_SKIP)
8134 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8135 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8137 if (file_slot->file_ptr) {
8138 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8139 err = io_queue_rsrc_removal(data, up->offset + done,
8140 ctx->rsrc_node, file);
8143 file_slot->file_ptr = 0;
8144 needs_switch = true;
8153 * Don't allow io_uring instances to be registered. If
8154 * UNIX isn't enabled, then this causes a reference
8155 * cycle and this instance can never get freed. If UNIX
8156 * is enabled we'll handle it just fine, but there's
8157 * still no point in allowing a ring fd as it doesn't
8158 * support regular read/write anyway.
8160 if (file->f_op == &io_uring_fops) {
8165 *io_get_tag_slot(data, up->offset + done) = tag;
8166 io_fixed_file_set(file_slot, file);
8167 err = io_sqe_file_register(ctx, file, i);
8169 file_slot->file_ptr = 0;
8177 io_rsrc_node_switch(ctx, data);
8178 return done ? done : err;
8181 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8182 struct task_struct *task)
8184 struct io_wq_hash *hash;
8185 struct io_wq_data data;
8186 unsigned int concurrency;
8188 mutex_lock(&ctx->uring_lock);
8189 hash = ctx->hash_map;
8191 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8193 mutex_unlock(&ctx->uring_lock);
8194 return ERR_PTR(-ENOMEM);
8196 refcount_set(&hash->refs, 1);
8197 init_waitqueue_head(&hash->wait);
8198 ctx->hash_map = hash;
8200 mutex_unlock(&ctx->uring_lock);
8204 data.free_work = io_wq_free_work;
8205 data.do_work = io_wq_submit_work;
8207 /* Do QD, or 4 * CPUS, whatever is smallest */
8208 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8210 return io_wq_create(concurrency, &data);
8213 static int io_uring_alloc_task_context(struct task_struct *task,
8214 struct io_ring_ctx *ctx)
8216 struct io_uring_task *tctx;
8219 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8220 if (unlikely(!tctx))
8223 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8224 if (unlikely(ret)) {
8229 tctx->io_wq = io_init_wq_offload(ctx, task);
8230 if (IS_ERR(tctx->io_wq)) {
8231 ret = PTR_ERR(tctx->io_wq);
8232 percpu_counter_destroy(&tctx->inflight);
8238 init_waitqueue_head(&tctx->wait);
8239 atomic_set(&tctx->in_idle, 0);
8240 atomic_set(&tctx->inflight_tracked, 0);
8241 task->io_uring = tctx;
8242 spin_lock_init(&tctx->task_lock);
8243 INIT_WQ_LIST(&tctx->task_list);
8244 init_task_work(&tctx->task_work, tctx_task_work);
8248 void __io_uring_free(struct task_struct *tsk)
8250 struct io_uring_task *tctx = tsk->io_uring;
8252 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8253 WARN_ON_ONCE(tctx->io_wq);
8254 WARN_ON_ONCE(tctx->cached_refs);
8256 percpu_counter_destroy(&tctx->inflight);
8258 tsk->io_uring = NULL;
8261 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8262 struct io_uring_params *p)
8266 /* Retain compatibility with failing for an invalid attach attempt */
8267 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8268 IORING_SETUP_ATTACH_WQ) {
8271 f = fdget(p->wq_fd);
8274 if (f.file->f_op != &io_uring_fops) {
8280 if (ctx->flags & IORING_SETUP_SQPOLL) {
8281 struct task_struct *tsk;
8282 struct io_sq_data *sqd;
8285 sqd = io_get_sq_data(p, &attached);
8291 ctx->sq_creds = get_current_cred();
8293 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8294 if (!ctx->sq_thread_idle)
8295 ctx->sq_thread_idle = HZ;
8297 io_sq_thread_park(sqd);
8298 list_add(&ctx->sqd_list, &sqd->ctx_list);
8299 io_sqd_update_thread_idle(sqd);
8300 /* don't attach to a dying SQPOLL thread, would be racy */
8301 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8302 io_sq_thread_unpark(sqd);
8309 if (p->flags & IORING_SETUP_SQ_AFF) {
8310 int cpu = p->sq_thread_cpu;
8313 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8320 sqd->task_pid = current->pid;
8321 sqd->task_tgid = current->tgid;
8322 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8329 ret = io_uring_alloc_task_context(tsk, ctx);
8330 wake_up_new_task(tsk);
8333 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8334 /* Can't have SQ_AFF without SQPOLL */
8341 complete(&ctx->sq_data->exited);
8343 io_sq_thread_finish(ctx);
8347 static inline void __io_unaccount_mem(struct user_struct *user,
8348 unsigned long nr_pages)
8350 atomic_long_sub(nr_pages, &user->locked_vm);
8353 static inline int __io_account_mem(struct user_struct *user,
8354 unsigned long nr_pages)
8356 unsigned long page_limit, cur_pages, new_pages;
8358 /* Don't allow more pages than we can safely lock */
8359 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8362 cur_pages = atomic_long_read(&user->locked_vm);
8363 new_pages = cur_pages + nr_pages;
8364 if (new_pages > page_limit)
8366 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8367 new_pages) != cur_pages);
8372 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8375 __io_unaccount_mem(ctx->user, nr_pages);
8377 if (ctx->mm_account)
8378 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8381 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8386 ret = __io_account_mem(ctx->user, nr_pages);
8391 if (ctx->mm_account)
8392 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8397 static void io_mem_free(void *ptr)
8404 page = virt_to_head_page(ptr);
8405 if (put_page_testzero(page))
8406 free_compound_page(page);
8409 static void *io_mem_alloc(size_t size)
8411 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8412 __GFP_NORETRY | __GFP_ACCOUNT;
8414 return (void *) __get_free_pages(gfp_flags, get_order(size));
8417 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8420 struct io_rings *rings;
8421 size_t off, sq_array_size;
8423 off = struct_size(rings, cqes, cq_entries);
8424 if (off == SIZE_MAX)
8428 off = ALIGN(off, SMP_CACHE_BYTES);
8436 sq_array_size = array_size(sizeof(u32), sq_entries);
8437 if (sq_array_size == SIZE_MAX)
8440 if (check_add_overflow(off, sq_array_size, &off))
8446 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8448 struct io_mapped_ubuf *imu = *slot;
8451 if (imu != ctx->dummy_ubuf) {
8452 for (i = 0; i < imu->nr_bvecs; i++)
8453 unpin_user_page(imu->bvec[i].bv_page);
8454 if (imu->acct_pages)
8455 io_unaccount_mem(ctx, imu->acct_pages);
8461 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8463 io_buffer_unmap(ctx, &prsrc->buf);
8467 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8471 for (i = 0; i < ctx->nr_user_bufs; i++)
8472 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8473 kfree(ctx->user_bufs);
8474 io_rsrc_data_free(ctx->buf_data);
8475 ctx->user_bufs = NULL;
8476 ctx->buf_data = NULL;
8477 ctx->nr_user_bufs = 0;
8480 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8487 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8489 __io_sqe_buffers_unregister(ctx);
8493 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8494 void __user *arg, unsigned index)
8496 struct iovec __user *src;
8498 #ifdef CONFIG_COMPAT
8500 struct compat_iovec __user *ciovs;
8501 struct compat_iovec ciov;
8503 ciovs = (struct compat_iovec __user *) arg;
8504 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8507 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8508 dst->iov_len = ciov.iov_len;
8512 src = (struct iovec __user *) arg;
8513 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8519 * Not super efficient, but this is just a registration time. And we do cache
8520 * the last compound head, so generally we'll only do a full search if we don't
8523 * We check if the given compound head page has already been accounted, to
8524 * avoid double accounting it. This allows us to account the full size of the
8525 * page, not just the constituent pages of a huge page.
8527 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8528 int nr_pages, struct page *hpage)
8532 /* check current page array */
8533 for (i = 0; i < nr_pages; i++) {
8534 if (!PageCompound(pages[i]))
8536 if (compound_head(pages[i]) == hpage)
8540 /* check previously registered pages */
8541 for (i = 0; i < ctx->nr_user_bufs; i++) {
8542 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8544 for (j = 0; j < imu->nr_bvecs; j++) {
8545 if (!PageCompound(imu->bvec[j].bv_page))
8547 if (compound_head(imu->bvec[j].bv_page) == hpage)
8555 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8556 int nr_pages, struct io_mapped_ubuf *imu,
8557 struct page **last_hpage)
8561 imu->acct_pages = 0;
8562 for (i = 0; i < nr_pages; i++) {
8563 if (!PageCompound(pages[i])) {
8568 hpage = compound_head(pages[i]);
8569 if (hpage == *last_hpage)
8571 *last_hpage = hpage;
8572 if (headpage_already_acct(ctx, pages, i, hpage))
8574 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8578 if (!imu->acct_pages)
8581 ret = io_account_mem(ctx, imu->acct_pages);
8583 imu->acct_pages = 0;
8587 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8588 struct io_mapped_ubuf **pimu,
8589 struct page **last_hpage)
8591 struct io_mapped_ubuf *imu = NULL;
8592 struct vm_area_struct **vmas = NULL;
8593 struct page **pages = NULL;
8594 unsigned long off, start, end, ubuf;
8596 int ret, pret, nr_pages, i;
8598 if (!iov->iov_base) {
8599 *pimu = ctx->dummy_ubuf;
8603 ubuf = (unsigned long) iov->iov_base;
8604 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8605 start = ubuf >> PAGE_SHIFT;
8606 nr_pages = end - start;
8611 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8615 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8620 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8625 mmap_read_lock(current->mm);
8626 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8628 if (pret == nr_pages) {
8629 /* don't support file backed memory */
8630 for (i = 0; i < nr_pages; i++) {
8631 struct vm_area_struct *vma = vmas[i];
8633 if (vma_is_shmem(vma))
8636 !is_file_hugepages(vma->vm_file)) {
8642 ret = pret < 0 ? pret : -EFAULT;
8644 mmap_read_unlock(current->mm);
8647 * if we did partial map, or found file backed vmas,
8648 * release any pages we did get
8651 unpin_user_pages(pages, pret);
8655 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8657 unpin_user_pages(pages, pret);
8661 off = ubuf & ~PAGE_MASK;
8662 size = iov->iov_len;
8663 for (i = 0; i < nr_pages; i++) {
8666 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8667 imu->bvec[i].bv_page = pages[i];
8668 imu->bvec[i].bv_len = vec_len;
8669 imu->bvec[i].bv_offset = off;
8673 /* store original address for later verification */
8675 imu->ubuf_end = ubuf + iov->iov_len;
8676 imu->nr_bvecs = nr_pages;
8687 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8689 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8690 return ctx->user_bufs ? 0 : -ENOMEM;
8693 static int io_buffer_validate(struct iovec *iov)
8695 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8698 * Don't impose further limits on the size and buffer
8699 * constraints here, we'll -EINVAL later when IO is
8700 * submitted if they are wrong.
8703 return iov->iov_len ? -EFAULT : 0;
8707 /* arbitrary limit, but we need something */
8708 if (iov->iov_len > SZ_1G)
8711 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8717 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8718 unsigned int nr_args, u64 __user *tags)
8720 struct page *last_hpage = NULL;
8721 struct io_rsrc_data *data;
8727 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8729 ret = io_rsrc_node_switch_start(ctx);
8732 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8735 ret = io_buffers_map_alloc(ctx, nr_args);
8737 io_rsrc_data_free(data);
8741 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8742 ret = io_copy_iov(ctx, &iov, arg, i);
8745 ret = io_buffer_validate(&iov);
8748 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8753 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8759 WARN_ON_ONCE(ctx->buf_data);
8761 ctx->buf_data = data;
8763 __io_sqe_buffers_unregister(ctx);
8765 io_rsrc_node_switch(ctx, NULL);
8769 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8770 struct io_uring_rsrc_update2 *up,
8771 unsigned int nr_args)
8773 u64 __user *tags = u64_to_user_ptr(up->tags);
8774 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8775 struct page *last_hpage = NULL;
8776 bool needs_switch = false;
8782 if (up->offset + nr_args > ctx->nr_user_bufs)
8785 for (done = 0; done < nr_args; done++) {
8786 struct io_mapped_ubuf *imu;
8787 int offset = up->offset + done;
8790 err = io_copy_iov(ctx, &iov, iovs, done);
8793 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8797 err = io_buffer_validate(&iov);
8800 if (!iov.iov_base && tag) {
8804 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8808 i = array_index_nospec(offset, ctx->nr_user_bufs);
8809 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8810 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8811 ctx->rsrc_node, ctx->user_bufs[i]);
8812 if (unlikely(err)) {
8813 io_buffer_unmap(ctx, &imu);
8816 ctx->user_bufs[i] = NULL;
8817 needs_switch = true;
8820 ctx->user_bufs[i] = imu;
8821 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8825 io_rsrc_node_switch(ctx, ctx->buf_data);
8826 return done ? done : err;
8829 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8831 __s32 __user *fds = arg;
8837 if (copy_from_user(&fd, fds, sizeof(*fds)))
8840 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8841 if (IS_ERR(ctx->cq_ev_fd)) {
8842 int ret = PTR_ERR(ctx->cq_ev_fd);
8844 ctx->cq_ev_fd = NULL;
8851 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8853 if (ctx->cq_ev_fd) {
8854 eventfd_ctx_put(ctx->cq_ev_fd);
8855 ctx->cq_ev_fd = NULL;
8862 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8864 struct io_buffer *buf;
8865 unsigned long index;
8867 xa_for_each(&ctx->io_buffers, index, buf)
8868 __io_remove_buffers(ctx, buf, index, -1U);
8871 static void io_req_cache_free(struct list_head *list)
8873 struct io_kiocb *req, *nxt;
8875 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8876 list_del(&req->inflight_entry);
8877 kmem_cache_free(req_cachep, req);
8881 static void io_req_caches_free(struct io_ring_ctx *ctx)
8883 struct io_submit_state *state = &ctx->submit_state;
8885 mutex_lock(&ctx->uring_lock);
8887 if (state->free_reqs) {
8888 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8889 state->free_reqs = 0;
8892 io_flush_cached_locked_reqs(ctx, state);
8893 io_req_cache_free(&state->free_list);
8894 mutex_unlock(&ctx->uring_lock);
8897 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8899 if (data && !atomic_dec_and_test(&data->refs))
8900 wait_for_completion(&data->done);
8903 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8905 io_sq_thread_finish(ctx);
8907 if (ctx->mm_account) {
8908 mmdrop(ctx->mm_account);
8909 ctx->mm_account = NULL;
8912 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8913 io_wait_rsrc_data(ctx->buf_data);
8914 io_wait_rsrc_data(ctx->file_data);
8916 mutex_lock(&ctx->uring_lock);
8918 __io_sqe_buffers_unregister(ctx);
8920 __io_sqe_files_unregister(ctx);
8922 __io_cqring_overflow_flush(ctx, true);
8923 mutex_unlock(&ctx->uring_lock);
8924 io_eventfd_unregister(ctx);
8925 io_destroy_buffers(ctx);
8927 put_cred(ctx->sq_creds);
8929 /* there are no registered resources left, nobody uses it */
8931 io_rsrc_node_destroy(ctx->rsrc_node);
8932 if (ctx->rsrc_backup_node)
8933 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8934 flush_delayed_work(&ctx->rsrc_put_work);
8936 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8937 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8939 #if defined(CONFIG_UNIX)
8940 if (ctx->ring_sock) {
8941 ctx->ring_sock->file = NULL; /* so that iput() is called */
8942 sock_release(ctx->ring_sock);
8945 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8947 io_mem_free(ctx->rings);
8948 io_mem_free(ctx->sq_sqes);
8950 percpu_ref_exit(&ctx->refs);
8951 free_uid(ctx->user);
8952 io_req_caches_free(ctx);
8954 io_wq_put_hash(ctx->hash_map);
8955 kfree(ctx->cancel_hash);
8956 kfree(ctx->dummy_ubuf);
8960 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8962 struct io_ring_ctx *ctx = file->private_data;
8965 poll_wait(file, &ctx->poll_wait, wait);
8967 * synchronizes with barrier from wq_has_sleeper call in
8971 if (!io_sqring_full(ctx))
8972 mask |= EPOLLOUT | EPOLLWRNORM;
8975 * Don't flush cqring overflow list here, just do a simple check.
8976 * Otherwise there could possible be ABBA deadlock:
8979 * lock(&ctx->uring_lock);
8981 * lock(&ctx->uring_lock);
8984 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8985 * pushs them to do the flush.
8987 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8988 mask |= EPOLLIN | EPOLLRDNORM;
8993 static int io_uring_fasync(int fd, struct file *file, int on)
8995 struct io_ring_ctx *ctx = file->private_data;
8997 return fasync_helper(fd, file, on, &ctx->cq_fasync);
9000 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9002 const struct cred *creds;
9004 creds = xa_erase(&ctx->personalities, id);
9013 struct io_tctx_exit {
9014 struct callback_head task_work;
9015 struct completion completion;
9016 struct io_ring_ctx *ctx;
9019 static void io_tctx_exit_cb(struct callback_head *cb)
9021 struct io_uring_task *tctx = current->io_uring;
9022 struct io_tctx_exit *work;
9024 work = container_of(cb, struct io_tctx_exit, task_work);
9026 * When @in_idle, we're in cancellation and it's racy to remove the
9027 * node. It'll be removed by the end of cancellation, just ignore it.
9029 if (!atomic_read(&tctx->in_idle))
9030 io_uring_del_tctx_node((unsigned long)work->ctx);
9031 complete(&work->completion);
9034 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9036 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9038 return req->ctx == data;
9041 static void io_ring_exit_work(struct work_struct *work)
9043 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9044 unsigned long timeout = jiffies + HZ * 60 * 5;
9045 unsigned long interval = HZ / 20;
9046 struct io_tctx_exit exit;
9047 struct io_tctx_node *node;
9051 * If we're doing polled IO and end up having requests being
9052 * submitted async (out-of-line), then completions can come in while
9053 * we're waiting for refs to drop. We need to reap these manually,
9054 * as nobody else will be looking for them.
9057 io_uring_try_cancel_requests(ctx, NULL, true);
9059 struct io_sq_data *sqd = ctx->sq_data;
9060 struct task_struct *tsk;
9062 io_sq_thread_park(sqd);
9064 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9065 io_wq_cancel_cb(tsk->io_uring->io_wq,
9066 io_cancel_ctx_cb, ctx, true);
9067 io_sq_thread_unpark(sqd);
9070 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9071 /* there is little hope left, don't run it too often */
9074 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9076 init_completion(&exit.completion);
9077 init_task_work(&exit.task_work, io_tctx_exit_cb);
9080 * Some may use context even when all refs and requests have been put,
9081 * and they are free to do so while still holding uring_lock or
9082 * completion_lock, see io_req_task_submit(). Apart from other work,
9083 * this lock/unlock section also waits them to finish.
9085 mutex_lock(&ctx->uring_lock);
9086 while (!list_empty(&ctx->tctx_list)) {
9087 WARN_ON_ONCE(time_after(jiffies, timeout));
9089 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9091 /* don't spin on a single task if cancellation failed */
9092 list_rotate_left(&ctx->tctx_list);
9093 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9094 if (WARN_ON_ONCE(ret))
9096 wake_up_process(node->task);
9098 mutex_unlock(&ctx->uring_lock);
9099 wait_for_completion(&exit.completion);
9100 mutex_lock(&ctx->uring_lock);
9102 mutex_unlock(&ctx->uring_lock);
9103 spin_lock(&ctx->completion_lock);
9104 spin_unlock(&ctx->completion_lock);
9106 io_ring_ctx_free(ctx);
9109 /* Returns true if we found and killed one or more timeouts */
9110 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9113 struct io_kiocb *req, *tmp;
9116 spin_lock(&ctx->completion_lock);
9117 spin_lock_irq(&ctx->timeout_lock);
9118 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9119 if (io_match_task(req, tsk, cancel_all)) {
9120 io_kill_timeout(req, -ECANCELED);
9124 spin_unlock_irq(&ctx->timeout_lock);
9126 io_commit_cqring(ctx);
9127 spin_unlock(&ctx->completion_lock);
9129 io_cqring_ev_posted(ctx);
9130 return canceled != 0;
9133 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9135 unsigned long index;
9136 struct creds *creds;
9138 mutex_lock(&ctx->uring_lock);
9139 percpu_ref_kill(&ctx->refs);
9141 __io_cqring_overflow_flush(ctx, true);
9142 xa_for_each(&ctx->personalities, index, creds)
9143 io_unregister_personality(ctx, index);
9144 mutex_unlock(&ctx->uring_lock);
9146 io_kill_timeouts(ctx, NULL, true);
9147 io_poll_remove_all(ctx, NULL, true);
9149 /* if we failed setting up the ctx, we might not have any rings */
9150 io_iopoll_try_reap_events(ctx);
9152 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9154 * Use system_unbound_wq to avoid spawning tons of event kworkers
9155 * if we're exiting a ton of rings at the same time. It just adds
9156 * noise and overhead, there's no discernable change in runtime
9157 * over using system_wq.
9159 queue_work(system_unbound_wq, &ctx->exit_work);
9162 static int io_uring_release(struct inode *inode, struct file *file)
9164 struct io_ring_ctx *ctx = file->private_data;
9166 file->private_data = NULL;
9167 io_ring_ctx_wait_and_kill(ctx);
9171 struct io_task_cancel {
9172 struct task_struct *task;
9176 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9178 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9179 struct io_task_cancel *cancel = data;
9182 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9183 struct io_ring_ctx *ctx = req->ctx;
9185 /* protect against races with linked timeouts */
9186 spin_lock(&ctx->completion_lock);
9187 ret = io_match_task(req, cancel->task, cancel->all);
9188 spin_unlock(&ctx->completion_lock);
9190 ret = io_match_task(req, cancel->task, cancel->all);
9195 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9196 struct task_struct *task, bool cancel_all)
9198 struct io_defer_entry *de;
9201 spin_lock(&ctx->completion_lock);
9202 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9203 if (io_match_task(de->req, task, cancel_all)) {
9204 list_cut_position(&list, &ctx->defer_list, &de->list);
9208 spin_unlock(&ctx->completion_lock);
9209 if (list_empty(&list))
9212 while (!list_empty(&list)) {
9213 de = list_first_entry(&list, struct io_defer_entry, list);
9214 list_del_init(&de->list);
9215 io_req_complete_failed(de->req, -ECANCELED);
9221 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9223 struct io_tctx_node *node;
9224 enum io_wq_cancel cret;
9227 mutex_lock(&ctx->uring_lock);
9228 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9229 struct io_uring_task *tctx = node->task->io_uring;
9232 * io_wq will stay alive while we hold uring_lock, because it's
9233 * killed after ctx nodes, which requires to take the lock.
9235 if (!tctx || !tctx->io_wq)
9237 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9238 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9240 mutex_unlock(&ctx->uring_lock);
9245 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9246 struct task_struct *task,
9249 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9250 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9253 enum io_wq_cancel cret;
9257 ret |= io_uring_try_cancel_iowq(ctx);
9258 } else if (tctx && tctx->io_wq) {
9260 * Cancels requests of all rings, not only @ctx, but
9261 * it's fine as the task is in exit/exec.
9263 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9265 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9268 /* SQPOLL thread does its own polling */
9269 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9270 (ctx->sq_data && ctx->sq_data->thread == current)) {
9271 while (!list_empty_careful(&ctx->iopoll_list)) {
9272 io_iopoll_try_reap_events(ctx);
9277 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9278 ret |= io_poll_remove_all(ctx, task, cancel_all);
9279 ret |= io_kill_timeouts(ctx, task, cancel_all);
9281 ret |= io_run_task_work();
9288 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9290 struct io_uring_task *tctx = current->io_uring;
9291 struct io_tctx_node *node;
9294 if (unlikely(!tctx)) {
9295 ret = io_uring_alloc_task_context(current, ctx);
9298 tctx = current->io_uring;
9300 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9301 node = kmalloc(sizeof(*node), GFP_KERNEL);
9305 node->task = current;
9307 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9314 mutex_lock(&ctx->uring_lock);
9315 list_add(&node->ctx_node, &ctx->tctx_list);
9316 mutex_unlock(&ctx->uring_lock);
9323 * Note that this task has used io_uring. We use it for cancelation purposes.
9325 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9327 struct io_uring_task *tctx = current->io_uring;
9329 if (likely(tctx && tctx->last == ctx))
9331 return __io_uring_add_tctx_node(ctx);
9335 * Remove this io_uring_file -> task mapping.
9337 static void io_uring_del_tctx_node(unsigned long index)
9339 struct io_uring_task *tctx = current->io_uring;
9340 struct io_tctx_node *node;
9344 node = xa_erase(&tctx->xa, index);
9348 WARN_ON_ONCE(current != node->task);
9349 WARN_ON_ONCE(list_empty(&node->ctx_node));
9351 mutex_lock(&node->ctx->uring_lock);
9352 list_del(&node->ctx_node);
9353 mutex_unlock(&node->ctx->uring_lock);
9355 if (tctx->last == node->ctx)
9360 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9362 struct io_wq *wq = tctx->io_wq;
9363 struct io_tctx_node *node;
9364 unsigned long index;
9366 xa_for_each(&tctx->xa, index, node)
9367 io_uring_del_tctx_node(index);
9370 * Must be after io_uring_del_task_file() (removes nodes under
9371 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9373 io_wq_put_and_exit(wq);
9378 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9381 return atomic_read(&tctx->inflight_tracked);
9382 return percpu_counter_sum(&tctx->inflight);
9385 static void io_uring_drop_tctx_refs(struct task_struct *task)
9387 struct io_uring_task *tctx = task->io_uring;
9388 unsigned int refs = tctx->cached_refs;
9391 tctx->cached_refs = 0;
9392 percpu_counter_sub(&tctx->inflight, refs);
9393 put_task_struct_many(task, refs);
9398 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9399 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9401 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9403 struct io_uring_task *tctx = current->io_uring;
9404 struct io_ring_ctx *ctx;
9408 WARN_ON_ONCE(sqd && sqd->thread != current);
9410 if (!current->io_uring)
9413 io_wq_exit_start(tctx->io_wq);
9415 atomic_inc(&tctx->in_idle);
9417 io_uring_drop_tctx_refs(current);
9418 /* read completions before cancelations */
9419 inflight = tctx_inflight(tctx, !cancel_all);
9424 struct io_tctx_node *node;
9425 unsigned long index;
9427 xa_for_each(&tctx->xa, index, node) {
9428 /* sqpoll task will cancel all its requests */
9429 if (node->ctx->sq_data)
9431 io_uring_try_cancel_requests(node->ctx, current,
9435 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9436 io_uring_try_cancel_requests(ctx, current,
9440 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9441 io_uring_drop_tctx_refs(current);
9443 * If we've seen completions, retry without waiting. This
9444 * avoids a race where a completion comes in before we did
9445 * prepare_to_wait().
9447 if (inflight == tctx_inflight(tctx, !cancel_all))
9449 finish_wait(&tctx->wait, &wait);
9451 atomic_dec(&tctx->in_idle);
9453 io_uring_clean_tctx(tctx);
9455 /* for exec all current's requests should be gone, kill tctx */
9456 __io_uring_free(current);
9460 void __io_uring_cancel(bool cancel_all)
9462 io_uring_cancel_generic(cancel_all, NULL);
9465 static void *io_uring_validate_mmap_request(struct file *file,
9466 loff_t pgoff, size_t sz)
9468 struct io_ring_ctx *ctx = file->private_data;
9469 loff_t offset = pgoff << PAGE_SHIFT;
9474 case IORING_OFF_SQ_RING:
9475 case IORING_OFF_CQ_RING:
9478 case IORING_OFF_SQES:
9482 return ERR_PTR(-EINVAL);
9485 page = virt_to_head_page(ptr);
9486 if (sz > page_size(page))
9487 return ERR_PTR(-EINVAL);
9494 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9496 size_t sz = vma->vm_end - vma->vm_start;
9500 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9502 return PTR_ERR(ptr);
9504 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9505 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9508 #else /* !CONFIG_MMU */
9510 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9512 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9515 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9517 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9520 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9521 unsigned long addr, unsigned long len,
9522 unsigned long pgoff, unsigned long flags)
9526 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9528 return PTR_ERR(ptr);
9530 return (unsigned long) ptr;
9533 #endif /* !CONFIG_MMU */
9535 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9540 if (!io_sqring_full(ctx))
9542 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9544 if (!io_sqring_full(ctx))
9547 } while (!signal_pending(current));
9549 finish_wait(&ctx->sqo_sq_wait, &wait);
9553 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9554 struct __kernel_timespec __user **ts,
9555 const sigset_t __user **sig)
9557 struct io_uring_getevents_arg arg;
9560 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9561 * is just a pointer to the sigset_t.
9563 if (!(flags & IORING_ENTER_EXT_ARG)) {
9564 *sig = (const sigset_t __user *) argp;
9570 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9571 * timespec and sigset_t pointers if good.
9573 if (*argsz != sizeof(arg))
9575 if (copy_from_user(&arg, argp, sizeof(arg)))
9577 *sig = u64_to_user_ptr(arg.sigmask);
9578 *argsz = arg.sigmask_sz;
9579 *ts = u64_to_user_ptr(arg.ts);
9583 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9584 u32, min_complete, u32, flags, const void __user *, argp,
9587 struct io_ring_ctx *ctx;
9594 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9595 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9599 if (unlikely(!f.file))
9603 if (unlikely(f.file->f_op != &io_uring_fops))
9607 ctx = f.file->private_data;
9608 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9612 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9616 * For SQ polling, the thread will do all submissions and completions.
9617 * Just return the requested submit count, and wake the thread if
9621 if (ctx->flags & IORING_SETUP_SQPOLL) {
9622 io_cqring_overflow_flush(ctx);
9624 if (unlikely(ctx->sq_data->thread == NULL)) {
9628 if (flags & IORING_ENTER_SQ_WAKEUP)
9629 wake_up(&ctx->sq_data->wait);
9630 if (flags & IORING_ENTER_SQ_WAIT) {
9631 ret = io_sqpoll_wait_sq(ctx);
9635 submitted = to_submit;
9636 } else if (to_submit) {
9637 ret = io_uring_add_tctx_node(ctx);
9640 mutex_lock(&ctx->uring_lock);
9641 submitted = io_submit_sqes(ctx, to_submit);
9642 mutex_unlock(&ctx->uring_lock);
9644 if (submitted != to_submit)
9647 if (flags & IORING_ENTER_GETEVENTS) {
9648 const sigset_t __user *sig;
9649 struct __kernel_timespec __user *ts;
9651 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9655 min_complete = min(min_complete, ctx->cq_entries);
9658 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9659 * space applications don't need to do io completion events
9660 * polling again, they can rely on io_sq_thread to do polling
9661 * work, which can reduce cpu usage and uring_lock contention.
9663 if (ctx->flags & IORING_SETUP_IOPOLL &&
9664 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9665 ret = io_iopoll_check(ctx, min_complete);
9667 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9672 percpu_ref_put(&ctx->refs);
9675 return submitted ? submitted : ret;
9678 #ifdef CONFIG_PROC_FS
9679 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9680 const struct cred *cred)
9682 struct user_namespace *uns = seq_user_ns(m);
9683 struct group_info *gi;
9688 seq_printf(m, "%5d\n", id);
9689 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9690 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9691 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9692 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9693 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9694 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9695 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9696 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9697 seq_puts(m, "\n\tGroups:\t");
9698 gi = cred->group_info;
9699 for (g = 0; g < gi->ngroups; g++) {
9700 seq_put_decimal_ull(m, g ? " " : "",
9701 from_kgid_munged(uns, gi->gid[g]));
9703 seq_puts(m, "\n\tCapEff:\t");
9704 cap = cred->cap_effective;
9705 CAP_FOR_EACH_U32(__capi)
9706 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9711 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9713 struct io_sq_data *sq = NULL;
9718 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9719 * since fdinfo case grabs it in the opposite direction of normal use
9720 * cases. If we fail to get the lock, we just don't iterate any
9721 * structures that could be going away outside the io_uring mutex.
9723 has_lock = mutex_trylock(&ctx->uring_lock);
9725 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9731 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9732 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9733 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9734 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9735 struct file *f = io_file_from_index(ctx, i);
9738 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9740 seq_printf(m, "%5u: <none>\n", i);
9742 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9743 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9744 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9745 unsigned int len = buf->ubuf_end - buf->ubuf;
9747 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9749 if (has_lock && !xa_empty(&ctx->personalities)) {
9750 unsigned long index;
9751 const struct cred *cred;
9753 seq_printf(m, "Personalities:\n");
9754 xa_for_each(&ctx->personalities, index, cred)
9755 io_uring_show_cred(m, index, cred);
9757 seq_printf(m, "PollList:\n");
9758 spin_lock(&ctx->completion_lock);
9759 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9760 struct hlist_head *list = &ctx->cancel_hash[i];
9761 struct io_kiocb *req;
9763 hlist_for_each_entry(req, list, hash_node)
9764 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9765 req->task->task_works != NULL);
9767 spin_unlock(&ctx->completion_lock);
9769 mutex_unlock(&ctx->uring_lock);
9772 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9774 struct io_ring_ctx *ctx = f->private_data;
9776 if (percpu_ref_tryget(&ctx->refs)) {
9777 __io_uring_show_fdinfo(ctx, m);
9778 percpu_ref_put(&ctx->refs);
9783 static const struct file_operations io_uring_fops = {
9784 .release = io_uring_release,
9785 .mmap = io_uring_mmap,
9787 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9788 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9790 .poll = io_uring_poll,
9791 .fasync = io_uring_fasync,
9792 #ifdef CONFIG_PROC_FS
9793 .show_fdinfo = io_uring_show_fdinfo,
9797 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9798 struct io_uring_params *p)
9800 struct io_rings *rings;
9801 size_t size, sq_array_offset;
9803 /* make sure these are sane, as we already accounted them */
9804 ctx->sq_entries = p->sq_entries;
9805 ctx->cq_entries = p->cq_entries;
9807 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9808 if (size == SIZE_MAX)
9811 rings = io_mem_alloc(size);
9816 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9817 rings->sq_ring_mask = p->sq_entries - 1;
9818 rings->cq_ring_mask = p->cq_entries - 1;
9819 rings->sq_ring_entries = p->sq_entries;
9820 rings->cq_ring_entries = p->cq_entries;
9822 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9823 if (size == SIZE_MAX) {
9824 io_mem_free(ctx->rings);
9829 ctx->sq_sqes = io_mem_alloc(size);
9830 if (!ctx->sq_sqes) {
9831 io_mem_free(ctx->rings);
9839 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9843 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9847 ret = io_uring_add_tctx_node(ctx);
9852 fd_install(fd, file);
9857 * Allocate an anonymous fd, this is what constitutes the application
9858 * visible backing of an io_uring instance. The application mmaps this
9859 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9860 * we have to tie this fd to a socket for file garbage collection purposes.
9862 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9865 #if defined(CONFIG_UNIX)
9868 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9871 return ERR_PTR(ret);
9874 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9875 O_RDWR | O_CLOEXEC);
9876 #if defined(CONFIG_UNIX)
9878 sock_release(ctx->ring_sock);
9879 ctx->ring_sock = NULL;
9881 ctx->ring_sock->file = file;
9887 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9888 struct io_uring_params __user *params)
9890 struct io_ring_ctx *ctx;
9896 if (entries > IORING_MAX_ENTRIES) {
9897 if (!(p->flags & IORING_SETUP_CLAMP))
9899 entries = IORING_MAX_ENTRIES;
9903 * Use twice as many entries for the CQ ring. It's possible for the
9904 * application to drive a higher depth than the size of the SQ ring,
9905 * since the sqes are only used at submission time. This allows for
9906 * some flexibility in overcommitting a bit. If the application has
9907 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9908 * of CQ ring entries manually.
9910 p->sq_entries = roundup_pow_of_two(entries);
9911 if (p->flags & IORING_SETUP_CQSIZE) {
9913 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9914 * to a power-of-two, if it isn't already. We do NOT impose
9915 * any cq vs sq ring sizing.
9919 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9920 if (!(p->flags & IORING_SETUP_CLAMP))
9922 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9924 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9925 if (p->cq_entries < p->sq_entries)
9928 p->cq_entries = 2 * p->sq_entries;
9931 ctx = io_ring_ctx_alloc(p);
9934 ctx->compat = in_compat_syscall();
9935 if (!capable(CAP_IPC_LOCK))
9936 ctx->user = get_uid(current_user());
9939 * This is just grabbed for accounting purposes. When a process exits,
9940 * the mm is exited and dropped before the files, hence we need to hang
9941 * on to this mm purely for the purposes of being able to unaccount
9942 * memory (locked/pinned vm). It's not used for anything else.
9944 mmgrab(current->mm);
9945 ctx->mm_account = current->mm;
9947 ret = io_allocate_scq_urings(ctx, p);
9951 ret = io_sq_offload_create(ctx, p);
9954 /* always set a rsrc node */
9955 ret = io_rsrc_node_switch_start(ctx);
9958 io_rsrc_node_switch(ctx, NULL);
9960 memset(&p->sq_off, 0, sizeof(p->sq_off));
9961 p->sq_off.head = offsetof(struct io_rings, sq.head);
9962 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9963 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9964 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9965 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9966 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9967 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9969 memset(&p->cq_off, 0, sizeof(p->cq_off));
9970 p->cq_off.head = offsetof(struct io_rings, cq.head);
9971 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9972 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9973 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9974 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9975 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9976 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9978 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9979 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9980 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9981 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9982 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9983 IORING_FEAT_RSRC_TAGS;
9985 if (copy_to_user(params, p, sizeof(*p))) {
9990 file = io_uring_get_file(ctx);
9992 ret = PTR_ERR(file);
9997 * Install ring fd as the very last thing, so we don't risk someone
9998 * having closed it before we finish setup
10000 ret = io_uring_install_fd(ctx, file);
10002 /* fput will clean it up */
10007 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10010 io_ring_ctx_wait_and_kill(ctx);
10015 * Sets up an aio uring context, and returns the fd. Applications asks for a
10016 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10017 * params structure passed in.
10019 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10021 struct io_uring_params p;
10024 if (copy_from_user(&p, params, sizeof(p)))
10026 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10031 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10032 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10033 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10034 IORING_SETUP_R_DISABLED))
10037 return io_uring_create(entries, &p, params);
10040 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10041 struct io_uring_params __user *, params)
10043 return io_uring_setup(entries, params);
10046 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10048 struct io_uring_probe *p;
10052 size = struct_size(p, ops, nr_args);
10053 if (size == SIZE_MAX)
10055 p = kzalloc(size, GFP_KERNEL);
10060 if (copy_from_user(p, arg, size))
10063 if (memchr_inv(p, 0, size))
10066 p->last_op = IORING_OP_LAST - 1;
10067 if (nr_args > IORING_OP_LAST)
10068 nr_args = IORING_OP_LAST;
10070 for (i = 0; i < nr_args; i++) {
10072 if (!io_op_defs[i].not_supported)
10073 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10078 if (copy_to_user(arg, p, size))
10085 static int io_register_personality(struct io_ring_ctx *ctx)
10087 const struct cred *creds;
10091 creds = get_current_cred();
10093 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10094 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10102 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10103 unsigned int nr_args)
10105 struct io_uring_restriction *res;
10109 /* Restrictions allowed only if rings started disabled */
10110 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10113 /* We allow only a single restrictions registration */
10114 if (ctx->restrictions.registered)
10117 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10120 size = array_size(nr_args, sizeof(*res));
10121 if (size == SIZE_MAX)
10124 res = memdup_user(arg, size);
10126 return PTR_ERR(res);
10130 for (i = 0; i < nr_args; i++) {
10131 switch (res[i].opcode) {
10132 case IORING_RESTRICTION_REGISTER_OP:
10133 if (res[i].register_op >= IORING_REGISTER_LAST) {
10138 __set_bit(res[i].register_op,
10139 ctx->restrictions.register_op);
10141 case IORING_RESTRICTION_SQE_OP:
10142 if (res[i].sqe_op >= IORING_OP_LAST) {
10147 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10149 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10150 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10152 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10153 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10162 /* Reset all restrictions if an error happened */
10164 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10166 ctx->restrictions.registered = true;
10172 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10174 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10177 if (ctx->restrictions.registered)
10178 ctx->restricted = 1;
10180 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10181 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10182 wake_up(&ctx->sq_data->wait);
10186 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10187 struct io_uring_rsrc_update2 *up,
10195 if (check_add_overflow(up->offset, nr_args, &tmp))
10197 err = io_rsrc_node_switch_start(ctx);
10202 case IORING_RSRC_FILE:
10203 return __io_sqe_files_update(ctx, up, nr_args);
10204 case IORING_RSRC_BUFFER:
10205 return __io_sqe_buffers_update(ctx, up, nr_args);
10210 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10213 struct io_uring_rsrc_update2 up;
10217 memset(&up, 0, sizeof(up));
10218 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10220 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10223 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10224 unsigned size, unsigned type)
10226 struct io_uring_rsrc_update2 up;
10228 if (size != sizeof(up))
10230 if (copy_from_user(&up, arg, sizeof(up)))
10232 if (!up.nr || up.resv)
10234 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10237 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10238 unsigned int size, unsigned int type)
10240 struct io_uring_rsrc_register rr;
10242 /* keep it extendible */
10243 if (size != sizeof(rr))
10246 memset(&rr, 0, sizeof(rr));
10247 if (copy_from_user(&rr, arg, size))
10249 if (!rr.nr || rr.resv || rr.resv2)
10253 case IORING_RSRC_FILE:
10254 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10255 rr.nr, u64_to_user_ptr(rr.tags));
10256 case IORING_RSRC_BUFFER:
10257 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10258 rr.nr, u64_to_user_ptr(rr.tags));
10263 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10266 struct io_uring_task *tctx = current->io_uring;
10267 cpumask_var_t new_mask;
10270 if (!tctx || !tctx->io_wq)
10273 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10276 cpumask_clear(new_mask);
10277 if (len > cpumask_size())
10278 len = cpumask_size();
10280 if (copy_from_user(new_mask, arg, len)) {
10281 free_cpumask_var(new_mask);
10285 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10286 free_cpumask_var(new_mask);
10290 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10292 struct io_uring_task *tctx = current->io_uring;
10294 if (!tctx || !tctx->io_wq)
10297 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10300 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10303 struct io_uring_task *tctx = current->io_uring;
10304 __u32 new_count[2];
10307 if (!tctx || !tctx->io_wq)
10309 if (copy_from_user(new_count, arg, sizeof(new_count)))
10311 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10312 if (new_count[i] > INT_MAX)
10315 ret = io_wq_max_workers(tctx->io_wq, new_count);
10319 if (copy_to_user(arg, new_count, sizeof(new_count)))
10325 static bool io_register_op_must_quiesce(int op)
10328 case IORING_REGISTER_BUFFERS:
10329 case IORING_UNREGISTER_BUFFERS:
10330 case IORING_REGISTER_FILES:
10331 case IORING_UNREGISTER_FILES:
10332 case IORING_REGISTER_FILES_UPDATE:
10333 case IORING_REGISTER_PROBE:
10334 case IORING_REGISTER_PERSONALITY:
10335 case IORING_UNREGISTER_PERSONALITY:
10336 case IORING_REGISTER_FILES2:
10337 case IORING_REGISTER_FILES_UPDATE2:
10338 case IORING_REGISTER_BUFFERS2:
10339 case IORING_REGISTER_BUFFERS_UPDATE:
10340 case IORING_REGISTER_IOWQ_AFF:
10341 case IORING_UNREGISTER_IOWQ_AFF:
10342 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10349 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10353 percpu_ref_kill(&ctx->refs);
10356 * Drop uring mutex before waiting for references to exit. If another
10357 * thread is currently inside io_uring_enter() it might need to grab the
10358 * uring_lock to make progress. If we hold it here across the drain
10359 * wait, then we can deadlock. It's safe to drop the mutex here, since
10360 * no new references will come in after we've killed the percpu ref.
10362 mutex_unlock(&ctx->uring_lock);
10364 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10367 ret = io_run_task_work_sig();
10368 } while (ret >= 0);
10369 mutex_lock(&ctx->uring_lock);
10372 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10376 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10377 void __user *arg, unsigned nr_args)
10378 __releases(ctx->uring_lock)
10379 __acquires(ctx->uring_lock)
10384 * We're inside the ring mutex, if the ref is already dying, then
10385 * someone else killed the ctx or is already going through
10386 * io_uring_register().
10388 if (percpu_ref_is_dying(&ctx->refs))
10391 if (ctx->restricted) {
10392 if (opcode >= IORING_REGISTER_LAST)
10394 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10395 if (!test_bit(opcode, ctx->restrictions.register_op))
10399 if (io_register_op_must_quiesce(opcode)) {
10400 ret = io_ctx_quiesce(ctx);
10406 case IORING_REGISTER_BUFFERS:
10407 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10409 case IORING_UNREGISTER_BUFFERS:
10411 if (arg || nr_args)
10413 ret = io_sqe_buffers_unregister(ctx);
10415 case IORING_REGISTER_FILES:
10416 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10418 case IORING_UNREGISTER_FILES:
10420 if (arg || nr_args)
10422 ret = io_sqe_files_unregister(ctx);
10424 case IORING_REGISTER_FILES_UPDATE:
10425 ret = io_register_files_update(ctx, arg, nr_args);
10427 case IORING_REGISTER_EVENTFD:
10428 case IORING_REGISTER_EVENTFD_ASYNC:
10432 ret = io_eventfd_register(ctx, arg);
10435 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10436 ctx->eventfd_async = 1;
10438 ctx->eventfd_async = 0;
10440 case IORING_UNREGISTER_EVENTFD:
10442 if (arg || nr_args)
10444 ret = io_eventfd_unregister(ctx);
10446 case IORING_REGISTER_PROBE:
10448 if (!arg || nr_args > 256)
10450 ret = io_probe(ctx, arg, nr_args);
10452 case IORING_REGISTER_PERSONALITY:
10454 if (arg || nr_args)
10456 ret = io_register_personality(ctx);
10458 case IORING_UNREGISTER_PERSONALITY:
10462 ret = io_unregister_personality(ctx, nr_args);
10464 case IORING_REGISTER_ENABLE_RINGS:
10466 if (arg || nr_args)
10468 ret = io_register_enable_rings(ctx);
10470 case IORING_REGISTER_RESTRICTIONS:
10471 ret = io_register_restrictions(ctx, arg, nr_args);
10473 case IORING_REGISTER_FILES2:
10474 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10476 case IORING_REGISTER_FILES_UPDATE2:
10477 ret = io_register_rsrc_update(ctx, arg, nr_args,
10480 case IORING_REGISTER_BUFFERS2:
10481 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10483 case IORING_REGISTER_BUFFERS_UPDATE:
10484 ret = io_register_rsrc_update(ctx, arg, nr_args,
10485 IORING_RSRC_BUFFER);
10487 case IORING_REGISTER_IOWQ_AFF:
10489 if (!arg || !nr_args)
10491 ret = io_register_iowq_aff(ctx, arg, nr_args);
10493 case IORING_UNREGISTER_IOWQ_AFF:
10495 if (arg || nr_args)
10497 ret = io_unregister_iowq_aff(ctx);
10499 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10501 if (!arg || nr_args != 2)
10503 ret = io_register_iowq_max_workers(ctx, arg);
10510 if (io_register_op_must_quiesce(opcode)) {
10511 /* bring the ctx back to life */
10512 percpu_ref_reinit(&ctx->refs);
10513 reinit_completion(&ctx->ref_comp);
10518 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10519 void __user *, arg, unsigned int, nr_args)
10521 struct io_ring_ctx *ctx;
10530 if (f.file->f_op != &io_uring_fops)
10533 ctx = f.file->private_data;
10535 io_run_task_work();
10537 mutex_lock(&ctx->uring_lock);
10538 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10539 mutex_unlock(&ctx->uring_lock);
10540 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10541 ctx->cq_ev_fd != NULL, ret);
10547 static int __init io_uring_init(void)
10549 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10550 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10551 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10554 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10555 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10556 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10557 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10558 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10559 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10560 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10561 BUILD_BUG_SQE_ELEM(8, __u64, off);
10562 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10563 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10564 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10565 BUILD_BUG_SQE_ELEM(24, __u32, len);
10566 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10567 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10568 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10569 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10570 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10571 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10572 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10573 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10574 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10575 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10576 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10577 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10578 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10579 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10580 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10581 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10582 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10583 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10584 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10585 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10586 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10588 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10589 sizeof(struct io_uring_rsrc_update));
10590 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10591 sizeof(struct io_uring_rsrc_update2));
10593 /* ->buf_index is u16 */
10594 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10596 /* should fit into one byte */
10597 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10599 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10600 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10602 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10606 __initcall(io_uring_init);