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>
88 #include "../fs/internal.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 unsigned cq_last_tm_flush;
407 } ____cacheline_aligned_in_smp;
410 spinlock_t completion_lock;
412 spinlock_t timeout_lock;
415 * ->iopoll_list is protected by the ctx->uring_lock for
416 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417 * For SQPOLL, only the single threaded io_sq_thread() will
418 * manipulate the list, hence no extra locking is needed there.
420 struct list_head iopoll_list;
421 struct hlist_head *cancel_hash;
422 unsigned cancel_hash_bits;
423 bool poll_multi_queue;
424 } ____cacheline_aligned_in_smp;
426 struct io_restriction restrictions;
428 /* slow path rsrc auxilary data, used by update/register */
430 struct io_rsrc_node *rsrc_backup_node;
431 struct io_mapped_ubuf *dummy_ubuf;
432 struct io_rsrc_data *file_data;
433 struct io_rsrc_data *buf_data;
435 struct delayed_work rsrc_put_work;
436 struct llist_head rsrc_put_llist;
437 struct list_head rsrc_ref_list;
438 spinlock_t rsrc_ref_lock;
441 /* Keep this last, we don't need it for the fast path */
443 #if defined(CONFIG_UNIX)
444 struct socket *ring_sock;
446 /* hashed buffered write serialization */
447 struct io_wq_hash *hash_map;
449 /* Only used for accounting purposes */
450 struct user_struct *user;
451 struct mm_struct *mm_account;
453 /* ctx exit and cancelation */
454 struct llist_head fallback_llist;
455 struct delayed_work fallback_work;
456 struct work_struct exit_work;
457 struct list_head tctx_list;
458 struct completion ref_comp;
460 bool iowq_limits_set;
464 struct io_uring_task {
465 /* submission side */
468 struct wait_queue_head wait;
469 const struct io_ring_ctx *last;
471 struct percpu_counter inflight;
472 atomic_t inflight_tracked;
475 spinlock_t task_lock;
476 struct io_wq_work_list task_list;
477 struct callback_head task_work;
482 * First field must be the file pointer in all the
483 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
485 struct io_poll_iocb {
487 struct wait_queue_head *head;
490 struct wait_queue_entry wait;
493 struct io_poll_update {
499 bool update_user_data;
508 struct io_timeout_data {
509 struct io_kiocb *req;
510 struct hrtimer timer;
511 struct timespec64 ts;
512 enum hrtimer_mode mode;
518 struct sockaddr __user *addr;
519 int __user *addr_len;
522 unsigned long nofile;
542 struct list_head list;
543 /* head of the link, used by linked timeouts only */
544 struct io_kiocb *head;
545 /* for linked completions */
546 struct io_kiocb *prev;
549 struct io_timeout_rem {
554 struct timespec64 ts;
560 /* NOTE: kiocb has the file as the first member, so don't do it here */
568 struct sockaddr __user *addr;
575 struct compat_msghdr __user *umsg_compat;
576 struct user_msghdr __user *umsg;
583 struct io_buffer *kbuf;
584 void __user *msg_control;
591 struct filename *filename;
593 unsigned long nofile;
596 struct io_rsrc_update {
622 struct epoll_event event;
626 struct file *file_out;
634 struct io_provide_buf {
648 const char __user *filename;
649 struct statx __user *buffer;
661 struct filename *oldpath;
662 struct filename *newpath;
670 struct filename *filename;
677 struct filename *filename;
683 struct filename *oldpath;
684 struct filename *newpath;
691 struct filename *oldpath;
692 struct filename *newpath;
696 struct io_completion {
701 struct io_async_connect {
702 struct sockaddr_storage address;
705 struct io_async_msghdr {
706 struct iovec fast_iov[UIO_FASTIOV];
707 /* points to an allocated iov, if NULL we use fast_iov instead */
708 struct iovec *free_iov;
709 struct sockaddr __user *uaddr;
711 struct sockaddr_storage addr;
715 struct iovec fast_iov[UIO_FASTIOV];
716 const struct iovec *free_iovec;
717 struct iov_iter iter;
718 struct iov_iter_state iter_state;
720 struct wait_page_queue wpq;
724 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
725 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
726 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
727 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
728 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
729 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
731 /* first byte is taken by user flags, shift it to not overlap */
736 REQ_F_LINK_TIMEOUT_BIT,
737 REQ_F_NEED_CLEANUP_BIT,
739 REQ_F_BUFFER_SELECTED_BIT,
740 REQ_F_COMPLETE_INLINE_BIT,
744 REQ_F_ARM_LTIMEOUT_BIT,
745 REQ_F_PARTIAL_IO_BIT,
746 /* keep async read/write and isreg together and in order */
747 REQ_F_NOWAIT_READ_BIT,
748 REQ_F_NOWAIT_WRITE_BIT,
751 /* not a real bit, just to check we're not overflowing the space */
757 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
758 /* drain existing IO first */
759 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
761 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
762 /* doesn't sever on completion < 0 */
763 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
765 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
766 /* IOSQE_BUFFER_SELECT */
767 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
769 /* fail rest of links */
770 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
771 /* on inflight list, should be cancelled and waited on exit reliably */
772 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
773 /* read/write uses file position */
774 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
775 /* must not punt to workers */
776 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
777 /* has or had linked timeout */
778 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
780 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
781 /* already went through poll handler */
782 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
783 /* buffer already selected */
784 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
785 /* completion is deferred through io_comp_state */
786 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
787 /* caller should reissue async */
788 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
789 /* supports async reads */
790 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
791 /* supports async writes */
792 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
794 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
795 /* has creds assigned */
796 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
797 /* skip refcounting if not set */
798 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
799 /* there is a linked timeout that has to be armed */
800 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
801 /* request has already done partial IO */
802 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
806 struct io_poll_iocb poll;
807 struct io_poll_iocb *double_poll;
810 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
812 struct io_task_work {
814 struct io_wq_work_node node;
815 struct llist_node fallback_node;
817 io_req_tw_func_t func;
821 IORING_RSRC_FILE = 0,
822 IORING_RSRC_BUFFER = 1,
826 * NOTE! Each of the iocb union members has the file pointer
827 * as the first entry in their struct definition. So you can
828 * access the file pointer through any of the sub-structs,
829 * or directly as just 'ki_filp' in this struct.
835 struct io_poll_iocb poll;
836 struct io_poll_update poll_update;
837 struct io_accept accept;
839 struct io_cancel cancel;
840 struct io_timeout timeout;
841 struct io_timeout_rem timeout_rem;
842 struct io_connect connect;
843 struct io_sr_msg sr_msg;
845 struct io_close close;
846 struct io_rsrc_update rsrc_update;
847 struct io_fadvise fadvise;
848 struct io_madvise madvise;
849 struct io_epoll epoll;
850 struct io_splice splice;
851 struct io_provide_buf pbuf;
852 struct io_statx statx;
853 struct io_shutdown shutdown;
854 struct io_rename rename;
855 struct io_unlink unlink;
856 struct io_mkdir mkdir;
857 struct io_symlink symlink;
858 struct io_hardlink hardlink;
859 /* use only after cleaning per-op data, see io_clean_op() */
860 struct io_completion compl;
863 /* opcode allocated if it needs to store data for async defer */
866 /* polled IO has completed */
872 struct io_ring_ctx *ctx;
875 struct task_struct *task;
878 struct io_kiocb *link;
879 struct percpu_ref *fixed_rsrc_refs;
881 /* used with ctx->iopoll_list with reads/writes */
882 struct list_head inflight_entry;
883 struct io_task_work io_task_work;
884 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
885 struct hlist_node hash_node;
886 struct async_poll *apoll;
887 struct io_wq_work work;
888 const struct cred *creds;
890 /* store used ubuf, so we can prevent reloading */
891 struct io_mapped_ubuf *imu;
892 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
893 struct io_buffer *kbuf;
897 struct io_tctx_node {
898 struct list_head ctx_node;
899 struct task_struct *task;
900 struct io_ring_ctx *ctx;
903 struct io_defer_entry {
904 struct list_head list;
905 struct io_kiocb *req;
910 /* needs req->file assigned */
911 unsigned needs_file : 1;
912 /* hash wq insertion if file is a regular file */
913 unsigned hash_reg_file : 1;
914 /* unbound wq insertion if file is a non-regular file */
915 unsigned unbound_nonreg_file : 1;
916 /* opcode is not supported by this kernel */
917 unsigned not_supported : 1;
918 /* set if opcode supports polled "wait" */
920 unsigned pollout : 1;
921 /* op supports buffer selection */
922 unsigned buffer_select : 1;
923 /* do prep async if is going to be punted */
924 unsigned needs_async_setup : 1;
925 /* should block plug */
927 /* size of async data needed, if any */
928 unsigned short async_size;
931 static const struct io_op_def io_op_defs[] = {
932 [IORING_OP_NOP] = {},
933 [IORING_OP_READV] = {
935 .unbound_nonreg_file = 1,
938 .needs_async_setup = 1,
940 .async_size = sizeof(struct io_async_rw),
942 [IORING_OP_WRITEV] = {
945 .unbound_nonreg_file = 1,
947 .needs_async_setup = 1,
949 .async_size = sizeof(struct io_async_rw),
951 [IORING_OP_FSYNC] = {
954 [IORING_OP_READ_FIXED] = {
956 .unbound_nonreg_file = 1,
959 .async_size = sizeof(struct io_async_rw),
961 [IORING_OP_WRITE_FIXED] = {
964 .unbound_nonreg_file = 1,
967 .async_size = sizeof(struct io_async_rw),
969 [IORING_OP_POLL_ADD] = {
971 .unbound_nonreg_file = 1,
973 [IORING_OP_POLL_REMOVE] = {},
974 [IORING_OP_SYNC_FILE_RANGE] = {
977 [IORING_OP_SENDMSG] = {
979 .unbound_nonreg_file = 1,
981 .needs_async_setup = 1,
982 .async_size = sizeof(struct io_async_msghdr),
984 [IORING_OP_RECVMSG] = {
986 .unbound_nonreg_file = 1,
989 .needs_async_setup = 1,
990 .async_size = sizeof(struct io_async_msghdr),
992 [IORING_OP_TIMEOUT] = {
993 .async_size = sizeof(struct io_timeout_data),
995 [IORING_OP_TIMEOUT_REMOVE] = {
996 /* used by timeout updates' prep() */
998 [IORING_OP_ACCEPT] = {
1000 .unbound_nonreg_file = 1,
1003 [IORING_OP_ASYNC_CANCEL] = {},
1004 [IORING_OP_LINK_TIMEOUT] = {
1005 .async_size = sizeof(struct io_timeout_data),
1007 [IORING_OP_CONNECT] = {
1009 .unbound_nonreg_file = 1,
1011 .needs_async_setup = 1,
1012 .async_size = sizeof(struct io_async_connect),
1014 [IORING_OP_FALLOCATE] = {
1017 [IORING_OP_OPENAT] = {},
1018 [IORING_OP_CLOSE] = {},
1019 [IORING_OP_FILES_UPDATE] = {},
1020 [IORING_OP_STATX] = {},
1021 [IORING_OP_READ] = {
1023 .unbound_nonreg_file = 1,
1027 .async_size = sizeof(struct io_async_rw),
1029 [IORING_OP_WRITE] = {
1032 .unbound_nonreg_file = 1,
1035 .async_size = sizeof(struct io_async_rw),
1037 [IORING_OP_FADVISE] = {
1040 [IORING_OP_MADVISE] = {},
1041 [IORING_OP_SEND] = {
1043 .unbound_nonreg_file = 1,
1046 [IORING_OP_RECV] = {
1048 .unbound_nonreg_file = 1,
1052 [IORING_OP_OPENAT2] = {
1054 [IORING_OP_EPOLL_CTL] = {
1055 .unbound_nonreg_file = 1,
1057 [IORING_OP_SPLICE] = {
1060 .unbound_nonreg_file = 1,
1062 [IORING_OP_PROVIDE_BUFFERS] = {},
1063 [IORING_OP_REMOVE_BUFFERS] = {},
1067 .unbound_nonreg_file = 1,
1069 [IORING_OP_SHUTDOWN] = {
1072 [IORING_OP_RENAMEAT] = {},
1073 [IORING_OP_UNLINKAT] = {},
1074 [IORING_OP_MKDIRAT] = {},
1075 [IORING_OP_SYMLINKAT] = {},
1076 [IORING_OP_LINKAT] = {},
1079 /* requests with any of those set should undergo io_disarm_next() */
1080 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1082 static bool io_disarm_next(struct io_kiocb *req);
1083 static void io_uring_del_tctx_node(unsigned long index);
1084 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1085 struct task_struct *task,
1087 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1089 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1091 static void io_put_req(struct io_kiocb *req);
1092 static void io_put_req_deferred(struct io_kiocb *req);
1093 static void io_dismantle_req(struct io_kiocb *req);
1094 static void io_queue_linked_timeout(struct io_kiocb *req);
1095 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1096 struct io_uring_rsrc_update2 *up,
1098 static void io_clean_op(struct io_kiocb *req);
1099 static struct file *io_file_get(struct io_ring_ctx *ctx,
1100 struct io_kiocb *req, int fd, bool fixed,
1101 unsigned int issue_flags);
1102 static void __io_queue_sqe(struct io_kiocb *req);
1103 static void io_rsrc_put_work(struct work_struct *work);
1105 static void io_req_task_queue(struct io_kiocb *req);
1106 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1107 static int io_req_prep_async(struct io_kiocb *req);
1109 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1110 unsigned int issue_flags, u32 slot_index);
1111 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1113 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1115 static struct kmem_cache *req_cachep;
1117 static const struct file_operations io_uring_fops;
1119 struct sock *io_uring_get_socket(struct file *file)
1121 #if defined(CONFIG_UNIX)
1122 if (file->f_op == &io_uring_fops) {
1123 struct io_ring_ctx *ctx = file->private_data;
1125 return ctx->ring_sock->sk;
1130 EXPORT_SYMBOL(io_uring_get_socket);
1132 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1135 mutex_lock(&ctx->uring_lock);
1140 #define io_for_each_link(pos, head) \
1141 for (pos = (head); pos; pos = pos->link)
1144 * Shamelessly stolen from the mm implementation of page reference checking,
1145 * see commit f958d7b528b1 for details.
1147 #define req_ref_zero_or_close_to_overflow(req) \
1148 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1150 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1152 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1153 return atomic_inc_not_zero(&req->refs);
1156 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1158 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1161 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1162 return atomic_dec_and_test(&req->refs);
1165 static inline void req_ref_get(struct io_kiocb *req)
1167 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1168 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1169 atomic_inc(&req->refs);
1172 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1174 if (!(req->flags & REQ_F_REFCOUNT)) {
1175 req->flags |= REQ_F_REFCOUNT;
1176 atomic_set(&req->refs, nr);
1180 static inline void io_req_set_refcount(struct io_kiocb *req)
1182 __io_req_set_refcount(req, 1);
1185 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1187 struct io_ring_ctx *ctx = req->ctx;
1189 if (!req->fixed_rsrc_refs) {
1190 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1191 percpu_ref_get(req->fixed_rsrc_refs);
1195 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1197 bool got = percpu_ref_tryget(ref);
1199 /* already at zero, wait for ->release() */
1201 wait_for_completion(compl);
1202 percpu_ref_resurrect(ref);
1204 percpu_ref_put(ref);
1207 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1209 __must_hold(&req->ctx->timeout_lock)
1211 struct io_kiocb *req;
1213 if (task && head->task != task)
1218 io_for_each_link(req, head) {
1219 if (req->flags & REQ_F_INFLIGHT)
1225 static bool io_match_linked(struct io_kiocb *head)
1227 struct io_kiocb *req;
1229 io_for_each_link(req, head) {
1230 if (req->flags & REQ_F_INFLIGHT)
1237 * As io_match_task() but protected against racing with linked timeouts.
1238 * User must not hold timeout_lock.
1240 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1245 if (task && head->task != task)
1250 if (head->flags & REQ_F_LINK_TIMEOUT) {
1251 struct io_ring_ctx *ctx = head->ctx;
1253 /* protect against races with linked timeouts */
1254 spin_lock_irq(&ctx->timeout_lock);
1255 matched = io_match_linked(head);
1256 spin_unlock_irq(&ctx->timeout_lock);
1258 matched = io_match_linked(head);
1263 static inline void req_set_fail(struct io_kiocb *req)
1265 req->flags |= REQ_F_FAIL;
1268 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1274 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1276 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1278 complete(&ctx->ref_comp);
1281 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1283 return !req->timeout.off;
1286 static void io_fallback_req_func(struct work_struct *work)
1288 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1289 fallback_work.work);
1290 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1291 struct io_kiocb *req, *tmp;
1292 bool locked = false;
1294 percpu_ref_get(&ctx->refs);
1295 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1296 req->io_task_work.func(req, &locked);
1299 if (ctx->submit_state.compl_nr)
1300 io_submit_flush_completions(ctx);
1301 mutex_unlock(&ctx->uring_lock);
1303 percpu_ref_put(&ctx->refs);
1307 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1309 struct io_ring_ctx *ctx;
1312 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1317 * Use 5 bits less than the max cq entries, that should give us around
1318 * 32 entries per hash list if totally full and uniformly spread.
1320 hash_bits = ilog2(p->cq_entries);
1324 ctx->cancel_hash_bits = hash_bits;
1325 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1327 if (!ctx->cancel_hash)
1329 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1331 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1332 if (!ctx->dummy_ubuf)
1334 /* set invalid range, so io_import_fixed() fails meeting it */
1335 ctx->dummy_ubuf->ubuf = -1UL;
1337 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1338 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1341 ctx->flags = p->flags;
1342 init_waitqueue_head(&ctx->sqo_sq_wait);
1343 INIT_LIST_HEAD(&ctx->sqd_list);
1344 init_waitqueue_head(&ctx->poll_wait);
1345 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1346 init_completion(&ctx->ref_comp);
1347 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1348 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1349 mutex_init(&ctx->uring_lock);
1350 init_waitqueue_head(&ctx->cq_wait);
1351 spin_lock_init(&ctx->completion_lock);
1352 spin_lock_init(&ctx->timeout_lock);
1353 INIT_LIST_HEAD(&ctx->iopoll_list);
1354 INIT_LIST_HEAD(&ctx->defer_list);
1355 INIT_LIST_HEAD(&ctx->timeout_list);
1356 INIT_LIST_HEAD(&ctx->ltimeout_list);
1357 spin_lock_init(&ctx->rsrc_ref_lock);
1358 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1359 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1360 init_llist_head(&ctx->rsrc_put_llist);
1361 INIT_LIST_HEAD(&ctx->tctx_list);
1362 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1363 INIT_LIST_HEAD(&ctx->locked_free_list);
1364 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1367 kfree(ctx->dummy_ubuf);
1368 kfree(ctx->cancel_hash);
1373 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1375 struct io_rings *r = ctx->rings;
1377 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1381 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1383 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1384 struct io_ring_ctx *ctx = req->ctx;
1386 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1392 #define FFS_ASYNC_READ 0x1UL
1393 #define FFS_ASYNC_WRITE 0x2UL
1395 #define FFS_ISREG 0x4UL
1397 #define FFS_ISREG 0x0UL
1399 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1401 static inline bool io_req_ffs_set(struct io_kiocb *req)
1403 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1406 static void io_req_track_inflight(struct io_kiocb *req)
1408 if (!(req->flags & REQ_F_INFLIGHT)) {
1409 req->flags |= REQ_F_INFLIGHT;
1410 atomic_inc(&req->task->io_uring->inflight_tracked);
1414 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1416 if (WARN_ON_ONCE(!req->link))
1419 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1420 req->flags |= REQ_F_LINK_TIMEOUT;
1422 /* linked timeouts should have two refs once prep'ed */
1423 io_req_set_refcount(req);
1424 __io_req_set_refcount(req->link, 2);
1428 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1430 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1432 return __io_prep_linked_timeout(req);
1435 static void io_prep_async_work(struct io_kiocb *req)
1437 const struct io_op_def *def = &io_op_defs[req->opcode];
1438 struct io_ring_ctx *ctx = req->ctx;
1440 if (!(req->flags & REQ_F_CREDS)) {
1441 req->flags |= REQ_F_CREDS;
1442 req->creds = get_current_cred();
1445 req->work.list.next = NULL;
1446 req->work.flags = 0;
1447 if (req->flags & REQ_F_FORCE_ASYNC)
1448 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1450 if (req->flags & REQ_F_ISREG) {
1451 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1452 io_wq_hash_work(&req->work, file_inode(req->file));
1453 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1454 if (def->unbound_nonreg_file)
1455 req->work.flags |= IO_WQ_WORK_UNBOUND;
1459 static void io_prep_async_link(struct io_kiocb *req)
1461 struct io_kiocb *cur;
1463 if (req->flags & REQ_F_LINK_TIMEOUT) {
1464 struct io_ring_ctx *ctx = req->ctx;
1466 spin_lock_irq(&ctx->timeout_lock);
1467 io_for_each_link(cur, req)
1468 io_prep_async_work(cur);
1469 spin_unlock_irq(&ctx->timeout_lock);
1471 io_for_each_link(cur, req)
1472 io_prep_async_work(cur);
1476 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1478 struct io_ring_ctx *ctx = req->ctx;
1479 struct io_kiocb *link = io_prep_linked_timeout(req);
1480 struct io_uring_task *tctx = req->task->io_uring;
1482 /* must not take the lock, NULL it as a precaution */
1486 BUG_ON(!tctx->io_wq);
1488 /* init ->work of the whole link before punting */
1489 io_prep_async_link(req);
1492 * Not expected to happen, but if we do have a bug where this _can_
1493 * happen, catch it here and ensure the request is marked as
1494 * canceled. That will make io-wq go through the usual work cancel
1495 * procedure rather than attempt to run this request (or create a new
1498 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1499 req->work.flags |= IO_WQ_WORK_CANCEL;
1501 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1502 &req->work, req->flags);
1503 io_wq_enqueue(tctx->io_wq, &req->work);
1505 io_queue_linked_timeout(link);
1508 static void io_kill_timeout(struct io_kiocb *req, int status)
1509 __must_hold(&req->ctx->completion_lock)
1510 __must_hold(&req->ctx->timeout_lock)
1512 struct io_timeout_data *io = req->async_data;
1514 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1517 atomic_set(&req->ctx->cq_timeouts,
1518 atomic_read(&req->ctx->cq_timeouts) + 1);
1519 list_del_init(&req->timeout.list);
1520 io_fill_cqe_req(req, status, 0);
1521 io_put_req_deferred(req);
1525 static void io_queue_deferred(struct io_ring_ctx *ctx)
1527 lockdep_assert_held(&ctx->completion_lock);
1529 while (!list_empty(&ctx->defer_list)) {
1530 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1531 struct io_defer_entry, list);
1533 if (req_need_defer(de->req, de->seq))
1535 list_del_init(&de->list);
1536 io_req_task_queue(de->req);
1541 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1542 __must_hold(&ctx->completion_lock)
1544 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1545 struct io_kiocb *req, *tmp;
1547 spin_lock_irq(&ctx->timeout_lock);
1548 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1549 u32 events_needed, events_got;
1551 if (io_is_timeout_noseq(req))
1555 * Since seq can easily wrap around over time, subtract
1556 * the last seq at which timeouts were flushed before comparing.
1557 * Assuming not more than 2^31-1 events have happened since,
1558 * these subtractions won't have wrapped, so we can check if
1559 * target is in [last_seq, current_seq] by comparing the two.
1561 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1562 events_got = seq - ctx->cq_last_tm_flush;
1563 if (events_got < events_needed)
1566 io_kill_timeout(req, 0);
1568 ctx->cq_last_tm_flush = seq;
1569 spin_unlock_irq(&ctx->timeout_lock);
1572 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1574 if (ctx->off_timeout_used)
1575 io_flush_timeouts(ctx);
1576 if (ctx->drain_active)
1577 io_queue_deferred(ctx);
1580 static inline bool io_commit_needs_flush(struct io_ring_ctx *ctx)
1582 return ctx->off_timeout_used || ctx->drain_active;
1585 static inline void __io_commit_cqring(struct io_ring_ctx *ctx)
1587 /* order cqe stores with ring update */
1588 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1591 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1593 if (unlikely(io_commit_needs_flush(ctx)))
1594 __io_commit_cqring_flush(ctx);
1595 __io_commit_cqring(ctx);
1598 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1600 struct io_rings *r = ctx->rings;
1602 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1605 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1607 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1610 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1612 struct io_rings *rings = ctx->rings;
1613 unsigned tail, mask = ctx->cq_entries - 1;
1616 * writes to the cq entry need to come after reading head; the
1617 * control dependency is enough as we're using WRITE_ONCE to
1620 if (__io_cqring_events(ctx) == ctx->cq_entries)
1623 tail = ctx->cached_cq_tail++;
1624 return &rings->cqes[tail & mask];
1627 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1629 if (likely(!ctx->cq_ev_fd))
1631 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1633 return !ctx->eventfd_async || io_wq_current_is_worker();
1637 * This should only get called when at least one event has been posted.
1638 * Some applications rely on the eventfd notification count only changing
1639 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1640 * 1:1 relationship between how many times this function is called (and
1641 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1643 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1646 * wake_up_all() may seem excessive, but io_wake_function() and
1647 * io_should_wake() handle the termination of the loop and only
1648 * wake as many waiters as we need to.
1650 if (wq_has_sleeper(&ctx->cq_wait))
1651 __wake_up(&ctx->cq_wait, TASK_NORMAL, 0,
1652 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1653 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1654 wake_up(&ctx->sq_data->wait);
1655 if (io_should_trigger_evfd(ctx))
1656 eventfd_signal_mask(ctx->cq_ev_fd, 1, EPOLL_URING_WAKE);
1657 if (waitqueue_active(&ctx->poll_wait))
1658 __wake_up(&ctx->poll_wait, TASK_INTERRUPTIBLE, 0,
1659 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1662 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1664 /* see waitqueue_active() comment */
1667 if (ctx->flags & IORING_SETUP_SQPOLL) {
1668 if (waitqueue_active(&ctx->cq_wait))
1669 __wake_up(&ctx->cq_wait, TASK_NORMAL, 0,
1670 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1672 if (io_should_trigger_evfd(ctx))
1673 eventfd_signal_mask(ctx->cq_ev_fd, 1, EPOLL_URING_WAKE);
1674 if (waitqueue_active(&ctx->poll_wait))
1675 __wake_up(&ctx->poll_wait, TASK_INTERRUPTIBLE, 0,
1676 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1679 /* Returns true if there are no backlogged entries after the flush */
1680 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1682 bool all_flushed, posted;
1684 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1688 spin_lock(&ctx->completion_lock);
1689 while (!list_empty(&ctx->cq_overflow_list)) {
1690 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1691 struct io_overflow_cqe *ocqe;
1695 ocqe = list_first_entry(&ctx->cq_overflow_list,
1696 struct io_overflow_cqe, list);
1698 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1700 io_account_cq_overflow(ctx);
1703 list_del(&ocqe->list);
1707 all_flushed = list_empty(&ctx->cq_overflow_list);
1709 clear_bit(0, &ctx->check_cq_overflow);
1710 WRITE_ONCE(ctx->rings->sq_flags,
1711 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1715 io_commit_cqring(ctx);
1716 spin_unlock(&ctx->completion_lock);
1718 io_cqring_ev_posted(ctx);
1722 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1726 if (test_bit(0, &ctx->check_cq_overflow)) {
1727 /* iopoll syncs against uring_lock, not completion_lock */
1728 if (ctx->flags & IORING_SETUP_IOPOLL)
1729 mutex_lock(&ctx->uring_lock);
1730 ret = __io_cqring_overflow_flush(ctx, false);
1731 if (ctx->flags & IORING_SETUP_IOPOLL)
1732 mutex_unlock(&ctx->uring_lock);
1738 /* must to be called somewhat shortly after putting a request */
1739 static inline void io_put_task(struct task_struct *task, int nr)
1741 struct io_uring_task *tctx = task->io_uring;
1743 if (likely(task == current)) {
1744 tctx->cached_refs += nr;
1746 percpu_counter_sub(&tctx->inflight, nr);
1747 if (unlikely(atomic_read(&tctx->in_idle)))
1748 wake_up(&tctx->wait);
1749 put_task_struct_many(task, nr);
1753 static void io_task_refs_refill(struct io_uring_task *tctx)
1755 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1757 percpu_counter_add(&tctx->inflight, refill);
1758 refcount_add(refill, ¤t->usage);
1759 tctx->cached_refs += refill;
1762 static inline void io_get_task_refs(int nr)
1764 struct io_uring_task *tctx = current->io_uring;
1766 tctx->cached_refs -= nr;
1767 if (unlikely(tctx->cached_refs < 0))
1768 io_task_refs_refill(tctx);
1771 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1773 struct io_uring_task *tctx = task->io_uring;
1774 unsigned int refs = tctx->cached_refs;
1777 tctx->cached_refs = 0;
1778 percpu_counter_sub(&tctx->inflight, refs);
1779 put_task_struct_many(task, refs);
1783 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1784 s32 res, u32 cflags)
1786 struct io_overflow_cqe *ocqe;
1788 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1791 * If we're in ring overflow flush mode, or in task cancel mode,
1792 * or cannot allocate an overflow entry, then we need to drop it
1795 io_account_cq_overflow(ctx);
1798 if (list_empty(&ctx->cq_overflow_list)) {
1799 set_bit(0, &ctx->check_cq_overflow);
1800 WRITE_ONCE(ctx->rings->sq_flags,
1801 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1804 ocqe->cqe.user_data = user_data;
1805 ocqe->cqe.res = res;
1806 ocqe->cqe.flags = cflags;
1807 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1811 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
1812 s32 res, u32 cflags)
1814 struct io_uring_cqe *cqe;
1816 trace_io_uring_complete(ctx, user_data, res, cflags);
1819 * If we can't get a cq entry, userspace overflowed the
1820 * submission (by quite a lot). Increment the overflow count in
1823 cqe = io_get_cqe(ctx);
1825 WRITE_ONCE(cqe->user_data, user_data);
1826 WRITE_ONCE(cqe->res, res);
1827 WRITE_ONCE(cqe->flags, cflags);
1830 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1833 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
1835 __io_fill_cqe(req->ctx, req->user_data, res, cflags);
1838 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1839 s32 res, u32 cflags)
1842 return __io_fill_cqe(ctx, user_data, res, cflags);
1845 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1848 struct io_ring_ctx *ctx = req->ctx;
1850 spin_lock(&ctx->completion_lock);
1851 __io_fill_cqe(ctx, req->user_data, res, cflags);
1853 * If we're the last reference to this request, add to our locked
1856 if (req_ref_put_and_test(req)) {
1857 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1858 if (req->flags & IO_DISARM_MASK)
1859 io_disarm_next(req);
1861 io_req_task_queue(req->link);
1865 io_dismantle_req(req);
1866 io_put_task(req->task, 1);
1867 list_add(&req->inflight_entry, &ctx->locked_free_list);
1868 ctx->locked_free_nr++;
1870 if (!percpu_ref_tryget(&ctx->refs))
1873 io_commit_cqring(ctx);
1874 spin_unlock(&ctx->completion_lock);
1877 io_cqring_ev_posted(ctx);
1878 percpu_ref_put(&ctx->refs);
1882 static inline bool io_req_needs_clean(struct io_kiocb *req)
1884 return req->flags & IO_REQ_CLEAN_FLAGS;
1887 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1890 if (io_req_needs_clean(req))
1893 req->compl.cflags = cflags;
1894 req->flags |= REQ_F_COMPLETE_INLINE;
1897 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1898 s32 res, u32 cflags)
1900 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1901 io_req_complete_state(req, res, cflags);
1903 io_req_complete_post(req, res, cflags);
1906 static inline void io_req_complete(struct io_kiocb *req, s32 res)
1908 __io_req_complete(req, 0, res, 0);
1911 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1914 io_req_complete_post(req, res, 0);
1917 static void io_req_complete_fail_submit(struct io_kiocb *req)
1920 * We don't submit, fail them all, for that replace hardlinks with
1921 * normal links. Extra REQ_F_LINK is tolerated.
1923 req->flags &= ~REQ_F_HARDLINK;
1924 req->flags |= REQ_F_LINK;
1925 io_req_complete_failed(req, req->result);
1929 * Don't initialise the fields below on every allocation, but do that in
1930 * advance and keep them valid across allocations.
1932 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1936 req->async_data = NULL;
1937 /* not necessary, but safer to zero */
1941 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1942 struct io_submit_state *state)
1944 spin_lock(&ctx->completion_lock);
1945 list_splice_init(&ctx->locked_free_list, &state->free_list);
1946 ctx->locked_free_nr = 0;
1947 spin_unlock(&ctx->completion_lock);
1950 /* Returns true IFF there are requests in the cache */
1951 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1953 struct io_submit_state *state = &ctx->submit_state;
1957 * If we have more than a batch's worth of requests in our IRQ side
1958 * locked cache, grab the lock and move them over to our submission
1961 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1962 io_flush_cached_locked_reqs(ctx, state);
1964 nr = state->free_reqs;
1965 while (!list_empty(&state->free_list)) {
1966 struct io_kiocb *req = list_first_entry(&state->free_list,
1967 struct io_kiocb, inflight_entry);
1969 list_del(&req->inflight_entry);
1970 state->reqs[nr++] = req;
1971 if (nr == ARRAY_SIZE(state->reqs))
1975 state->free_reqs = nr;
1980 * A request might get retired back into the request caches even before opcode
1981 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1982 * Because of that, io_alloc_req() should be called only under ->uring_lock
1983 * and with extra caution to not get a request that is still worked on.
1985 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1986 __must_hold(&ctx->uring_lock)
1988 struct io_submit_state *state = &ctx->submit_state;
1989 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1992 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1994 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1997 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
2001 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2002 * retry single alloc to be on the safe side.
2004 if (unlikely(ret <= 0)) {
2005 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2006 if (!state->reqs[0])
2011 for (i = 0; i < ret; i++)
2012 io_preinit_req(state->reqs[i], ctx);
2013 state->free_reqs = ret;
2016 return state->reqs[state->free_reqs];
2019 static inline void io_put_file(struct file *file)
2025 static void io_dismantle_req(struct io_kiocb *req)
2027 unsigned int flags = req->flags;
2029 if (io_req_needs_clean(req))
2031 if (!(flags & REQ_F_FIXED_FILE))
2032 io_put_file(req->file);
2033 if (req->fixed_rsrc_refs)
2034 percpu_ref_put(req->fixed_rsrc_refs);
2035 if (req->async_data) {
2036 kfree(req->async_data);
2037 req->async_data = NULL;
2041 static void __io_free_req(struct io_kiocb *req)
2043 struct io_ring_ctx *ctx = req->ctx;
2045 io_dismantle_req(req);
2046 io_put_task(req->task, 1);
2048 spin_lock(&ctx->completion_lock);
2049 list_add(&req->inflight_entry, &ctx->locked_free_list);
2050 ctx->locked_free_nr++;
2051 spin_unlock(&ctx->completion_lock);
2053 percpu_ref_put(&ctx->refs);
2056 static inline void io_remove_next_linked(struct io_kiocb *req)
2058 struct io_kiocb *nxt = req->link;
2060 req->link = nxt->link;
2064 static bool io_kill_linked_timeout(struct io_kiocb *req)
2065 __must_hold(&req->ctx->completion_lock)
2066 __must_hold(&req->ctx->timeout_lock)
2068 struct io_kiocb *link = req->link;
2070 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2071 struct io_timeout_data *io = link->async_data;
2073 io_remove_next_linked(req);
2074 link->timeout.head = NULL;
2075 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2076 list_del(&link->timeout.list);
2077 io_fill_cqe_req(link, -ECANCELED, 0);
2078 io_put_req_deferred(link);
2085 static void io_fail_links(struct io_kiocb *req)
2086 __must_hold(&req->ctx->completion_lock)
2088 struct io_kiocb *nxt, *link = req->link;
2092 long res = -ECANCELED;
2094 if (link->flags & REQ_F_FAIL)
2100 trace_io_uring_fail_link(req, link);
2101 io_fill_cqe_req(link, res, 0);
2102 io_put_req_deferred(link);
2107 static bool io_disarm_next(struct io_kiocb *req)
2108 __must_hold(&req->ctx->completion_lock)
2110 bool posted = false;
2112 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2113 struct io_kiocb *link = req->link;
2115 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2116 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2117 io_remove_next_linked(req);
2118 io_fill_cqe_req(link, -ECANCELED, 0);
2119 io_put_req_deferred(link);
2122 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2123 struct io_ring_ctx *ctx = req->ctx;
2125 spin_lock_irq(&ctx->timeout_lock);
2126 posted = io_kill_linked_timeout(req);
2127 spin_unlock_irq(&ctx->timeout_lock);
2129 if (unlikely((req->flags & REQ_F_FAIL) &&
2130 !(req->flags & REQ_F_HARDLINK))) {
2131 posted |= (req->link != NULL);
2137 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2139 struct io_kiocb *nxt;
2142 * If LINK is set, we have dependent requests in this chain. If we
2143 * didn't fail this request, queue the first one up, moving any other
2144 * dependencies to the next request. In case of failure, fail the rest
2147 if (req->flags & IO_DISARM_MASK) {
2148 struct io_ring_ctx *ctx = req->ctx;
2151 spin_lock(&ctx->completion_lock);
2152 posted = io_disarm_next(req);
2154 io_commit_cqring(req->ctx);
2155 spin_unlock(&ctx->completion_lock);
2157 io_cqring_ev_posted(ctx);
2164 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2166 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2168 return __io_req_find_next(req);
2171 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2176 if (ctx->submit_state.compl_nr)
2177 io_submit_flush_completions(ctx);
2178 mutex_unlock(&ctx->uring_lock);
2181 percpu_ref_put(&ctx->refs);
2184 static void tctx_task_work(struct callback_head *cb)
2186 bool locked = false;
2187 struct io_ring_ctx *ctx = NULL;
2188 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2192 struct io_wq_work_node *node;
2194 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2195 io_submit_flush_completions(ctx);
2197 spin_lock_irq(&tctx->task_lock);
2198 node = tctx->task_list.first;
2199 INIT_WQ_LIST(&tctx->task_list);
2201 tctx->task_running = false;
2202 spin_unlock_irq(&tctx->task_lock);
2207 struct io_wq_work_node *next = node->next;
2208 struct io_kiocb *req = container_of(node, struct io_kiocb,
2211 if (req->ctx != ctx) {
2212 ctx_flush_and_put(ctx, &locked);
2214 /* if not contended, grab and improve batching */
2215 locked = mutex_trylock(&ctx->uring_lock);
2216 percpu_ref_get(&ctx->refs);
2218 req->io_task_work.func(req, &locked);
2220 if (unlikely(need_resched())) {
2221 ctx_flush_and_put(ctx, &locked);
2228 ctx_flush_and_put(ctx, &locked);
2230 /* relaxed read is enough as only the task itself sets ->in_idle */
2231 if (unlikely(atomic_read(&tctx->in_idle)))
2232 io_uring_drop_tctx_refs(current);
2235 static void io_req_task_work_add(struct io_kiocb *req)
2237 struct task_struct *tsk = req->task;
2238 struct io_uring_task *tctx = tsk->io_uring;
2239 enum task_work_notify_mode notify;
2240 struct io_wq_work_node *node;
2241 unsigned long flags;
2244 WARN_ON_ONCE(!tctx);
2246 spin_lock_irqsave(&tctx->task_lock, flags);
2247 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2248 running = tctx->task_running;
2250 tctx->task_running = true;
2251 spin_unlock_irqrestore(&tctx->task_lock, flags);
2253 /* task_work already pending, we're done */
2258 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2259 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2260 * processing task_work. There's no reliable way to tell if TWA_RESUME
2263 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2264 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2265 wake_up_process(tsk);
2269 spin_lock_irqsave(&tctx->task_lock, flags);
2270 tctx->task_running = false;
2271 node = tctx->task_list.first;
2272 INIT_WQ_LIST(&tctx->task_list);
2273 spin_unlock_irqrestore(&tctx->task_lock, flags);
2276 req = container_of(node, struct io_kiocb, io_task_work.node);
2278 if (llist_add(&req->io_task_work.fallback_node,
2279 &req->ctx->fallback_llist))
2280 schedule_delayed_work(&req->ctx->fallback_work, 1);
2284 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2286 struct io_ring_ctx *ctx = req->ctx;
2288 /* not needed for normal modes, but SQPOLL depends on it */
2289 io_tw_lock(ctx, locked);
2290 io_req_complete_failed(req, req->result);
2293 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2295 struct io_ring_ctx *ctx = req->ctx;
2297 io_tw_lock(ctx, locked);
2298 /* req->task == current here, checking PF_EXITING is safe */
2299 if (likely(!(req->task->flags & PF_EXITING)))
2300 __io_queue_sqe(req);
2302 io_req_complete_failed(req, -EFAULT);
2305 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2308 req->io_task_work.func = io_req_task_cancel;
2309 io_req_task_work_add(req);
2312 static void io_req_task_queue(struct io_kiocb *req)
2314 req->io_task_work.func = io_req_task_submit;
2315 io_req_task_work_add(req);
2318 static void io_req_task_queue_reissue(struct io_kiocb *req)
2320 req->io_task_work.func = io_queue_async_work;
2321 io_req_task_work_add(req);
2324 static inline void io_queue_next(struct io_kiocb *req)
2326 struct io_kiocb *nxt = io_req_find_next(req);
2329 io_req_task_queue(nxt);
2332 static void io_free_req(struct io_kiocb *req)
2338 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2344 struct task_struct *task;
2349 static inline void io_init_req_batch(struct req_batch *rb)
2356 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2357 struct req_batch *rb)
2360 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2362 io_put_task(rb->task, rb->task_refs);
2365 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2366 struct io_submit_state *state)
2369 io_dismantle_req(req);
2371 if (req->task != rb->task) {
2373 io_put_task(rb->task, rb->task_refs);
2374 rb->task = req->task;
2380 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2381 state->reqs[state->free_reqs++] = req;
2383 list_add(&req->inflight_entry, &state->free_list);
2386 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2387 __must_hold(&ctx->uring_lock)
2389 struct io_submit_state *state = &ctx->submit_state;
2390 int i, nr = state->compl_nr;
2391 struct req_batch rb;
2393 spin_lock(&ctx->completion_lock);
2394 for (i = 0; i < nr; i++) {
2395 struct io_kiocb *req = state->compl_reqs[i];
2397 __io_fill_cqe(ctx, req->user_data, req->result,
2400 io_commit_cqring(ctx);
2401 spin_unlock(&ctx->completion_lock);
2402 io_cqring_ev_posted(ctx);
2404 io_init_req_batch(&rb);
2405 for (i = 0; i < nr; i++) {
2406 struct io_kiocb *req = state->compl_reqs[i];
2408 if (req_ref_put_and_test(req))
2409 io_req_free_batch(&rb, req, &ctx->submit_state);
2412 io_req_free_batch_finish(ctx, &rb);
2413 state->compl_nr = 0;
2417 * Drop reference to request, return next in chain (if there is one) if this
2418 * was the last reference to this request.
2420 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2422 struct io_kiocb *nxt = NULL;
2424 if (req_ref_put_and_test(req)) {
2425 nxt = io_req_find_next(req);
2431 static inline void io_put_req(struct io_kiocb *req)
2433 if (req_ref_put_and_test(req))
2437 static inline void io_put_req_deferred(struct io_kiocb *req)
2439 if (req_ref_put_and_test(req)) {
2440 req->io_task_work.func = io_free_req_work;
2441 io_req_task_work_add(req);
2445 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2447 /* See comment at the top of this file */
2449 return __io_cqring_events(ctx);
2452 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2454 struct io_rings *rings = ctx->rings;
2456 /* make sure SQ entry isn't read before tail */
2457 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2460 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2462 unsigned int cflags;
2464 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2465 cflags |= IORING_CQE_F_BUFFER;
2466 req->flags &= ~REQ_F_BUFFER_SELECTED;
2471 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2473 struct io_buffer *kbuf;
2475 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2477 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2478 return io_put_kbuf(req, kbuf);
2481 static inline bool io_run_task_work(void)
2484 * PF_IO_WORKER never returns to userspace, so check here if we have
2485 * notify work that needs processing.
2487 if (current->flags & PF_IO_WORKER &&
2488 test_thread_flag(TIF_NOTIFY_RESUME)) {
2489 __set_current_state(TASK_RUNNING);
2490 tracehook_notify_resume(NULL);
2492 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2493 __set_current_state(TASK_RUNNING);
2494 tracehook_notify_signal();
2502 * Find and free completed poll iocbs
2504 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2505 struct list_head *done)
2507 struct req_batch rb;
2508 struct io_kiocb *req;
2510 /* order with ->result store in io_complete_rw_iopoll() */
2513 io_init_req_batch(&rb);
2514 while (!list_empty(done)) {
2515 struct io_uring_cqe *cqe;
2518 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2519 list_del(&req->inflight_entry);
2520 cflags = io_put_rw_kbuf(req);
2523 cqe = io_get_cqe(ctx);
2525 WRITE_ONCE(cqe->user_data, req->user_data);
2526 WRITE_ONCE(cqe->res, req->result);
2527 WRITE_ONCE(cqe->flags, cflags);
2529 spin_lock(&ctx->completion_lock);
2530 io_cqring_event_overflow(ctx, req->user_data,
2531 req->result, cflags);
2532 spin_unlock(&ctx->completion_lock);
2535 if (req_ref_put_and_test(req))
2536 io_req_free_batch(&rb, req, &ctx->submit_state);
2539 if (io_commit_needs_flush(ctx)) {
2540 spin_lock(&ctx->completion_lock);
2541 __io_commit_cqring_flush(ctx);
2542 spin_unlock(&ctx->completion_lock);
2544 __io_commit_cqring(ctx);
2545 io_cqring_ev_posted_iopoll(ctx);
2546 io_req_free_batch_finish(ctx, &rb);
2549 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2552 struct io_kiocb *req, *tmp;
2557 * Only spin for completions if we don't have multiple devices hanging
2558 * off our complete list, and we're under the requested amount.
2560 spin = !ctx->poll_multi_queue && *nr_events < min;
2562 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2563 struct kiocb *kiocb = &req->rw.kiocb;
2567 * Move completed and retryable entries to our local lists.
2568 * If we find a request that requires polling, break out
2569 * and complete those lists first, if we have entries there.
2571 if (READ_ONCE(req->iopoll_completed)) {
2572 list_move_tail(&req->inflight_entry, &done);
2575 if (!list_empty(&done))
2578 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2579 if (unlikely(ret < 0))
2584 /* iopoll may have completed current req */
2585 if (READ_ONCE(req->iopoll_completed))
2586 list_move_tail(&req->inflight_entry, &done);
2589 if (!list_empty(&done))
2590 io_iopoll_complete(ctx, nr_events, &done);
2596 * We can't just wait for polled events to come to us, we have to actively
2597 * find and complete them.
2599 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2601 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2604 mutex_lock(&ctx->uring_lock);
2605 while (!list_empty(&ctx->iopoll_list)) {
2606 unsigned int nr_events = 0;
2608 io_do_iopoll(ctx, &nr_events, 0);
2610 /* let it sleep and repeat later if can't complete a request */
2614 * Ensure we allow local-to-the-cpu processing to take place,
2615 * in this case we need to ensure that we reap all events.
2616 * Also let task_work, etc. to progress by releasing the mutex
2618 if (need_resched()) {
2619 mutex_unlock(&ctx->uring_lock);
2621 mutex_lock(&ctx->uring_lock);
2624 mutex_unlock(&ctx->uring_lock);
2627 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2629 unsigned int nr_events = 0;
2633 * We disallow the app entering submit/complete with polling, but we
2634 * still need to lock the ring to prevent racing with polled issue
2635 * that got punted to a workqueue.
2637 mutex_lock(&ctx->uring_lock);
2639 * Don't enter poll loop if we already have events pending.
2640 * If we do, we can potentially be spinning for commands that
2641 * already triggered a CQE (eg in error).
2643 if (test_bit(0, &ctx->check_cq_overflow))
2644 __io_cqring_overflow_flush(ctx, false);
2645 if (io_cqring_events(ctx))
2649 * If a submit got punted to a workqueue, we can have the
2650 * application entering polling for a command before it gets
2651 * issued. That app will hold the uring_lock for the duration
2652 * of the poll right here, so we need to take a breather every
2653 * now and then to ensure that the issue has a chance to add
2654 * the poll to the issued list. Otherwise we can spin here
2655 * forever, while the workqueue is stuck trying to acquire the
2658 if (list_empty(&ctx->iopoll_list)) {
2659 u32 tail = ctx->cached_cq_tail;
2661 mutex_unlock(&ctx->uring_lock);
2663 mutex_lock(&ctx->uring_lock);
2665 /* some requests don't go through iopoll_list */
2666 if (tail != ctx->cached_cq_tail ||
2667 list_empty(&ctx->iopoll_list))
2670 ret = io_do_iopoll(ctx, &nr_events, min);
2672 if (task_sigpending(current)) {
2676 } while (!ret && nr_events < min && !need_resched());
2678 mutex_unlock(&ctx->uring_lock);
2682 static void kiocb_end_write(struct io_kiocb *req)
2685 * Tell lockdep we inherited freeze protection from submission
2688 if (req->flags & REQ_F_ISREG) {
2689 struct super_block *sb = file_inode(req->file)->i_sb;
2691 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2697 static bool io_resubmit_prep(struct io_kiocb *req)
2699 struct io_async_rw *rw = req->async_data;
2702 return !io_req_prep_async(req);
2703 iov_iter_restore(&rw->iter, &rw->iter_state);
2707 static bool io_rw_should_reissue(struct io_kiocb *req)
2709 umode_t mode = file_inode(req->file)->i_mode;
2710 struct io_ring_ctx *ctx = req->ctx;
2712 if (!S_ISBLK(mode) && !S_ISREG(mode))
2714 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2715 !(ctx->flags & IORING_SETUP_IOPOLL)))
2718 * If ref is dying, we might be running poll reap from the exit work.
2719 * Don't attempt to reissue from that path, just let it fail with
2722 if (percpu_ref_is_dying(&ctx->refs))
2725 * Play it safe and assume not safe to re-import and reissue if we're
2726 * not in the original thread group (or in task context).
2728 if (!same_thread_group(req->task, current) || !in_task())
2733 static bool io_resubmit_prep(struct io_kiocb *req)
2737 static bool io_rw_should_reissue(struct io_kiocb *req)
2744 * Trigger the notifications after having done some IO, and finish the write
2745 * accounting, if any.
2747 static void io_req_io_end(struct io_kiocb *req)
2749 struct io_rw *rw = &req->rw;
2751 if (rw->kiocb.ki_flags & IOCB_WRITE) {
2752 kiocb_end_write(req);
2753 fsnotify_modify(req->file);
2755 fsnotify_access(req->file);
2759 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2761 if (res != req->result) {
2762 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2763 io_rw_should_reissue(req)) {
2765 * Reissue will start accounting again, finish the
2769 req->flags |= REQ_F_REISSUE;
2778 static inline int io_fixup_rw_res(struct io_kiocb *req, long res)
2780 struct io_async_rw *io = req->async_data;
2782 /* add previously done IO, if any */
2783 if (io && io->bytes_done > 0) {
2785 res = io->bytes_done;
2787 res += io->bytes_done;
2792 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2794 unsigned int cflags = io_put_rw_kbuf(req);
2795 int res = req->result;
2798 struct io_ring_ctx *ctx = req->ctx;
2799 struct io_submit_state *state = &ctx->submit_state;
2801 io_req_complete_state(req, res, cflags);
2802 state->compl_reqs[state->compl_nr++] = req;
2803 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2804 io_submit_flush_completions(ctx);
2806 io_req_complete_post(req, res, cflags);
2810 static void io_req_rw_complete(struct io_kiocb *req, bool *locked)
2813 io_req_task_complete(req, locked);
2816 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2818 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2820 if (__io_complete_rw_common(req, res))
2822 req->result = io_fixup_rw_res(req, res);
2823 req->io_task_work.func = io_req_rw_complete;
2824 io_req_task_work_add(req);
2827 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2829 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2831 if (kiocb->ki_flags & IOCB_WRITE)
2832 kiocb_end_write(req);
2833 if (unlikely(res != req->result)) {
2834 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2835 req->flags |= REQ_F_REISSUE;
2840 WRITE_ONCE(req->result, res);
2841 /* order with io_iopoll_complete() checking ->result */
2843 WRITE_ONCE(req->iopoll_completed, 1);
2847 * After the iocb has been issued, it's safe to be found on the poll list.
2848 * Adding the kiocb to the list AFTER submission ensures that we don't
2849 * find it from a io_do_iopoll() thread before the issuer is done
2850 * accessing the kiocb cookie.
2852 static void io_iopoll_req_issued(struct io_kiocb *req)
2854 struct io_ring_ctx *ctx = req->ctx;
2855 const bool in_async = io_wq_current_is_worker();
2857 /* workqueue context doesn't hold uring_lock, grab it now */
2858 if (unlikely(in_async))
2859 mutex_lock(&ctx->uring_lock);
2862 * Track whether we have multiple files in our lists. This will impact
2863 * how we do polling eventually, not spinning if we're on potentially
2864 * different devices.
2866 if (list_empty(&ctx->iopoll_list)) {
2867 ctx->poll_multi_queue = false;
2868 } else if (!ctx->poll_multi_queue) {
2869 struct io_kiocb *list_req;
2870 unsigned int queue_num0, queue_num1;
2872 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2875 if (list_req->file != req->file) {
2876 ctx->poll_multi_queue = true;
2878 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2879 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2880 if (queue_num0 != queue_num1)
2881 ctx->poll_multi_queue = true;
2886 * For fast devices, IO may have already completed. If it has, add
2887 * it to the front so we find it first.
2889 if (READ_ONCE(req->iopoll_completed))
2890 list_add(&req->inflight_entry, &ctx->iopoll_list);
2892 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2894 if (unlikely(in_async)) {
2896 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2897 * in sq thread task context or in io worker task context. If
2898 * current task context is sq thread, we don't need to check
2899 * whether should wake up sq thread.
2901 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2902 wq_has_sleeper(&ctx->sq_data->wait))
2903 wake_up(&ctx->sq_data->wait);
2905 mutex_unlock(&ctx->uring_lock);
2909 static bool io_bdev_nowait(struct block_device *bdev)
2911 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2915 * If we tracked the file through the SCM inflight mechanism, we could support
2916 * any file. For now, just ensure that anything potentially problematic is done
2919 static bool __io_file_supports_nowait(struct file *file, int rw)
2921 umode_t mode = file_inode(file)->i_mode;
2923 if (S_ISBLK(mode)) {
2924 if (IS_ENABLED(CONFIG_BLOCK) &&
2925 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2931 if (S_ISREG(mode)) {
2932 if (IS_ENABLED(CONFIG_BLOCK) &&
2933 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2934 file->f_op != &io_uring_fops)
2939 /* any ->read/write should understand O_NONBLOCK */
2940 if (file->f_flags & O_NONBLOCK)
2943 if (!(file->f_mode & FMODE_NOWAIT))
2947 return file->f_op->read_iter != NULL;
2949 return file->f_op->write_iter != NULL;
2952 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2954 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2956 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2959 return __io_file_supports_nowait(req->file, rw);
2962 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2965 struct io_ring_ctx *ctx = req->ctx;
2966 struct kiocb *kiocb = &req->rw.kiocb;
2967 struct file *file = req->file;
2971 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2972 req->flags |= REQ_F_ISREG;
2974 kiocb->ki_pos = READ_ONCE(sqe->off);
2975 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2976 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2977 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2982 * If the file is marked O_NONBLOCK, still allow retry for it if it
2983 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2984 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2986 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2987 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req, rw)))
2988 req->flags |= REQ_F_NOWAIT;
2990 ioprio = READ_ONCE(sqe->ioprio);
2992 ret = ioprio_check_cap(ioprio);
2996 kiocb->ki_ioprio = ioprio;
2998 kiocb->ki_ioprio = get_current_ioprio();
3000 if (ctx->flags & IORING_SETUP_IOPOLL) {
3001 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
3002 !kiocb->ki_filp->f_op->iopoll)
3005 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3006 kiocb->ki_complete = io_complete_rw_iopoll;
3007 req->iopoll_completed = 0;
3009 if (kiocb->ki_flags & IOCB_HIPRI)
3011 kiocb->ki_complete = io_complete_rw;
3014 /* used for fixed read/write too - just read unconditionally */
3015 req->buf_index = READ_ONCE(sqe->buf_index);
3018 if (req->opcode == IORING_OP_READ_FIXED ||
3019 req->opcode == IORING_OP_WRITE_FIXED) {
3020 struct io_ring_ctx *ctx = req->ctx;
3023 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3025 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3026 req->imu = ctx->user_bufs[index];
3027 io_req_set_rsrc_node(req);
3030 req->rw.addr = READ_ONCE(sqe->addr);
3031 req->rw.len = READ_ONCE(sqe->len);
3035 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3041 case -ERESTARTNOINTR:
3042 case -ERESTARTNOHAND:
3043 case -ERESTART_RESTARTBLOCK:
3045 * We can't just restart the syscall, since previously
3046 * submitted sqes may already be in progress. Just fail this
3052 kiocb->ki_complete(kiocb, ret, 0);
3056 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3058 struct kiocb *kiocb = &req->rw.kiocb;
3060 if (kiocb->ki_pos != -1)
3061 return &kiocb->ki_pos;
3063 if (!(req->file->f_mode & FMODE_STREAM)) {
3064 req->flags |= REQ_F_CUR_POS;
3065 kiocb->ki_pos = req->file->f_pos;
3066 return &kiocb->ki_pos;
3073 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3074 unsigned int issue_flags)
3076 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3078 if (req->flags & REQ_F_CUR_POS)
3079 req->file->f_pos = kiocb->ki_pos;
3080 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw)) {
3081 if (!__io_complete_rw_common(req, ret)) {
3083 * Safe to call io_end from here as we're inline
3084 * from the submission path.
3087 __io_req_complete(req, issue_flags,
3088 io_fixup_rw_res(req, ret),
3089 io_put_rw_kbuf(req));
3092 io_rw_done(kiocb, ret);
3095 if (req->flags & REQ_F_REISSUE) {
3096 req->flags &= ~REQ_F_REISSUE;
3097 if (io_resubmit_prep(req)) {
3098 io_req_task_queue_reissue(req);
3100 unsigned int cflags = io_put_rw_kbuf(req);
3101 struct io_ring_ctx *ctx = req->ctx;
3103 ret = io_fixup_rw_res(req, ret);
3105 if (!(issue_flags & IO_URING_F_NONBLOCK)) {
3106 mutex_lock(&ctx->uring_lock);
3107 __io_req_complete(req, issue_flags, ret, cflags);
3108 mutex_unlock(&ctx->uring_lock);
3110 __io_req_complete(req, issue_flags, ret, cflags);
3116 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3117 struct io_mapped_ubuf *imu)
3119 size_t len = req->rw.len;
3120 u64 buf_end, buf_addr = req->rw.addr;
3123 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3125 /* not inside the mapped region */
3126 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3130 * May not be a start of buffer, set size appropriately
3131 * and advance us to the beginning.
3133 offset = buf_addr - imu->ubuf;
3134 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3138 * Don't use iov_iter_advance() here, as it's really slow for
3139 * using the latter parts of a big fixed buffer - it iterates
3140 * over each segment manually. We can cheat a bit here, because
3143 * 1) it's a BVEC iter, we set it up
3144 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3145 * first and last bvec
3147 * So just find our index, and adjust the iterator afterwards.
3148 * If the offset is within the first bvec (or the whole first
3149 * bvec, just use iov_iter_advance(). This makes it easier
3150 * since we can just skip the first segment, which may not
3151 * be PAGE_SIZE aligned.
3153 const struct bio_vec *bvec = imu->bvec;
3155 if (offset <= bvec->bv_len) {
3156 iov_iter_advance(iter, offset);
3158 unsigned long seg_skip;
3160 /* skip first vec */
3161 offset -= bvec->bv_len;
3162 seg_skip = 1 + (offset >> PAGE_SHIFT);
3164 iter->bvec = bvec + seg_skip;
3165 iter->nr_segs -= seg_skip;
3166 iter->count -= bvec->bv_len + offset;
3167 iter->iov_offset = offset & ~PAGE_MASK;
3174 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3176 if (WARN_ON_ONCE(!req->imu))
3178 return __io_import_fixed(req, rw, iter, req->imu);
3181 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3184 mutex_unlock(&ctx->uring_lock);
3187 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3190 * "Normal" inline submissions always hold the uring_lock, since we
3191 * grab it from the system call. Same is true for the SQPOLL offload.
3192 * The only exception is when we've detached the request and issue it
3193 * from an async worker thread, grab the lock for that case.
3196 mutex_lock(&ctx->uring_lock);
3199 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3200 int bgid, struct io_buffer *kbuf,
3203 struct io_buffer *head;
3205 if (req->flags & REQ_F_BUFFER_SELECTED)
3208 io_ring_submit_lock(req->ctx, needs_lock);
3210 lockdep_assert_held(&req->ctx->uring_lock);
3212 head = xa_load(&req->ctx->io_buffers, bgid);
3214 if (!list_empty(&head->list)) {
3215 kbuf = list_last_entry(&head->list, struct io_buffer,
3217 list_del(&kbuf->list);
3220 xa_erase(&req->ctx->io_buffers, bgid);
3222 if (*len > kbuf->len)
3225 kbuf = ERR_PTR(-ENOBUFS);
3228 io_ring_submit_unlock(req->ctx, needs_lock);
3233 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3236 struct io_buffer *kbuf;
3239 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3240 bgid = req->buf_index;
3241 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3244 req->rw.addr = (u64) (unsigned long) kbuf;
3245 req->flags |= REQ_F_BUFFER_SELECTED;
3246 return u64_to_user_ptr(kbuf->addr);
3249 #ifdef CONFIG_COMPAT
3250 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3253 struct compat_iovec __user *uiov;
3254 compat_ssize_t clen;
3258 uiov = u64_to_user_ptr(req->rw.addr);
3259 if (!access_ok(uiov, sizeof(*uiov)))
3261 if (__get_user(clen, &uiov->iov_len))
3267 buf = io_rw_buffer_select(req, &len, needs_lock);
3269 return PTR_ERR(buf);
3270 iov[0].iov_base = buf;
3271 iov[0].iov_len = (compat_size_t) len;
3276 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3279 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3283 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3286 len = iov[0].iov_len;
3289 buf = io_rw_buffer_select(req, &len, needs_lock);
3291 return PTR_ERR(buf);
3292 iov[0].iov_base = buf;
3293 iov[0].iov_len = len;
3297 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3300 if (req->flags & REQ_F_BUFFER_SELECTED) {
3301 struct io_buffer *kbuf;
3303 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3304 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3305 iov[0].iov_len = kbuf->len;
3308 if (req->rw.len != 1)
3311 #ifdef CONFIG_COMPAT
3312 if (req->ctx->compat)
3313 return io_compat_import(req, iov, needs_lock);
3316 return __io_iov_buffer_select(req, iov, needs_lock);
3319 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3320 struct iov_iter *iter, bool needs_lock)
3322 void __user *buf = u64_to_user_ptr(req->rw.addr);
3323 size_t sqe_len = req->rw.len;
3324 u8 opcode = req->opcode;
3327 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3329 return io_import_fixed(req, rw, iter);
3332 /* buffer index only valid with fixed read/write, or buffer select */
3333 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3336 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3337 if (req->flags & REQ_F_BUFFER_SELECT) {
3338 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3340 return PTR_ERR(buf);
3341 req->rw.len = sqe_len;
3344 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3349 if (req->flags & REQ_F_BUFFER_SELECT) {
3350 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3352 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3357 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3361 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3363 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3367 * For files that don't have ->read_iter() and ->write_iter(), handle them
3368 * by looping over ->read() or ->write() manually.
3370 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3372 struct kiocb *kiocb = &req->rw.kiocb;
3373 struct file *file = req->file;
3378 * Don't support polled IO through this interface, and we can't
3379 * support non-blocking either. For the latter, this just causes
3380 * the kiocb to be handled from an async context.
3382 if (kiocb->ki_flags & IOCB_HIPRI)
3384 if (kiocb->ki_flags & IOCB_NOWAIT)
3387 ppos = io_kiocb_ppos(kiocb);
3389 while (iov_iter_count(iter)) {
3393 if (!iov_iter_is_bvec(iter)) {
3394 iovec = iov_iter_iovec(iter);
3396 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3397 iovec.iov_len = req->rw.len;
3401 nr = file->f_op->read(file, iovec.iov_base,
3402 iovec.iov_len, ppos);
3404 nr = file->f_op->write(file, iovec.iov_base,
3405 iovec.iov_len, ppos);
3414 if (!iov_iter_is_bvec(iter)) {
3415 iov_iter_advance(iter, nr);
3422 if (nr != iovec.iov_len)
3429 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3430 const struct iovec *fast_iov, struct iov_iter *iter)
3432 struct io_async_rw *rw = req->async_data;
3434 memcpy(&rw->iter, iter, sizeof(*iter));
3435 rw->free_iovec = iovec;
3437 /* can only be fixed buffers, no need to do anything */
3438 if (iov_iter_is_bvec(iter))
3441 unsigned iov_off = 0;
3443 rw->iter.iov = rw->fast_iov;
3444 if (iter->iov != fast_iov) {
3445 iov_off = iter->iov - fast_iov;
3446 rw->iter.iov += iov_off;
3448 if (rw->fast_iov != fast_iov)
3449 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3450 sizeof(struct iovec) * iter->nr_segs);
3452 req->flags |= REQ_F_NEED_CLEANUP;
3456 static inline int io_alloc_async_data(struct io_kiocb *req)
3458 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3459 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3460 return req->async_data == NULL;
3463 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3464 const struct iovec *fast_iov,
3465 struct iov_iter *iter, bool force)
3467 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3469 if (!req->async_data) {
3470 struct io_async_rw *iorw;
3472 if (io_alloc_async_data(req)) {
3477 io_req_map_rw(req, iovec, fast_iov, iter);
3478 iorw = req->async_data;
3479 /* we've copied and mapped the iter, ensure state is saved */
3480 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3485 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3487 struct io_async_rw *iorw = req->async_data;
3488 struct iovec *iov = iorw->fast_iov;
3491 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3492 if (unlikely(ret < 0))
3495 iorw->bytes_done = 0;
3496 iorw->free_iovec = iov;
3498 req->flags |= REQ_F_NEED_CLEANUP;
3499 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3503 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3505 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3507 return io_prep_rw(req, sqe, READ);
3511 * This is our waitqueue callback handler, registered through lock_page_async()
3512 * when we initially tried to do the IO with the iocb armed our waitqueue.
3513 * This gets called when the page is unlocked, and we generally expect that to
3514 * happen when the page IO is completed and the page is now uptodate. This will
3515 * queue a task_work based retry of the operation, attempting to copy the data
3516 * again. If the latter fails because the page was NOT uptodate, then we will
3517 * do a thread based blocking retry of the operation. That's the unexpected
3520 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3521 int sync, void *arg)
3523 struct wait_page_queue *wpq;
3524 struct io_kiocb *req = wait->private;
3525 struct wait_page_key *key = arg;
3527 wpq = container_of(wait, struct wait_page_queue, wait);
3529 if (!wake_page_match(wpq, key))
3532 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3533 list_del_init(&wait->entry);
3534 io_req_task_queue(req);
3539 * This controls whether a given IO request should be armed for async page
3540 * based retry. If we return false here, the request is handed to the async
3541 * worker threads for retry. If we're doing buffered reads on a regular file,
3542 * we prepare a private wait_page_queue entry and retry the operation. This
3543 * will either succeed because the page is now uptodate and unlocked, or it
3544 * will register a callback when the page is unlocked at IO completion. Through
3545 * that callback, io_uring uses task_work to setup a retry of the operation.
3546 * That retry will attempt the buffered read again. The retry will generally
3547 * succeed, or in rare cases where it fails, we then fall back to using the
3548 * async worker threads for a blocking retry.
3550 static bool io_rw_should_retry(struct io_kiocb *req)
3552 struct io_async_rw *rw = req->async_data;
3553 struct wait_page_queue *wait = &rw->wpq;
3554 struct kiocb *kiocb = &req->rw.kiocb;
3556 /* never retry for NOWAIT, we just complete with -EAGAIN */
3557 if (req->flags & REQ_F_NOWAIT)
3560 /* Only for buffered IO */
3561 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3565 * just use poll if we can, and don't attempt if the fs doesn't
3566 * support callback based unlocks
3568 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3571 wait->wait.func = io_async_buf_func;
3572 wait->wait.private = req;
3573 wait->wait.flags = 0;
3574 INIT_LIST_HEAD(&wait->wait.entry);
3575 kiocb->ki_flags |= IOCB_WAITQ;
3576 kiocb->ki_flags &= ~IOCB_NOWAIT;
3577 kiocb->ki_waitq = wait;
3581 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3583 if (req->file->f_op->read_iter)
3584 return call_read_iter(req->file, &req->rw.kiocb, iter);
3585 else if (req->file->f_op->read)
3586 return loop_rw_iter(READ, req, iter);
3591 static bool need_read_all(struct io_kiocb *req)
3593 return req->flags & REQ_F_ISREG ||
3594 S_ISBLK(file_inode(req->file)->i_mode);
3597 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3599 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3600 struct kiocb *kiocb = &req->rw.kiocb;
3601 struct iov_iter __iter, *iter = &__iter;
3602 struct io_async_rw *rw = req->async_data;
3603 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3604 struct iov_iter_state __state, *state;
3610 state = &rw->iter_state;
3612 * We come here from an earlier attempt, restore our state to
3613 * match in case it doesn't. It's cheap enough that we don't
3614 * need to make this conditional.
3616 iov_iter_restore(iter, state);
3619 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3623 iov_iter_save_state(iter, state);
3625 req->result = iov_iter_count(iter);
3627 /* Ensure we clear previously set non-block flag */
3628 if (!force_nonblock)
3629 kiocb->ki_flags &= ~IOCB_NOWAIT;
3631 kiocb->ki_flags |= IOCB_NOWAIT;
3633 /* If the file doesn't support async, just async punt */
3634 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3635 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3636 return ret ?: -EAGAIN;
3639 ppos = io_kiocb_update_pos(req);
3641 ret = rw_verify_area(READ, req->file, ppos, req->result);
3642 if (unlikely(ret)) {
3647 ret = io_iter_do_read(req, iter);
3649 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3650 req->flags &= ~REQ_F_REISSUE;
3651 /* IOPOLL retry should happen for io-wq threads */
3652 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3654 /* no retry on NONBLOCK nor RWF_NOWAIT */
3655 if (req->flags & REQ_F_NOWAIT)
3658 } else if (ret == -EIOCBQUEUED) {
3660 } else if (ret <= 0 || ret == req->result || !force_nonblock ||
3661 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3662 /* read all, failed, already did sync or don't want to retry */
3667 * Don't depend on the iter state matching what was consumed, or being
3668 * untouched in case of error. Restore it and we'll advance it
3669 * manually if we need to.
3671 iov_iter_restore(iter, state);
3673 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3678 rw = req->async_data;
3680 * Now use our persistent iterator and state, if we aren't already.
3681 * We've restored and mapped the iter to match.
3683 if (iter != &rw->iter) {
3685 state = &rw->iter_state;
3690 * We end up here because of a partial read, either from
3691 * above or inside this loop. Advance the iter by the bytes
3692 * that were consumed.
3694 iov_iter_advance(iter, ret);
3695 if (!iov_iter_count(iter))
3697 rw->bytes_done += ret;
3698 iov_iter_save_state(iter, state);
3700 /* if we can retry, do so with the callbacks armed */
3701 if (!io_rw_should_retry(req)) {
3702 kiocb->ki_flags &= ~IOCB_WAITQ;
3706 req->result = iov_iter_count(iter);
3708 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3709 * we get -EIOCBQUEUED, then we'll get a notification when the
3710 * desired page gets unlocked. We can also get a partial read
3711 * here, and if we do, then just retry at the new offset.
3713 ret = io_iter_do_read(req, iter);
3714 if (ret == -EIOCBQUEUED)
3716 /* we got some bytes, but not all. retry. */
3717 kiocb->ki_flags &= ~IOCB_WAITQ;
3718 iov_iter_restore(iter, state);
3721 kiocb_done(kiocb, ret, issue_flags);
3723 /* it's faster to check here then delegate to kfree */
3729 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3731 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3733 return io_prep_rw(req, sqe, WRITE);
3736 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3738 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3739 struct kiocb *kiocb = &req->rw.kiocb;
3740 struct iov_iter __iter, *iter = &__iter;
3741 struct io_async_rw *rw = req->async_data;
3742 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3743 struct iov_iter_state __state, *state;
3749 state = &rw->iter_state;
3750 iov_iter_restore(iter, state);
3753 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3757 iov_iter_save_state(iter, state);
3759 req->result = iov_iter_count(iter);
3761 /* Ensure we clear previously set non-block flag */
3762 if (!force_nonblock)
3763 kiocb->ki_flags &= ~IOCB_NOWAIT;
3765 kiocb->ki_flags |= IOCB_NOWAIT;
3767 /* If the file doesn't support async, just async punt */
3768 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3771 /* file path doesn't support NOWAIT for non-direct_IO */
3772 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3773 (req->flags & REQ_F_ISREG))
3776 ppos = io_kiocb_update_pos(req);
3778 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3783 * Open-code file_start_write here to grab freeze protection,
3784 * which will be released by another thread in
3785 * io_complete_rw(). Fool lockdep by telling it the lock got
3786 * released so that it doesn't complain about the held lock when
3787 * we return to userspace.
3789 if (req->flags & REQ_F_ISREG) {
3790 sb_start_write(file_inode(req->file)->i_sb);
3791 __sb_writers_release(file_inode(req->file)->i_sb,
3794 kiocb->ki_flags |= IOCB_WRITE;
3796 if (req->file->f_op->write_iter)
3797 ret2 = call_write_iter(req->file, kiocb, iter);
3798 else if (req->file->f_op->write)
3799 ret2 = loop_rw_iter(WRITE, req, iter);
3803 if (req->flags & REQ_F_REISSUE) {
3804 req->flags &= ~REQ_F_REISSUE;
3809 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3810 * retry them without IOCB_NOWAIT.
3812 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3814 /* no retry on NONBLOCK nor RWF_NOWAIT */
3815 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3817 if (!force_nonblock || ret2 != -EAGAIN) {
3818 /* IOPOLL retry should happen for io-wq threads */
3819 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3822 kiocb_done(kiocb, ret2, issue_flags);
3825 iov_iter_restore(iter, state);
3826 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3828 if (kiocb->ki_flags & IOCB_WRITE)
3829 kiocb_end_write(req);
3835 /* it's reportedly faster than delegating the null check to kfree() */
3841 static int io_renameat_prep(struct io_kiocb *req,
3842 const struct io_uring_sqe *sqe)
3844 struct io_rename *ren = &req->rename;
3845 const char __user *oldf, *newf;
3847 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3849 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3851 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3854 ren->old_dfd = READ_ONCE(sqe->fd);
3855 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3856 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3857 ren->new_dfd = READ_ONCE(sqe->len);
3858 ren->flags = READ_ONCE(sqe->rename_flags);
3860 ren->oldpath = getname(oldf);
3861 if (IS_ERR(ren->oldpath))
3862 return PTR_ERR(ren->oldpath);
3864 ren->newpath = getname(newf);
3865 if (IS_ERR(ren->newpath)) {
3866 putname(ren->oldpath);
3867 return PTR_ERR(ren->newpath);
3870 req->flags |= REQ_F_NEED_CLEANUP;
3874 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3876 struct io_rename *ren = &req->rename;
3879 if (issue_flags & IO_URING_F_NONBLOCK)
3882 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3883 ren->newpath, ren->flags);
3885 req->flags &= ~REQ_F_NEED_CLEANUP;
3888 io_req_complete(req, ret);
3892 static int io_unlinkat_prep(struct io_kiocb *req,
3893 const struct io_uring_sqe *sqe)
3895 struct io_unlink *un = &req->unlink;
3896 const char __user *fname;
3898 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3900 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3903 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3906 un->dfd = READ_ONCE(sqe->fd);
3908 un->flags = READ_ONCE(sqe->unlink_flags);
3909 if (un->flags & ~AT_REMOVEDIR)
3912 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3913 un->filename = getname(fname);
3914 if (IS_ERR(un->filename))
3915 return PTR_ERR(un->filename);
3917 req->flags |= REQ_F_NEED_CLEANUP;
3921 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3923 struct io_unlink *un = &req->unlink;
3926 if (issue_flags & IO_URING_F_NONBLOCK)
3929 if (un->flags & AT_REMOVEDIR)
3930 ret = do_rmdir(un->dfd, un->filename);
3932 ret = do_unlinkat(un->dfd, un->filename);
3934 req->flags &= ~REQ_F_NEED_CLEANUP;
3937 io_req_complete(req, ret);
3941 static int io_mkdirat_prep(struct io_kiocb *req,
3942 const struct io_uring_sqe *sqe)
3944 struct io_mkdir *mkd = &req->mkdir;
3945 const char __user *fname;
3947 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3949 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3952 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3955 mkd->dfd = READ_ONCE(sqe->fd);
3956 mkd->mode = READ_ONCE(sqe->len);
3958 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3959 mkd->filename = getname(fname);
3960 if (IS_ERR(mkd->filename))
3961 return PTR_ERR(mkd->filename);
3963 req->flags |= REQ_F_NEED_CLEANUP;
3967 static int io_mkdirat(struct io_kiocb *req, int issue_flags)
3969 struct io_mkdir *mkd = &req->mkdir;
3972 if (issue_flags & IO_URING_F_NONBLOCK)
3975 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3977 req->flags &= ~REQ_F_NEED_CLEANUP;
3980 io_req_complete(req, ret);
3984 static int io_symlinkat_prep(struct io_kiocb *req,
3985 const struct io_uring_sqe *sqe)
3987 struct io_symlink *sl = &req->symlink;
3988 const char __user *oldpath, *newpath;
3990 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3992 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3995 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3998 sl->new_dfd = READ_ONCE(sqe->fd);
3999 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4000 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4002 sl->oldpath = getname(oldpath);
4003 if (IS_ERR(sl->oldpath))
4004 return PTR_ERR(sl->oldpath);
4006 sl->newpath = getname(newpath);
4007 if (IS_ERR(sl->newpath)) {
4008 putname(sl->oldpath);
4009 return PTR_ERR(sl->newpath);
4012 req->flags |= REQ_F_NEED_CLEANUP;
4016 static int io_symlinkat(struct io_kiocb *req, int issue_flags)
4018 struct io_symlink *sl = &req->symlink;
4021 if (issue_flags & IO_URING_F_NONBLOCK)
4024 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4026 req->flags &= ~REQ_F_NEED_CLEANUP;
4029 io_req_complete(req, ret);
4033 static int io_linkat_prep(struct io_kiocb *req,
4034 const struct io_uring_sqe *sqe)
4036 struct io_hardlink *lnk = &req->hardlink;
4037 const char __user *oldf, *newf;
4039 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4041 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4043 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4046 lnk->old_dfd = READ_ONCE(sqe->fd);
4047 lnk->new_dfd = READ_ONCE(sqe->len);
4048 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4049 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4050 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4052 lnk->oldpath = getname(oldf);
4053 if (IS_ERR(lnk->oldpath))
4054 return PTR_ERR(lnk->oldpath);
4056 lnk->newpath = getname(newf);
4057 if (IS_ERR(lnk->newpath)) {
4058 putname(lnk->oldpath);
4059 return PTR_ERR(lnk->newpath);
4062 req->flags |= REQ_F_NEED_CLEANUP;
4066 static int io_linkat(struct io_kiocb *req, int issue_flags)
4068 struct io_hardlink *lnk = &req->hardlink;
4071 if (issue_flags & IO_URING_F_NONBLOCK)
4074 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4075 lnk->newpath, lnk->flags);
4077 req->flags &= ~REQ_F_NEED_CLEANUP;
4080 io_req_complete(req, ret);
4084 static int io_shutdown_prep(struct io_kiocb *req,
4085 const struct io_uring_sqe *sqe)
4087 #if defined(CONFIG_NET)
4088 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4090 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4091 sqe->buf_index || sqe->splice_fd_in))
4094 req->shutdown.how = READ_ONCE(sqe->len);
4101 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4103 #if defined(CONFIG_NET)
4104 struct socket *sock;
4107 if (issue_flags & IO_URING_F_NONBLOCK)
4110 sock = sock_from_file(req->file);
4111 if (unlikely(!sock))
4114 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4117 io_req_complete(req, ret);
4124 static int __io_splice_prep(struct io_kiocb *req,
4125 const struct io_uring_sqe *sqe)
4127 struct io_splice *sp = &req->splice;
4128 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4130 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4133 sp->len = READ_ONCE(sqe->len);
4134 sp->flags = READ_ONCE(sqe->splice_flags);
4135 if (unlikely(sp->flags & ~valid_flags))
4137 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4141 static int io_tee_prep(struct io_kiocb *req,
4142 const struct io_uring_sqe *sqe)
4144 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4146 return __io_splice_prep(req, sqe);
4149 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4151 struct io_splice *sp = &req->splice;
4152 struct file *out = sp->file_out;
4153 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4157 if (issue_flags & IO_URING_F_NONBLOCK)
4160 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4161 (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4168 ret = do_tee(in, out, sp->len, flags);
4170 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4175 io_req_complete(req, ret);
4179 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4181 struct io_splice *sp = &req->splice;
4183 sp->off_in = READ_ONCE(sqe->splice_off_in);
4184 sp->off_out = READ_ONCE(sqe->off);
4185 return __io_splice_prep(req, sqe);
4188 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4190 struct io_splice *sp = &req->splice;
4191 struct file *out = sp->file_out;
4192 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4193 loff_t *poff_in, *poff_out;
4197 if (issue_flags & IO_URING_F_NONBLOCK)
4200 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4201 (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4207 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4208 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4211 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4213 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4218 io_req_complete(req, ret);
4223 * IORING_OP_NOP just posts a completion event, nothing else.
4225 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4227 struct io_ring_ctx *ctx = req->ctx;
4229 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4232 __io_req_complete(req, issue_flags, 0, 0);
4236 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4238 struct io_ring_ctx *ctx = req->ctx;
4240 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4242 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4246 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4247 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4250 req->sync.off = READ_ONCE(sqe->off);
4251 req->sync.len = READ_ONCE(sqe->len);
4255 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4257 loff_t end = req->sync.off + req->sync.len;
4260 /* fsync always requires a blocking context */
4261 if (issue_flags & IO_URING_F_NONBLOCK)
4264 ret = vfs_fsync_range(req->file, req->sync.off,
4265 end > 0 ? end : LLONG_MAX,
4266 req->sync.flags & IORING_FSYNC_DATASYNC);
4269 io_req_complete(req, ret);
4273 static int io_fallocate_prep(struct io_kiocb *req,
4274 const struct io_uring_sqe *sqe)
4276 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4279 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4282 req->sync.off = READ_ONCE(sqe->off);
4283 req->sync.len = READ_ONCE(sqe->addr);
4284 req->sync.mode = READ_ONCE(sqe->len);
4288 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4292 /* fallocate always requiring blocking context */
4293 if (issue_flags & IO_URING_F_NONBLOCK)
4295 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4300 fsnotify_modify(req->file);
4301 io_req_complete(req, ret);
4305 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4307 const char __user *fname;
4310 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4312 if (unlikely(sqe->ioprio || sqe->buf_index))
4314 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4317 /* open.how should be already initialised */
4318 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4319 req->open.how.flags |= O_LARGEFILE;
4321 req->open.dfd = READ_ONCE(sqe->fd);
4322 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4323 req->open.filename = getname(fname);
4324 if (IS_ERR(req->open.filename)) {
4325 ret = PTR_ERR(req->open.filename);
4326 req->open.filename = NULL;
4330 req->open.file_slot = READ_ONCE(sqe->file_index);
4331 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4334 req->open.nofile = rlimit(RLIMIT_NOFILE);
4335 req->flags |= REQ_F_NEED_CLEANUP;
4339 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4341 u64 mode = READ_ONCE(sqe->len);
4342 u64 flags = READ_ONCE(sqe->open_flags);
4344 req->open.how = build_open_how(flags, mode);
4345 return __io_openat_prep(req, sqe);
4348 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4350 struct open_how __user *how;
4354 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4355 len = READ_ONCE(sqe->len);
4356 if (len < OPEN_HOW_SIZE_VER0)
4359 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4364 return __io_openat_prep(req, sqe);
4367 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4369 struct open_flags op;
4371 bool resolve_nonblock, nonblock_set;
4372 bool fixed = !!req->open.file_slot;
4375 ret = build_open_flags(&req->open.how, &op);
4378 nonblock_set = op.open_flag & O_NONBLOCK;
4379 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4380 if (issue_flags & IO_URING_F_NONBLOCK) {
4382 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4383 * it'll always -EAGAIN. Note that we test for __O_TMPFILE
4384 * because O_TMPFILE includes O_DIRECTORY, which isn't a flag
4385 * we need to force async for.
4387 if (req->open.how.flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
4389 op.lookup_flags |= LOOKUP_CACHED;
4390 op.open_flag |= O_NONBLOCK;
4394 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4399 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4402 * We could hang on to this 'fd' on retrying, but seems like
4403 * marginal gain for something that is now known to be a slower
4404 * path. So just put it, and we'll get a new one when we retry.
4409 ret = PTR_ERR(file);
4410 /* only retry if RESOLVE_CACHED wasn't already set by application */
4411 if (ret == -EAGAIN &&
4412 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4417 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4418 file->f_flags &= ~O_NONBLOCK;
4419 fsnotify_open(file);
4422 fd_install(ret, file);
4424 ret = io_install_fixed_file(req, file, issue_flags,
4425 req->open.file_slot - 1);
4427 putname(req->open.filename);
4428 req->flags &= ~REQ_F_NEED_CLEANUP;
4431 __io_req_complete(req, issue_flags, ret, 0);
4435 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4437 return io_openat2(req, issue_flags);
4440 static int io_remove_buffers_prep(struct io_kiocb *req,
4441 const struct io_uring_sqe *sqe)
4443 struct io_provide_buf *p = &req->pbuf;
4446 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4450 tmp = READ_ONCE(sqe->fd);
4451 if (!tmp || tmp > USHRT_MAX)
4454 memset(p, 0, sizeof(*p));
4456 p->bgid = READ_ONCE(sqe->buf_group);
4460 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4461 int bgid, unsigned nbufs)
4465 /* shouldn't happen */
4469 /* the head kbuf is the list itself */
4470 while (!list_empty(&buf->list)) {
4471 struct io_buffer *nxt;
4473 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4474 list_del(&nxt->list);
4482 xa_erase(&ctx->io_buffers, bgid);
4487 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4489 struct io_provide_buf *p = &req->pbuf;
4490 struct io_ring_ctx *ctx = req->ctx;
4491 struct io_buffer *head;
4493 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4495 io_ring_submit_lock(ctx, !force_nonblock);
4497 lockdep_assert_held(&ctx->uring_lock);
4500 head = xa_load(&ctx->io_buffers, p->bgid);
4502 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4506 /* complete before unlock, IOPOLL may need the lock */
4507 __io_req_complete(req, issue_flags, ret, 0);
4508 io_ring_submit_unlock(ctx, !force_nonblock);
4512 static int io_provide_buffers_prep(struct io_kiocb *req,
4513 const struct io_uring_sqe *sqe)
4515 unsigned long size, tmp_check;
4516 struct io_provide_buf *p = &req->pbuf;
4519 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4522 tmp = READ_ONCE(sqe->fd);
4523 if (!tmp || tmp > USHRT_MAX)
4526 p->addr = READ_ONCE(sqe->addr);
4527 p->len = READ_ONCE(sqe->len);
4529 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4532 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4535 size = (unsigned long)p->len * p->nbufs;
4536 if (!access_ok(u64_to_user_ptr(p->addr), size))
4539 p->bgid = READ_ONCE(sqe->buf_group);
4540 tmp = READ_ONCE(sqe->off);
4541 if (tmp > USHRT_MAX)
4547 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4549 struct io_buffer *buf;
4550 u64 addr = pbuf->addr;
4551 int i, bid = pbuf->bid;
4553 for (i = 0; i < pbuf->nbufs; i++) {
4554 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4559 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4564 INIT_LIST_HEAD(&buf->list);
4567 list_add_tail(&buf->list, &(*head)->list);
4572 return i ? i : -ENOMEM;
4575 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4577 struct io_provide_buf *p = &req->pbuf;
4578 struct io_ring_ctx *ctx = req->ctx;
4579 struct io_buffer *head, *list;
4581 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4583 io_ring_submit_lock(ctx, !force_nonblock);
4585 lockdep_assert_held(&ctx->uring_lock);
4587 list = head = xa_load(&ctx->io_buffers, p->bgid);
4589 ret = io_add_buffers(p, &head);
4590 if (ret >= 0 && !list) {
4591 ret = xa_insert(&ctx->io_buffers, p->bgid, head,
4592 GFP_KERNEL_ACCOUNT);
4594 __io_remove_buffers(ctx, head, p->bgid, -1U);
4598 /* complete before unlock, IOPOLL may need the lock */
4599 __io_req_complete(req, issue_flags, ret, 0);
4600 io_ring_submit_unlock(ctx, !force_nonblock);
4604 static int io_epoll_ctl_prep(struct io_kiocb *req,
4605 const struct io_uring_sqe *sqe)
4607 #if defined(CONFIG_EPOLL)
4608 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4610 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4613 req->epoll.epfd = READ_ONCE(sqe->fd);
4614 req->epoll.op = READ_ONCE(sqe->len);
4615 req->epoll.fd = READ_ONCE(sqe->off);
4617 if (ep_op_has_event(req->epoll.op)) {
4618 struct epoll_event __user *ev;
4620 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4621 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4631 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4633 #if defined(CONFIG_EPOLL)
4634 struct io_epoll *ie = &req->epoll;
4636 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4638 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4639 if (force_nonblock && ret == -EAGAIN)
4644 __io_req_complete(req, issue_flags, ret, 0);
4651 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4653 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4654 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4656 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4659 req->madvise.addr = READ_ONCE(sqe->addr);
4660 req->madvise.len = READ_ONCE(sqe->len);
4661 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4668 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4670 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4671 struct io_madvise *ma = &req->madvise;
4674 if (issue_flags & IO_URING_F_NONBLOCK)
4677 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4680 io_req_complete(req, ret);
4687 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4689 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4691 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4694 req->fadvise.offset = READ_ONCE(sqe->off);
4695 req->fadvise.len = READ_ONCE(sqe->len);
4696 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4700 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4702 struct io_fadvise *fa = &req->fadvise;
4705 if (issue_flags & IO_URING_F_NONBLOCK) {
4706 switch (fa->advice) {
4707 case POSIX_FADV_NORMAL:
4708 case POSIX_FADV_RANDOM:
4709 case POSIX_FADV_SEQUENTIAL:
4716 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4719 __io_req_complete(req, issue_flags, ret, 0);
4723 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4725 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4727 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4729 if (req->flags & REQ_F_FIXED_FILE)
4732 req->statx.dfd = READ_ONCE(sqe->fd);
4733 req->statx.mask = READ_ONCE(sqe->len);
4734 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4735 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4736 req->statx.flags = READ_ONCE(sqe->statx_flags);
4741 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4743 struct io_statx *ctx = &req->statx;
4746 if (issue_flags & IO_URING_F_NONBLOCK)
4749 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4754 io_req_complete(req, ret);
4758 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4760 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4762 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4763 sqe->rw_flags || sqe->buf_index)
4765 if (req->flags & REQ_F_FIXED_FILE)
4768 req->close.fd = READ_ONCE(sqe->fd);
4769 req->close.file_slot = READ_ONCE(sqe->file_index);
4770 if (req->close.file_slot && req->close.fd)
4776 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4778 struct files_struct *files = current->files;
4779 struct io_close *close = &req->close;
4780 struct fdtable *fdt;
4781 struct file *file = NULL;
4784 if (req->close.file_slot) {
4785 ret = io_close_fixed(req, issue_flags);
4789 spin_lock(&files->file_lock);
4790 fdt = files_fdtable(files);
4791 if (close->fd >= fdt->max_fds) {
4792 spin_unlock(&files->file_lock);
4795 file = fdt->fd[close->fd];
4796 if (!file || file->f_op == &io_uring_fops) {
4797 spin_unlock(&files->file_lock);
4802 /* if the file has a flush method, be safe and punt to async */
4803 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4804 spin_unlock(&files->file_lock);
4808 ret = __close_fd_get_file(close->fd, &file);
4809 spin_unlock(&files->file_lock);
4816 /* No ->flush() or already async, safely close from here */
4817 ret = filp_close(file, current->files);
4823 __io_req_complete(req, issue_flags, ret, 0);
4827 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4829 struct io_ring_ctx *ctx = req->ctx;
4831 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4833 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4837 req->sync.off = READ_ONCE(sqe->off);
4838 req->sync.len = READ_ONCE(sqe->len);
4839 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4843 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4847 /* sync_file_range always requires a blocking context */
4848 if (issue_flags & IO_URING_F_NONBLOCK)
4851 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4855 io_req_complete(req, ret);
4859 #if defined(CONFIG_NET)
4860 static bool io_net_retry(struct socket *sock, int flags)
4862 if (!(flags & MSG_WAITALL))
4864 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4867 static int io_setup_async_msg(struct io_kiocb *req,
4868 struct io_async_msghdr *kmsg)
4870 struct io_async_msghdr *async_msg = req->async_data;
4874 if (io_alloc_async_data(req)) {
4875 kfree(kmsg->free_iov);
4878 async_msg = req->async_data;
4879 req->flags |= REQ_F_NEED_CLEANUP;
4880 memcpy(async_msg, kmsg, sizeof(*kmsg));
4881 if (async_msg->msg.msg_name)
4882 async_msg->msg.msg_name = &async_msg->addr;
4883 /* if were using fast_iov, set it to the new one */
4884 if (!kmsg->free_iov) {
4885 size_t fast_idx = kmsg->msg.msg_iter.iov - kmsg->fast_iov;
4886 async_msg->msg.msg_iter.iov = &async_msg->fast_iov[fast_idx];
4892 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4893 struct io_async_msghdr *iomsg)
4895 struct io_sr_msg *sr = &req->sr_msg;
4898 iomsg->msg.msg_name = &iomsg->addr;
4899 iomsg->free_iov = iomsg->fast_iov;
4900 ret = sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4901 req->sr_msg.msg_flags, &iomsg->free_iov);
4902 /* save msg_control as sys_sendmsg() overwrites it */
4903 sr->msg_control = iomsg->msg.msg_control;
4907 static int io_sendmsg_prep_async(struct io_kiocb *req)
4911 ret = io_sendmsg_copy_hdr(req, req->async_data);
4913 req->flags |= REQ_F_NEED_CLEANUP;
4917 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4919 struct io_sr_msg *sr = &req->sr_msg;
4921 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4923 if (unlikely(sqe->addr2 || sqe->file_index))
4925 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
4928 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4929 sr->len = READ_ONCE(sqe->len);
4930 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4931 if (sr->msg_flags & MSG_DONTWAIT)
4932 req->flags |= REQ_F_NOWAIT;
4934 #ifdef CONFIG_COMPAT
4935 if (req->ctx->compat)
4936 sr->msg_flags |= MSG_CMSG_COMPAT;
4942 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4944 struct io_async_msghdr iomsg, *kmsg;
4945 struct io_sr_msg *sr = &req->sr_msg;
4946 struct socket *sock;
4951 sock = sock_from_file(req->file);
4952 if (unlikely(!sock))
4955 kmsg = req->async_data;
4957 ret = io_sendmsg_copy_hdr(req, &iomsg);
4962 kmsg->msg.msg_control = sr->msg_control;
4965 flags = req->sr_msg.msg_flags;
4966 if (issue_flags & IO_URING_F_NONBLOCK)
4967 flags |= MSG_DONTWAIT;
4968 if (flags & MSG_WAITALL)
4969 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4971 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4973 if (ret < min_ret) {
4974 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4975 return io_setup_async_msg(req, kmsg);
4976 if (ret == -ERESTARTSYS)
4978 if (ret > 0 && io_net_retry(sock, flags)) {
4979 kmsg->msg.msg_controllen = 0;
4980 kmsg->msg.msg_control = NULL;
4982 req->flags |= REQ_F_PARTIAL_IO;
4983 return io_setup_async_msg(req, kmsg);
4987 /* fast path, check for non-NULL to avoid function call */
4989 kfree(kmsg->free_iov);
4990 req->flags &= ~REQ_F_NEED_CLEANUP;
4993 else if (sr->done_io)
4995 __io_req_complete(req, issue_flags, ret, 0);
4999 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5001 struct io_sr_msg *sr = &req->sr_msg;
5004 struct socket *sock;
5009 sock = sock_from_file(req->file);
5010 if (unlikely(!sock))
5013 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5017 msg.msg_name = NULL;
5018 msg.msg_control = NULL;
5019 msg.msg_controllen = 0;
5020 msg.msg_namelen = 0;
5022 flags = req->sr_msg.msg_flags;
5023 if (issue_flags & IO_URING_F_NONBLOCK)
5024 flags |= MSG_DONTWAIT;
5025 if (flags & MSG_WAITALL)
5026 min_ret = iov_iter_count(&msg.msg_iter);
5028 msg.msg_flags = flags;
5029 ret = sock_sendmsg(sock, &msg);
5030 if (ret < min_ret) {
5031 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5033 if (ret == -ERESTARTSYS)
5035 if (ret > 0 && io_net_retry(sock, flags)) {
5039 req->flags |= REQ_F_PARTIAL_IO;
5046 else if (sr->done_io)
5048 __io_req_complete(req, issue_flags, ret, 0);
5052 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5053 struct io_async_msghdr *iomsg)
5055 struct io_sr_msg *sr = &req->sr_msg;
5056 struct iovec __user *uiov;
5060 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5061 &iomsg->uaddr, &uiov, &iov_len);
5065 if (req->flags & REQ_F_BUFFER_SELECT) {
5068 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5070 sr->len = iomsg->fast_iov[0].iov_len;
5071 iomsg->free_iov = NULL;
5073 iomsg->free_iov = iomsg->fast_iov;
5074 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5075 &iomsg->free_iov, &iomsg->msg.msg_iter,
5084 #ifdef CONFIG_COMPAT
5085 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5086 struct io_async_msghdr *iomsg)
5088 struct io_sr_msg *sr = &req->sr_msg;
5089 struct compat_iovec __user *uiov;
5094 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5099 uiov = compat_ptr(ptr);
5100 if (req->flags & REQ_F_BUFFER_SELECT) {
5101 compat_ssize_t clen;
5105 if (!access_ok(uiov, sizeof(*uiov)))
5107 if (__get_user(clen, &uiov->iov_len))
5112 iomsg->free_iov = NULL;
5114 iomsg->free_iov = iomsg->fast_iov;
5115 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5116 UIO_FASTIOV, &iomsg->free_iov,
5117 &iomsg->msg.msg_iter, true);
5126 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5127 struct io_async_msghdr *iomsg)
5129 iomsg->msg.msg_name = &iomsg->addr;
5131 #ifdef CONFIG_COMPAT
5132 if (req->ctx->compat)
5133 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5136 return __io_recvmsg_copy_hdr(req, iomsg);
5139 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5142 struct io_sr_msg *sr = &req->sr_msg;
5143 struct io_buffer *kbuf;
5145 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
5150 req->flags |= REQ_F_BUFFER_SELECTED;
5154 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
5156 return io_put_kbuf(req, req->sr_msg.kbuf);
5159 static int io_recvmsg_prep_async(struct io_kiocb *req)
5163 ret = io_recvmsg_copy_hdr(req, req->async_data);
5165 req->flags |= REQ_F_NEED_CLEANUP;
5169 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5171 struct io_sr_msg *sr = &req->sr_msg;
5173 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5175 if (unlikely(sqe->addr2 || sqe->file_index))
5177 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
5180 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5181 sr->len = READ_ONCE(sqe->len);
5182 sr->bgid = READ_ONCE(sqe->buf_group);
5183 sr->msg_flags = READ_ONCE(sqe->msg_flags);
5184 if (sr->msg_flags & MSG_DONTWAIT)
5185 req->flags |= REQ_F_NOWAIT;
5187 #ifdef CONFIG_COMPAT
5188 if (req->ctx->compat)
5189 sr->msg_flags |= MSG_CMSG_COMPAT;
5195 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5197 struct io_async_msghdr iomsg, *kmsg;
5198 struct io_sr_msg *sr = &req->sr_msg;
5199 struct socket *sock;
5200 struct io_buffer *kbuf;
5203 int ret, cflags = 0;
5204 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5206 sock = sock_from_file(req->file);
5207 if (unlikely(!sock))
5210 kmsg = req->async_data;
5212 ret = io_recvmsg_copy_hdr(req, &iomsg);
5218 if (req->flags & REQ_F_BUFFER_SELECT) {
5219 kbuf = io_recv_buffer_select(req, !force_nonblock);
5221 return PTR_ERR(kbuf);
5222 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5223 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5224 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5225 1, req->sr_msg.len);
5228 flags = req->sr_msg.msg_flags;
5230 flags |= MSG_DONTWAIT;
5231 if (flags & MSG_WAITALL && !kmsg->msg.msg_controllen)
5232 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5234 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5235 kmsg->uaddr, flags);
5236 if (ret < min_ret) {
5237 if (ret == -EAGAIN && force_nonblock)
5238 return io_setup_async_msg(req, kmsg);
5239 if (ret == -ERESTARTSYS)
5241 if (ret > 0 && io_net_retry(sock, flags)) {
5243 req->flags |= REQ_F_PARTIAL_IO;
5244 return io_setup_async_msg(req, kmsg);
5247 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5251 if (req->flags & REQ_F_BUFFER_SELECTED)
5252 cflags = io_put_recv_kbuf(req);
5253 /* fast path, check for non-NULL to avoid function call */
5255 kfree(kmsg->free_iov);
5256 req->flags &= ~REQ_F_NEED_CLEANUP;
5259 else if (sr->done_io)
5261 __io_req_complete(req, issue_flags, ret, cflags);
5265 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5267 struct io_buffer *kbuf;
5268 struct io_sr_msg *sr = &req->sr_msg;
5270 void __user *buf = sr->buf;
5271 struct socket *sock;
5275 int ret, cflags = 0;
5276 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5278 sock = sock_from_file(req->file);
5279 if (unlikely(!sock))
5282 if (req->flags & REQ_F_BUFFER_SELECT) {
5283 kbuf = io_recv_buffer_select(req, !force_nonblock);
5285 return PTR_ERR(kbuf);
5286 buf = u64_to_user_ptr(kbuf->addr);
5289 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5293 msg.msg_name = NULL;
5294 msg.msg_control = NULL;
5295 msg.msg_controllen = 0;
5296 msg.msg_namelen = 0;
5297 msg.msg_iocb = NULL;
5300 flags = req->sr_msg.msg_flags;
5302 flags |= MSG_DONTWAIT;
5303 if (flags & MSG_WAITALL)
5304 min_ret = iov_iter_count(&msg.msg_iter);
5306 ret = sock_recvmsg(sock, &msg, flags);
5307 if (ret < min_ret) {
5308 if (ret == -EAGAIN && force_nonblock)
5310 if (ret == -ERESTARTSYS)
5312 if (ret > 0 && io_net_retry(sock, flags)) {
5316 req->flags |= REQ_F_PARTIAL_IO;
5320 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5324 if (req->flags & REQ_F_BUFFER_SELECTED)
5325 cflags = io_put_recv_kbuf(req);
5328 else if (sr->done_io)
5330 __io_req_complete(req, issue_flags, ret, cflags);
5334 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5336 struct io_accept *accept = &req->accept;
5338 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5340 if (sqe->ioprio || sqe->len || sqe->buf_index)
5343 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5344 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5345 accept->flags = READ_ONCE(sqe->accept_flags);
5346 accept->nofile = rlimit(RLIMIT_NOFILE);
5348 accept->file_slot = READ_ONCE(sqe->file_index);
5349 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5351 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5353 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5354 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5358 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5360 struct io_accept *accept = &req->accept;
5361 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5362 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5363 bool fixed = !!accept->file_slot;
5368 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5369 if (unlikely(fd < 0))
5372 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5377 ret = PTR_ERR(file);
5379 req->flags |= REQ_F_PARTIAL_IO;
5380 if (ret == -EAGAIN && force_nonblock)
5382 if (ret == -ERESTARTSYS)
5385 } else if (!fixed) {
5386 fd_install(fd, file);
5389 ret = io_install_fixed_file(req, file, issue_flags,
5390 accept->file_slot - 1);
5392 __io_req_complete(req, issue_flags, ret, 0);
5396 static int io_connect_prep_async(struct io_kiocb *req)
5398 struct io_async_connect *io = req->async_data;
5399 struct io_connect *conn = &req->connect;
5401 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5404 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5406 struct io_connect *conn = &req->connect;
5408 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5410 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5414 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5415 conn->addr_len = READ_ONCE(sqe->addr2);
5419 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5421 struct io_async_connect __io, *io;
5422 unsigned file_flags;
5424 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5426 if (req->async_data) {
5427 io = req->async_data;
5429 ret = move_addr_to_kernel(req->connect.addr,
5430 req->connect.addr_len,
5437 file_flags = force_nonblock ? O_NONBLOCK : 0;
5439 ret = __sys_connect_file(req->file, &io->address,
5440 req->connect.addr_len, file_flags);
5441 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5442 if (req->async_data)
5444 if (io_alloc_async_data(req)) {
5448 memcpy(req->async_data, &__io, sizeof(__io));
5451 if (ret == -ERESTARTSYS)
5456 __io_req_complete(req, issue_flags, ret, 0);
5459 #else /* !CONFIG_NET */
5460 #define IO_NETOP_FN(op) \
5461 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5463 return -EOPNOTSUPP; \
5466 #define IO_NETOP_PREP(op) \
5468 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5470 return -EOPNOTSUPP; \
5473 #define IO_NETOP_PREP_ASYNC(op) \
5475 static int io_##op##_prep_async(struct io_kiocb *req) \
5477 return -EOPNOTSUPP; \
5480 IO_NETOP_PREP_ASYNC(sendmsg);
5481 IO_NETOP_PREP_ASYNC(recvmsg);
5482 IO_NETOP_PREP_ASYNC(connect);
5483 IO_NETOP_PREP(accept);
5486 #endif /* CONFIG_NET */
5488 struct io_poll_table {
5489 struct poll_table_struct pt;
5490 struct io_kiocb *req;
5495 #define IO_POLL_CANCEL_FLAG BIT(31)
5496 #define IO_POLL_RETRY_FLAG BIT(30)
5497 #define IO_POLL_REF_MASK GENMASK(29, 0)
5500 * We usually have 1-2 refs taken, 128 is more than enough and we want to
5501 * maximise the margin between this amount and the moment when it overflows.
5503 #define IO_POLL_REF_BIAS 128
5505 static bool io_poll_get_ownership_slowpath(struct io_kiocb *req)
5510 * poll_refs are already elevated and we don't have much hope for
5511 * grabbing the ownership. Instead of incrementing set a retry flag
5512 * to notify the loop that there might have been some change.
5514 v = atomic_fetch_or(IO_POLL_RETRY_FLAG, &req->poll_refs);
5515 if (v & IO_POLL_REF_MASK)
5517 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5521 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5522 * bump it and acquire ownership. It's disallowed to modify requests while not
5523 * owning it, that prevents from races for enqueueing task_work's and b/w
5524 * arming poll and wakeups.
5526 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5528 if (unlikely(atomic_read(&req->poll_refs) >= IO_POLL_REF_BIAS))
5529 return io_poll_get_ownership_slowpath(req);
5530 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5533 static void io_poll_mark_cancelled(struct io_kiocb *req)
5535 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5538 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5540 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5541 if (req->opcode == IORING_OP_POLL_ADD)
5542 return req->async_data;
5543 return req->apoll->double_poll;
5546 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5548 if (req->opcode == IORING_OP_POLL_ADD)
5550 return &req->apoll->poll;
5553 static void io_poll_req_insert(struct io_kiocb *req)
5555 struct io_ring_ctx *ctx = req->ctx;
5556 struct hlist_head *list;
5558 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5559 hlist_add_head(&req->hash_node, list);
5562 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5563 wait_queue_func_t wake_func)
5566 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5567 /* mask in events that we always want/need */
5568 poll->events = events | IO_POLL_UNMASK;
5569 INIT_LIST_HEAD(&poll->wait.entry);
5570 init_waitqueue_func_entry(&poll->wait, wake_func);
5573 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5575 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5578 spin_lock_irq(&head->lock);
5579 list_del_init(&poll->wait.entry);
5581 spin_unlock_irq(&head->lock);
5585 static void io_poll_remove_entries(struct io_kiocb *req)
5587 struct io_poll_iocb *poll = io_poll_get_single(req);
5588 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5591 * While we hold the waitqueue lock and the waitqueue is nonempty,
5592 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5593 * lock in the first place can race with the waitqueue being freed.
5595 * We solve this as eventpoll does: by taking advantage of the fact that
5596 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5597 * we enter rcu_read_lock() and see that the pointer to the queue is
5598 * non-NULL, we can then lock it without the memory being freed out from
5601 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5602 * case the caller deletes the entry from the queue, leaving it empty.
5603 * In that case, only RCU prevents the queue memory from being freed.
5606 io_poll_remove_entry(poll);
5608 io_poll_remove_entry(poll_double);
5613 * All poll tw should go through this. Checks for poll events, manages
5614 * references, does rewait, etc.
5616 * Returns a negative error on failure. >0 when no action require, which is
5617 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5618 * the request, then the mask is stored in req->result.
5620 static int io_poll_check_events(struct io_kiocb *req)
5622 struct io_ring_ctx *ctx = req->ctx;
5623 struct io_poll_iocb *poll = io_poll_get_single(req);
5626 /* req->task == current here, checking PF_EXITING is safe */
5627 if (unlikely(req->task->flags & PF_EXITING))
5628 io_poll_mark_cancelled(req);
5631 v = atomic_read(&req->poll_refs);
5633 /* tw handler should be the owner, and so have some references */
5634 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5636 if (v & IO_POLL_CANCEL_FLAG)
5639 * cqe.res contains only events of the first wake up
5640 * and all others are be lost. Redo vfs_poll() to get
5643 if ((v & IO_POLL_REF_MASK) != 1)
5645 if (v & IO_POLL_RETRY_FLAG) {
5648 * We won't find new events that came in between
5649 * vfs_poll and the ref put unless we clear the
5652 atomic_andnot(IO_POLL_RETRY_FLAG, &req->poll_refs);
5653 v &= ~IO_POLL_RETRY_FLAG;
5657 struct poll_table_struct pt = { ._key = poll->events };
5659 req->result = vfs_poll(req->file, &pt) & poll->events;
5662 /* multishot, just fill an CQE and proceed */
5663 if (req->result && !(poll->events & EPOLLONESHOT)) {
5664 __poll_t mask = mangle_poll(req->result & poll->events);
5667 spin_lock(&ctx->completion_lock);
5668 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5670 io_commit_cqring(ctx);
5671 spin_unlock(&ctx->completion_lock);
5672 if (unlikely(!filled))
5674 io_cqring_ev_posted(ctx);
5675 } else if (req->result) {
5679 /* force the next iteration to vfs_poll() */
5683 * Release all references, retry if someone tried to restart
5684 * task_work while we were executing it.
5686 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs) &
5692 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5694 struct io_ring_ctx *ctx = req->ctx;
5697 ret = io_poll_check_events(req);
5702 req->result = mangle_poll(req->result & req->poll.events);
5708 io_poll_remove_entries(req);
5709 spin_lock(&ctx->completion_lock);
5710 hash_del(&req->hash_node);
5711 spin_unlock(&ctx->completion_lock);
5712 io_req_complete_post(req, req->result, 0);
5715 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5717 struct io_ring_ctx *ctx = req->ctx;
5720 ret = io_poll_check_events(req);
5724 io_tw_lock(req->ctx, locked);
5725 io_poll_remove_entries(req);
5726 spin_lock(&ctx->completion_lock);
5727 hash_del(&req->hash_node);
5728 spin_unlock(&ctx->completion_lock);
5731 io_req_task_submit(req, locked);
5733 io_req_complete_failed(req, ret);
5736 static void __io_poll_execute(struct io_kiocb *req, int mask)
5739 if (req->opcode == IORING_OP_POLL_ADD)
5740 req->io_task_work.func = io_poll_task_func;
5742 req->io_task_work.func = io_apoll_task_func;
5744 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5745 io_req_task_work_add(req);
5748 static inline void io_poll_execute(struct io_kiocb *req, int res)
5750 if (io_poll_get_ownership(req))
5751 __io_poll_execute(req, res);
5754 static void io_poll_cancel_req(struct io_kiocb *req)
5756 io_poll_mark_cancelled(req);
5757 /* kick tw, which should complete the request */
5758 io_poll_execute(req, 0);
5761 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5764 struct io_kiocb *req = wait->private;
5765 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5767 __poll_t mask = key_to_poll(key);
5769 if (unlikely(mask & POLLFREE)) {
5770 io_poll_mark_cancelled(req);
5771 /* we have to kick tw in case it's not already */
5772 io_poll_execute(req, 0);
5775 * If the waitqueue is being freed early but someone is already
5776 * holds ownership over it, we have to tear down the request as
5777 * best we can. That means immediately removing the request from
5778 * its waitqueue and preventing all further accesses to the
5779 * waitqueue via the request.
5781 list_del_init(&poll->wait.entry);
5784 * Careful: this *must* be the last step, since as soon
5785 * as req->head is NULL'ed out, the request can be
5786 * completed and freed, since aio_poll_complete_work()
5787 * will no longer need to take the waitqueue lock.
5789 smp_store_release(&poll->head, NULL);
5793 /* for instances that support it check for an event match first */
5794 if (mask && !(mask & poll->events))
5797 if (io_poll_get_ownership(req)) {
5799 * If we trigger a multishot poll off our own wakeup path,
5800 * disable multishot as there is a circular dependency between
5801 * CQ posting and triggering the event.
5803 if (mask & EPOLL_URING_WAKE)
5804 poll->events |= EPOLLONESHOT;
5806 __io_poll_execute(req, mask);
5811 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5812 struct wait_queue_head *head,
5813 struct io_poll_iocb **poll_ptr)
5815 struct io_kiocb *req = pt->req;
5818 * The file being polled uses multiple waitqueues for poll handling
5819 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5822 if (unlikely(pt->nr_entries)) {
5823 struct io_poll_iocb *first = poll;
5825 /* double add on the same waitqueue head, ignore */
5826 if (first->head == head)
5828 /* already have a 2nd entry, fail a third attempt */
5830 if ((*poll_ptr)->head == head)
5832 pt->error = -EINVAL;
5836 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5838 pt->error = -ENOMEM;
5841 io_init_poll_iocb(poll, first->events, first->wait.func);
5847 poll->wait.private = req;
5849 if (poll->events & EPOLLEXCLUSIVE)
5850 add_wait_queue_exclusive(head, &poll->wait);
5852 add_wait_queue(head, &poll->wait);
5855 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5856 struct poll_table_struct *p)
5858 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5860 __io_queue_proc(&pt->req->poll, pt, head,
5861 (struct io_poll_iocb **) &pt->req->async_data);
5864 static int __io_arm_poll_handler(struct io_kiocb *req,
5865 struct io_poll_iocb *poll,
5866 struct io_poll_table *ipt, __poll_t mask)
5868 struct io_ring_ctx *ctx = req->ctx;
5870 INIT_HLIST_NODE(&req->hash_node);
5871 io_init_poll_iocb(poll, mask, io_poll_wake);
5872 poll->file = req->file;
5873 poll->wait.private = req;
5875 ipt->pt._key = mask;
5878 ipt->nr_entries = 0;
5881 * Take the ownership to delay any tw execution up until we're done
5882 * with poll arming. see io_poll_get_ownership().
5884 atomic_set(&req->poll_refs, 1);
5885 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5887 if (mask && (poll->events & EPOLLONESHOT)) {
5888 io_poll_remove_entries(req);
5889 /* no one else has access to the req, forget about the ref */
5892 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5893 io_poll_remove_entries(req);
5895 ipt->error = -EINVAL;
5899 spin_lock(&ctx->completion_lock);
5900 io_poll_req_insert(req);
5901 spin_unlock(&ctx->completion_lock);
5904 /* can't multishot if failed, just queue the event we've got */
5905 if (unlikely(ipt->error || !ipt->nr_entries)) {
5906 poll->events |= EPOLLONESHOT;
5909 __io_poll_execute(req, mask);
5914 * Try to release ownership. If we see a change of state, e.g.
5915 * poll was waken up, queue up a tw, it'll deal with it.
5917 if (atomic_cmpxchg(&req->poll_refs, 1, 0) != 1)
5918 __io_poll_execute(req, 0);
5922 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5923 struct poll_table_struct *p)
5925 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5926 struct async_poll *apoll = pt->req->apoll;
5928 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5938 * We can't reliably detect loops in repeated poll triggers and issue
5939 * subsequently failing. But rather than fail these immediately, allow a
5940 * certain amount of retries before we give up. Given that this condition
5941 * should _rarely_ trigger even once, we should be fine with a larger value.
5943 #define APOLL_MAX_RETRY 128
5945 static int io_arm_poll_handler(struct io_kiocb *req)
5947 const struct io_op_def *def = &io_op_defs[req->opcode];
5948 struct io_ring_ctx *ctx = req->ctx;
5949 struct async_poll *apoll;
5950 struct io_poll_table ipt;
5951 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5954 if (!req->file || !file_can_poll(req->file))
5955 return IO_APOLL_ABORTED;
5956 if (!def->pollin && !def->pollout)
5957 return IO_APOLL_ABORTED;
5960 mask |= POLLIN | POLLRDNORM;
5962 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5963 if ((req->opcode == IORING_OP_RECVMSG) &&
5964 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5967 mask |= POLLOUT | POLLWRNORM;
5970 if (req->flags & REQ_F_POLLED) {
5972 kfree(apoll->double_poll);
5973 if (unlikely(!--apoll->poll.retries)) {
5974 apoll->double_poll = NULL;
5975 return IO_APOLL_ABORTED;
5978 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5979 if (unlikely(!apoll))
5980 return IO_APOLL_ABORTED;
5981 apoll->poll.retries = APOLL_MAX_RETRY;
5983 apoll->double_poll = NULL;
5985 req->flags |= REQ_F_POLLED;
5986 ipt.pt._qproc = io_async_queue_proc;
5988 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5989 if (ret || ipt.error)
5990 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5992 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5993 mask, apoll->poll.events);
5998 * Returns true if we found and killed one or more poll requests
6000 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
6003 struct hlist_node *tmp;
6004 struct io_kiocb *req;
6008 spin_lock(&ctx->completion_lock);
6009 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6010 struct hlist_head *list;
6012 list = &ctx->cancel_hash[i];
6013 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6014 if (io_match_task_safe(req, tsk, cancel_all)) {
6015 hlist_del_init(&req->hash_node);
6016 io_poll_cancel_req(req);
6021 spin_unlock(&ctx->completion_lock);
6025 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6027 __must_hold(&ctx->completion_lock)
6029 struct hlist_head *list;
6030 struct io_kiocb *req;
6032 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6033 hlist_for_each_entry(req, list, hash_node) {
6034 if (sqe_addr != req->user_data)
6036 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6043 static bool io_poll_disarm(struct io_kiocb *req)
6044 __must_hold(&ctx->completion_lock)
6046 if (!io_poll_get_ownership(req))
6048 io_poll_remove_entries(req);
6049 hash_del(&req->hash_node);
6053 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6055 __must_hold(&ctx->completion_lock)
6057 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6061 io_poll_cancel_req(req);
6065 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6070 events = READ_ONCE(sqe->poll32_events);
6072 events = swahw32(events);
6074 if (!(flags & IORING_POLL_ADD_MULTI))
6075 events |= EPOLLONESHOT;
6076 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6079 static int io_poll_update_prep(struct io_kiocb *req,
6080 const struct io_uring_sqe *sqe)
6082 struct io_poll_update *upd = &req->poll_update;
6085 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6087 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6089 flags = READ_ONCE(sqe->len);
6090 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6091 IORING_POLL_ADD_MULTI))
6093 /* meaningless without update */
6094 if (flags == IORING_POLL_ADD_MULTI)
6097 upd->old_user_data = READ_ONCE(sqe->addr);
6098 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6099 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6101 upd->new_user_data = READ_ONCE(sqe->off);
6102 if (!upd->update_user_data && upd->new_user_data)
6104 if (upd->update_events)
6105 upd->events = io_poll_parse_events(sqe, flags);
6106 else if (sqe->poll32_events)
6112 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6114 struct io_poll_iocb *poll = &req->poll;
6117 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6119 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6121 flags = READ_ONCE(sqe->len);
6122 if (flags & ~IORING_POLL_ADD_MULTI)
6125 io_req_set_refcount(req);
6126 poll->events = io_poll_parse_events(sqe, flags);
6130 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6132 struct io_poll_iocb *poll = &req->poll;
6133 struct io_poll_table ipt;
6136 ipt.pt._qproc = io_poll_queue_proc;
6138 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6139 if (!ret && ipt.error)
6141 ret = ret ?: ipt.error;
6143 __io_req_complete(req, issue_flags, ret, 0);
6147 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6149 struct io_ring_ctx *ctx = req->ctx;
6150 struct io_kiocb *preq;
6153 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6155 spin_lock(&ctx->completion_lock);
6156 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6157 if (!preq || !io_poll_disarm(preq)) {
6158 spin_unlock(&ctx->completion_lock);
6159 ret = preq ? -EALREADY : -ENOENT;
6162 spin_unlock(&ctx->completion_lock);
6164 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6165 /* only mask one event flags, keep behavior flags */
6166 if (req->poll_update.update_events) {
6167 preq->poll.events &= ~0xffff;
6168 preq->poll.events |= req->poll_update.events & 0xffff;
6169 preq->poll.events |= IO_POLL_UNMASK;
6171 if (req->poll_update.update_user_data)
6172 preq->user_data = req->poll_update.new_user_data;
6174 ret2 = io_poll_add(preq, issue_flags);
6175 /* successfully updated, don't complete poll request */
6180 io_req_complete(preq, -ECANCELED);
6184 /* complete update request, we're done with it */
6185 io_req_complete(req, ret);
6186 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6190 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
6193 io_req_complete_post(req, -ETIME, 0);
6196 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6198 struct io_timeout_data *data = container_of(timer,
6199 struct io_timeout_data, timer);
6200 struct io_kiocb *req = data->req;
6201 struct io_ring_ctx *ctx = req->ctx;
6202 unsigned long flags;
6204 spin_lock_irqsave(&ctx->timeout_lock, flags);
6205 list_del_init(&req->timeout.list);
6206 atomic_set(&req->ctx->cq_timeouts,
6207 atomic_read(&req->ctx->cq_timeouts) + 1);
6208 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6210 req->io_task_work.func = io_req_task_timeout;
6211 io_req_task_work_add(req);
6212 return HRTIMER_NORESTART;
6215 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6217 __must_hold(&ctx->timeout_lock)
6219 struct io_timeout_data *io;
6220 struct io_kiocb *req;
6223 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6224 found = user_data == req->user_data;
6229 return ERR_PTR(-ENOENT);
6231 io = req->async_data;
6232 if (hrtimer_try_to_cancel(&io->timer) == -1)
6233 return ERR_PTR(-EALREADY);
6234 list_del_init(&req->timeout.list);
6238 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6239 __must_hold(&ctx->completion_lock)
6240 __must_hold(&ctx->timeout_lock)
6242 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6245 return PTR_ERR(req);
6248 io_fill_cqe_req(req, -ECANCELED, 0);
6249 io_put_req_deferred(req);
6253 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6255 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6256 case IORING_TIMEOUT_BOOTTIME:
6257 return CLOCK_BOOTTIME;
6258 case IORING_TIMEOUT_REALTIME:
6259 return CLOCK_REALTIME;
6261 /* can't happen, vetted at prep time */
6265 return CLOCK_MONOTONIC;
6269 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6270 struct timespec64 *ts, enum hrtimer_mode mode)
6271 __must_hold(&ctx->timeout_lock)
6273 struct io_timeout_data *io;
6274 struct io_kiocb *req;
6277 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6278 found = user_data == req->user_data;
6285 io = req->async_data;
6286 if (hrtimer_try_to_cancel(&io->timer) == -1)
6288 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6289 io->timer.function = io_link_timeout_fn;
6290 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6294 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6295 struct timespec64 *ts, enum hrtimer_mode mode)
6296 __must_hold(&ctx->timeout_lock)
6298 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6299 struct io_timeout_data *data;
6302 return PTR_ERR(req);
6304 req->timeout.off = 0; /* noseq */
6305 data = req->async_data;
6306 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6307 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6308 data->timer.function = io_timeout_fn;
6309 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6313 static int io_timeout_remove_prep(struct io_kiocb *req,
6314 const struct io_uring_sqe *sqe)
6316 struct io_timeout_rem *tr = &req->timeout_rem;
6318 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6320 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6322 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6325 tr->ltimeout = false;
6326 tr->addr = READ_ONCE(sqe->addr);
6327 tr->flags = READ_ONCE(sqe->timeout_flags);
6328 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6329 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6331 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6332 tr->ltimeout = true;
6333 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6335 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6337 } else if (tr->flags) {
6338 /* timeout removal doesn't support flags */
6345 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6347 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6352 * Remove or update an existing timeout command
6354 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6356 struct io_timeout_rem *tr = &req->timeout_rem;
6357 struct io_ring_ctx *ctx = req->ctx;
6360 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6361 spin_lock(&ctx->completion_lock);
6362 spin_lock_irq(&ctx->timeout_lock);
6363 ret = io_timeout_cancel(ctx, tr->addr);
6364 spin_unlock_irq(&ctx->timeout_lock);
6365 spin_unlock(&ctx->completion_lock);
6367 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6369 spin_lock_irq(&ctx->timeout_lock);
6371 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6373 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6374 spin_unlock_irq(&ctx->timeout_lock);
6379 io_req_complete_post(req, ret, 0);
6383 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6384 bool is_timeout_link)
6386 struct io_timeout_data *data;
6388 u32 off = READ_ONCE(sqe->off);
6390 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6392 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6395 if (off && is_timeout_link)
6397 flags = READ_ONCE(sqe->timeout_flags);
6398 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6400 /* more than one clock specified is invalid, obviously */
6401 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6404 INIT_LIST_HEAD(&req->timeout.list);
6405 req->timeout.off = off;
6406 if (unlikely(off && !req->ctx->off_timeout_used))
6407 req->ctx->off_timeout_used = true;
6409 if (!req->async_data && io_alloc_async_data(req))
6412 data = req->async_data;
6414 data->flags = flags;
6416 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6419 INIT_LIST_HEAD(&req->timeout.list);
6420 data->mode = io_translate_timeout_mode(flags);
6421 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6423 if (is_timeout_link) {
6424 struct io_submit_link *link = &req->ctx->submit_state.link;
6428 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6430 req->timeout.head = link->last;
6431 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6436 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6438 struct io_ring_ctx *ctx = req->ctx;
6439 struct io_timeout_data *data = req->async_data;
6440 struct list_head *entry;
6441 u32 tail, off = req->timeout.off;
6443 spin_lock_irq(&ctx->timeout_lock);
6446 * sqe->off holds how many events that need to occur for this
6447 * timeout event to be satisfied. If it isn't set, then this is
6448 * a pure timeout request, sequence isn't used.
6450 if (io_is_timeout_noseq(req)) {
6451 entry = ctx->timeout_list.prev;
6455 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6456 req->timeout.target_seq = tail + off;
6458 /* Update the last seq here in case io_flush_timeouts() hasn't.
6459 * This is safe because ->completion_lock is held, and submissions
6460 * and completions are never mixed in the same ->completion_lock section.
6462 ctx->cq_last_tm_flush = tail;
6465 * Insertion sort, ensuring the first entry in the list is always
6466 * the one we need first.
6468 list_for_each_prev(entry, &ctx->timeout_list) {
6469 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6472 if (io_is_timeout_noseq(nxt))
6474 /* nxt.seq is behind @tail, otherwise would've been completed */
6475 if (off >= nxt->timeout.target_seq - tail)
6479 list_add(&req->timeout.list, entry);
6480 data->timer.function = io_timeout_fn;
6481 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6482 spin_unlock_irq(&ctx->timeout_lock);
6486 struct io_cancel_data {
6487 struct io_ring_ctx *ctx;
6491 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6493 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6494 struct io_cancel_data *cd = data;
6496 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6499 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6500 struct io_ring_ctx *ctx)
6502 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6503 enum io_wq_cancel cancel_ret;
6506 if (!tctx || !tctx->io_wq)
6509 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6510 switch (cancel_ret) {
6511 case IO_WQ_CANCEL_OK:
6514 case IO_WQ_CANCEL_RUNNING:
6517 case IO_WQ_CANCEL_NOTFOUND:
6525 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6527 struct io_ring_ctx *ctx = req->ctx;
6530 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6532 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6536 spin_lock(&ctx->completion_lock);
6537 spin_lock_irq(&ctx->timeout_lock);
6538 ret = io_timeout_cancel(ctx, sqe_addr);
6539 spin_unlock_irq(&ctx->timeout_lock);
6542 ret = io_poll_cancel(ctx, sqe_addr, false);
6544 spin_unlock(&ctx->completion_lock);
6548 static int io_async_cancel_prep(struct io_kiocb *req,
6549 const struct io_uring_sqe *sqe)
6551 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6553 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6555 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6559 req->cancel.addr = READ_ONCE(sqe->addr);
6563 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6565 struct io_ring_ctx *ctx = req->ctx;
6566 u64 sqe_addr = req->cancel.addr;
6567 struct io_tctx_node *node;
6570 ret = io_try_cancel_userdata(req, sqe_addr);
6574 /* slow path, try all io-wq's */
6575 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6577 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6578 struct io_uring_task *tctx = node->task->io_uring;
6580 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6584 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6588 io_req_complete_post(req, ret, 0);
6592 static int io_rsrc_update_prep(struct io_kiocb *req,
6593 const struct io_uring_sqe *sqe)
6595 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6597 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6600 req->rsrc_update.offset = READ_ONCE(sqe->off);
6601 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6602 if (!req->rsrc_update.nr_args)
6604 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6608 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6610 struct io_ring_ctx *ctx = req->ctx;
6611 struct io_uring_rsrc_update2 up;
6614 up.offset = req->rsrc_update.offset;
6615 up.data = req->rsrc_update.arg;
6621 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6622 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6623 &up, req->rsrc_update.nr_args);
6624 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6628 __io_req_complete(req, issue_flags, ret, 0);
6632 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6634 switch (req->opcode) {
6637 case IORING_OP_READV:
6638 case IORING_OP_READ_FIXED:
6639 case IORING_OP_READ:
6640 return io_read_prep(req, sqe);
6641 case IORING_OP_WRITEV:
6642 case IORING_OP_WRITE_FIXED:
6643 case IORING_OP_WRITE:
6644 return io_write_prep(req, sqe);
6645 case IORING_OP_POLL_ADD:
6646 return io_poll_add_prep(req, sqe);
6647 case IORING_OP_POLL_REMOVE:
6648 return io_poll_update_prep(req, sqe);
6649 case IORING_OP_FSYNC:
6650 return io_fsync_prep(req, sqe);
6651 case IORING_OP_SYNC_FILE_RANGE:
6652 return io_sfr_prep(req, sqe);
6653 case IORING_OP_SENDMSG:
6654 case IORING_OP_SEND:
6655 return io_sendmsg_prep(req, sqe);
6656 case IORING_OP_RECVMSG:
6657 case IORING_OP_RECV:
6658 return io_recvmsg_prep(req, sqe);
6659 case IORING_OP_CONNECT:
6660 return io_connect_prep(req, sqe);
6661 case IORING_OP_TIMEOUT:
6662 return io_timeout_prep(req, sqe, false);
6663 case IORING_OP_TIMEOUT_REMOVE:
6664 return io_timeout_remove_prep(req, sqe);
6665 case IORING_OP_ASYNC_CANCEL:
6666 return io_async_cancel_prep(req, sqe);
6667 case IORING_OP_LINK_TIMEOUT:
6668 return io_timeout_prep(req, sqe, true);
6669 case IORING_OP_ACCEPT:
6670 return io_accept_prep(req, sqe);
6671 case IORING_OP_FALLOCATE:
6672 return io_fallocate_prep(req, sqe);
6673 case IORING_OP_OPENAT:
6674 return io_openat_prep(req, sqe);
6675 case IORING_OP_CLOSE:
6676 return io_close_prep(req, sqe);
6677 case IORING_OP_FILES_UPDATE:
6678 return io_rsrc_update_prep(req, sqe);
6679 case IORING_OP_STATX:
6680 return io_statx_prep(req, sqe);
6681 case IORING_OP_FADVISE:
6682 return io_fadvise_prep(req, sqe);
6683 case IORING_OP_MADVISE:
6684 return io_madvise_prep(req, sqe);
6685 case IORING_OP_OPENAT2:
6686 return io_openat2_prep(req, sqe);
6687 case IORING_OP_EPOLL_CTL:
6688 return io_epoll_ctl_prep(req, sqe);
6689 case IORING_OP_SPLICE:
6690 return io_splice_prep(req, sqe);
6691 case IORING_OP_PROVIDE_BUFFERS:
6692 return io_provide_buffers_prep(req, sqe);
6693 case IORING_OP_REMOVE_BUFFERS:
6694 return io_remove_buffers_prep(req, sqe);
6696 return io_tee_prep(req, sqe);
6697 case IORING_OP_SHUTDOWN:
6698 return io_shutdown_prep(req, sqe);
6699 case IORING_OP_RENAMEAT:
6700 return io_renameat_prep(req, sqe);
6701 case IORING_OP_UNLINKAT:
6702 return io_unlinkat_prep(req, sqe);
6703 case IORING_OP_MKDIRAT:
6704 return io_mkdirat_prep(req, sqe);
6705 case IORING_OP_SYMLINKAT:
6706 return io_symlinkat_prep(req, sqe);
6707 case IORING_OP_LINKAT:
6708 return io_linkat_prep(req, sqe);
6711 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6716 static int io_req_prep_async(struct io_kiocb *req)
6718 if (!io_op_defs[req->opcode].needs_async_setup)
6720 if (WARN_ON_ONCE(req->async_data))
6722 if (io_alloc_async_data(req))
6725 switch (req->opcode) {
6726 case IORING_OP_READV:
6727 return io_rw_prep_async(req, READ);
6728 case IORING_OP_WRITEV:
6729 return io_rw_prep_async(req, WRITE);
6730 case IORING_OP_SENDMSG:
6731 return io_sendmsg_prep_async(req);
6732 case IORING_OP_RECVMSG:
6733 return io_recvmsg_prep_async(req);
6734 case IORING_OP_CONNECT:
6735 return io_connect_prep_async(req);
6737 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6742 static u32 io_get_sequence(struct io_kiocb *req)
6744 u32 seq = req->ctx->cached_sq_head;
6746 /* need original cached_sq_head, but it was increased for each req */
6747 io_for_each_link(req, req)
6752 static bool io_drain_req(struct io_kiocb *req)
6754 struct io_kiocb *pos;
6755 struct io_ring_ctx *ctx = req->ctx;
6756 struct io_defer_entry *de;
6760 if (req->flags & REQ_F_FAIL) {
6761 io_req_complete_fail_submit(req);
6766 * If we need to drain a request in the middle of a link, drain the
6767 * head request and the next request/link after the current link.
6768 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6769 * maintained for every request of our link.
6771 if (ctx->drain_next) {
6772 req->flags |= REQ_F_IO_DRAIN;
6773 ctx->drain_next = false;
6775 /* not interested in head, start from the first linked */
6776 io_for_each_link(pos, req->link) {
6777 if (pos->flags & REQ_F_IO_DRAIN) {
6778 ctx->drain_next = true;
6779 req->flags |= REQ_F_IO_DRAIN;
6784 /* Still need defer if there is pending req in defer list. */
6785 spin_lock(&ctx->completion_lock);
6786 if (likely(list_empty_careful(&ctx->defer_list) &&
6787 !(req->flags & REQ_F_IO_DRAIN))) {
6788 spin_unlock(&ctx->completion_lock);
6789 ctx->drain_active = false;
6792 spin_unlock(&ctx->completion_lock);
6794 seq = io_get_sequence(req);
6795 /* Still a chance to pass the sequence check */
6796 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6799 ret = io_req_prep_async(req);
6802 io_prep_async_link(req);
6803 de = kmalloc(sizeof(*de), GFP_KERNEL);
6807 io_req_complete_failed(req, ret);
6811 spin_lock(&ctx->completion_lock);
6812 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6813 spin_unlock(&ctx->completion_lock);
6815 io_queue_async_work(req, NULL);
6819 trace_io_uring_defer(ctx, req, req->user_data);
6822 list_add_tail(&de->list, &ctx->defer_list);
6823 spin_unlock(&ctx->completion_lock);
6827 static void io_clean_op(struct io_kiocb *req)
6829 if (req->flags & REQ_F_BUFFER_SELECTED) {
6830 switch (req->opcode) {
6831 case IORING_OP_READV:
6832 case IORING_OP_READ_FIXED:
6833 case IORING_OP_READ:
6834 kfree((void *)(unsigned long)req->rw.addr);
6836 case IORING_OP_RECVMSG:
6837 case IORING_OP_RECV:
6838 kfree(req->sr_msg.kbuf);
6843 if (req->flags & REQ_F_NEED_CLEANUP) {
6844 switch (req->opcode) {
6845 case IORING_OP_READV:
6846 case IORING_OP_READ_FIXED:
6847 case IORING_OP_READ:
6848 case IORING_OP_WRITEV:
6849 case IORING_OP_WRITE_FIXED:
6850 case IORING_OP_WRITE: {
6851 struct io_async_rw *io = req->async_data;
6853 kfree(io->free_iovec);
6856 case IORING_OP_RECVMSG:
6857 case IORING_OP_SENDMSG: {
6858 struct io_async_msghdr *io = req->async_data;
6860 kfree(io->free_iov);
6863 case IORING_OP_OPENAT:
6864 case IORING_OP_OPENAT2:
6865 if (req->open.filename)
6866 putname(req->open.filename);
6868 case IORING_OP_RENAMEAT:
6869 putname(req->rename.oldpath);
6870 putname(req->rename.newpath);
6872 case IORING_OP_UNLINKAT:
6873 putname(req->unlink.filename);
6875 case IORING_OP_MKDIRAT:
6876 putname(req->mkdir.filename);
6878 case IORING_OP_SYMLINKAT:
6879 putname(req->symlink.oldpath);
6880 putname(req->symlink.newpath);
6882 case IORING_OP_LINKAT:
6883 putname(req->hardlink.oldpath);
6884 putname(req->hardlink.newpath);
6888 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6889 kfree(req->apoll->double_poll);
6893 if (req->flags & REQ_F_INFLIGHT) {
6894 struct io_uring_task *tctx = req->task->io_uring;
6896 atomic_dec(&tctx->inflight_tracked);
6898 if (req->flags & REQ_F_CREDS)
6899 put_cred(req->creds);
6901 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6904 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6906 struct io_ring_ctx *ctx = req->ctx;
6907 const struct cred *creds = NULL;
6910 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6911 creds = override_creds(req->creds);
6913 switch (req->opcode) {
6915 ret = io_nop(req, issue_flags);
6917 case IORING_OP_READV:
6918 case IORING_OP_READ_FIXED:
6919 case IORING_OP_READ:
6920 ret = io_read(req, issue_flags);
6922 case IORING_OP_WRITEV:
6923 case IORING_OP_WRITE_FIXED:
6924 case IORING_OP_WRITE:
6925 ret = io_write(req, issue_flags);
6927 case IORING_OP_FSYNC:
6928 ret = io_fsync(req, issue_flags);
6930 case IORING_OP_POLL_ADD:
6931 ret = io_poll_add(req, issue_flags);
6933 case IORING_OP_POLL_REMOVE:
6934 ret = io_poll_update(req, issue_flags);
6936 case IORING_OP_SYNC_FILE_RANGE:
6937 ret = io_sync_file_range(req, issue_flags);
6939 case IORING_OP_SENDMSG:
6940 ret = io_sendmsg(req, issue_flags);
6942 case IORING_OP_SEND:
6943 ret = io_send(req, issue_flags);
6945 case IORING_OP_RECVMSG:
6946 ret = io_recvmsg(req, issue_flags);
6948 case IORING_OP_RECV:
6949 ret = io_recv(req, issue_flags);
6951 case IORING_OP_TIMEOUT:
6952 ret = io_timeout(req, issue_flags);
6954 case IORING_OP_TIMEOUT_REMOVE:
6955 ret = io_timeout_remove(req, issue_flags);
6957 case IORING_OP_ACCEPT:
6958 ret = io_accept(req, issue_flags);
6960 case IORING_OP_CONNECT:
6961 ret = io_connect(req, issue_flags);
6963 case IORING_OP_ASYNC_CANCEL:
6964 ret = io_async_cancel(req, issue_flags);
6966 case IORING_OP_FALLOCATE:
6967 ret = io_fallocate(req, issue_flags);
6969 case IORING_OP_OPENAT:
6970 ret = io_openat(req, issue_flags);
6972 case IORING_OP_CLOSE:
6973 ret = io_close(req, issue_flags);
6975 case IORING_OP_FILES_UPDATE:
6976 ret = io_files_update(req, issue_flags);
6978 case IORING_OP_STATX:
6979 ret = io_statx(req, issue_flags);
6981 case IORING_OP_FADVISE:
6982 ret = io_fadvise(req, issue_flags);
6984 case IORING_OP_MADVISE:
6985 ret = io_madvise(req, issue_flags);
6987 case IORING_OP_OPENAT2:
6988 ret = io_openat2(req, issue_flags);
6990 case IORING_OP_EPOLL_CTL:
6991 ret = io_epoll_ctl(req, issue_flags);
6993 case IORING_OP_SPLICE:
6994 ret = io_splice(req, issue_flags);
6996 case IORING_OP_PROVIDE_BUFFERS:
6997 ret = io_provide_buffers(req, issue_flags);
6999 case IORING_OP_REMOVE_BUFFERS:
7000 ret = io_remove_buffers(req, issue_flags);
7003 ret = io_tee(req, issue_flags);
7005 case IORING_OP_SHUTDOWN:
7006 ret = io_shutdown(req, issue_flags);
7008 case IORING_OP_RENAMEAT:
7009 ret = io_renameat(req, issue_flags);
7011 case IORING_OP_UNLINKAT:
7012 ret = io_unlinkat(req, issue_flags);
7014 case IORING_OP_MKDIRAT:
7015 ret = io_mkdirat(req, issue_flags);
7017 case IORING_OP_SYMLINKAT:
7018 ret = io_symlinkat(req, issue_flags);
7020 case IORING_OP_LINKAT:
7021 ret = io_linkat(req, issue_flags);
7029 revert_creds(creds);
7032 /* If the op doesn't have a file, we're not polling for it */
7033 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7034 io_iopoll_req_issued(req);
7039 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7041 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7043 req = io_put_req_find_next(req);
7044 return req ? &req->work : NULL;
7047 static void io_wq_submit_work(struct io_wq_work *work)
7049 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7050 struct io_kiocb *timeout;
7053 /* one will be dropped by ->io_free_work() after returning to io-wq */
7054 if (!(req->flags & REQ_F_REFCOUNT))
7055 __io_req_set_refcount(req, 2);
7059 timeout = io_prep_linked_timeout(req);
7061 io_queue_linked_timeout(timeout);
7063 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7064 if (work->flags & IO_WQ_WORK_CANCEL)
7069 ret = io_issue_sqe(req, 0);
7071 * We can get EAGAIN for polled IO even though we're
7072 * forcing a sync submission from here, since we can't
7073 * wait for request slots on the block side.
7075 if (ret != -EAGAIN || !(req->ctx->flags & IORING_SETUP_IOPOLL))
7077 if (io_wq_worker_stopped())
7080 * If REQ_F_NOWAIT is set, then don't wait or retry with
7081 * poll. -EAGAIN is final for that case.
7083 if (req->flags & REQ_F_NOWAIT)
7090 /* avoid locking problems by failing it from a clean context */
7092 io_req_task_queue_fail(req, ret);
7095 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7098 return &table->files[i];
7101 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7104 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7106 return (struct file *) (slot->file_ptr & FFS_MASK);
7109 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7111 unsigned long file_ptr = (unsigned long) file;
7113 if (__io_file_supports_nowait(file, READ))
7114 file_ptr |= FFS_ASYNC_READ;
7115 if (__io_file_supports_nowait(file, WRITE))
7116 file_ptr |= FFS_ASYNC_WRITE;
7117 if (S_ISREG(file_inode(file)->i_mode))
7118 file_ptr |= FFS_ISREG;
7119 file_slot->file_ptr = file_ptr;
7122 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7123 struct io_kiocb *req, int fd,
7124 unsigned int issue_flags)
7126 struct file *file = NULL;
7127 unsigned long file_ptr;
7129 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
7131 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7133 fd = array_index_nospec(fd, ctx->nr_user_files);
7134 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7135 file = (struct file *) (file_ptr & FFS_MASK);
7136 file_ptr &= ~FFS_MASK;
7137 /* mask in overlapping REQ_F and FFS bits */
7138 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
7139 io_req_set_rsrc_node(req);
7141 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
7145 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7146 struct io_kiocb *req, int fd)
7148 struct file *file = fget(fd);
7150 trace_io_uring_file_get(ctx, fd);
7152 /* we don't allow fixed io_uring files */
7153 if (file && unlikely(file->f_op == &io_uring_fops))
7154 io_req_track_inflight(req);
7158 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7159 struct io_kiocb *req, int fd, bool fixed,
7160 unsigned int issue_flags)
7163 return io_file_get_fixed(ctx, req, fd, issue_flags);
7165 return io_file_get_normal(ctx, req, fd);
7168 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7170 struct io_kiocb *prev = req->timeout.prev;
7174 if (!(req->task->flags & PF_EXITING))
7175 ret = io_try_cancel_userdata(req, prev->user_data);
7176 io_req_complete_post(req, ret ?: -ETIME, 0);
7179 io_req_complete_post(req, -ETIME, 0);
7183 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7185 struct io_timeout_data *data = container_of(timer,
7186 struct io_timeout_data, timer);
7187 struct io_kiocb *prev, *req = data->req;
7188 struct io_ring_ctx *ctx = req->ctx;
7189 unsigned long flags;
7191 spin_lock_irqsave(&ctx->timeout_lock, flags);
7192 prev = req->timeout.head;
7193 req->timeout.head = NULL;
7196 * We don't expect the list to be empty, that will only happen if we
7197 * race with the completion of the linked work.
7200 io_remove_next_linked(prev);
7201 if (!req_ref_inc_not_zero(prev))
7204 list_del(&req->timeout.list);
7205 req->timeout.prev = prev;
7206 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7208 req->io_task_work.func = io_req_task_link_timeout;
7209 io_req_task_work_add(req);
7210 return HRTIMER_NORESTART;
7213 static void io_queue_linked_timeout(struct io_kiocb *req)
7215 struct io_ring_ctx *ctx = req->ctx;
7217 spin_lock_irq(&ctx->timeout_lock);
7219 * If the back reference is NULL, then our linked request finished
7220 * before we got a chance to setup the timer
7222 if (req->timeout.head) {
7223 struct io_timeout_data *data = req->async_data;
7225 data->timer.function = io_link_timeout_fn;
7226 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7228 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7230 spin_unlock_irq(&ctx->timeout_lock);
7231 /* drop submission reference */
7235 static void __io_queue_sqe(struct io_kiocb *req)
7236 __must_hold(&req->ctx->uring_lock)
7238 struct io_kiocb *linked_timeout;
7242 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7245 * We async punt it if the file wasn't marked NOWAIT, or if the file
7246 * doesn't support non-blocking read/write attempts
7249 if (req->flags & REQ_F_COMPLETE_INLINE) {
7250 struct io_ring_ctx *ctx = req->ctx;
7251 struct io_submit_state *state = &ctx->submit_state;
7253 state->compl_reqs[state->compl_nr++] = req;
7254 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
7255 io_submit_flush_completions(ctx);
7259 linked_timeout = io_prep_linked_timeout(req);
7261 io_queue_linked_timeout(linked_timeout);
7262 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7263 linked_timeout = io_prep_linked_timeout(req);
7265 switch (io_arm_poll_handler(req)) {
7266 case IO_APOLL_READY:
7268 io_queue_linked_timeout(linked_timeout);
7270 case IO_APOLL_ABORTED:
7272 * Queued up for async execution, worker will release
7273 * submit reference when the iocb is actually submitted.
7275 io_queue_async_work(req, NULL);
7280 io_queue_linked_timeout(linked_timeout);
7282 io_req_complete_failed(req, ret);
7286 static inline void io_queue_sqe(struct io_kiocb *req)
7287 __must_hold(&req->ctx->uring_lock)
7289 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
7292 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
7293 __io_queue_sqe(req);
7294 } else if (req->flags & REQ_F_FAIL) {
7295 io_req_complete_fail_submit(req);
7297 int ret = io_req_prep_async(req);
7300 io_req_complete_failed(req, ret);
7302 io_queue_async_work(req, NULL);
7307 * Check SQE restrictions (opcode and flags).
7309 * Returns 'true' if SQE is allowed, 'false' otherwise.
7311 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7312 struct io_kiocb *req,
7313 unsigned int sqe_flags)
7315 if (likely(!ctx->restricted))
7318 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7321 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7322 ctx->restrictions.sqe_flags_required)
7325 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7326 ctx->restrictions.sqe_flags_required))
7332 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7333 const struct io_uring_sqe *sqe)
7334 __must_hold(&ctx->uring_lock)
7336 struct io_submit_state *state;
7337 unsigned int sqe_flags;
7338 int personality, ret = 0;
7340 /* req is partially pre-initialised, see io_preinit_req() */
7341 req->opcode = READ_ONCE(sqe->opcode);
7342 /* same numerical values with corresponding REQ_F_*, safe to copy */
7343 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7344 req->user_data = READ_ONCE(sqe->user_data);
7346 req->fixed_rsrc_refs = NULL;
7347 req->task = current;
7349 /* enforce forwards compatibility on users */
7350 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
7352 if (unlikely(req->opcode >= IORING_OP_LAST))
7354 if (!io_check_restriction(ctx, req, sqe_flags))
7357 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7358 !io_op_defs[req->opcode].buffer_select)
7360 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
7361 ctx->drain_active = true;
7363 personality = READ_ONCE(sqe->personality);
7365 req->creds = xa_load(&ctx->personalities, personality);
7368 get_cred(req->creds);
7369 req->flags |= REQ_F_CREDS;
7371 state = &ctx->submit_state;
7374 * Plug now if we have more than 1 IO left after this, and the target
7375 * is potentially a read/write to block based storage.
7377 if (!state->plug_started && state->ios_left > 1 &&
7378 io_op_defs[req->opcode].plug) {
7379 blk_start_plug(&state->plug);
7380 state->plug_started = true;
7383 if (io_op_defs[req->opcode].needs_file) {
7384 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7385 (sqe_flags & IOSQE_FIXED_FILE),
7386 IO_URING_F_NONBLOCK);
7387 if (unlikely(!req->file))
7395 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7396 const struct io_uring_sqe *sqe)
7397 __must_hold(&ctx->uring_lock)
7399 struct io_submit_link *link = &ctx->submit_state.link;
7402 ret = io_init_req(ctx, req, sqe);
7403 if (unlikely(ret)) {
7405 /* fail even hard links since we don't submit */
7408 * we can judge a link req is failed or cancelled by if
7409 * REQ_F_FAIL is set, but the head is an exception since
7410 * it may be set REQ_F_FAIL because of other req's failure
7411 * so let's leverage req->result to distinguish if a head
7412 * is set REQ_F_FAIL because of its failure or other req's
7413 * failure so that we can set the correct ret code for it.
7414 * init result here to avoid affecting the normal path.
7416 if (!(link->head->flags & REQ_F_FAIL))
7417 req_fail_link_node(link->head, -ECANCELED);
7418 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7420 * the current req is a normal req, we should return
7421 * error and thus break the submittion loop.
7423 io_req_complete_failed(req, ret);
7426 req_fail_link_node(req, ret);
7428 ret = io_req_prep(req, sqe);
7433 /* don't need @sqe from now on */
7434 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7436 ctx->flags & IORING_SETUP_SQPOLL);
7439 * If we already have a head request, queue this one for async
7440 * submittal once the head completes. If we don't have a head but
7441 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7442 * submitted sync once the chain is complete. If none of those
7443 * conditions are true (normal request), then just queue it.
7446 struct io_kiocb *head = link->head;
7448 if (!(req->flags & REQ_F_FAIL)) {
7449 ret = io_req_prep_async(req);
7450 if (unlikely(ret)) {
7451 req_fail_link_node(req, ret);
7452 if (!(head->flags & REQ_F_FAIL))
7453 req_fail_link_node(head, -ECANCELED);
7456 trace_io_uring_link(ctx, req, head);
7457 link->last->link = req;
7460 /* last request of a link, enqueue the link */
7461 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7466 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7478 * Batched submission is done, ensure local IO is flushed out.
7480 static void io_submit_state_end(struct io_submit_state *state,
7481 struct io_ring_ctx *ctx)
7483 if (state->link.head)
7484 io_queue_sqe(state->link.head);
7485 if (state->compl_nr)
7486 io_submit_flush_completions(ctx);
7487 if (state->plug_started)
7488 blk_finish_plug(&state->plug);
7492 * Start submission side cache.
7494 static void io_submit_state_start(struct io_submit_state *state,
7495 unsigned int max_ios)
7497 state->plug_started = false;
7498 state->ios_left = max_ios;
7499 /* set only head, no need to init link_last in advance */
7500 state->link.head = NULL;
7503 static void io_commit_sqring(struct io_ring_ctx *ctx)
7505 struct io_rings *rings = ctx->rings;
7508 * Ensure any loads from the SQEs are done at this point,
7509 * since once we write the new head, the application could
7510 * write new data to them.
7512 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7516 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7517 * that is mapped by userspace. This means that care needs to be taken to
7518 * ensure that reads are stable, as we cannot rely on userspace always
7519 * being a good citizen. If members of the sqe are validated and then later
7520 * used, it's important that those reads are done through READ_ONCE() to
7521 * prevent a re-load down the line.
7523 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7525 unsigned head, mask = ctx->sq_entries - 1;
7526 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7529 * The cached sq head (or cq tail) serves two purposes:
7531 * 1) allows us to batch the cost of updating the user visible
7533 * 2) allows the kernel side to track the head on its own, even
7534 * though the application is the one updating it.
7536 head = READ_ONCE(ctx->sq_array[sq_idx]);
7537 if (likely(head < ctx->sq_entries))
7538 return &ctx->sq_sqes[head];
7540 /* drop invalid entries */
7541 spin_lock(&ctx->completion_lock);
7543 spin_unlock(&ctx->completion_lock);
7544 WRITE_ONCE(ctx->rings->sq_dropped,
7545 READ_ONCE(ctx->rings->sq_dropped) + 1);
7549 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7550 __must_hold(&ctx->uring_lock)
7554 /* make sure SQ entry isn't read before tail */
7555 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7556 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7558 io_get_task_refs(nr);
7560 io_submit_state_start(&ctx->submit_state, nr);
7561 while (submitted < nr) {
7562 const struct io_uring_sqe *sqe;
7563 struct io_kiocb *req;
7565 req = io_alloc_req(ctx);
7566 if (unlikely(!req)) {
7568 submitted = -EAGAIN;
7571 sqe = io_get_sqe(ctx);
7572 if (unlikely(!sqe)) {
7573 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7576 /* will complete beyond this point, count as submitted */
7578 if (io_submit_sqe(ctx, req, sqe))
7582 if (unlikely(submitted != nr)) {
7583 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7584 int unused = nr - ref_used;
7586 current->io_uring->cached_refs += unused;
7587 percpu_ref_put_many(&ctx->refs, unused);
7590 io_submit_state_end(&ctx->submit_state, ctx);
7591 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7592 io_commit_sqring(ctx);
7597 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7599 return READ_ONCE(sqd->state);
7602 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7604 /* Tell userspace we may need a wakeup call */
7605 spin_lock(&ctx->completion_lock);
7606 WRITE_ONCE(ctx->rings->sq_flags,
7607 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7608 spin_unlock(&ctx->completion_lock);
7611 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7613 spin_lock(&ctx->completion_lock);
7614 WRITE_ONCE(ctx->rings->sq_flags,
7615 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7616 spin_unlock(&ctx->completion_lock);
7619 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7621 unsigned int to_submit;
7624 to_submit = io_sqring_entries(ctx);
7625 /* if we're handling multiple rings, cap submit size for fairness */
7626 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7627 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7629 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7630 unsigned nr_events = 0;
7631 const struct cred *creds = NULL;
7633 if (ctx->sq_creds != current_cred())
7634 creds = override_creds(ctx->sq_creds);
7636 mutex_lock(&ctx->uring_lock);
7637 if (!list_empty(&ctx->iopoll_list))
7638 io_do_iopoll(ctx, &nr_events, 0);
7641 * Don't submit if refs are dying, good for io_uring_register(),
7642 * but also it is relied upon by io_ring_exit_work()
7644 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7645 !(ctx->flags & IORING_SETUP_R_DISABLED))
7646 ret = io_submit_sqes(ctx, to_submit);
7647 mutex_unlock(&ctx->uring_lock);
7649 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7650 wake_up(&ctx->sqo_sq_wait);
7652 revert_creds(creds);
7658 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7660 struct io_ring_ctx *ctx;
7661 unsigned sq_thread_idle = 0;
7663 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7664 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7665 sqd->sq_thread_idle = sq_thread_idle;
7668 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7670 bool did_sig = false;
7671 struct ksignal ksig;
7673 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7674 signal_pending(current)) {
7675 mutex_unlock(&sqd->lock);
7676 if (signal_pending(current))
7677 did_sig = get_signal(&ksig);
7679 mutex_lock(&sqd->lock);
7681 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7684 static int io_sq_thread(void *data)
7686 struct io_sq_data *sqd = data;
7687 struct io_ring_ctx *ctx;
7688 unsigned long timeout = 0;
7689 char buf[TASK_COMM_LEN];
7692 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7693 set_task_comm(current, buf);
7695 if (sqd->sq_cpu != -1)
7696 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7698 set_cpus_allowed_ptr(current, cpu_online_mask);
7699 current->flags |= PF_NO_SETAFFINITY;
7701 mutex_lock(&sqd->lock);
7703 bool cap_entries, sqt_spin = false;
7705 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7706 if (io_sqd_handle_event(sqd))
7708 timeout = jiffies + sqd->sq_thread_idle;
7711 cap_entries = !list_is_singular(&sqd->ctx_list);
7712 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7713 int ret = __io_sq_thread(ctx, cap_entries);
7715 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7718 if (io_run_task_work())
7721 if (sqt_spin || !time_after(jiffies, timeout)) {
7724 timeout = jiffies + sqd->sq_thread_idle;
7728 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7729 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7730 bool needs_sched = true;
7732 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7733 io_ring_set_wakeup_flag(ctx);
7735 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7736 !list_empty_careful(&ctx->iopoll_list)) {
7737 needs_sched = false;
7740 if (io_sqring_entries(ctx)) {
7741 needs_sched = false;
7747 mutex_unlock(&sqd->lock);
7749 mutex_lock(&sqd->lock);
7751 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7752 io_ring_clear_wakeup_flag(ctx);
7755 finish_wait(&sqd->wait, &wait);
7756 timeout = jiffies + sqd->sq_thread_idle;
7759 io_uring_cancel_generic(true, sqd);
7761 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7762 io_ring_set_wakeup_flag(ctx);
7764 mutex_unlock(&sqd->lock);
7766 complete(&sqd->exited);
7770 struct io_wait_queue {
7771 struct wait_queue_entry wq;
7772 struct io_ring_ctx *ctx;
7774 unsigned nr_timeouts;
7777 static inline bool io_should_wake(struct io_wait_queue *iowq)
7779 struct io_ring_ctx *ctx = iowq->ctx;
7780 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7783 * Wake up if we have enough events, or if a timeout occurred since we
7784 * started waiting. For timeouts, we always want to return to userspace,
7785 * regardless of event count.
7787 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7790 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7791 int wake_flags, void *key)
7793 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7797 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7798 * the task, and the next invocation will do it.
7800 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7801 return autoremove_wake_function(curr, mode, wake_flags, key);
7805 static int io_run_task_work_sig(void)
7807 if (io_run_task_work())
7809 if (!signal_pending(current))
7811 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7812 return -ERESTARTSYS;
7816 static bool current_pending_io(void)
7818 struct io_uring_task *tctx = current->io_uring;
7822 return percpu_counter_read_positive(&tctx->inflight);
7825 /* when returns >0, the caller should retry */
7826 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7827 struct io_wait_queue *iowq,
7832 /* make sure we run task_work before checking for signals */
7833 ret = io_run_task_work_sig();
7834 if (ret || io_should_wake(iowq))
7836 /* let the caller flush overflows, retry */
7837 if (test_bit(0, &ctx->check_cq_overflow))
7841 * Mark us as being in io_wait if we have pending requests, so cpufreq
7842 * can take into account that the task is waiting for IO - turns out
7843 * to be important for low QD IO.
7845 io_wait = current->in_iowait;
7846 if (current_pending_io())
7847 current->in_iowait = 1;
7849 if (!schedule_hrtimeout(timeout, HRTIMER_MODE_ABS))
7851 current->in_iowait = io_wait;
7856 * Wait until events become available, if we don't already have some. The
7857 * application must reap them itself, as they reside on the shared cq ring.
7859 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7860 const sigset_t __user *sig, size_t sigsz,
7861 struct __kernel_timespec __user *uts)
7863 struct io_wait_queue iowq;
7864 struct io_rings *rings = ctx->rings;
7865 ktime_t timeout = KTIME_MAX;
7869 io_cqring_overflow_flush(ctx);
7870 if (io_cqring_events(ctx) >= min_events)
7872 if (!io_run_task_work())
7877 struct timespec64 ts;
7879 if (get_timespec64(&ts, uts))
7881 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7885 #ifdef CONFIG_COMPAT
7886 if (in_compat_syscall())
7887 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7891 ret = set_user_sigmask(sig, sigsz);
7897 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7898 iowq.wq.private = current;
7899 INIT_LIST_HEAD(&iowq.wq.entry);
7901 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7902 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7904 trace_io_uring_cqring_wait(ctx, min_events);
7906 /* if we can't even flush overflow, don't wait for more */
7907 if (!io_cqring_overflow_flush(ctx)) {
7911 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7912 TASK_INTERRUPTIBLE);
7913 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7914 finish_wait(&ctx->cq_wait, &iowq.wq);
7918 restore_saved_sigmask_unless(ret == -EINTR);
7920 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7923 static void io_free_page_table(void **table, size_t size)
7925 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7927 for (i = 0; i < nr_tables; i++)
7932 static void **io_alloc_page_table(size_t size)
7934 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7935 size_t init_size = size;
7938 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7942 for (i = 0; i < nr_tables; i++) {
7943 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7945 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7947 io_free_page_table(table, init_size);
7955 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7957 percpu_ref_exit(&ref_node->refs);
7961 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7963 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7964 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7965 unsigned long flags;
7966 bool first_add = false;
7967 unsigned long delay = HZ;
7969 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7972 /* if we are mid-quiesce then do not delay */
7973 if (node->rsrc_data->quiesce)
7976 while (!list_empty(&ctx->rsrc_ref_list)) {
7977 node = list_first_entry(&ctx->rsrc_ref_list,
7978 struct io_rsrc_node, node);
7979 /* recycle ref nodes in order */
7982 list_del(&node->node);
7983 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7985 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7988 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7991 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7993 struct io_rsrc_node *ref_node;
7995 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7999 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8004 INIT_LIST_HEAD(&ref_node->node);
8005 INIT_LIST_HEAD(&ref_node->rsrc_list);
8006 ref_node->done = false;
8010 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8011 struct io_rsrc_data *data_to_kill)
8013 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8014 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8017 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8019 rsrc_node->rsrc_data = data_to_kill;
8020 spin_lock_irq(&ctx->rsrc_ref_lock);
8021 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8022 spin_unlock_irq(&ctx->rsrc_ref_lock);
8024 atomic_inc(&data_to_kill->refs);
8025 percpu_ref_kill(&rsrc_node->refs);
8026 ctx->rsrc_node = NULL;
8029 if (!ctx->rsrc_node) {
8030 ctx->rsrc_node = ctx->rsrc_backup_node;
8031 ctx->rsrc_backup_node = NULL;
8035 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8037 if (ctx->rsrc_backup_node)
8039 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
8040 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8043 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
8047 /* As we may drop ->uring_lock, other task may have started quiesce */
8051 data->quiesce = true;
8053 ret = io_rsrc_node_switch_start(ctx);
8056 io_rsrc_node_switch(ctx, data);
8058 /* kill initial ref, already quiesced if zero */
8059 if (atomic_dec_and_test(&data->refs))
8061 mutex_unlock(&ctx->uring_lock);
8062 flush_delayed_work(&ctx->rsrc_put_work);
8063 ret = wait_for_completion_interruptible(&data->done);
8065 mutex_lock(&ctx->uring_lock);
8066 if (atomic_read(&data->refs) > 0) {
8068 * it has been revived by another thread while
8071 mutex_unlock(&ctx->uring_lock);
8077 atomic_inc(&data->refs);
8078 /* wait for all works potentially completing data->done */
8079 flush_delayed_work(&ctx->rsrc_put_work);
8080 reinit_completion(&data->done);
8082 ret = io_run_task_work_sig();
8083 mutex_lock(&ctx->uring_lock);
8085 data->quiesce = false;
8090 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8092 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8093 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8095 return &data->tags[table_idx][off];
8098 static void io_rsrc_data_free(struct io_rsrc_data *data)
8100 size_t size = data->nr * sizeof(data->tags[0][0]);
8103 io_free_page_table((void **)data->tags, size);
8107 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8108 u64 __user *utags, unsigned nr,
8109 struct io_rsrc_data **pdata)
8111 struct io_rsrc_data *data;
8115 data = kzalloc(sizeof(*data), GFP_KERNEL);
8118 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8126 data->do_put = do_put;
8129 for (i = 0; i < nr; i++) {
8130 u64 *tag_slot = io_get_tag_slot(data, i);
8132 if (copy_from_user(tag_slot, &utags[i],
8138 atomic_set(&data->refs, 1);
8139 init_completion(&data->done);
8143 io_rsrc_data_free(data);
8147 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8149 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8150 GFP_KERNEL_ACCOUNT);
8151 return !!table->files;
8154 static void io_free_file_tables(struct io_file_table *table)
8156 kvfree(table->files);
8157 table->files = NULL;
8160 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8162 #if defined(CONFIG_UNIX)
8163 if (ctx->ring_sock) {
8164 struct sock *sock = ctx->ring_sock->sk;
8165 struct sk_buff *skb;
8167 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8173 for (i = 0; i < ctx->nr_user_files; i++) {
8176 file = io_file_from_index(ctx, i);
8181 io_free_file_tables(&ctx->file_table);
8182 io_rsrc_data_free(ctx->file_data);
8183 ctx->file_data = NULL;
8184 ctx->nr_user_files = 0;
8187 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8189 unsigned nr = ctx->nr_user_files;
8192 if (!ctx->file_data)
8196 * Quiesce may unlock ->uring_lock, and while it's not held
8197 * prevent new requests using the table.
8199 ctx->nr_user_files = 0;
8200 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8201 ctx->nr_user_files = nr;
8203 __io_sqe_files_unregister(ctx);
8207 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8208 __releases(&sqd->lock)
8210 WARN_ON_ONCE(sqd->thread == current);
8213 * Do the dance but not conditional clear_bit() because it'd race with
8214 * other threads incrementing park_pending and setting the bit.
8216 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8217 if (atomic_dec_return(&sqd->park_pending))
8218 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8219 mutex_unlock(&sqd->lock);
8222 static void io_sq_thread_park(struct io_sq_data *sqd)
8223 __acquires(&sqd->lock)
8225 WARN_ON_ONCE(sqd->thread == current);
8227 atomic_inc(&sqd->park_pending);
8228 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8229 mutex_lock(&sqd->lock);
8231 wake_up_process(sqd->thread);
8234 static void io_sq_thread_stop(struct io_sq_data *sqd)
8236 WARN_ON_ONCE(sqd->thread == current);
8237 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8239 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8240 mutex_lock(&sqd->lock);
8242 wake_up_process(sqd->thread);
8243 mutex_unlock(&sqd->lock);
8244 wait_for_completion(&sqd->exited);
8247 static void io_put_sq_data(struct io_sq_data *sqd)
8249 if (refcount_dec_and_test(&sqd->refs)) {
8250 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8252 io_sq_thread_stop(sqd);
8257 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8259 struct io_sq_data *sqd = ctx->sq_data;
8262 io_sq_thread_park(sqd);
8263 list_del_init(&ctx->sqd_list);
8264 io_sqd_update_thread_idle(sqd);
8265 io_sq_thread_unpark(sqd);
8267 io_put_sq_data(sqd);
8268 ctx->sq_data = NULL;
8272 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8274 struct io_ring_ctx *ctx_attach;
8275 struct io_sq_data *sqd;
8278 f = fdget(p->wq_fd);
8280 return ERR_PTR(-ENXIO);
8281 if (f.file->f_op != &io_uring_fops) {
8283 return ERR_PTR(-EINVAL);
8286 ctx_attach = f.file->private_data;
8287 sqd = ctx_attach->sq_data;
8290 return ERR_PTR(-EINVAL);
8292 if (sqd->task_tgid != current->tgid) {
8294 return ERR_PTR(-EPERM);
8297 refcount_inc(&sqd->refs);
8302 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8305 struct io_sq_data *sqd;
8308 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8309 sqd = io_attach_sq_data(p);
8314 /* fall through for EPERM case, setup new sqd/task */
8315 if (PTR_ERR(sqd) != -EPERM)
8319 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8321 return ERR_PTR(-ENOMEM);
8323 atomic_set(&sqd->park_pending, 0);
8324 refcount_set(&sqd->refs, 1);
8325 INIT_LIST_HEAD(&sqd->ctx_list);
8326 mutex_init(&sqd->lock);
8327 init_waitqueue_head(&sqd->wait);
8328 init_completion(&sqd->exited);
8332 #if defined(CONFIG_UNIX)
8334 * Ensure the UNIX gc is aware of our file set, so we are certain that
8335 * the io_uring can be safely unregistered on process exit, even if we have
8336 * loops in the file referencing.
8338 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8340 struct sock *sk = ctx->ring_sock->sk;
8341 struct scm_fp_list *fpl;
8342 struct sk_buff *skb;
8345 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8349 skb = alloc_skb(0, GFP_KERNEL);
8356 skb->scm_io_uring = 1;
8359 fpl->user = get_uid(current_user());
8360 for (i = 0; i < nr; i++) {
8361 struct file *file = io_file_from_index(ctx, i + offset);
8365 fpl->fp[nr_files] = get_file(file);
8366 unix_inflight(fpl->user, fpl->fp[nr_files]);
8371 fpl->max = SCM_MAX_FD;
8372 fpl->count = nr_files;
8373 UNIXCB(skb).fp = fpl;
8374 skb->destructor = unix_destruct_scm;
8375 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8376 skb_queue_head(&sk->sk_receive_queue, skb);
8378 for (i = 0; i < nr; i++) {
8379 struct file *file = io_file_from_index(ctx, i + offset);
8386 free_uid(fpl->user);
8394 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8395 * causes regular reference counting to break down. We rely on the UNIX
8396 * garbage collection to take care of this problem for us.
8398 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8400 unsigned left, total;
8404 left = ctx->nr_user_files;
8406 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8408 ret = __io_sqe_files_scm(ctx, this_files, total);
8412 total += this_files;
8418 while (total < ctx->nr_user_files) {
8419 struct file *file = io_file_from_index(ctx, total);
8429 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8435 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8437 struct file *file = prsrc->file;
8438 #if defined(CONFIG_UNIX)
8439 struct sock *sock = ctx->ring_sock->sk;
8440 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8441 struct sk_buff *skb;
8444 __skb_queue_head_init(&list);
8447 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8448 * remove this entry and rearrange the file array.
8450 skb = skb_dequeue(head);
8452 struct scm_fp_list *fp;
8454 fp = UNIXCB(skb).fp;
8455 for (i = 0; i < fp->count; i++) {
8458 if (fp->fp[i] != file)
8461 unix_notinflight(fp->user, fp->fp[i]);
8462 left = fp->count - 1 - i;
8464 memmove(&fp->fp[i], &fp->fp[i + 1],
8465 left * sizeof(struct file *));
8472 __skb_queue_tail(&list, skb);
8482 __skb_queue_tail(&list, skb);
8484 skb = skb_dequeue(head);
8487 if (skb_peek(&list)) {
8488 spin_lock_irq(&head->lock);
8489 while ((skb = __skb_dequeue(&list)) != NULL)
8490 __skb_queue_tail(head, skb);
8491 spin_unlock_irq(&head->lock);
8498 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8500 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8501 struct io_ring_ctx *ctx = rsrc_data->ctx;
8502 struct io_rsrc_put *prsrc, *tmp;
8504 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8505 list_del(&prsrc->list);
8508 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8510 io_ring_submit_lock(ctx, lock_ring);
8511 spin_lock(&ctx->completion_lock);
8512 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8513 io_commit_cqring(ctx);
8514 spin_unlock(&ctx->completion_lock);
8515 io_cqring_ev_posted(ctx);
8516 io_ring_submit_unlock(ctx, lock_ring);
8519 rsrc_data->do_put(ctx, prsrc);
8523 io_rsrc_node_destroy(ref_node);
8524 if (atomic_dec_and_test(&rsrc_data->refs))
8525 complete(&rsrc_data->done);
8528 static void io_rsrc_put_work(struct work_struct *work)
8530 struct io_ring_ctx *ctx;
8531 struct llist_node *node;
8533 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8534 node = llist_del_all(&ctx->rsrc_put_llist);
8537 struct io_rsrc_node *ref_node;
8538 struct llist_node *next = node->next;
8540 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8541 __io_rsrc_put_work(ref_node);
8546 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8547 unsigned nr_args, u64 __user *tags)
8549 __s32 __user *fds = (__s32 __user *) arg;
8558 if (nr_args > IORING_MAX_FIXED_FILES)
8560 if (nr_args > rlimit(RLIMIT_NOFILE))
8562 ret = io_rsrc_node_switch_start(ctx);
8565 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8571 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8574 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8575 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8579 /* allow sparse sets */
8582 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8589 if (unlikely(!file))
8593 * Don't allow io_uring instances to be registered. If UNIX
8594 * isn't enabled, then this causes a reference cycle and this
8595 * instance can never get freed. If UNIX is enabled we'll
8596 * handle it just fine, but there's still no point in allowing
8597 * a ring fd as it doesn't support regular read/write anyway.
8599 if (file->f_op == &io_uring_fops) {
8603 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8606 ret = io_sqe_files_scm(ctx);
8608 __io_sqe_files_unregister(ctx);
8612 io_rsrc_node_switch(ctx, NULL);
8615 for (i = 0; i < ctx->nr_user_files; i++) {
8616 file = io_file_from_index(ctx, i);
8620 io_free_file_tables(&ctx->file_table);
8621 ctx->nr_user_files = 0;
8623 io_rsrc_data_free(ctx->file_data);
8624 ctx->file_data = NULL;
8628 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8631 #if defined(CONFIG_UNIX)
8632 struct sock *sock = ctx->ring_sock->sk;
8633 struct sk_buff_head *head = &sock->sk_receive_queue;
8634 struct sk_buff *skb;
8637 * See if we can merge this file into an existing skb SCM_RIGHTS
8638 * file set. If there's no room, fall back to allocating a new skb
8639 * and filling it in.
8641 spin_lock_irq(&head->lock);
8642 skb = skb_peek(head);
8644 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8646 if (fpl->count < SCM_MAX_FD) {
8647 __skb_unlink(skb, head);
8648 spin_unlock_irq(&head->lock);
8649 fpl->fp[fpl->count] = get_file(file);
8650 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8652 spin_lock_irq(&head->lock);
8653 __skb_queue_head(head, skb);
8658 spin_unlock_irq(&head->lock);
8665 return __io_sqe_files_scm(ctx, 1, index);
8671 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8672 struct io_rsrc_node *node, void *rsrc)
8674 u64 *tag_slot = io_get_tag_slot(data, idx);
8675 struct io_rsrc_put *prsrc;
8677 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8681 prsrc->tag = *tag_slot;
8684 list_add(&prsrc->list, &node->rsrc_list);
8688 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8689 unsigned int issue_flags, u32 slot_index)
8691 struct io_ring_ctx *ctx = req->ctx;
8692 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8693 bool needs_switch = false;
8694 struct io_fixed_file *file_slot;
8697 io_ring_submit_lock(ctx, !force_nonblock);
8698 if (file->f_op == &io_uring_fops)
8701 if (!ctx->file_data)
8704 if (slot_index >= ctx->nr_user_files)
8707 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8708 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8710 if (file_slot->file_ptr) {
8711 struct file *old_file;
8713 ret = io_rsrc_node_switch_start(ctx);
8717 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8718 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8719 ctx->rsrc_node, old_file);
8722 file_slot->file_ptr = 0;
8723 needs_switch = true;
8726 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8727 io_fixed_file_set(file_slot, file);
8728 ret = io_sqe_file_register(ctx, file, slot_index);
8730 file_slot->file_ptr = 0;
8737 io_rsrc_node_switch(ctx, ctx->file_data);
8738 io_ring_submit_unlock(ctx, !force_nonblock);
8744 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8746 unsigned int offset = req->close.file_slot - 1;
8747 struct io_ring_ctx *ctx = req->ctx;
8748 struct io_fixed_file *file_slot;
8752 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8754 if (unlikely(!ctx->file_data))
8757 if (offset >= ctx->nr_user_files)
8759 ret = io_rsrc_node_switch_start(ctx);
8763 offset = array_index_nospec(offset, ctx->nr_user_files);
8764 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8766 if (!file_slot->file_ptr)
8769 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8770 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8774 file_slot->file_ptr = 0;
8775 io_rsrc_node_switch(ctx, ctx->file_data);
8778 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8782 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8783 struct io_uring_rsrc_update2 *up,
8786 u64 __user *tags = u64_to_user_ptr(up->tags);
8787 __s32 __user *fds = u64_to_user_ptr(up->data);
8788 struct io_rsrc_data *data = ctx->file_data;
8789 struct io_fixed_file *file_slot;
8793 bool needs_switch = false;
8795 if (!ctx->file_data)
8797 if (up->offset + nr_args > ctx->nr_user_files)
8800 for (done = 0; done < nr_args; done++) {
8803 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8804 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8808 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8812 if (fd == IORING_REGISTER_FILES_SKIP)
8815 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8816 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8818 if (file_slot->file_ptr) {
8819 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8820 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8823 file_slot->file_ptr = 0;
8824 needs_switch = true;
8833 * Don't allow io_uring instances to be registered. If
8834 * UNIX isn't enabled, then this causes a reference
8835 * cycle and this instance can never get freed. If UNIX
8836 * is enabled we'll handle it just fine, but there's
8837 * still no point in allowing a ring fd as it doesn't
8838 * support regular read/write anyway.
8840 if (file->f_op == &io_uring_fops) {
8845 *io_get_tag_slot(data, i) = tag;
8846 io_fixed_file_set(file_slot, file);
8847 err = io_sqe_file_register(ctx, file, i);
8849 file_slot->file_ptr = 0;
8857 io_rsrc_node_switch(ctx, data);
8858 return done ? done : err;
8861 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8862 struct task_struct *task)
8864 struct io_wq_hash *hash;
8865 struct io_wq_data data;
8866 unsigned int concurrency;
8868 mutex_lock(&ctx->uring_lock);
8869 hash = ctx->hash_map;
8871 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8873 mutex_unlock(&ctx->uring_lock);
8874 return ERR_PTR(-ENOMEM);
8876 refcount_set(&hash->refs, 1);
8877 init_waitqueue_head(&hash->wait);
8878 ctx->hash_map = hash;
8880 mutex_unlock(&ctx->uring_lock);
8884 data.free_work = io_wq_free_work;
8885 data.do_work = io_wq_submit_work;
8887 /* Do QD, or 4 * CPUS, whatever is smallest */
8888 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8890 return io_wq_create(concurrency, &data);
8893 static int io_uring_alloc_task_context(struct task_struct *task,
8894 struct io_ring_ctx *ctx)
8896 struct io_uring_task *tctx;
8899 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8900 if (unlikely(!tctx))
8903 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8904 if (unlikely(ret)) {
8909 tctx->io_wq = io_init_wq_offload(ctx, task);
8910 if (IS_ERR(tctx->io_wq)) {
8911 ret = PTR_ERR(tctx->io_wq);
8912 percpu_counter_destroy(&tctx->inflight);
8918 init_waitqueue_head(&tctx->wait);
8919 atomic_set(&tctx->in_idle, 0);
8920 atomic_set(&tctx->inflight_tracked, 0);
8921 task->io_uring = tctx;
8922 spin_lock_init(&tctx->task_lock);
8923 INIT_WQ_LIST(&tctx->task_list);
8924 init_task_work(&tctx->task_work, tctx_task_work);
8928 void __io_uring_free(struct task_struct *tsk)
8930 struct io_uring_task *tctx = tsk->io_uring;
8932 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8933 WARN_ON_ONCE(tctx->io_wq);
8934 WARN_ON_ONCE(tctx->cached_refs);
8936 percpu_counter_destroy(&tctx->inflight);
8938 tsk->io_uring = NULL;
8941 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8942 struct io_uring_params *p)
8946 /* Retain compatibility with failing for an invalid attach attempt */
8947 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8948 IORING_SETUP_ATTACH_WQ) {
8951 f = fdget(p->wq_fd);
8954 if (f.file->f_op != &io_uring_fops) {
8960 if (ctx->flags & IORING_SETUP_SQPOLL) {
8961 struct task_struct *tsk;
8962 struct io_sq_data *sqd;
8965 sqd = io_get_sq_data(p, &attached);
8971 ctx->sq_creds = get_current_cred();
8973 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8974 if (!ctx->sq_thread_idle)
8975 ctx->sq_thread_idle = HZ;
8977 io_sq_thread_park(sqd);
8978 list_add(&ctx->sqd_list, &sqd->ctx_list);
8979 io_sqd_update_thread_idle(sqd);
8980 /* don't attach to a dying SQPOLL thread, would be racy */
8981 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8982 io_sq_thread_unpark(sqd);
8989 if (p->flags & IORING_SETUP_SQ_AFF) {
8990 int cpu = p->sq_thread_cpu;
8993 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9000 sqd->task_pid = current->pid;
9001 sqd->task_tgid = current->tgid;
9002 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9009 ret = io_uring_alloc_task_context(tsk, ctx);
9010 wake_up_new_task(tsk);
9013 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9014 /* Can't have SQ_AFF without SQPOLL */
9021 complete(&ctx->sq_data->exited);
9023 io_sq_thread_finish(ctx);
9027 static inline void __io_unaccount_mem(struct user_struct *user,
9028 unsigned long nr_pages)
9030 atomic_long_sub(nr_pages, &user->locked_vm);
9033 static inline int __io_account_mem(struct user_struct *user,
9034 unsigned long nr_pages)
9036 unsigned long page_limit, cur_pages, new_pages;
9038 /* Don't allow more pages than we can safely lock */
9039 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9042 cur_pages = atomic_long_read(&user->locked_vm);
9043 new_pages = cur_pages + nr_pages;
9044 if (new_pages > page_limit)
9046 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9047 new_pages) != cur_pages);
9052 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9055 __io_unaccount_mem(ctx->user, nr_pages);
9057 if (ctx->mm_account)
9058 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9061 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9066 ret = __io_account_mem(ctx->user, nr_pages);
9071 if (ctx->mm_account)
9072 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9077 static void io_mem_free(void *ptr)
9084 page = virt_to_head_page(ptr);
9085 if (put_page_testzero(page))
9086 free_compound_page(page);
9089 static void *io_mem_alloc(size_t size)
9091 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9093 return (void *) __get_free_pages(gfp, get_order(size));
9096 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9099 struct io_rings *rings;
9100 size_t off, sq_array_size;
9102 off = struct_size(rings, cqes, cq_entries);
9103 if (off == SIZE_MAX)
9107 off = ALIGN(off, SMP_CACHE_BYTES);
9115 sq_array_size = array_size(sizeof(u32), sq_entries);
9116 if (sq_array_size == SIZE_MAX)
9119 if (check_add_overflow(off, sq_array_size, &off))
9125 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9127 struct io_mapped_ubuf *imu = *slot;
9130 if (imu != ctx->dummy_ubuf) {
9131 for (i = 0; i < imu->nr_bvecs; i++)
9132 unpin_user_page(imu->bvec[i].bv_page);
9133 if (imu->acct_pages)
9134 io_unaccount_mem(ctx, imu->acct_pages);
9140 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9142 io_buffer_unmap(ctx, &prsrc->buf);
9146 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9150 for (i = 0; i < ctx->nr_user_bufs; i++)
9151 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9152 kfree(ctx->user_bufs);
9153 io_rsrc_data_free(ctx->buf_data);
9154 ctx->user_bufs = NULL;
9155 ctx->buf_data = NULL;
9156 ctx->nr_user_bufs = 0;
9159 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9161 unsigned nr = ctx->nr_user_bufs;
9168 * Quiesce may unlock ->uring_lock, and while it's not held
9169 * prevent new requests using the table.
9171 ctx->nr_user_bufs = 0;
9172 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9173 ctx->nr_user_bufs = nr;
9175 __io_sqe_buffers_unregister(ctx);
9179 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9180 void __user *arg, unsigned index)
9182 struct iovec __user *src;
9184 #ifdef CONFIG_COMPAT
9186 struct compat_iovec __user *ciovs;
9187 struct compat_iovec ciov;
9189 ciovs = (struct compat_iovec __user *) arg;
9190 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9193 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9194 dst->iov_len = ciov.iov_len;
9198 src = (struct iovec __user *) arg;
9199 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9205 * Not super efficient, but this is just a registration time. And we do cache
9206 * the last compound head, so generally we'll only do a full search if we don't
9209 * We check if the given compound head page has already been accounted, to
9210 * avoid double accounting it. This allows us to account the full size of the
9211 * page, not just the constituent pages of a huge page.
9213 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9214 int nr_pages, struct page *hpage)
9218 /* check current page array */
9219 for (i = 0; i < nr_pages; i++) {
9220 if (!PageCompound(pages[i]))
9222 if (compound_head(pages[i]) == hpage)
9226 /* check previously registered pages */
9227 for (i = 0; i < ctx->nr_user_bufs; i++) {
9228 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9230 for (j = 0; j < imu->nr_bvecs; j++) {
9231 if (!PageCompound(imu->bvec[j].bv_page))
9233 if (compound_head(imu->bvec[j].bv_page) == hpage)
9241 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9242 int nr_pages, struct io_mapped_ubuf *imu,
9243 struct page **last_hpage)
9247 imu->acct_pages = 0;
9248 for (i = 0; i < nr_pages; i++) {
9249 if (!PageCompound(pages[i])) {
9254 hpage = compound_head(pages[i]);
9255 if (hpage == *last_hpage)
9257 *last_hpage = hpage;
9258 if (headpage_already_acct(ctx, pages, i, hpage))
9260 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9264 if (!imu->acct_pages)
9267 ret = io_account_mem(ctx, imu->acct_pages);
9269 imu->acct_pages = 0;
9273 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9274 struct io_mapped_ubuf **pimu,
9275 struct page **last_hpage)
9277 struct io_mapped_ubuf *imu = NULL;
9278 struct vm_area_struct **vmas = NULL;
9279 struct page **pages = NULL;
9280 unsigned long off, start, end, ubuf;
9282 int ret, pret, nr_pages, i;
9284 if (!iov->iov_base) {
9285 *pimu = ctx->dummy_ubuf;
9289 ubuf = (unsigned long) iov->iov_base;
9290 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9291 start = ubuf >> PAGE_SHIFT;
9292 nr_pages = end - start;
9297 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9301 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9306 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9311 mmap_read_lock(current->mm);
9312 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9314 if (pret == nr_pages) {
9315 struct file *file = vmas[0]->vm_file;
9317 /* don't support file backed memory */
9318 for (i = 0; i < nr_pages; i++) {
9319 if (vmas[i]->vm_file != file) {
9325 if (!vma_is_shmem(vmas[i]) && !is_file_hugepages(file)) {
9331 ret = pret < 0 ? pret : -EFAULT;
9333 mmap_read_unlock(current->mm);
9336 * if we did partial map, or found file backed vmas,
9337 * release any pages we did get
9340 unpin_user_pages(pages, pret);
9344 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9346 unpin_user_pages(pages, pret);
9350 off = ubuf & ~PAGE_MASK;
9351 size = iov->iov_len;
9352 for (i = 0; i < nr_pages; i++) {
9355 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9356 imu->bvec[i].bv_page = pages[i];
9357 imu->bvec[i].bv_len = vec_len;
9358 imu->bvec[i].bv_offset = off;
9362 /* store original address for later verification */
9364 imu->ubuf_end = ubuf + iov->iov_len;
9365 imu->nr_bvecs = nr_pages;
9376 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9378 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9379 return ctx->user_bufs ? 0 : -ENOMEM;
9382 static int io_buffer_validate(struct iovec *iov)
9384 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9387 * Don't impose further limits on the size and buffer
9388 * constraints here, we'll -EINVAL later when IO is
9389 * submitted if they are wrong.
9392 return iov->iov_len ? -EFAULT : 0;
9396 /* arbitrary limit, but we need something */
9397 if (iov->iov_len > SZ_1G)
9400 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9406 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9407 unsigned int nr_args, u64 __user *tags)
9409 struct page *last_hpage = NULL;
9410 struct io_rsrc_data *data;
9416 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9418 ret = io_rsrc_node_switch_start(ctx);
9421 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9424 ret = io_buffers_map_alloc(ctx, nr_args);
9426 io_rsrc_data_free(data);
9430 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9431 ret = io_copy_iov(ctx, &iov, arg, i);
9434 ret = io_buffer_validate(&iov);
9437 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9442 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9448 WARN_ON_ONCE(ctx->buf_data);
9450 ctx->buf_data = data;
9452 __io_sqe_buffers_unregister(ctx);
9454 io_rsrc_node_switch(ctx, NULL);
9458 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9459 struct io_uring_rsrc_update2 *up,
9460 unsigned int nr_args)
9462 u64 __user *tags = u64_to_user_ptr(up->tags);
9463 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9464 struct page *last_hpage = NULL;
9465 bool needs_switch = false;
9471 if (up->offset + nr_args > ctx->nr_user_bufs)
9474 for (done = 0; done < nr_args; done++) {
9475 struct io_mapped_ubuf *imu;
9476 int offset = up->offset + done;
9479 err = io_copy_iov(ctx, &iov, iovs, done);
9482 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9486 err = io_buffer_validate(&iov);
9489 if (!iov.iov_base && tag) {
9493 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9497 i = array_index_nospec(offset, ctx->nr_user_bufs);
9498 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9499 err = io_queue_rsrc_removal(ctx->buf_data, i,
9500 ctx->rsrc_node, ctx->user_bufs[i]);
9501 if (unlikely(err)) {
9502 io_buffer_unmap(ctx, &imu);
9505 ctx->user_bufs[i] = NULL;
9506 needs_switch = true;
9509 ctx->user_bufs[i] = imu;
9510 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9514 io_rsrc_node_switch(ctx, ctx->buf_data);
9515 return done ? done : err;
9518 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9520 __s32 __user *fds = arg;
9526 if (copy_from_user(&fd, fds, sizeof(*fds)))
9529 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9530 if (IS_ERR(ctx->cq_ev_fd)) {
9531 int ret = PTR_ERR(ctx->cq_ev_fd);
9533 ctx->cq_ev_fd = NULL;
9540 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9542 if (ctx->cq_ev_fd) {
9543 eventfd_ctx_put(ctx->cq_ev_fd);
9544 ctx->cq_ev_fd = NULL;
9551 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9553 struct io_buffer *buf;
9554 unsigned long index;
9556 xa_for_each(&ctx->io_buffers, index, buf)
9557 __io_remove_buffers(ctx, buf, index, -1U);
9560 static void io_req_cache_free(struct list_head *list)
9562 struct io_kiocb *req, *nxt;
9564 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9565 list_del(&req->inflight_entry);
9566 kmem_cache_free(req_cachep, req);
9570 static void io_req_caches_free(struct io_ring_ctx *ctx)
9572 struct io_submit_state *state = &ctx->submit_state;
9574 mutex_lock(&ctx->uring_lock);
9576 if (state->free_reqs) {
9577 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9578 state->free_reqs = 0;
9581 io_flush_cached_locked_reqs(ctx, state);
9582 io_req_cache_free(&state->free_list);
9583 mutex_unlock(&ctx->uring_lock);
9586 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9588 if (data && !atomic_dec_and_test(&data->refs))
9589 wait_for_completion(&data->done);
9592 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9594 io_sq_thread_finish(ctx);
9596 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9597 io_wait_rsrc_data(ctx->buf_data);
9598 io_wait_rsrc_data(ctx->file_data);
9600 mutex_lock(&ctx->uring_lock);
9602 __io_sqe_buffers_unregister(ctx);
9604 __io_sqe_files_unregister(ctx);
9606 __io_cqring_overflow_flush(ctx, true);
9607 mutex_unlock(&ctx->uring_lock);
9608 io_eventfd_unregister(ctx);
9609 io_destroy_buffers(ctx);
9611 put_cred(ctx->sq_creds);
9613 /* there are no registered resources left, nobody uses it */
9615 io_rsrc_node_destroy(ctx->rsrc_node);
9616 if (ctx->rsrc_backup_node)
9617 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9618 flush_delayed_work(&ctx->rsrc_put_work);
9620 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9621 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9623 #if defined(CONFIG_UNIX)
9624 if (ctx->ring_sock) {
9625 ctx->ring_sock->file = NULL; /* so that iput() is called */
9626 sock_release(ctx->ring_sock);
9629 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9631 if (ctx->mm_account) {
9632 mmdrop(ctx->mm_account);
9633 ctx->mm_account = NULL;
9636 io_mem_free(ctx->rings);
9637 io_mem_free(ctx->sq_sqes);
9639 percpu_ref_exit(&ctx->refs);
9640 free_uid(ctx->user);
9641 io_req_caches_free(ctx);
9643 io_wq_put_hash(ctx->hash_map);
9644 kfree(ctx->cancel_hash);
9645 kfree(ctx->dummy_ubuf);
9649 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9651 struct io_ring_ctx *ctx = file->private_data;
9654 poll_wait(file, &ctx->poll_wait, wait);
9656 * synchronizes with barrier from wq_has_sleeper call in
9660 if (!io_sqring_full(ctx))
9661 mask |= EPOLLOUT | EPOLLWRNORM;
9664 * Don't flush cqring overflow list here, just do a simple check.
9665 * Otherwise there could possible be ABBA deadlock:
9668 * lock(&ctx->uring_lock);
9670 * lock(&ctx->uring_lock);
9673 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9674 * pushs them to do the flush.
9676 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9677 mask |= EPOLLIN | EPOLLRDNORM;
9682 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9684 const struct cred *creds;
9686 creds = xa_erase(&ctx->personalities, id);
9695 struct io_tctx_exit {
9696 struct callback_head task_work;
9697 struct completion completion;
9698 struct io_ring_ctx *ctx;
9701 static void io_tctx_exit_cb(struct callback_head *cb)
9703 struct io_uring_task *tctx = current->io_uring;
9704 struct io_tctx_exit *work;
9706 work = container_of(cb, struct io_tctx_exit, task_work);
9708 * When @in_idle, we're in cancellation and it's racy to remove the
9709 * node. It'll be removed by the end of cancellation, just ignore it.
9710 * tctx can be NULL if the queueing of this task_work raced with
9711 * work cancelation off the exec path.
9713 if (tctx && !atomic_read(&tctx->in_idle))
9714 io_uring_del_tctx_node((unsigned long)work->ctx);
9715 complete(&work->completion);
9718 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9720 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9722 return req->ctx == data;
9725 static void io_ring_exit_work(struct work_struct *work)
9727 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9728 unsigned long timeout = jiffies + HZ * 60 * 5;
9729 unsigned long interval = HZ / 20;
9730 struct io_tctx_exit exit;
9731 struct io_tctx_node *node;
9735 * If we're doing polled IO and end up having requests being
9736 * submitted async (out-of-line), then completions can come in while
9737 * we're waiting for refs to drop. We need to reap these manually,
9738 * as nobody else will be looking for them.
9741 io_uring_try_cancel_requests(ctx, NULL, true);
9743 struct io_sq_data *sqd = ctx->sq_data;
9744 struct task_struct *tsk;
9746 io_sq_thread_park(sqd);
9748 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9749 io_wq_cancel_cb(tsk->io_uring->io_wq,
9750 io_cancel_ctx_cb, ctx, true);
9751 io_sq_thread_unpark(sqd);
9754 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9755 /* there is little hope left, don't run it too often */
9759 * This is really an uninterruptible wait, as it has to be
9760 * complete. But it's also run from a kworker, which doesn't
9761 * take signals, so it's fine to make it interruptible. This
9762 * avoids scenarios where we knowingly can wait much longer
9763 * on completions, for example if someone does a SIGSTOP on
9764 * a task that needs to finish task_work to make this loop
9765 * complete. That's a synthetic situation that should not
9766 * cause a stuck task backtrace, and hence a potential panic
9767 * on stuck tasks if that is enabled.
9769 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
9771 init_completion(&exit.completion);
9772 init_task_work(&exit.task_work, io_tctx_exit_cb);
9775 * Some may use context even when all refs and requests have been put,
9776 * and they are free to do so while still holding uring_lock or
9777 * completion_lock, see io_req_task_submit(). Apart from other work,
9778 * this lock/unlock section also waits them to finish.
9780 mutex_lock(&ctx->uring_lock);
9781 while (!list_empty(&ctx->tctx_list)) {
9782 WARN_ON_ONCE(time_after(jiffies, timeout));
9784 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9786 /* don't spin on a single task if cancellation failed */
9787 list_rotate_left(&ctx->tctx_list);
9788 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9789 if (WARN_ON_ONCE(ret))
9791 wake_up_process(node->task);
9793 mutex_unlock(&ctx->uring_lock);
9795 * See comment above for
9796 * wait_for_completion_interruptible_timeout() on why this
9797 * wait is marked as interruptible.
9799 wait_for_completion_interruptible(&exit.completion);
9800 mutex_lock(&ctx->uring_lock);
9802 mutex_unlock(&ctx->uring_lock);
9803 spin_lock(&ctx->completion_lock);
9804 spin_unlock(&ctx->completion_lock);
9806 io_ring_ctx_free(ctx);
9809 /* Returns true if we found and killed one or more timeouts */
9810 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9813 struct io_kiocb *req, *tmp;
9816 spin_lock(&ctx->completion_lock);
9817 spin_lock_irq(&ctx->timeout_lock);
9818 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9819 if (io_match_task(req, tsk, cancel_all)) {
9820 io_kill_timeout(req, -ECANCELED);
9824 spin_unlock_irq(&ctx->timeout_lock);
9826 io_commit_cqring(ctx);
9827 spin_unlock(&ctx->completion_lock);
9829 io_cqring_ev_posted(ctx);
9830 return canceled != 0;
9833 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9835 unsigned long index;
9836 struct creds *creds;
9838 mutex_lock(&ctx->uring_lock);
9839 percpu_ref_kill(&ctx->refs);
9841 __io_cqring_overflow_flush(ctx, true);
9842 xa_for_each(&ctx->personalities, index, creds)
9843 io_unregister_personality(ctx, index);
9844 mutex_unlock(&ctx->uring_lock);
9846 io_kill_timeouts(ctx, NULL, true);
9847 io_poll_remove_all(ctx, NULL, true);
9849 /* if we failed setting up the ctx, we might not have any rings */
9850 io_iopoll_try_reap_events(ctx);
9852 /* drop cached put refs after potentially doing completions */
9853 if (current->io_uring)
9854 io_uring_drop_tctx_refs(current);
9856 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9858 * Use system_unbound_wq to avoid spawning tons of event kworkers
9859 * if we're exiting a ton of rings at the same time. It just adds
9860 * noise and overhead, there's no discernable change in runtime
9861 * over using system_wq.
9863 queue_work(system_unbound_wq, &ctx->exit_work);
9866 static int io_uring_release(struct inode *inode, struct file *file)
9868 struct io_ring_ctx *ctx = file->private_data;
9870 file->private_data = NULL;
9871 io_ring_ctx_wait_and_kill(ctx);
9875 struct io_task_cancel {
9876 struct task_struct *task;
9880 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9882 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9883 struct io_task_cancel *cancel = data;
9885 return io_match_task_safe(req, cancel->task, cancel->all);
9888 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9889 struct task_struct *task, bool cancel_all)
9891 struct io_defer_entry *de;
9894 spin_lock(&ctx->completion_lock);
9895 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9896 if (io_match_task_safe(de->req, task, cancel_all)) {
9897 list_cut_position(&list, &ctx->defer_list, &de->list);
9901 spin_unlock(&ctx->completion_lock);
9902 if (list_empty(&list))
9905 while (!list_empty(&list)) {
9906 de = list_first_entry(&list, struct io_defer_entry, list);
9907 list_del_init(&de->list);
9908 io_req_complete_failed(de->req, -ECANCELED);
9914 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9916 struct io_tctx_node *node;
9917 enum io_wq_cancel cret;
9920 mutex_lock(&ctx->uring_lock);
9921 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9922 struct io_uring_task *tctx = node->task->io_uring;
9925 * io_wq will stay alive while we hold uring_lock, because it's
9926 * killed after ctx nodes, which requires to take the lock.
9928 if (!tctx || !tctx->io_wq)
9930 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9931 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9933 mutex_unlock(&ctx->uring_lock);
9938 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9939 struct task_struct *task,
9942 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9943 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9946 enum io_wq_cancel cret;
9950 ret |= io_uring_try_cancel_iowq(ctx);
9951 } else if (tctx && tctx->io_wq) {
9953 * Cancels requests of all rings, not only @ctx, but
9954 * it's fine as the task is in exit/exec.
9956 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9958 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9961 /* SQPOLL thread does its own polling */
9962 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9963 (ctx->sq_data && ctx->sq_data->thread == current)) {
9964 while (!list_empty_careful(&ctx->iopoll_list)) {
9965 io_iopoll_try_reap_events(ctx);
9971 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9972 ret |= io_poll_remove_all(ctx, task, cancel_all);
9973 ret |= io_kill_timeouts(ctx, task, cancel_all);
9975 ret |= io_run_task_work();
9982 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9984 struct io_uring_task *tctx = current->io_uring;
9985 struct io_tctx_node *node;
9988 if (unlikely(!tctx)) {
9989 ret = io_uring_alloc_task_context(current, ctx);
9993 tctx = current->io_uring;
9994 if (ctx->iowq_limits_set) {
9995 unsigned int limits[2] = { ctx->iowq_limits[0],
9996 ctx->iowq_limits[1], };
9998 ret = io_wq_max_workers(tctx->io_wq, limits);
10003 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10004 node = kmalloc(sizeof(*node), GFP_KERNEL);
10008 node->task = current;
10010 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10011 node, GFP_KERNEL));
10017 mutex_lock(&ctx->uring_lock);
10018 list_add(&node->ctx_node, &ctx->tctx_list);
10019 mutex_unlock(&ctx->uring_lock);
10026 * Note that this task has used io_uring. We use it for cancelation purposes.
10028 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10030 struct io_uring_task *tctx = current->io_uring;
10032 if (likely(tctx && tctx->last == ctx))
10034 return __io_uring_add_tctx_node(ctx);
10038 * Remove this io_uring_file -> task mapping.
10040 static void io_uring_del_tctx_node(unsigned long index)
10042 struct io_uring_task *tctx = current->io_uring;
10043 struct io_tctx_node *node;
10047 node = xa_erase(&tctx->xa, index);
10051 WARN_ON_ONCE(current != node->task);
10052 WARN_ON_ONCE(list_empty(&node->ctx_node));
10054 mutex_lock(&node->ctx->uring_lock);
10055 list_del(&node->ctx_node);
10056 mutex_unlock(&node->ctx->uring_lock);
10058 if (tctx->last == node->ctx)
10063 static void io_uring_clean_tctx(struct io_uring_task *tctx)
10065 struct io_wq *wq = tctx->io_wq;
10066 struct io_tctx_node *node;
10067 unsigned long index;
10069 xa_for_each(&tctx->xa, index, node) {
10070 io_uring_del_tctx_node(index);
10075 * Must be after io_uring_del_task_file() (removes nodes under
10076 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10078 io_wq_put_and_exit(wq);
10079 tctx->io_wq = NULL;
10083 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10086 return atomic_read(&tctx->inflight_tracked);
10087 return percpu_counter_sum(&tctx->inflight);
10091 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10092 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10094 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
10096 struct io_uring_task *tctx = current->io_uring;
10097 struct io_ring_ctx *ctx;
10101 WARN_ON_ONCE(sqd && sqd->thread != current);
10103 if (!current->io_uring)
10106 io_wq_exit_start(tctx->io_wq);
10108 atomic_inc(&tctx->in_idle);
10110 io_uring_drop_tctx_refs(current);
10111 /* read completions before cancelations */
10112 inflight = tctx_inflight(tctx, !cancel_all);
10117 struct io_tctx_node *node;
10118 unsigned long index;
10120 xa_for_each(&tctx->xa, index, node) {
10121 /* sqpoll task will cancel all its requests */
10122 if (node->ctx->sq_data)
10124 io_uring_try_cancel_requests(node->ctx, current,
10128 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10129 io_uring_try_cancel_requests(ctx, current,
10133 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10134 io_run_task_work();
10135 io_uring_drop_tctx_refs(current);
10138 * If we've seen completions, retry without waiting. This
10139 * avoids a race where a completion comes in before we did
10140 * prepare_to_wait().
10142 if (inflight == tctx_inflight(tctx, !cancel_all))
10144 finish_wait(&tctx->wait, &wait);
10147 io_uring_clean_tctx(tctx);
10150 * We shouldn't run task_works after cancel, so just leave
10151 * ->in_idle set for normal exit.
10153 atomic_dec(&tctx->in_idle);
10154 /* for exec all current's requests should be gone, kill tctx */
10155 __io_uring_free(current);
10159 void __io_uring_cancel(bool cancel_all)
10161 io_uring_cancel_generic(cancel_all, NULL);
10164 static void *io_uring_validate_mmap_request(struct file *file,
10165 loff_t pgoff, size_t sz)
10167 struct io_ring_ctx *ctx = file->private_data;
10168 loff_t offset = pgoff << PAGE_SHIFT;
10173 case IORING_OFF_SQ_RING:
10174 case IORING_OFF_CQ_RING:
10177 case IORING_OFF_SQES:
10178 ptr = ctx->sq_sqes;
10181 return ERR_PTR(-EINVAL);
10184 page = virt_to_head_page(ptr);
10185 if (sz > page_size(page))
10186 return ERR_PTR(-EINVAL);
10193 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10195 size_t sz = vma->vm_end - vma->vm_start;
10199 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10201 return PTR_ERR(ptr);
10203 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10204 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10207 #else /* !CONFIG_MMU */
10209 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10211 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10214 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10216 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10219 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10220 unsigned long addr, unsigned long len,
10221 unsigned long pgoff, unsigned long flags)
10225 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10227 return PTR_ERR(ptr);
10229 return (unsigned long) ptr;
10232 #endif /* !CONFIG_MMU */
10234 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10239 if (!io_sqring_full(ctx))
10241 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10243 if (!io_sqring_full(ctx))
10246 } while (!signal_pending(current));
10248 finish_wait(&ctx->sqo_sq_wait, &wait);
10252 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10253 struct __kernel_timespec __user **ts,
10254 const sigset_t __user **sig)
10256 struct io_uring_getevents_arg arg;
10259 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10260 * is just a pointer to the sigset_t.
10262 if (!(flags & IORING_ENTER_EXT_ARG)) {
10263 *sig = (const sigset_t __user *) argp;
10269 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10270 * timespec and sigset_t pointers if good.
10272 if (*argsz != sizeof(arg))
10274 if (copy_from_user(&arg, argp, sizeof(arg)))
10278 *sig = u64_to_user_ptr(arg.sigmask);
10279 *argsz = arg.sigmask_sz;
10280 *ts = u64_to_user_ptr(arg.ts);
10284 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10285 u32, min_complete, u32, flags, const void __user *, argp,
10288 struct io_ring_ctx *ctx;
10293 io_run_task_work();
10295 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10296 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10300 if (unlikely(!f.file))
10304 if (unlikely(f.file->f_op != &io_uring_fops))
10308 ctx = f.file->private_data;
10309 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10313 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10317 * For SQ polling, the thread will do all submissions and completions.
10318 * Just return the requested submit count, and wake the thread if
10319 * we were asked to.
10322 if (ctx->flags & IORING_SETUP_SQPOLL) {
10323 io_cqring_overflow_flush(ctx);
10325 if (unlikely(ctx->sq_data->thread == NULL)) {
10329 if (flags & IORING_ENTER_SQ_WAKEUP)
10330 wake_up(&ctx->sq_data->wait);
10331 if (flags & IORING_ENTER_SQ_WAIT) {
10332 ret = io_sqpoll_wait_sq(ctx);
10336 submitted = to_submit;
10337 } else if (to_submit) {
10338 ret = io_uring_add_tctx_node(ctx);
10341 mutex_lock(&ctx->uring_lock);
10342 submitted = io_submit_sqes(ctx, to_submit);
10343 mutex_unlock(&ctx->uring_lock);
10345 if (submitted != to_submit)
10348 if (flags & IORING_ENTER_GETEVENTS) {
10349 const sigset_t __user *sig;
10350 struct __kernel_timespec __user *ts;
10352 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10356 min_complete = min(min_complete, ctx->cq_entries);
10359 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10360 * space applications don't need to do io completion events
10361 * polling again, they can rely on io_sq_thread to do polling
10362 * work, which can reduce cpu usage and uring_lock contention.
10364 if (ctx->flags & IORING_SETUP_IOPOLL &&
10365 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10366 ret = io_iopoll_check(ctx, min_complete);
10368 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10373 percpu_ref_put(&ctx->refs);
10376 return submitted ? submitted : ret;
10379 #ifdef CONFIG_PROC_FS
10380 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
10381 const struct cred *cred)
10383 struct user_namespace *uns = seq_user_ns(m);
10384 struct group_info *gi;
10389 seq_printf(m, "%5d\n", id);
10390 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10391 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10392 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10393 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10394 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10395 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10396 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10397 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10398 seq_puts(m, "\n\tGroups:\t");
10399 gi = cred->group_info;
10400 for (g = 0; g < gi->ngroups; g++) {
10401 seq_put_decimal_ull(m, g ? " " : "",
10402 from_kgid_munged(uns, gi->gid[g]));
10404 seq_puts(m, "\n\tCapEff:\t");
10405 cap = cred->cap_effective;
10406 CAP_FOR_EACH_U32(__capi)
10407 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10412 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
10414 struct io_sq_data *sq = NULL;
10419 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10420 * since fdinfo case grabs it in the opposite direction of normal use
10421 * cases. If we fail to get the lock, we just don't iterate any
10422 * structures that could be going away outside the io_uring mutex.
10424 has_lock = mutex_trylock(&ctx->uring_lock);
10426 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10432 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10433 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10434 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10435 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10436 struct file *f = io_file_from_index(ctx, i);
10439 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10441 seq_printf(m, "%5u: <none>\n", i);
10443 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10444 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10445 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10446 unsigned int len = buf->ubuf_end - buf->ubuf;
10448 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10450 if (has_lock && !xa_empty(&ctx->personalities)) {
10451 unsigned long index;
10452 const struct cred *cred;
10454 seq_printf(m, "Personalities:\n");
10455 xa_for_each(&ctx->personalities, index, cred)
10456 io_uring_show_cred(m, index, cred);
10458 seq_printf(m, "PollList:\n");
10459 spin_lock(&ctx->completion_lock);
10460 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10461 struct hlist_head *list = &ctx->cancel_hash[i];
10462 struct io_kiocb *req;
10464 hlist_for_each_entry(req, list, hash_node)
10465 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10466 req->task->task_works != NULL);
10468 spin_unlock(&ctx->completion_lock);
10470 mutex_unlock(&ctx->uring_lock);
10473 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10475 struct io_ring_ctx *ctx = f->private_data;
10477 if (percpu_ref_tryget(&ctx->refs)) {
10478 __io_uring_show_fdinfo(ctx, m);
10479 percpu_ref_put(&ctx->refs);
10484 static const struct file_operations io_uring_fops = {
10485 .release = io_uring_release,
10486 .mmap = io_uring_mmap,
10488 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10489 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10491 .poll = io_uring_poll,
10492 #ifdef CONFIG_PROC_FS
10493 .show_fdinfo = io_uring_show_fdinfo,
10497 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10498 struct io_uring_params *p)
10500 struct io_rings *rings;
10501 size_t size, sq_array_offset;
10503 /* make sure these are sane, as we already accounted them */
10504 ctx->sq_entries = p->sq_entries;
10505 ctx->cq_entries = p->cq_entries;
10507 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10508 if (size == SIZE_MAX)
10511 rings = io_mem_alloc(size);
10515 ctx->rings = rings;
10516 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10517 rings->sq_ring_mask = p->sq_entries - 1;
10518 rings->cq_ring_mask = p->cq_entries - 1;
10519 rings->sq_ring_entries = p->sq_entries;
10520 rings->cq_ring_entries = p->cq_entries;
10522 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10523 if (size == SIZE_MAX) {
10524 io_mem_free(ctx->rings);
10529 ctx->sq_sqes = io_mem_alloc(size);
10530 if (!ctx->sq_sqes) {
10531 io_mem_free(ctx->rings);
10539 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10543 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10547 ret = io_uring_add_tctx_node(ctx);
10552 fd_install(fd, file);
10557 * Allocate an anonymous fd, this is what constitutes the application
10558 * visible backing of an io_uring instance. The application mmaps this
10559 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10560 * we have to tie this fd to a socket for file garbage collection purposes.
10562 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10565 #if defined(CONFIG_UNIX)
10568 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10571 return ERR_PTR(ret);
10574 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10575 O_RDWR | O_CLOEXEC);
10576 #if defined(CONFIG_UNIX)
10577 if (IS_ERR(file)) {
10578 sock_release(ctx->ring_sock);
10579 ctx->ring_sock = NULL;
10581 ctx->ring_sock->file = file;
10587 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10588 struct io_uring_params __user *params)
10590 struct io_ring_ctx *ctx;
10596 if (entries > IORING_MAX_ENTRIES) {
10597 if (!(p->flags & IORING_SETUP_CLAMP))
10599 entries = IORING_MAX_ENTRIES;
10603 * Use twice as many entries for the CQ ring. It's possible for the
10604 * application to drive a higher depth than the size of the SQ ring,
10605 * since the sqes are only used at submission time. This allows for
10606 * some flexibility in overcommitting a bit. If the application has
10607 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10608 * of CQ ring entries manually.
10610 p->sq_entries = roundup_pow_of_two(entries);
10611 if (p->flags & IORING_SETUP_CQSIZE) {
10613 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10614 * to a power-of-two, if it isn't already. We do NOT impose
10615 * any cq vs sq ring sizing.
10617 if (!p->cq_entries)
10619 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10620 if (!(p->flags & IORING_SETUP_CLAMP))
10622 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10624 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10625 if (p->cq_entries < p->sq_entries)
10628 p->cq_entries = 2 * p->sq_entries;
10631 ctx = io_ring_ctx_alloc(p);
10634 ctx->compat = in_compat_syscall();
10635 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
10636 ctx->user = get_uid(current_user());
10639 * This is just grabbed for accounting purposes. When a process exits,
10640 * the mm is exited and dropped before the files, hence we need to hang
10641 * on to this mm purely for the purposes of being able to unaccount
10642 * memory (locked/pinned vm). It's not used for anything else.
10644 mmgrab(current->mm);
10645 ctx->mm_account = current->mm;
10647 ret = io_allocate_scq_urings(ctx, p);
10651 ret = io_sq_offload_create(ctx, p);
10654 /* always set a rsrc node */
10655 ret = io_rsrc_node_switch_start(ctx);
10658 io_rsrc_node_switch(ctx, NULL);
10660 memset(&p->sq_off, 0, sizeof(p->sq_off));
10661 p->sq_off.head = offsetof(struct io_rings, sq.head);
10662 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10663 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10664 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10665 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10666 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10667 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10669 memset(&p->cq_off, 0, sizeof(p->cq_off));
10670 p->cq_off.head = offsetof(struct io_rings, cq.head);
10671 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10672 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10673 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10674 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10675 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10676 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10678 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10679 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10680 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10681 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10682 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10683 IORING_FEAT_RSRC_TAGS;
10685 if (copy_to_user(params, p, sizeof(*p))) {
10690 file = io_uring_get_file(ctx);
10691 if (IS_ERR(file)) {
10692 ret = PTR_ERR(file);
10697 * Install ring fd as the very last thing, so we don't risk someone
10698 * having closed it before we finish setup
10700 ret = io_uring_install_fd(ctx, file);
10702 /* fput will clean it up */
10707 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10710 io_ring_ctx_wait_and_kill(ctx);
10715 * Sets up an aio uring context, and returns the fd. Applications asks for a
10716 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10717 * params structure passed in.
10719 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10721 struct io_uring_params p;
10724 if (copy_from_user(&p, params, sizeof(p)))
10726 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10731 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10732 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10733 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10734 IORING_SETUP_R_DISABLED))
10737 return io_uring_create(entries, &p, params);
10740 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10741 struct io_uring_params __user *, params)
10743 return io_uring_setup(entries, params);
10746 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10748 struct io_uring_probe *p;
10752 size = struct_size(p, ops, nr_args);
10753 if (size == SIZE_MAX)
10755 p = kzalloc(size, GFP_KERNEL);
10760 if (copy_from_user(p, arg, size))
10763 if (memchr_inv(p, 0, size))
10766 p->last_op = IORING_OP_LAST - 1;
10767 if (nr_args > IORING_OP_LAST)
10768 nr_args = IORING_OP_LAST;
10770 for (i = 0; i < nr_args; i++) {
10772 if (!io_op_defs[i].not_supported)
10773 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10778 if (copy_to_user(arg, p, size))
10785 static int io_register_personality(struct io_ring_ctx *ctx)
10787 const struct cred *creds;
10791 creds = get_current_cred();
10793 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10794 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10802 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10803 unsigned int nr_args)
10805 struct io_uring_restriction *res;
10809 /* Restrictions allowed only if rings started disabled */
10810 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10813 /* We allow only a single restrictions registration */
10814 if (ctx->restrictions.registered)
10817 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10820 size = array_size(nr_args, sizeof(*res));
10821 if (size == SIZE_MAX)
10824 res = memdup_user(arg, size);
10826 return PTR_ERR(res);
10830 for (i = 0; i < nr_args; i++) {
10831 switch (res[i].opcode) {
10832 case IORING_RESTRICTION_REGISTER_OP:
10833 if (res[i].register_op >= IORING_REGISTER_LAST) {
10838 __set_bit(res[i].register_op,
10839 ctx->restrictions.register_op);
10841 case IORING_RESTRICTION_SQE_OP:
10842 if (res[i].sqe_op >= IORING_OP_LAST) {
10847 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10849 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10850 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10852 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10853 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10862 /* Reset all restrictions if an error happened */
10864 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10866 ctx->restrictions.registered = true;
10872 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10874 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10877 if (ctx->restrictions.registered)
10878 ctx->restricted = 1;
10880 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10881 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10882 wake_up(&ctx->sq_data->wait);
10886 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10887 struct io_uring_rsrc_update2 *up,
10893 if (check_add_overflow(up->offset, nr_args, &tmp))
10895 err = io_rsrc_node_switch_start(ctx);
10900 case IORING_RSRC_FILE:
10901 return __io_sqe_files_update(ctx, up, nr_args);
10902 case IORING_RSRC_BUFFER:
10903 return __io_sqe_buffers_update(ctx, up, nr_args);
10908 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10911 struct io_uring_rsrc_update2 up;
10915 memset(&up, 0, sizeof(up));
10916 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10918 if (up.resv || up.resv2)
10920 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10923 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10924 unsigned size, unsigned type)
10926 struct io_uring_rsrc_update2 up;
10928 if (size != sizeof(up))
10930 if (copy_from_user(&up, arg, sizeof(up)))
10932 if (!up.nr || up.resv || up.resv2)
10934 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10937 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10938 unsigned int size, unsigned int type)
10940 struct io_uring_rsrc_register rr;
10942 /* keep it extendible */
10943 if (size != sizeof(rr))
10946 memset(&rr, 0, sizeof(rr));
10947 if (copy_from_user(&rr, arg, size))
10949 if (!rr.nr || rr.resv || rr.resv2)
10953 case IORING_RSRC_FILE:
10954 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10955 rr.nr, u64_to_user_ptr(rr.tags));
10956 case IORING_RSRC_BUFFER:
10957 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10958 rr.nr, u64_to_user_ptr(rr.tags));
10963 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10966 struct io_uring_task *tctx = current->io_uring;
10967 cpumask_var_t new_mask;
10970 if (!tctx || !tctx->io_wq)
10973 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10976 cpumask_clear(new_mask);
10977 if (len > cpumask_size())
10978 len = cpumask_size();
10980 if (in_compat_syscall()) {
10981 ret = compat_get_bitmap(cpumask_bits(new_mask),
10982 (const compat_ulong_t __user *)arg,
10983 len * 8 /* CHAR_BIT */);
10985 ret = copy_from_user(new_mask, arg, len);
10989 free_cpumask_var(new_mask);
10993 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10994 free_cpumask_var(new_mask);
10998 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11000 struct io_uring_task *tctx = current->io_uring;
11002 if (!tctx || !tctx->io_wq)
11005 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11008 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11010 __must_hold(&ctx->uring_lock)
11012 struct io_tctx_node *node;
11013 struct io_uring_task *tctx = NULL;
11014 struct io_sq_data *sqd = NULL;
11015 __u32 new_count[2];
11018 if (copy_from_user(new_count, arg, sizeof(new_count)))
11020 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11021 if (new_count[i] > INT_MAX)
11024 if (ctx->flags & IORING_SETUP_SQPOLL) {
11025 sqd = ctx->sq_data;
11028 * Observe the correct sqd->lock -> ctx->uring_lock
11029 * ordering. Fine to drop uring_lock here, we hold
11030 * a ref to the ctx.
11032 refcount_inc(&sqd->refs);
11033 mutex_unlock(&ctx->uring_lock);
11034 mutex_lock(&sqd->lock);
11035 mutex_lock(&ctx->uring_lock);
11037 tctx = sqd->thread->io_uring;
11040 tctx = current->io_uring;
11043 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11045 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11047 ctx->iowq_limits[i] = new_count[i];
11048 ctx->iowq_limits_set = true;
11051 if (tctx && tctx->io_wq) {
11052 ret = io_wq_max_workers(tctx->io_wq, new_count);
11056 memset(new_count, 0, sizeof(new_count));
11060 mutex_unlock(&sqd->lock);
11061 io_put_sq_data(sqd);
11064 if (copy_to_user(arg, new_count, sizeof(new_count)))
11067 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11071 /* now propagate the restriction to all registered users */
11072 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11073 struct io_uring_task *tctx = node->task->io_uring;
11075 if (WARN_ON_ONCE(!tctx->io_wq))
11078 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11079 new_count[i] = ctx->iowq_limits[i];
11080 /* ignore errors, it always returns zero anyway */
11081 (void)io_wq_max_workers(tctx->io_wq, new_count);
11086 mutex_unlock(&sqd->lock);
11087 io_put_sq_data(sqd);
11092 static bool io_register_op_must_quiesce(int op)
11095 case IORING_REGISTER_BUFFERS:
11096 case IORING_UNREGISTER_BUFFERS:
11097 case IORING_REGISTER_FILES:
11098 case IORING_UNREGISTER_FILES:
11099 case IORING_REGISTER_FILES_UPDATE:
11100 case IORING_REGISTER_PROBE:
11101 case IORING_REGISTER_PERSONALITY:
11102 case IORING_UNREGISTER_PERSONALITY:
11103 case IORING_REGISTER_FILES2:
11104 case IORING_REGISTER_FILES_UPDATE2:
11105 case IORING_REGISTER_BUFFERS2:
11106 case IORING_REGISTER_BUFFERS_UPDATE:
11107 case IORING_REGISTER_IOWQ_AFF:
11108 case IORING_UNREGISTER_IOWQ_AFF:
11109 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11116 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
11120 percpu_ref_kill(&ctx->refs);
11123 * Drop uring mutex before waiting for references to exit. If another
11124 * thread is currently inside io_uring_enter() it might need to grab the
11125 * uring_lock to make progress. If we hold it here across the drain
11126 * wait, then we can deadlock. It's safe to drop the mutex here, since
11127 * no new references will come in after we've killed the percpu ref.
11129 mutex_unlock(&ctx->uring_lock);
11131 ret = wait_for_completion_interruptible(&ctx->ref_comp);
11134 ret = io_run_task_work_sig();
11135 } while (ret >= 0);
11136 mutex_lock(&ctx->uring_lock);
11139 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
11143 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11144 void __user *arg, unsigned nr_args)
11145 __releases(ctx->uring_lock)
11146 __acquires(ctx->uring_lock)
11151 * We're inside the ring mutex, if the ref is already dying, then
11152 * someone else killed the ctx or is already going through
11153 * io_uring_register().
11155 if (percpu_ref_is_dying(&ctx->refs))
11158 if (ctx->restricted) {
11159 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11160 if (!test_bit(opcode, ctx->restrictions.register_op))
11164 if (io_register_op_must_quiesce(opcode)) {
11165 ret = io_ctx_quiesce(ctx);
11171 case IORING_REGISTER_BUFFERS:
11172 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11174 case IORING_UNREGISTER_BUFFERS:
11176 if (arg || nr_args)
11178 ret = io_sqe_buffers_unregister(ctx);
11180 case IORING_REGISTER_FILES:
11181 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11183 case IORING_UNREGISTER_FILES:
11185 if (arg || nr_args)
11187 ret = io_sqe_files_unregister(ctx);
11189 case IORING_REGISTER_FILES_UPDATE:
11190 ret = io_register_files_update(ctx, arg, nr_args);
11192 case IORING_REGISTER_EVENTFD:
11193 case IORING_REGISTER_EVENTFD_ASYNC:
11197 ret = io_eventfd_register(ctx, arg);
11200 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
11201 ctx->eventfd_async = 1;
11203 ctx->eventfd_async = 0;
11205 case IORING_UNREGISTER_EVENTFD:
11207 if (arg || nr_args)
11209 ret = io_eventfd_unregister(ctx);
11211 case IORING_REGISTER_PROBE:
11213 if (!arg || nr_args > 256)
11215 ret = io_probe(ctx, arg, nr_args);
11217 case IORING_REGISTER_PERSONALITY:
11219 if (arg || nr_args)
11221 ret = io_register_personality(ctx);
11223 case IORING_UNREGISTER_PERSONALITY:
11227 ret = io_unregister_personality(ctx, nr_args);
11229 case IORING_REGISTER_ENABLE_RINGS:
11231 if (arg || nr_args)
11233 ret = io_register_enable_rings(ctx);
11235 case IORING_REGISTER_RESTRICTIONS:
11236 ret = io_register_restrictions(ctx, arg, nr_args);
11238 case IORING_REGISTER_FILES2:
11239 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11241 case IORING_REGISTER_FILES_UPDATE2:
11242 ret = io_register_rsrc_update(ctx, arg, nr_args,
11245 case IORING_REGISTER_BUFFERS2:
11246 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11248 case IORING_REGISTER_BUFFERS_UPDATE:
11249 ret = io_register_rsrc_update(ctx, arg, nr_args,
11250 IORING_RSRC_BUFFER);
11252 case IORING_REGISTER_IOWQ_AFF:
11254 if (!arg || !nr_args)
11256 ret = io_register_iowq_aff(ctx, arg, nr_args);
11258 case IORING_UNREGISTER_IOWQ_AFF:
11260 if (arg || nr_args)
11262 ret = io_unregister_iowq_aff(ctx);
11264 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11266 if (!arg || nr_args != 2)
11268 ret = io_register_iowq_max_workers(ctx, arg);
11275 if (io_register_op_must_quiesce(opcode)) {
11276 /* bring the ctx back to life */
11277 percpu_ref_reinit(&ctx->refs);
11278 reinit_completion(&ctx->ref_comp);
11283 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11284 void __user *, arg, unsigned int, nr_args)
11286 struct io_ring_ctx *ctx;
11290 if (opcode >= IORING_REGISTER_LAST)
11298 if (f.file->f_op != &io_uring_fops)
11301 ctx = f.file->private_data;
11303 io_run_task_work();
11305 mutex_lock(&ctx->uring_lock);
11306 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11307 mutex_unlock(&ctx->uring_lock);
11308 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11309 ctx->cq_ev_fd != NULL, ret);
11315 static int __init io_uring_init(void)
11317 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11318 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11319 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11322 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11323 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11324 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11325 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11326 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11327 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11328 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11329 BUILD_BUG_SQE_ELEM(8, __u64, off);
11330 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11331 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11332 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11333 BUILD_BUG_SQE_ELEM(24, __u32, len);
11334 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11335 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11336 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11337 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11338 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11339 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11340 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11341 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11342 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11343 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11344 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11345 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11346 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11347 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11348 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11349 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11350 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11351 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11352 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11353 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11354 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11356 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11357 sizeof(struct io_uring_rsrc_update));
11358 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11359 sizeof(struct io_uring_rsrc_update2));
11361 /* ->buf_index is u16 */
11362 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11364 /* should fit into one byte */
11365 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11367 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11368 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11370 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11374 __initcall(io_uring_init);