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);
2671 } while (!ret && nr_events < min && !need_resched());
2673 mutex_unlock(&ctx->uring_lock);
2677 static void kiocb_end_write(struct io_kiocb *req)
2680 * Tell lockdep we inherited freeze protection from submission
2683 if (req->flags & REQ_F_ISREG) {
2684 struct super_block *sb = file_inode(req->file)->i_sb;
2686 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2692 static bool io_resubmit_prep(struct io_kiocb *req)
2694 struct io_async_rw *rw = req->async_data;
2697 return !io_req_prep_async(req);
2698 iov_iter_restore(&rw->iter, &rw->iter_state);
2702 static bool io_rw_should_reissue(struct io_kiocb *req)
2704 umode_t mode = file_inode(req->file)->i_mode;
2705 struct io_ring_ctx *ctx = req->ctx;
2707 if (!S_ISBLK(mode) && !S_ISREG(mode))
2709 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2710 !(ctx->flags & IORING_SETUP_IOPOLL)))
2713 * If ref is dying, we might be running poll reap from the exit work.
2714 * Don't attempt to reissue from that path, just let it fail with
2717 if (percpu_ref_is_dying(&ctx->refs))
2720 * Play it safe and assume not safe to re-import and reissue if we're
2721 * not in the original thread group (or in task context).
2723 if (!same_thread_group(req->task, current) || !in_task())
2728 static bool io_resubmit_prep(struct io_kiocb *req)
2732 static bool io_rw_should_reissue(struct io_kiocb *req)
2739 * Trigger the notifications after having done some IO, and finish the write
2740 * accounting, if any.
2742 static void io_req_io_end(struct io_kiocb *req)
2744 struct io_rw *rw = &req->rw;
2746 if (rw->kiocb.ki_flags & IOCB_WRITE) {
2747 kiocb_end_write(req);
2748 fsnotify_modify(req->file);
2750 fsnotify_access(req->file);
2754 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2756 if (res != req->result) {
2757 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2758 io_rw_should_reissue(req)) {
2760 * Reissue will start accounting again, finish the
2764 req->flags |= REQ_F_REISSUE;
2773 static inline int io_fixup_rw_res(struct io_kiocb *req, long res)
2775 struct io_async_rw *io = req->async_data;
2777 /* add previously done IO, if any */
2778 if (io && io->bytes_done > 0) {
2780 res = io->bytes_done;
2782 res += io->bytes_done;
2787 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2789 unsigned int cflags = io_put_rw_kbuf(req);
2790 int res = req->result;
2793 struct io_ring_ctx *ctx = req->ctx;
2794 struct io_submit_state *state = &ctx->submit_state;
2796 io_req_complete_state(req, res, cflags);
2797 state->compl_reqs[state->compl_nr++] = req;
2798 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2799 io_submit_flush_completions(ctx);
2801 io_req_complete_post(req, res, cflags);
2805 static void io_req_rw_complete(struct io_kiocb *req, bool *locked)
2808 io_req_task_complete(req, locked);
2811 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2813 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2815 if (__io_complete_rw_common(req, res))
2817 req->result = io_fixup_rw_res(req, res);
2818 req->io_task_work.func = io_req_rw_complete;
2819 io_req_task_work_add(req);
2822 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2824 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2826 if (kiocb->ki_flags & IOCB_WRITE)
2827 kiocb_end_write(req);
2828 if (unlikely(res != req->result)) {
2829 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2830 req->flags |= REQ_F_REISSUE;
2835 WRITE_ONCE(req->result, res);
2836 /* order with io_iopoll_complete() checking ->result */
2838 WRITE_ONCE(req->iopoll_completed, 1);
2842 * After the iocb has been issued, it's safe to be found on the poll list.
2843 * Adding the kiocb to the list AFTER submission ensures that we don't
2844 * find it from a io_do_iopoll() thread before the issuer is done
2845 * accessing the kiocb cookie.
2847 static void io_iopoll_req_issued(struct io_kiocb *req)
2849 struct io_ring_ctx *ctx = req->ctx;
2850 const bool in_async = io_wq_current_is_worker();
2852 /* workqueue context doesn't hold uring_lock, grab it now */
2853 if (unlikely(in_async))
2854 mutex_lock(&ctx->uring_lock);
2857 * Track whether we have multiple files in our lists. This will impact
2858 * how we do polling eventually, not spinning if we're on potentially
2859 * different devices.
2861 if (list_empty(&ctx->iopoll_list)) {
2862 ctx->poll_multi_queue = false;
2863 } else if (!ctx->poll_multi_queue) {
2864 struct io_kiocb *list_req;
2865 unsigned int queue_num0, queue_num1;
2867 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2870 if (list_req->file != req->file) {
2871 ctx->poll_multi_queue = true;
2873 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2874 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2875 if (queue_num0 != queue_num1)
2876 ctx->poll_multi_queue = true;
2881 * For fast devices, IO may have already completed. If it has, add
2882 * it to the front so we find it first.
2884 if (READ_ONCE(req->iopoll_completed))
2885 list_add(&req->inflight_entry, &ctx->iopoll_list);
2887 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2889 if (unlikely(in_async)) {
2891 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2892 * in sq thread task context or in io worker task context. If
2893 * current task context is sq thread, we don't need to check
2894 * whether should wake up sq thread.
2896 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2897 wq_has_sleeper(&ctx->sq_data->wait))
2898 wake_up(&ctx->sq_data->wait);
2900 mutex_unlock(&ctx->uring_lock);
2904 static bool io_bdev_nowait(struct block_device *bdev)
2906 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2910 * If we tracked the file through the SCM inflight mechanism, we could support
2911 * any file. For now, just ensure that anything potentially problematic is done
2914 static bool __io_file_supports_nowait(struct file *file, int rw)
2916 umode_t mode = file_inode(file)->i_mode;
2918 if (S_ISBLK(mode)) {
2919 if (IS_ENABLED(CONFIG_BLOCK) &&
2920 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2926 if (S_ISREG(mode)) {
2927 if (IS_ENABLED(CONFIG_BLOCK) &&
2928 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2929 file->f_op != &io_uring_fops)
2934 /* any ->read/write should understand O_NONBLOCK */
2935 if (file->f_flags & O_NONBLOCK)
2938 if (!(file->f_mode & FMODE_NOWAIT))
2942 return file->f_op->read_iter != NULL;
2944 return file->f_op->write_iter != NULL;
2947 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2949 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2951 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2954 return __io_file_supports_nowait(req->file, rw);
2957 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2960 struct io_ring_ctx *ctx = req->ctx;
2961 struct kiocb *kiocb = &req->rw.kiocb;
2962 struct file *file = req->file;
2966 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2967 req->flags |= REQ_F_ISREG;
2969 kiocb->ki_pos = READ_ONCE(sqe->off);
2970 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2971 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2972 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2977 * If the file is marked O_NONBLOCK, still allow retry for it if it
2978 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2979 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2981 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2982 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req, rw)))
2983 req->flags |= REQ_F_NOWAIT;
2985 ioprio = READ_ONCE(sqe->ioprio);
2987 ret = ioprio_check_cap(ioprio);
2991 kiocb->ki_ioprio = ioprio;
2993 kiocb->ki_ioprio = get_current_ioprio();
2995 if (ctx->flags & IORING_SETUP_IOPOLL) {
2996 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2997 !kiocb->ki_filp->f_op->iopoll)
3000 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3001 kiocb->ki_complete = io_complete_rw_iopoll;
3002 req->iopoll_completed = 0;
3004 if (kiocb->ki_flags & IOCB_HIPRI)
3006 kiocb->ki_complete = io_complete_rw;
3009 /* used for fixed read/write too - just read unconditionally */
3010 req->buf_index = READ_ONCE(sqe->buf_index);
3013 if (req->opcode == IORING_OP_READ_FIXED ||
3014 req->opcode == IORING_OP_WRITE_FIXED) {
3015 struct io_ring_ctx *ctx = req->ctx;
3018 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3020 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3021 req->imu = ctx->user_bufs[index];
3022 io_req_set_rsrc_node(req);
3025 req->rw.addr = READ_ONCE(sqe->addr);
3026 req->rw.len = READ_ONCE(sqe->len);
3030 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3036 case -ERESTARTNOINTR:
3037 case -ERESTARTNOHAND:
3038 case -ERESTART_RESTARTBLOCK:
3040 * We can't just restart the syscall, since previously
3041 * submitted sqes may already be in progress. Just fail this
3047 kiocb->ki_complete(kiocb, ret, 0);
3051 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3053 struct kiocb *kiocb = &req->rw.kiocb;
3055 if (kiocb->ki_pos != -1)
3056 return &kiocb->ki_pos;
3058 if (!(req->file->f_mode & FMODE_STREAM)) {
3059 req->flags |= REQ_F_CUR_POS;
3060 kiocb->ki_pos = req->file->f_pos;
3061 return &kiocb->ki_pos;
3068 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3069 unsigned int issue_flags)
3071 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3073 if (req->flags & REQ_F_CUR_POS)
3074 req->file->f_pos = kiocb->ki_pos;
3075 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw)) {
3076 if (!__io_complete_rw_common(req, ret)) {
3078 * Safe to call io_end from here as we're inline
3079 * from the submission path.
3082 __io_req_complete(req, issue_flags,
3083 io_fixup_rw_res(req, ret),
3084 io_put_rw_kbuf(req));
3087 io_rw_done(kiocb, ret);
3090 if (req->flags & REQ_F_REISSUE) {
3091 req->flags &= ~REQ_F_REISSUE;
3092 if (io_resubmit_prep(req)) {
3093 io_req_task_queue_reissue(req);
3095 unsigned int cflags = io_put_rw_kbuf(req);
3096 struct io_ring_ctx *ctx = req->ctx;
3098 ret = io_fixup_rw_res(req, ret);
3100 if (!(issue_flags & IO_URING_F_NONBLOCK)) {
3101 mutex_lock(&ctx->uring_lock);
3102 __io_req_complete(req, issue_flags, ret, cflags);
3103 mutex_unlock(&ctx->uring_lock);
3105 __io_req_complete(req, issue_flags, ret, cflags);
3111 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3112 struct io_mapped_ubuf *imu)
3114 size_t len = req->rw.len;
3115 u64 buf_end, buf_addr = req->rw.addr;
3118 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3120 /* not inside the mapped region */
3121 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3125 * May not be a start of buffer, set size appropriately
3126 * and advance us to the beginning.
3128 offset = buf_addr - imu->ubuf;
3129 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3133 * Don't use iov_iter_advance() here, as it's really slow for
3134 * using the latter parts of a big fixed buffer - it iterates
3135 * over each segment manually. We can cheat a bit here, because
3138 * 1) it's a BVEC iter, we set it up
3139 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3140 * first and last bvec
3142 * So just find our index, and adjust the iterator afterwards.
3143 * If the offset is within the first bvec (or the whole first
3144 * bvec, just use iov_iter_advance(). This makes it easier
3145 * since we can just skip the first segment, which may not
3146 * be PAGE_SIZE aligned.
3148 const struct bio_vec *bvec = imu->bvec;
3150 if (offset <= bvec->bv_len) {
3151 iov_iter_advance(iter, offset);
3153 unsigned long seg_skip;
3155 /* skip first vec */
3156 offset -= bvec->bv_len;
3157 seg_skip = 1 + (offset >> PAGE_SHIFT);
3159 iter->bvec = bvec + seg_skip;
3160 iter->nr_segs -= seg_skip;
3161 iter->count -= bvec->bv_len + offset;
3162 iter->iov_offset = offset & ~PAGE_MASK;
3169 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3171 if (WARN_ON_ONCE(!req->imu))
3173 return __io_import_fixed(req, rw, iter, req->imu);
3176 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3179 mutex_unlock(&ctx->uring_lock);
3182 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3185 * "Normal" inline submissions always hold the uring_lock, since we
3186 * grab it from the system call. Same is true for the SQPOLL offload.
3187 * The only exception is when we've detached the request and issue it
3188 * from an async worker thread, grab the lock for that case.
3191 mutex_lock(&ctx->uring_lock);
3194 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3195 int bgid, struct io_buffer *kbuf,
3198 struct io_buffer *head;
3200 if (req->flags & REQ_F_BUFFER_SELECTED)
3203 io_ring_submit_lock(req->ctx, needs_lock);
3205 lockdep_assert_held(&req->ctx->uring_lock);
3207 head = xa_load(&req->ctx->io_buffers, bgid);
3209 if (!list_empty(&head->list)) {
3210 kbuf = list_last_entry(&head->list, struct io_buffer,
3212 list_del(&kbuf->list);
3215 xa_erase(&req->ctx->io_buffers, bgid);
3217 if (*len > kbuf->len)
3220 kbuf = ERR_PTR(-ENOBUFS);
3223 io_ring_submit_unlock(req->ctx, needs_lock);
3228 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3231 struct io_buffer *kbuf;
3234 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3235 bgid = req->buf_index;
3236 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3239 req->rw.addr = (u64) (unsigned long) kbuf;
3240 req->flags |= REQ_F_BUFFER_SELECTED;
3241 return u64_to_user_ptr(kbuf->addr);
3244 #ifdef CONFIG_COMPAT
3245 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3248 struct compat_iovec __user *uiov;
3249 compat_ssize_t clen;
3253 uiov = u64_to_user_ptr(req->rw.addr);
3254 if (!access_ok(uiov, sizeof(*uiov)))
3256 if (__get_user(clen, &uiov->iov_len))
3262 buf = io_rw_buffer_select(req, &len, needs_lock);
3264 return PTR_ERR(buf);
3265 iov[0].iov_base = buf;
3266 iov[0].iov_len = (compat_size_t) len;
3271 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3274 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3278 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3281 len = iov[0].iov_len;
3284 buf = io_rw_buffer_select(req, &len, needs_lock);
3286 return PTR_ERR(buf);
3287 iov[0].iov_base = buf;
3288 iov[0].iov_len = len;
3292 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3295 if (req->flags & REQ_F_BUFFER_SELECTED) {
3296 struct io_buffer *kbuf;
3298 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3299 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3300 iov[0].iov_len = kbuf->len;
3303 if (req->rw.len != 1)
3306 #ifdef CONFIG_COMPAT
3307 if (req->ctx->compat)
3308 return io_compat_import(req, iov, needs_lock);
3311 return __io_iov_buffer_select(req, iov, needs_lock);
3314 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3315 struct iov_iter *iter, bool needs_lock)
3317 void __user *buf = u64_to_user_ptr(req->rw.addr);
3318 size_t sqe_len = req->rw.len;
3319 u8 opcode = req->opcode;
3322 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3324 return io_import_fixed(req, rw, iter);
3327 /* buffer index only valid with fixed read/write, or buffer select */
3328 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3331 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3332 if (req->flags & REQ_F_BUFFER_SELECT) {
3333 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3335 return PTR_ERR(buf);
3336 req->rw.len = sqe_len;
3339 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3344 if (req->flags & REQ_F_BUFFER_SELECT) {
3345 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3347 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3352 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3356 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3358 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3362 * For files that don't have ->read_iter() and ->write_iter(), handle them
3363 * by looping over ->read() or ->write() manually.
3365 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3367 struct kiocb *kiocb = &req->rw.kiocb;
3368 struct file *file = req->file;
3373 * Don't support polled IO through this interface, and we can't
3374 * support non-blocking either. For the latter, this just causes
3375 * the kiocb to be handled from an async context.
3377 if (kiocb->ki_flags & IOCB_HIPRI)
3379 if (kiocb->ki_flags & IOCB_NOWAIT)
3382 ppos = io_kiocb_ppos(kiocb);
3384 while (iov_iter_count(iter)) {
3388 if (!iov_iter_is_bvec(iter)) {
3389 iovec = iov_iter_iovec(iter);
3391 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3392 iovec.iov_len = req->rw.len;
3396 nr = file->f_op->read(file, iovec.iov_base,
3397 iovec.iov_len, ppos);
3399 nr = file->f_op->write(file, iovec.iov_base,
3400 iovec.iov_len, ppos);
3409 if (!iov_iter_is_bvec(iter)) {
3410 iov_iter_advance(iter, nr);
3417 if (nr != iovec.iov_len)
3424 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3425 const struct iovec *fast_iov, struct iov_iter *iter)
3427 struct io_async_rw *rw = req->async_data;
3429 memcpy(&rw->iter, iter, sizeof(*iter));
3430 rw->free_iovec = iovec;
3432 /* can only be fixed buffers, no need to do anything */
3433 if (iov_iter_is_bvec(iter))
3436 unsigned iov_off = 0;
3438 rw->iter.iov = rw->fast_iov;
3439 if (iter->iov != fast_iov) {
3440 iov_off = iter->iov - fast_iov;
3441 rw->iter.iov += iov_off;
3443 if (rw->fast_iov != fast_iov)
3444 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3445 sizeof(struct iovec) * iter->nr_segs);
3447 req->flags |= REQ_F_NEED_CLEANUP;
3451 static inline int io_alloc_async_data(struct io_kiocb *req)
3453 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3454 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3455 return req->async_data == NULL;
3458 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3459 const struct iovec *fast_iov,
3460 struct iov_iter *iter, bool force)
3462 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3464 if (!req->async_data) {
3465 struct io_async_rw *iorw;
3467 if (io_alloc_async_data(req)) {
3472 io_req_map_rw(req, iovec, fast_iov, iter);
3473 iorw = req->async_data;
3474 /* we've copied and mapped the iter, ensure state is saved */
3475 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3480 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3482 struct io_async_rw *iorw = req->async_data;
3483 struct iovec *iov = iorw->fast_iov;
3486 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3487 if (unlikely(ret < 0))
3490 iorw->bytes_done = 0;
3491 iorw->free_iovec = iov;
3493 req->flags |= REQ_F_NEED_CLEANUP;
3494 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3498 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3500 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3502 return io_prep_rw(req, sqe, READ);
3506 * This is our waitqueue callback handler, registered through lock_page_async()
3507 * when we initially tried to do the IO with the iocb armed our waitqueue.
3508 * This gets called when the page is unlocked, and we generally expect that to
3509 * happen when the page IO is completed and the page is now uptodate. This will
3510 * queue a task_work based retry of the operation, attempting to copy the data
3511 * again. If the latter fails because the page was NOT uptodate, then we will
3512 * do a thread based blocking retry of the operation. That's the unexpected
3515 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3516 int sync, void *arg)
3518 struct wait_page_queue *wpq;
3519 struct io_kiocb *req = wait->private;
3520 struct wait_page_key *key = arg;
3522 wpq = container_of(wait, struct wait_page_queue, wait);
3524 if (!wake_page_match(wpq, key))
3527 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3528 list_del_init(&wait->entry);
3529 io_req_task_queue(req);
3534 * This controls whether a given IO request should be armed for async page
3535 * based retry. If we return false here, the request is handed to the async
3536 * worker threads for retry. If we're doing buffered reads on a regular file,
3537 * we prepare a private wait_page_queue entry and retry the operation. This
3538 * will either succeed because the page is now uptodate and unlocked, or it
3539 * will register a callback when the page is unlocked at IO completion. Through
3540 * that callback, io_uring uses task_work to setup a retry of the operation.
3541 * That retry will attempt the buffered read again. The retry will generally
3542 * succeed, or in rare cases where it fails, we then fall back to using the
3543 * async worker threads for a blocking retry.
3545 static bool io_rw_should_retry(struct io_kiocb *req)
3547 struct io_async_rw *rw = req->async_data;
3548 struct wait_page_queue *wait = &rw->wpq;
3549 struct kiocb *kiocb = &req->rw.kiocb;
3551 /* never retry for NOWAIT, we just complete with -EAGAIN */
3552 if (req->flags & REQ_F_NOWAIT)
3555 /* Only for buffered IO */
3556 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3560 * just use poll if we can, and don't attempt if the fs doesn't
3561 * support callback based unlocks
3563 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3566 wait->wait.func = io_async_buf_func;
3567 wait->wait.private = req;
3568 wait->wait.flags = 0;
3569 INIT_LIST_HEAD(&wait->wait.entry);
3570 kiocb->ki_flags |= IOCB_WAITQ;
3571 kiocb->ki_flags &= ~IOCB_NOWAIT;
3572 kiocb->ki_waitq = wait;
3576 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3578 if (req->file->f_op->read_iter)
3579 return call_read_iter(req->file, &req->rw.kiocb, iter);
3580 else if (req->file->f_op->read)
3581 return loop_rw_iter(READ, req, iter);
3586 static bool need_read_all(struct io_kiocb *req)
3588 return req->flags & REQ_F_ISREG ||
3589 S_ISBLK(file_inode(req->file)->i_mode);
3592 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3594 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3595 struct kiocb *kiocb = &req->rw.kiocb;
3596 struct iov_iter __iter, *iter = &__iter;
3597 struct io_async_rw *rw = req->async_data;
3598 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3599 struct iov_iter_state __state, *state;
3605 state = &rw->iter_state;
3607 * We come here from an earlier attempt, restore our state to
3608 * match in case it doesn't. It's cheap enough that we don't
3609 * need to make this conditional.
3611 iov_iter_restore(iter, state);
3614 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3618 iov_iter_save_state(iter, state);
3620 req->result = iov_iter_count(iter);
3622 /* Ensure we clear previously set non-block flag */
3623 if (!force_nonblock)
3624 kiocb->ki_flags &= ~IOCB_NOWAIT;
3626 kiocb->ki_flags |= IOCB_NOWAIT;
3628 /* If the file doesn't support async, just async punt */
3629 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3630 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3631 return ret ?: -EAGAIN;
3634 ppos = io_kiocb_update_pos(req);
3636 ret = rw_verify_area(READ, req->file, ppos, req->result);
3637 if (unlikely(ret)) {
3642 ret = io_iter_do_read(req, iter);
3644 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3645 req->flags &= ~REQ_F_REISSUE;
3646 /* IOPOLL retry should happen for io-wq threads */
3647 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3649 /* no retry on NONBLOCK nor RWF_NOWAIT */
3650 if (req->flags & REQ_F_NOWAIT)
3653 } else if (ret == -EIOCBQUEUED) {
3655 } else if (ret <= 0 || ret == req->result || !force_nonblock ||
3656 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3657 /* read all, failed, already did sync or don't want to retry */
3662 * Don't depend on the iter state matching what was consumed, or being
3663 * untouched in case of error. Restore it and we'll advance it
3664 * manually if we need to.
3666 iov_iter_restore(iter, state);
3668 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3673 rw = req->async_data;
3675 * Now use our persistent iterator and state, if we aren't already.
3676 * We've restored and mapped the iter to match.
3678 if (iter != &rw->iter) {
3680 state = &rw->iter_state;
3685 * We end up here because of a partial read, either from
3686 * above or inside this loop. Advance the iter by the bytes
3687 * that were consumed.
3689 iov_iter_advance(iter, ret);
3690 if (!iov_iter_count(iter))
3692 rw->bytes_done += ret;
3693 iov_iter_save_state(iter, state);
3695 /* if we can retry, do so with the callbacks armed */
3696 if (!io_rw_should_retry(req)) {
3697 kiocb->ki_flags &= ~IOCB_WAITQ;
3701 req->result = iov_iter_count(iter);
3703 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3704 * we get -EIOCBQUEUED, then we'll get a notification when the
3705 * desired page gets unlocked. We can also get a partial read
3706 * here, and if we do, then just retry at the new offset.
3708 ret = io_iter_do_read(req, iter);
3709 if (ret == -EIOCBQUEUED)
3711 /* we got some bytes, but not all. retry. */
3712 kiocb->ki_flags &= ~IOCB_WAITQ;
3713 iov_iter_restore(iter, state);
3716 kiocb_done(kiocb, ret, issue_flags);
3718 /* it's faster to check here then delegate to kfree */
3724 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3726 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3728 return io_prep_rw(req, sqe, WRITE);
3731 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3733 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3734 struct kiocb *kiocb = &req->rw.kiocb;
3735 struct iov_iter __iter, *iter = &__iter;
3736 struct io_async_rw *rw = req->async_data;
3737 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3738 struct iov_iter_state __state, *state;
3744 state = &rw->iter_state;
3745 iov_iter_restore(iter, state);
3748 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3752 iov_iter_save_state(iter, state);
3754 req->result = iov_iter_count(iter);
3756 /* Ensure we clear previously set non-block flag */
3757 if (!force_nonblock)
3758 kiocb->ki_flags &= ~IOCB_NOWAIT;
3760 kiocb->ki_flags |= IOCB_NOWAIT;
3762 /* If the file doesn't support async, just async punt */
3763 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3766 /* file path doesn't support NOWAIT for non-direct_IO */
3767 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3768 (req->flags & REQ_F_ISREG))
3771 ppos = io_kiocb_update_pos(req);
3773 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3778 * Open-code file_start_write here to grab freeze protection,
3779 * which will be released by another thread in
3780 * io_complete_rw(). Fool lockdep by telling it the lock got
3781 * released so that it doesn't complain about the held lock when
3782 * we return to userspace.
3784 if (req->flags & REQ_F_ISREG) {
3785 sb_start_write(file_inode(req->file)->i_sb);
3786 __sb_writers_release(file_inode(req->file)->i_sb,
3789 kiocb->ki_flags |= IOCB_WRITE;
3791 if (req->file->f_op->write_iter)
3792 ret2 = call_write_iter(req->file, kiocb, iter);
3793 else if (req->file->f_op->write)
3794 ret2 = loop_rw_iter(WRITE, req, iter);
3798 if (req->flags & REQ_F_REISSUE) {
3799 req->flags &= ~REQ_F_REISSUE;
3804 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3805 * retry them without IOCB_NOWAIT.
3807 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3809 /* no retry on NONBLOCK nor RWF_NOWAIT */
3810 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3812 if (!force_nonblock || ret2 != -EAGAIN) {
3813 /* IOPOLL retry should happen for io-wq threads */
3814 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3817 kiocb_done(kiocb, ret2, issue_flags);
3820 iov_iter_restore(iter, state);
3821 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3823 if (kiocb->ki_flags & IOCB_WRITE)
3824 kiocb_end_write(req);
3830 /* it's reportedly faster than delegating the null check to kfree() */
3836 static int io_renameat_prep(struct io_kiocb *req,
3837 const struct io_uring_sqe *sqe)
3839 struct io_rename *ren = &req->rename;
3840 const char __user *oldf, *newf;
3842 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3844 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3846 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3849 ren->old_dfd = READ_ONCE(sqe->fd);
3850 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3851 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3852 ren->new_dfd = READ_ONCE(sqe->len);
3853 ren->flags = READ_ONCE(sqe->rename_flags);
3855 ren->oldpath = getname(oldf);
3856 if (IS_ERR(ren->oldpath))
3857 return PTR_ERR(ren->oldpath);
3859 ren->newpath = getname(newf);
3860 if (IS_ERR(ren->newpath)) {
3861 putname(ren->oldpath);
3862 return PTR_ERR(ren->newpath);
3865 req->flags |= REQ_F_NEED_CLEANUP;
3869 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3871 struct io_rename *ren = &req->rename;
3874 if (issue_flags & IO_URING_F_NONBLOCK)
3877 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3878 ren->newpath, ren->flags);
3880 req->flags &= ~REQ_F_NEED_CLEANUP;
3883 io_req_complete(req, ret);
3887 static int io_unlinkat_prep(struct io_kiocb *req,
3888 const struct io_uring_sqe *sqe)
3890 struct io_unlink *un = &req->unlink;
3891 const char __user *fname;
3893 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3895 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3898 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3901 un->dfd = READ_ONCE(sqe->fd);
3903 un->flags = READ_ONCE(sqe->unlink_flags);
3904 if (un->flags & ~AT_REMOVEDIR)
3907 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3908 un->filename = getname(fname);
3909 if (IS_ERR(un->filename))
3910 return PTR_ERR(un->filename);
3912 req->flags |= REQ_F_NEED_CLEANUP;
3916 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3918 struct io_unlink *un = &req->unlink;
3921 if (issue_flags & IO_URING_F_NONBLOCK)
3924 if (un->flags & AT_REMOVEDIR)
3925 ret = do_rmdir(un->dfd, un->filename);
3927 ret = do_unlinkat(un->dfd, un->filename);
3929 req->flags &= ~REQ_F_NEED_CLEANUP;
3932 io_req_complete(req, ret);
3936 static int io_mkdirat_prep(struct io_kiocb *req,
3937 const struct io_uring_sqe *sqe)
3939 struct io_mkdir *mkd = &req->mkdir;
3940 const char __user *fname;
3942 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3944 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3947 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3950 mkd->dfd = READ_ONCE(sqe->fd);
3951 mkd->mode = READ_ONCE(sqe->len);
3953 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3954 mkd->filename = getname(fname);
3955 if (IS_ERR(mkd->filename))
3956 return PTR_ERR(mkd->filename);
3958 req->flags |= REQ_F_NEED_CLEANUP;
3962 static int io_mkdirat(struct io_kiocb *req, int issue_flags)
3964 struct io_mkdir *mkd = &req->mkdir;
3967 if (issue_flags & IO_URING_F_NONBLOCK)
3970 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3972 req->flags &= ~REQ_F_NEED_CLEANUP;
3975 io_req_complete(req, ret);
3979 static int io_symlinkat_prep(struct io_kiocb *req,
3980 const struct io_uring_sqe *sqe)
3982 struct io_symlink *sl = &req->symlink;
3983 const char __user *oldpath, *newpath;
3985 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3987 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3990 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3993 sl->new_dfd = READ_ONCE(sqe->fd);
3994 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3995 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3997 sl->oldpath = getname(oldpath);
3998 if (IS_ERR(sl->oldpath))
3999 return PTR_ERR(sl->oldpath);
4001 sl->newpath = getname(newpath);
4002 if (IS_ERR(sl->newpath)) {
4003 putname(sl->oldpath);
4004 return PTR_ERR(sl->newpath);
4007 req->flags |= REQ_F_NEED_CLEANUP;
4011 static int io_symlinkat(struct io_kiocb *req, int issue_flags)
4013 struct io_symlink *sl = &req->symlink;
4016 if (issue_flags & IO_URING_F_NONBLOCK)
4019 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4021 req->flags &= ~REQ_F_NEED_CLEANUP;
4024 io_req_complete(req, ret);
4028 static int io_linkat_prep(struct io_kiocb *req,
4029 const struct io_uring_sqe *sqe)
4031 struct io_hardlink *lnk = &req->hardlink;
4032 const char __user *oldf, *newf;
4034 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4036 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4038 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4041 lnk->old_dfd = READ_ONCE(sqe->fd);
4042 lnk->new_dfd = READ_ONCE(sqe->len);
4043 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4044 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4045 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4047 lnk->oldpath = getname(oldf);
4048 if (IS_ERR(lnk->oldpath))
4049 return PTR_ERR(lnk->oldpath);
4051 lnk->newpath = getname(newf);
4052 if (IS_ERR(lnk->newpath)) {
4053 putname(lnk->oldpath);
4054 return PTR_ERR(lnk->newpath);
4057 req->flags |= REQ_F_NEED_CLEANUP;
4061 static int io_linkat(struct io_kiocb *req, int issue_flags)
4063 struct io_hardlink *lnk = &req->hardlink;
4066 if (issue_flags & IO_URING_F_NONBLOCK)
4069 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4070 lnk->newpath, lnk->flags);
4072 req->flags &= ~REQ_F_NEED_CLEANUP;
4075 io_req_complete(req, ret);
4079 static int io_shutdown_prep(struct io_kiocb *req,
4080 const struct io_uring_sqe *sqe)
4082 #if defined(CONFIG_NET)
4083 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4085 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4086 sqe->buf_index || sqe->splice_fd_in))
4089 req->shutdown.how = READ_ONCE(sqe->len);
4096 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4098 #if defined(CONFIG_NET)
4099 struct socket *sock;
4102 if (issue_flags & IO_URING_F_NONBLOCK)
4105 sock = sock_from_file(req->file);
4106 if (unlikely(!sock))
4109 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4112 io_req_complete(req, ret);
4119 static int __io_splice_prep(struct io_kiocb *req,
4120 const struct io_uring_sqe *sqe)
4122 struct io_splice *sp = &req->splice;
4123 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4125 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4128 sp->len = READ_ONCE(sqe->len);
4129 sp->flags = READ_ONCE(sqe->splice_flags);
4130 if (unlikely(sp->flags & ~valid_flags))
4132 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4136 static int io_tee_prep(struct io_kiocb *req,
4137 const struct io_uring_sqe *sqe)
4139 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4141 return __io_splice_prep(req, sqe);
4144 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4146 struct io_splice *sp = &req->splice;
4147 struct file *out = sp->file_out;
4148 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4152 if (issue_flags & IO_URING_F_NONBLOCK)
4155 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4156 (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4163 ret = do_tee(in, out, sp->len, flags);
4165 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4170 io_req_complete(req, ret);
4174 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4176 struct io_splice *sp = &req->splice;
4178 sp->off_in = READ_ONCE(sqe->splice_off_in);
4179 sp->off_out = READ_ONCE(sqe->off);
4180 return __io_splice_prep(req, sqe);
4183 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4185 struct io_splice *sp = &req->splice;
4186 struct file *out = sp->file_out;
4187 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4188 loff_t *poff_in, *poff_out;
4192 if (issue_flags & IO_URING_F_NONBLOCK)
4195 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4196 (sp->flags & SPLICE_F_FD_IN_FIXED), issue_flags);
4202 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4203 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4206 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4208 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4213 io_req_complete(req, ret);
4218 * IORING_OP_NOP just posts a completion event, nothing else.
4220 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4222 struct io_ring_ctx *ctx = req->ctx;
4224 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4227 __io_req_complete(req, issue_flags, 0, 0);
4231 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4233 struct io_ring_ctx *ctx = req->ctx;
4235 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4237 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4241 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4242 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4245 req->sync.off = READ_ONCE(sqe->off);
4246 req->sync.len = READ_ONCE(sqe->len);
4250 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4252 loff_t end = req->sync.off + req->sync.len;
4255 /* fsync always requires a blocking context */
4256 if (issue_flags & IO_URING_F_NONBLOCK)
4259 ret = vfs_fsync_range(req->file, req->sync.off,
4260 end > 0 ? end : LLONG_MAX,
4261 req->sync.flags & IORING_FSYNC_DATASYNC);
4264 io_req_complete(req, ret);
4268 static int io_fallocate_prep(struct io_kiocb *req,
4269 const struct io_uring_sqe *sqe)
4271 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4274 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4277 req->sync.off = READ_ONCE(sqe->off);
4278 req->sync.len = READ_ONCE(sqe->addr);
4279 req->sync.mode = READ_ONCE(sqe->len);
4283 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4287 /* fallocate always requiring blocking context */
4288 if (issue_flags & IO_URING_F_NONBLOCK)
4290 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4295 fsnotify_modify(req->file);
4296 io_req_complete(req, ret);
4300 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4302 const char __user *fname;
4305 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4307 if (unlikely(sqe->ioprio || sqe->buf_index))
4309 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4312 /* open.how should be already initialised */
4313 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4314 req->open.how.flags |= O_LARGEFILE;
4316 req->open.dfd = READ_ONCE(sqe->fd);
4317 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4318 req->open.filename = getname(fname);
4319 if (IS_ERR(req->open.filename)) {
4320 ret = PTR_ERR(req->open.filename);
4321 req->open.filename = NULL;
4325 req->open.file_slot = READ_ONCE(sqe->file_index);
4326 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4329 req->open.nofile = rlimit(RLIMIT_NOFILE);
4330 req->flags |= REQ_F_NEED_CLEANUP;
4334 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4336 u64 mode = READ_ONCE(sqe->len);
4337 u64 flags = READ_ONCE(sqe->open_flags);
4339 req->open.how = build_open_how(flags, mode);
4340 return __io_openat_prep(req, sqe);
4343 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4345 struct open_how __user *how;
4349 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4350 len = READ_ONCE(sqe->len);
4351 if (len < OPEN_HOW_SIZE_VER0)
4354 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4359 return __io_openat_prep(req, sqe);
4362 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4364 struct open_flags op;
4366 bool resolve_nonblock, nonblock_set;
4367 bool fixed = !!req->open.file_slot;
4370 ret = build_open_flags(&req->open.how, &op);
4373 nonblock_set = op.open_flag & O_NONBLOCK;
4374 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4375 if (issue_flags & IO_URING_F_NONBLOCK) {
4377 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4378 * it'll always -EAGAIN. Note that we test for __O_TMPFILE
4379 * because O_TMPFILE includes O_DIRECTORY, which isn't a flag
4380 * we need to force async for.
4382 if (req->open.how.flags & (O_TRUNC | O_CREAT | __O_TMPFILE))
4384 op.lookup_flags |= LOOKUP_CACHED;
4385 op.open_flag |= O_NONBLOCK;
4389 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4394 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4397 * We could hang on to this 'fd' on retrying, but seems like
4398 * marginal gain for something that is now known to be a slower
4399 * path. So just put it, and we'll get a new one when we retry.
4404 ret = PTR_ERR(file);
4405 /* only retry if RESOLVE_CACHED wasn't already set by application */
4406 if (ret == -EAGAIN &&
4407 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4412 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4413 file->f_flags &= ~O_NONBLOCK;
4414 fsnotify_open(file);
4417 fd_install(ret, file);
4419 ret = io_install_fixed_file(req, file, issue_flags,
4420 req->open.file_slot - 1);
4422 putname(req->open.filename);
4423 req->flags &= ~REQ_F_NEED_CLEANUP;
4426 __io_req_complete(req, issue_flags, ret, 0);
4430 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4432 return io_openat2(req, issue_flags);
4435 static int io_remove_buffers_prep(struct io_kiocb *req,
4436 const struct io_uring_sqe *sqe)
4438 struct io_provide_buf *p = &req->pbuf;
4441 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4445 tmp = READ_ONCE(sqe->fd);
4446 if (!tmp || tmp > USHRT_MAX)
4449 memset(p, 0, sizeof(*p));
4451 p->bgid = READ_ONCE(sqe->buf_group);
4455 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4456 int bgid, unsigned nbufs)
4460 /* shouldn't happen */
4464 /* the head kbuf is the list itself */
4465 while (!list_empty(&buf->list)) {
4466 struct io_buffer *nxt;
4468 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4469 list_del(&nxt->list);
4477 xa_erase(&ctx->io_buffers, bgid);
4482 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4484 struct io_provide_buf *p = &req->pbuf;
4485 struct io_ring_ctx *ctx = req->ctx;
4486 struct io_buffer *head;
4488 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4490 io_ring_submit_lock(ctx, !force_nonblock);
4492 lockdep_assert_held(&ctx->uring_lock);
4495 head = xa_load(&ctx->io_buffers, p->bgid);
4497 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4501 /* complete before unlock, IOPOLL may need the lock */
4502 __io_req_complete(req, issue_flags, ret, 0);
4503 io_ring_submit_unlock(ctx, !force_nonblock);
4507 static int io_provide_buffers_prep(struct io_kiocb *req,
4508 const struct io_uring_sqe *sqe)
4510 unsigned long size, tmp_check;
4511 struct io_provide_buf *p = &req->pbuf;
4514 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4517 tmp = READ_ONCE(sqe->fd);
4518 if (!tmp || tmp > USHRT_MAX)
4521 p->addr = READ_ONCE(sqe->addr);
4522 p->len = READ_ONCE(sqe->len);
4524 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4527 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4530 size = (unsigned long)p->len * p->nbufs;
4531 if (!access_ok(u64_to_user_ptr(p->addr), size))
4534 p->bgid = READ_ONCE(sqe->buf_group);
4535 tmp = READ_ONCE(sqe->off);
4536 if (tmp > USHRT_MAX)
4542 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4544 struct io_buffer *buf;
4545 u64 addr = pbuf->addr;
4546 int i, bid = pbuf->bid;
4548 for (i = 0; i < pbuf->nbufs; i++) {
4549 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4554 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4559 INIT_LIST_HEAD(&buf->list);
4562 list_add_tail(&buf->list, &(*head)->list);
4567 return i ? i : -ENOMEM;
4570 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4572 struct io_provide_buf *p = &req->pbuf;
4573 struct io_ring_ctx *ctx = req->ctx;
4574 struct io_buffer *head, *list;
4576 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4578 io_ring_submit_lock(ctx, !force_nonblock);
4580 lockdep_assert_held(&ctx->uring_lock);
4582 list = head = xa_load(&ctx->io_buffers, p->bgid);
4584 ret = io_add_buffers(p, &head);
4585 if (ret >= 0 && !list) {
4586 ret = xa_insert(&ctx->io_buffers, p->bgid, head,
4587 GFP_KERNEL_ACCOUNT);
4589 __io_remove_buffers(ctx, head, p->bgid, -1U);
4593 /* complete before unlock, IOPOLL may need the lock */
4594 __io_req_complete(req, issue_flags, ret, 0);
4595 io_ring_submit_unlock(ctx, !force_nonblock);
4599 static int io_epoll_ctl_prep(struct io_kiocb *req,
4600 const struct io_uring_sqe *sqe)
4602 #if defined(CONFIG_EPOLL)
4603 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4605 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4608 req->epoll.epfd = READ_ONCE(sqe->fd);
4609 req->epoll.op = READ_ONCE(sqe->len);
4610 req->epoll.fd = READ_ONCE(sqe->off);
4612 if (ep_op_has_event(req->epoll.op)) {
4613 struct epoll_event __user *ev;
4615 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4616 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4626 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4628 #if defined(CONFIG_EPOLL)
4629 struct io_epoll *ie = &req->epoll;
4631 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4633 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4634 if (force_nonblock && ret == -EAGAIN)
4639 __io_req_complete(req, issue_flags, ret, 0);
4646 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4648 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4649 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4651 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4654 req->madvise.addr = READ_ONCE(sqe->addr);
4655 req->madvise.len = READ_ONCE(sqe->len);
4656 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4663 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4665 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4666 struct io_madvise *ma = &req->madvise;
4669 if (issue_flags & IO_URING_F_NONBLOCK)
4672 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4675 io_req_complete(req, ret);
4682 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4684 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4686 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4689 req->fadvise.offset = READ_ONCE(sqe->off);
4690 req->fadvise.len = READ_ONCE(sqe->len);
4691 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4695 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4697 struct io_fadvise *fa = &req->fadvise;
4700 if (issue_flags & IO_URING_F_NONBLOCK) {
4701 switch (fa->advice) {
4702 case POSIX_FADV_NORMAL:
4703 case POSIX_FADV_RANDOM:
4704 case POSIX_FADV_SEQUENTIAL:
4711 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4714 __io_req_complete(req, issue_flags, ret, 0);
4718 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4720 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4722 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4724 if (req->flags & REQ_F_FIXED_FILE)
4727 req->statx.dfd = READ_ONCE(sqe->fd);
4728 req->statx.mask = READ_ONCE(sqe->len);
4729 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4730 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4731 req->statx.flags = READ_ONCE(sqe->statx_flags);
4736 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4738 struct io_statx *ctx = &req->statx;
4741 if (issue_flags & IO_URING_F_NONBLOCK)
4744 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4749 io_req_complete(req, ret);
4753 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4755 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4757 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4758 sqe->rw_flags || sqe->buf_index)
4760 if (req->flags & REQ_F_FIXED_FILE)
4763 req->close.fd = READ_ONCE(sqe->fd);
4764 req->close.file_slot = READ_ONCE(sqe->file_index);
4765 if (req->close.file_slot && req->close.fd)
4771 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4773 struct files_struct *files = current->files;
4774 struct io_close *close = &req->close;
4775 struct fdtable *fdt;
4776 struct file *file = NULL;
4779 if (req->close.file_slot) {
4780 ret = io_close_fixed(req, issue_flags);
4784 spin_lock(&files->file_lock);
4785 fdt = files_fdtable(files);
4786 if (close->fd >= fdt->max_fds) {
4787 spin_unlock(&files->file_lock);
4790 file = fdt->fd[close->fd];
4791 if (!file || file->f_op == &io_uring_fops) {
4792 spin_unlock(&files->file_lock);
4797 /* if the file has a flush method, be safe and punt to async */
4798 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4799 spin_unlock(&files->file_lock);
4803 ret = __close_fd_get_file(close->fd, &file);
4804 spin_unlock(&files->file_lock);
4811 /* No ->flush() or already async, safely close from here */
4812 ret = filp_close(file, current->files);
4818 __io_req_complete(req, issue_flags, ret, 0);
4822 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4824 struct io_ring_ctx *ctx = req->ctx;
4826 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4828 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4832 req->sync.off = READ_ONCE(sqe->off);
4833 req->sync.len = READ_ONCE(sqe->len);
4834 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4838 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4842 /* sync_file_range always requires a blocking context */
4843 if (issue_flags & IO_URING_F_NONBLOCK)
4846 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4850 io_req_complete(req, ret);
4854 #if defined(CONFIG_NET)
4855 static bool io_net_retry(struct socket *sock, int flags)
4857 if (!(flags & MSG_WAITALL))
4859 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4862 static int io_setup_async_msg(struct io_kiocb *req,
4863 struct io_async_msghdr *kmsg)
4865 struct io_async_msghdr *async_msg = req->async_data;
4869 if (io_alloc_async_data(req)) {
4870 kfree(kmsg->free_iov);
4873 async_msg = req->async_data;
4874 req->flags |= REQ_F_NEED_CLEANUP;
4875 memcpy(async_msg, kmsg, sizeof(*kmsg));
4876 if (async_msg->msg.msg_name)
4877 async_msg->msg.msg_name = &async_msg->addr;
4878 /* if were using fast_iov, set it to the new one */
4879 if (!kmsg->free_iov) {
4880 size_t fast_idx = kmsg->msg.msg_iter.iov - kmsg->fast_iov;
4881 async_msg->msg.msg_iter.iov = &async_msg->fast_iov[fast_idx];
4887 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4888 struct io_async_msghdr *iomsg)
4890 struct io_sr_msg *sr = &req->sr_msg;
4893 iomsg->msg.msg_name = &iomsg->addr;
4894 iomsg->free_iov = iomsg->fast_iov;
4895 ret = sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4896 req->sr_msg.msg_flags, &iomsg->free_iov);
4897 /* save msg_control as sys_sendmsg() overwrites it */
4898 sr->msg_control = iomsg->msg.msg_control;
4902 static int io_sendmsg_prep_async(struct io_kiocb *req)
4906 ret = io_sendmsg_copy_hdr(req, req->async_data);
4908 req->flags |= REQ_F_NEED_CLEANUP;
4912 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4914 struct io_sr_msg *sr = &req->sr_msg;
4916 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4918 if (unlikely(sqe->addr2 || sqe->file_index))
4920 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
4923 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4924 sr->len = READ_ONCE(sqe->len);
4925 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4926 if (sr->msg_flags & MSG_DONTWAIT)
4927 req->flags |= REQ_F_NOWAIT;
4929 #ifdef CONFIG_COMPAT
4930 if (req->ctx->compat)
4931 sr->msg_flags |= MSG_CMSG_COMPAT;
4937 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4939 struct io_async_msghdr iomsg, *kmsg;
4940 struct io_sr_msg *sr = &req->sr_msg;
4941 struct socket *sock;
4946 sock = sock_from_file(req->file);
4947 if (unlikely(!sock))
4950 kmsg = req->async_data;
4952 ret = io_sendmsg_copy_hdr(req, &iomsg);
4957 kmsg->msg.msg_control = sr->msg_control;
4960 flags = req->sr_msg.msg_flags;
4961 if (issue_flags & IO_URING_F_NONBLOCK)
4962 flags |= MSG_DONTWAIT;
4963 if (flags & MSG_WAITALL)
4964 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4966 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4968 if (ret < min_ret) {
4969 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4970 return io_setup_async_msg(req, kmsg);
4971 if (ret == -ERESTARTSYS)
4973 if (ret > 0 && io_net_retry(sock, flags)) {
4974 kmsg->msg.msg_controllen = 0;
4975 kmsg->msg.msg_control = NULL;
4977 req->flags |= REQ_F_PARTIAL_IO;
4978 return io_setup_async_msg(req, kmsg);
4982 /* fast path, check for non-NULL to avoid function call */
4984 kfree(kmsg->free_iov);
4985 req->flags &= ~REQ_F_NEED_CLEANUP;
4988 else if (sr->done_io)
4990 __io_req_complete(req, issue_flags, ret, 0);
4994 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4996 struct io_sr_msg *sr = &req->sr_msg;
4999 struct socket *sock;
5004 sock = sock_from_file(req->file);
5005 if (unlikely(!sock))
5008 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5012 msg.msg_name = NULL;
5013 msg.msg_control = NULL;
5014 msg.msg_controllen = 0;
5015 msg.msg_namelen = 0;
5017 flags = req->sr_msg.msg_flags;
5018 if (issue_flags & IO_URING_F_NONBLOCK)
5019 flags |= MSG_DONTWAIT;
5020 if (flags & MSG_WAITALL)
5021 min_ret = iov_iter_count(&msg.msg_iter);
5023 msg.msg_flags = flags;
5024 ret = sock_sendmsg(sock, &msg);
5025 if (ret < min_ret) {
5026 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5028 if (ret == -ERESTARTSYS)
5030 if (ret > 0 && io_net_retry(sock, flags)) {
5034 req->flags |= REQ_F_PARTIAL_IO;
5041 else if (sr->done_io)
5043 __io_req_complete(req, issue_flags, ret, 0);
5047 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5048 struct io_async_msghdr *iomsg)
5050 struct io_sr_msg *sr = &req->sr_msg;
5051 struct iovec __user *uiov;
5055 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5056 &iomsg->uaddr, &uiov, &iov_len);
5060 if (req->flags & REQ_F_BUFFER_SELECT) {
5063 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5065 sr->len = iomsg->fast_iov[0].iov_len;
5066 iomsg->free_iov = NULL;
5068 iomsg->free_iov = iomsg->fast_iov;
5069 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5070 &iomsg->free_iov, &iomsg->msg.msg_iter,
5079 #ifdef CONFIG_COMPAT
5080 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5081 struct io_async_msghdr *iomsg)
5083 struct io_sr_msg *sr = &req->sr_msg;
5084 struct compat_iovec __user *uiov;
5089 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5094 uiov = compat_ptr(ptr);
5095 if (req->flags & REQ_F_BUFFER_SELECT) {
5096 compat_ssize_t clen;
5100 if (!access_ok(uiov, sizeof(*uiov)))
5102 if (__get_user(clen, &uiov->iov_len))
5107 iomsg->free_iov = NULL;
5109 iomsg->free_iov = iomsg->fast_iov;
5110 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5111 UIO_FASTIOV, &iomsg->free_iov,
5112 &iomsg->msg.msg_iter, true);
5121 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5122 struct io_async_msghdr *iomsg)
5124 iomsg->msg.msg_name = &iomsg->addr;
5126 #ifdef CONFIG_COMPAT
5127 if (req->ctx->compat)
5128 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5131 return __io_recvmsg_copy_hdr(req, iomsg);
5134 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5137 struct io_sr_msg *sr = &req->sr_msg;
5138 struct io_buffer *kbuf;
5140 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
5145 req->flags |= REQ_F_BUFFER_SELECTED;
5149 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
5151 return io_put_kbuf(req, req->sr_msg.kbuf);
5154 static int io_recvmsg_prep_async(struct io_kiocb *req)
5158 ret = io_recvmsg_copy_hdr(req, req->async_data);
5160 req->flags |= REQ_F_NEED_CLEANUP;
5164 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5166 struct io_sr_msg *sr = &req->sr_msg;
5168 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5170 if (unlikely(sqe->addr2 || sqe->file_index))
5172 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
5175 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5176 sr->len = READ_ONCE(sqe->len);
5177 sr->bgid = READ_ONCE(sqe->buf_group);
5178 sr->msg_flags = READ_ONCE(sqe->msg_flags);
5179 if (sr->msg_flags & MSG_DONTWAIT)
5180 req->flags |= REQ_F_NOWAIT;
5182 #ifdef CONFIG_COMPAT
5183 if (req->ctx->compat)
5184 sr->msg_flags |= MSG_CMSG_COMPAT;
5190 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5192 struct io_async_msghdr iomsg, *kmsg;
5193 struct io_sr_msg *sr = &req->sr_msg;
5194 struct socket *sock;
5195 struct io_buffer *kbuf;
5198 int ret, cflags = 0;
5199 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5201 sock = sock_from_file(req->file);
5202 if (unlikely(!sock))
5205 kmsg = req->async_data;
5207 ret = io_recvmsg_copy_hdr(req, &iomsg);
5213 if (req->flags & REQ_F_BUFFER_SELECT) {
5214 kbuf = io_recv_buffer_select(req, !force_nonblock);
5216 return PTR_ERR(kbuf);
5217 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5218 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5219 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5220 1, req->sr_msg.len);
5223 flags = req->sr_msg.msg_flags;
5225 flags |= MSG_DONTWAIT;
5226 if (flags & MSG_WAITALL && !kmsg->msg.msg_controllen)
5227 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5229 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5230 kmsg->uaddr, flags);
5231 if (ret < min_ret) {
5232 if (ret == -EAGAIN && force_nonblock)
5233 return io_setup_async_msg(req, kmsg);
5234 if (ret == -ERESTARTSYS)
5236 if (ret > 0 && io_net_retry(sock, flags)) {
5238 req->flags |= REQ_F_PARTIAL_IO;
5239 return io_setup_async_msg(req, kmsg);
5242 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5246 if (req->flags & REQ_F_BUFFER_SELECTED)
5247 cflags = io_put_recv_kbuf(req);
5248 /* fast path, check for non-NULL to avoid function call */
5250 kfree(kmsg->free_iov);
5251 req->flags &= ~REQ_F_NEED_CLEANUP;
5254 else if (sr->done_io)
5256 __io_req_complete(req, issue_flags, ret, cflags);
5260 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5262 struct io_buffer *kbuf;
5263 struct io_sr_msg *sr = &req->sr_msg;
5265 void __user *buf = sr->buf;
5266 struct socket *sock;
5270 int ret, cflags = 0;
5271 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5273 sock = sock_from_file(req->file);
5274 if (unlikely(!sock))
5277 if (req->flags & REQ_F_BUFFER_SELECT) {
5278 kbuf = io_recv_buffer_select(req, !force_nonblock);
5280 return PTR_ERR(kbuf);
5281 buf = u64_to_user_ptr(kbuf->addr);
5284 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5288 msg.msg_name = NULL;
5289 msg.msg_control = NULL;
5290 msg.msg_controllen = 0;
5291 msg.msg_namelen = 0;
5292 msg.msg_iocb = NULL;
5295 flags = req->sr_msg.msg_flags;
5297 flags |= MSG_DONTWAIT;
5298 if (flags & MSG_WAITALL)
5299 min_ret = iov_iter_count(&msg.msg_iter);
5301 ret = sock_recvmsg(sock, &msg, flags);
5302 if (ret < min_ret) {
5303 if (ret == -EAGAIN && force_nonblock)
5305 if (ret == -ERESTARTSYS)
5307 if (ret > 0 && io_net_retry(sock, flags)) {
5311 req->flags |= REQ_F_PARTIAL_IO;
5315 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5319 if (req->flags & REQ_F_BUFFER_SELECTED)
5320 cflags = io_put_recv_kbuf(req);
5323 else if (sr->done_io)
5325 __io_req_complete(req, issue_flags, ret, cflags);
5329 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5331 struct io_accept *accept = &req->accept;
5333 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5335 if (sqe->ioprio || sqe->len || sqe->buf_index)
5338 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5339 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5340 accept->flags = READ_ONCE(sqe->accept_flags);
5341 accept->nofile = rlimit(RLIMIT_NOFILE);
5343 accept->file_slot = READ_ONCE(sqe->file_index);
5344 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5346 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5348 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5349 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5353 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5355 struct io_accept *accept = &req->accept;
5356 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5357 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5358 bool fixed = !!accept->file_slot;
5363 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5364 if (unlikely(fd < 0))
5367 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5372 ret = PTR_ERR(file);
5374 req->flags |= REQ_F_PARTIAL_IO;
5375 if (ret == -EAGAIN && force_nonblock)
5377 if (ret == -ERESTARTSYS)
5380 } else if (!fixed) {
5381 fd_install(fd, file);
5384 ret = io_install_fixed_file(req, file, issue_flags,
5385 accept->file_slot - 1);
5387 __io_req_complete(req, issue_flags, ret, 0);
5391 static int io_connect_prep_async(struct io_kiocb *req)
5393 struct io_async_connect *io = req->async_data;
5394 struct io_connect *conn = &req->connect;
5396 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5399 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5401 struct io_connect *conn = &req->connect;
5403 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5405 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5409 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5410 conn->addr_len = READ_ONCE(sqe->addr2);
5414 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5416 struct io_async_connect __io, *io;
5417 unsigned file_flags;
5419 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5421 if (req->async_data) {
5422 io = req->async_data;
5424 ret = move_addr_to_kernel(req->connect.addr,
5425 req->connect.addr_len,
5432 file_flags = force_nonblock ? O_NONBLOCK : 0;
5434 ret = __sys_connect_file(req->file, &io->address,
5435 req->connect.addr_len, file_flags);
5436 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5437 if (req->async_data)
5439 if (io_alloc_async_data(req)) {
5443 memcpy(req->async_data, &__io, sizeof(__io));
5446 if (ret == -ERESTARTSYS)
5451 __io_req_complete(req, issue_flags, ret, 0);
5454 #else /* !CONFIG_NET */
5455 #define IO_NETOP_FN(op) \
5456 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5458 return -EOPNOTSUPP; \
5461 #define IO_NETOP_PREP(op) \
5463 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5465 return -EOPNOTSUPP; \
5468 #define IO_NETOP_PREP_ASYNC(op) \
5470 static int io_##op##_prep_async(struct io_kiocb *req) \
5472 return -EOPNOTSUPP; \
5475 IO_NETOP_PREP_ASYNC(sendmsg);
5476 IO_NETOP_PREP_ASYNC(recvmsg);
5477 IO_NETOP_PREP_ASYNC(connect);
5478 IO_NETOP_PREP(accept);
5481 #endif /* CONFIG_NET */
5483 struct io_poll_table {
5484 struct poll_table_struct pt;
5485 struct io_kiocb *req;
5490 #define IO_POLL_CANCEL_FLAG BIT(31)
5491 #define IO_POLL_RETRY_FLAG BIT(30)
5492 #define IO_POLL_REF_MASK GENMASK(29, 0)
5495 * We usually have 1-2 refs taken, 128 is more than enough and we want to
5496 * maximise the margin between this amount and the moment when it overflows.
5498 #define IO_POLL_REF_BIAS 128
5500 static bool io_poll_get_ownership_slowpath(struct io_kiocb *req)
5505 * poll_refs are already elevated and we don't have much hope for
5506 * grabbing the ownership. Instead of incrementing set a retry flag
5507 * to notify the loop that there might have been some change.
5509 v = atomic_fetch_or(IO_POLL_RETRY_FLAG, &req->poll_refs);
5510 if (v & IO_POLL_REF_MASK)
5512 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5516 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5517 * bump it and acquire ownership. It's disallowed to modify requests while not
5518 * owning it, that prevents from races for enqueueing task_work's and b/w
5519 * arming poll and wakeups.
5521 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5523 if (unlikely(atomic_read(&req->poll_refs) >= IO_POLL_REF_BIAS))
5524 return io_poll_get_ownership_slowpath(req);
5525 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5528 static void io_poll_mark_cancelled(struct io_kiocb *req)
5530 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5533 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5535 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5536 if (req->opcode == IORING_OP_POLL_ADD)
5537 return req->async_data;
5538 return req->apoll->double_poll;
5541 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5543 if (req->opcode == IORING_OP_POLL_ADD)
5545 return &req->apoll->poll;
5548 static void io_poll_req_insert(struct io_kiocb *req)
5550 struct io_ring_ctx *ctx = req->ctx;
5551 struct hlist_head *list;
5553 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5554 hlist_add_head(&req->hash_node, list);
5557 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5558 wait_queue_func_t wake_func)
5561 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5562 /* mask in events that we always want/need */
5563 poll->events = events | IO_POLL_UNMASK;
5564 INIT_LIST_HEAD(&poll->wait.entry);
5565 init_waitqueue_func_entry(&poll->wait, wake_func);
5568 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5570 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5573 spin_lock_irq(&head->lock);
5574 list_del_init(&poll->wait.entry);
5576 spin_unlock_irq(&head->lock);
5580 static void io_poll_remove_entries(struct io_kiocb *req)
5582 struct io_poll_iocb *poll = io_poll_get_single(req);
5583 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5586 * While we hold the waitqueue lock and the waitqueue is nonempty,
5587 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5588 * lock in the first place can race with the waitqueue being freed.
5590 * We solve this as eventpoll does: by taking advantage of the fact that
5591 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5592 * we enter rcu_read_lock() and see that the pointer to the queue is
5593 * non-NULL, we can then lock it without the memory being freed out from
5596 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5597 * case the caller deletes the entry from the queue, leaving it empty.
5598 * In that case, only RCU prevents the queue memory from being freed.
5601 io_poll_remove_entry(poll);
5603 io_poll_remove_entry(poll_double);
5608 * All poll tw should go through this. Checks for poll events, manages
5609 * references, does rewait, etc.
5611 * Returns a negative error on failure. >0 when no action require, which is
5612 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5613 * the request, then the mask is stored in req->result.
5615 static int io_poll_check_events(struct io_kiocb *req)
5617 struct io_ring_ctx *ctx = req->ctx;
5618 struct io_poll_iocb *poll = io_poll_get_single(req);
5621 /* req->task == current here, checking PF_EXITING is safe */
5622 if (unlikely(req->task->flags & PF_EXITING))
5623 io_poll_mark_cancelled(req);
5626 v = atomic_read(&req->poll_refs);
5628 /* tw handler should be the owner, and so have some references */
5629 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5631 if (v & IO_POLL_CANCEL_FLAG)
5634 * cqe.res contains only events of the first wake up
5635 * and all others are be lost. Redo vfs_poll() to get
5638 if ((v & IO_POLL_REF_MASK) != 1)
5640 if (v & IO_POLL_RETRY_FLAG) {
5643 * We won't find new events that came in between
5644 * vfs_poll and the ref put unless we clear the
5647 atomic_andnot(IO_POLL_RETRY_FLAG, &req->poll_refs);
5648 v &= ~IO_POLL_RETRY_FLAG;
5652 struct poll_table_struct pt = { ._key = poll->events };
5654 req->result = vfs_poll(req->file, &pt) & poll->events;
5657 /* multishot, just fill an CQE and proceed */
5658 if (req->result && !(poll->events & EPOLLONESHOT)) {
5659 __poll_t mask = mangle_poll(req->result & poll->events);
5662 spin_lock(&ctx->completion_lock);
5663 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5665 io_commit_cqring(ctx);
5666 spin_unlock(&ctx->completion_lock);
5667 if (unlikely(!filled))
5669 io_cqring_ev_posted(ctx);
5670 } else if (req->result) {
5674 /* force the next iteration to vfs_poll() */
5678 * Release all references, retry if someone tried to restart
5679 * task_work while we were executing it.
5681 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs) &
5687 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5689 struct io_ring_ctx *ctx = req->ctx;
5692 ret = io_poll_check_events(req);
5697 req->result = mangle_poll(req->result & req->poll.events);
5703 io_poll_remove_entries(req);
5704 spin_lock(&ctx->completion_lock);
5705 hash_del(&req->hash_node);
5706 spin_unlock(&ctx->completion_lock);
5707 io_req_complete_post(req, req->result, 0);
5710 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5712 struct io_ring_ctx *ctx = req->ctx;
5715 ret = io_poll_check_events(req);
5719 io_poll_remove_entries(req);
5720 spin_lock(&ctx->completion_lock);
5721 hash_del(&req->hash_node);
5722 spin_unlock(&ctx->completion_lock);
5725 io_req_task_submit(req, locked);
5727 io_req_complete_failed(req, ret);
5730 static void __io_poll_execute(struct io_kiocb *req, int mask)
5733 if (req->opcode == IORING_OP_POLL_ADD)
5734 req->io_task_work.func = io_poll_task_func;
5736 req->io_task_work.func = io_apoll_task_func;
5738 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5739 io_req_task_work_add(req);
5742 static inline void io_poll_execute(struct io_kiocb *req, int res)
5744 if (io_poll_get_ownership(req))
5745 __io_poll_execute(req, res);
5748 static void io_poll_cancel_req(struct io_kiocb *req)
5750 io_poll_mark_cancelled(req);
5751 /* kick tw, which should complete the request */
5752 io_poll_execute(req, 0);
5755 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5758 struct io_kiocb *req = wait->private;
5759 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5761 __poll_t mask = key_to_poll(key);
5763 if (unlikely(mask & POLLFREE)) {
5764 io_poll_mark_cancelled(req);
5765 /* we have to kick tw in case it's not already */
5766 io_poll_execute(req, 0);
5769 * If the waitqueue is being freed early but someone is already
5770 * holds ownership over it, we have to tear down the request as
5771 * best we can. That means immediately removing the request from
5772 * its waitqueue and preventing all further accesses to the
5773 * waitqueue via the request.
5775 list_del_init(&poll->wait.entry);
5778 * Careful: this *must* be the last step, since as soon
5779 * as req->head is NULL'ed out, the request can be
5780 * completed and freed, since aio_poll_complete_work()
5781 * will no longer need to take the waitqueue lock.
5783 smp_store_release(&poll->head, NULL);
5787 /* for instances that support it check for an event match first */
5788 if (mask && !(mask & poll->events))
5791 if (io_poll_get_ownership(req)) {
5793 * If we trigger a multishot poll off our own wakeup path,
5794 * disable multishot as there is a circular dependency between
5795 * CQ posting and triggering the event.
5797 if (mask & EPOLL_URING_WAKE)
5798 poll->events |= EPOLLONESHOT;
5800 __io_poll_execute(req, mask);
5805 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5806 struct wait_queue_head *head,
5807 struct io_poll_iocb **poll_ptr)
5809 struct io_kiocb *req = pt->req;
5812 * The file being polled uses multiple waitqueues for poll handling
5813 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5816 if (unlikely(pt->nr_entries)) {
5817 struct io_poll_iocb *first = poll;
5819 /* double add on the same waitqueue head, ignore */
5820 if (first->head == head)
5822 /* already have a 2nd entry, fail a third attempt */
5824 if ((*poll_ptr)->head == head)
5826 pt->error = -EINVAL;
5830 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5832 pt->error = -ENOMEM;
5835 io_init_poll_iocb(poll, first->events, first->wait.func);
5841 poll->wait.private = req;
5843 if (poll->events & EPOLLEXCLUSIVE)
5844 add_wait_queue_exclusive(head, &poll->wait);
5846 add_wait_queue(head, &poll->wait);
5849 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5850 struct poll_table_struct *p)
5852 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5854 __io_queue_proc(&pt->req->poll, pt, head,
5855 (struct io_poll_iocb **) &pt->req->async_data);
5858 static int __io_arm_poll_handler(struct io_kiocb *req,
5859 struct io_poll_iocb *poll,
5860 struct io_poll_table *ipt, __poll_t mask)
5862 struct io_ring_ctx *ctx = req->ctx;
5864 INIT_HLIST_NODE(&req->hash_node);
5865 io_init_poll_iocb(poll, mask, io_poll_wake);
5866 poll->file = req->file;
5867 poll->wait.private = req;
5869 ipt->pt._key = mask;
5872 ipt->nr_entries = 0;
5875 * Take the ownership to delay any tw execution up until we're done
5876 * with poll arming. see io_poll_get_ownership().
5878 atomic_set(&req->poll_refs, 1);
5879 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5881 if (mask && (poll->events & EPOLLONESHOT)) {
5882 io_poll_remove_entries(req);
5883 /* no one else has access to the req, forget about the ref */
5886 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5887 io_poll_remove_entries(req);
5889 ipt->error = -EINVAL;
5893 spin_lock(&ctx->completion_lock);
5894 io_poll_req_insert(req);
5895 spin_unlock(&ctx->completion_lock);
5898 /* can't multishot if failed, just queue the event we've got */
5899 if (unlikely(ipt->error || !ipt->nr_entries)) {
5900 poll->events |= EPOLLONESHOT;
5903 __io_poll_execute(req, mask);
5908 * Try to release ownership. If we see a change of state, e.g.
5909 * poll was waken up, queue up a tw, it'll deal with it.
5911 if (atomic_cmpxchg(&req->poll_refs, 1, 0) != 1)
5912 __io_poll_execute(req, 0);
5916 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5917 struct poll_table_struct *p)
5919 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5920 struct async_poll *apoll = pt->req->apoll;
5922 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5932 * We can't reliably detect loops in repeated poll triggers and issue
5933 * subsequently failing. But rather than fail these immediately, allow a
5934 * certain amount of retries before we give up. Given that this condition
5935 * should _rarely_ trigger even once, we should be fine with a larger value.
5937 #define APOLL_MAX_RETRY 128
5939 static int io_arm_poll_handler(struct io_kiocb *req)
5941 const struct io_op_def *def = &io_op_defs[req->opcode];
5942 struct io_ring_ctx *ctx = req->ctx;
5943 struct async_poll *apoll;
5944 struct io_poll_table ipt;
5945 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5948 if (!req->file || !file_can_poll(req->file))
5949 return IO_APOLL_ABORTED;
5950 if (!def->pollin && !def->pollout)
5951 return IO_APOLL_ABORTED;
5954 mask |= POLLIN | POLLRDNORM;
5956 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5957 if ((req->opcode == IORING_OP_RECVMSG) &&
5958 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5961 mask |= POLLOUT | POLLWRNORM;
5964 if (req->flags & REQ_F_POLLED) {
5966 kfree(apoll->double_poll);
5967 if (unlikely(!--apoll->poll.retries)) {
5968 apoll->double_poll = NULL;
5969 return IO_APOLL_ABORTED;
5972 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5973 if (unlikely(!apoll))
5974 return IO_APOLL_ABORTED;
5975 apoll->poll.retries = APOLL_MAX_RETRY;
5977 apoll->double_poll = NULL;
5979 req->flags |= REQ_F_POLLED;
5980 ipt.pt._qproc = io_async_queue_proc;
5982 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5983 if (ret || ipt.error)
5984 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5986 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5987 mask, apoll->poll.events);
5992 * Returns true if we found and killed one or more poll requests
5994 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5997 struct hlist_node *tmp;
5998 struct io_kiocb *req;
6002 spin_lock(&ctx->completion_lock);
6003 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6004 struct hlist_head *list;
6006 list = &ctx->cancel_hash[i];
6007 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6008 if (io_match_task_safe(req, tsk, cancel_all)) {
6009 hlist_del_init(&req->hash_node);
6010 io_poll_cancel_req(req);
6015 spin_unlock(&ctx->completion_lock);
6019 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6021 __must_hold(&ctx->completion_lock)
6023 struct hlist_head *list;
6024 struct io_kiocb *req;
6026 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6027 hlist_for_each_entry(req, list, hash_node) {
6028 if (sqe_addr != req->user_data)
6030 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6037 static bool io_poll_disarm(struct io_kiocb *req)
6038 __must_hold(&ctx->completion_lock)
6040 if (!io_poll_get_ownership(req))
6042 io_poll_remove_entries(req);
6043 hash_del(&req->hash_node);
6047 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6049 __must_hold(&ctx->completion_lock)
6051 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6055 io_poll_cancel_req(req);
6059 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6064 events = READ_ONCE(sqe->poll32_events);
6066 events = swahw32(events);
6068 if (!(flags & IORING_POLL_ADD_MULTI))
6069 events |= EPOLLONESHOT;
6070 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6073 static int io_poll_update_prep(struct io_kiocb *req,
6074 const struct io_uring_sqe *sqe)
6076 struct io_poll_update *upd = &req->poll_update;
6079 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6081 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6083 flags = READ_ONCE(sqe->len);
6084 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6085 IORING_POLL_ADD_MULTI))
6087 /* meaningless without update */
6088 if (flags == IORING_POLL_ADD_MULTI)
6091 upd->old_user_data = READ_ONCE(sqe->addr);
6092 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6093 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6095 upd->new_user_data = READ_ONCE(sqe->off);
6096 if (!upd->update_user_data && upd->new_user_data)
6098 if (upd->update_events)
6099 upd->events = io_poll_parse_events(sqe, flags);
6100 else if (sqe->poll32_events)
6106 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6108 struct io_poll_iocb *poll = &req->poll;
6111 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6113 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6115 flags = READ_ONCE(sqe->len);
6116 if (flags & ~IORING_POLL_ADD_MULTI)
6119 io_req_set_refcount(req);
6120 poll->events = io_poll_parse_events(sqe, flags);
6124 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6126 struct io_poll_iocb *poll = &req->poll;
6127 struct io_poll_table ipt;
6130 ipt.pt._qproc = io_poll_queue_proc;
6132 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6133 if (!ret && ipt.error)
6135 ret = ret ?: ipt.error;
6137 __io_req_complete(req, issue_flags, ret, 0);
6141 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6143 struct io_ring_ctx *ctx = req->ctx;
6144 struct io_kiocb *preq;
6147 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6149 spin_lock(&ctx->completion_lock);
6150 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6151 if (!preq || !io_poll_disarm(preq)) {
6152 spin_unlock(&ctx->completion_lock);
6153 ret = preq ? -EALREADY : -ENOENT;
6156 spin_unlock(&ctx->completion_lock);
6158 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6159 /* only mask one event flags, keep behavior flags */
6160 if (req->poll_update.update_events) {
6161 preq->poll.events &= ~0xffff;
6162 preq->poll.events |= req->poll_update.events & 0xffff;
6163 preq->poll.events |= IO_POLL_UNMASK;
6165 if (req->poll_update.update_user_data)
6166 preq->user_data = req->poll_update.new_user_data;
6168 ret2 = io_poll_add(preq, issue_flags);
6169 /* successfully updated, don't complete poll request */
6174 io_req_complete(preq, -ECANCELED);
6178 /* complete update request, we're done with it */
6179 io_req_complete(req, ret);
6180 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6184 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
6187 io_req_complete_post(req, -ETIME, 0);
6190 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6192 struct io_timeout_data *data = container_of(timer,
6193 struct io_timeout_data, timer);
6194 struct io_kiocb *req = data->req;
6195 struct io_ring_ctx *ctx = req->ctx;
6196 unsigned long flags;
6198 spin_lock_irqsave(&ctx->timeout_lock, flags);
6199 list_del_init(&req->timeout.list);
6200 atomic_set(&req->ctx->cq_timeouts,
6201 atomic_read(&req->ctx->cq_timeouts) + 1);
6202 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6204 req->io_task_work.func = io_req_task_timeout;
6205 io_req_task_work_add(req);
6206 return HRTIMER_NORESTART;
6209 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6211 __must_hold(&ctx->timeout_lock)
6213 struct io_timeout_data *io;
6214 struct io_kiocb *req;
6217 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6218 found = user_data == req->user_data;
6223 return ERR_PTR(-ENOENT);
6225 io = req->async_data;
6226 if (hrtimer_try_to_cancel(&io->timer) == -1)
6227 return ERR_PTR(-EALREADY);
6228 list_del_init(&req->timeout.list);
6232 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6233 __must_hold(&ctx->completion_lock)
6234 __must_hold(&ctx->timeout_lock)
6236 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6239 return PTR_ERR(req);
6242 io_fill_cqe_req(req, -ECANCELED, 0);
6243 io_put_req_deferred(req);
6247 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6249 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6250 case IORING_TIMEOUT_BOOTTIME:
6251 return CLOCK_BOOTTIME;
6252 case IORING_TIMEOUT_REALTIME:
6253 return CLOCK_REALTIME;
6255 /* can't happen, vetted at prep time */
6259 return CLOCK_MONOTONIC;
6263 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6264 struct timespec64 *ts, enum hrtimer_mode mode)
6265 __must_hold(&ctx->timeout_lock)
6267 struct io_timeout_data *io;
6268 struct io_kiocb *req;
6271 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6272 found = user_data == req->user_data;
6279 io = req->async_data;
6280 if (hrtimer_try_to_cancel(&io->timer) == -1)
6282 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6283 io->timer.function = io_link_timeout_fn;
6284 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6288 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6289 struct timespec64 *ts, enum hrtimer_mode mode)
6290 __must_hold(&ctx->timeout_lock)
6292 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6293 struct io_timeout_data *data;
6296 return PTR_ERR(req);
6298 req->timeout.off = 0; /* noseq */
6299 data = req->async_data;
6300 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6301 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6302 data->timer.function = io_timeout_fn;
6303 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6307 static int io_timeout_remove_prep(struct io_kiocb *req,
6308 const struct io_uring_sqe *sqe)
6310 struct io_timeout_rem *tr = &req->timeout_rem;
6312 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6314 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6316 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6319 tr->ltimeout = false;
6320 tr->addr = READ_ONCE(sqe->addr);
6321 tr->flags = READ_ONCE(sqe->timeout_flags);
6322 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6323 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6325 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6326 tr->ltimeout = true;
6327 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6329 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6331 } else if (tr->flags) {
6332 /* timeout removal doesn't support flags */
6339 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6341 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6346 * Remove or update an existing timeout command
6348 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6350 struct io_timeout_rem *tr = &req->timeout_rem;
6351 struct io_ring_ctx *ctx = req->ctx;
6354 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6355 spin_lock(&ctx->completion_lock);
6356 spin_lock_irq(&ctx->timeout_lock);
6357 ret = io_timeout_cancel(ctx, tr->addr);
6358 spin_unlock_irq(&ctx->timeout_lock);
6359 spin_unlock(&ctx->completion_lock);
6361 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6363 spin_lock_irq(&ctx->timeout_lock);
6365 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6367 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6368 spin_unlock_irq(&ctx->timeout_lock);
6373 io_req_complete_post(req, ret, 0);
6377 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6378 bool is_timeout_link)
6380 struct io_timeout_data *data;
6382 u32 off = READ_ONCE(sqe->off);
6384 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6386 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6389 if (off && is_timeout_link)
6391 flags = READ_ONCE(sqe->timeout_flags);
6392 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6394 /* more than one clock specified is invalid, obviously */
6395 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6398 INIT_LIST_HEAD(&req->timeout.list);
6399 req->timeout.off = off;
6400 if (unlikely(off && !req->ctx->off_timeout_used))
6401 req->ctx->off_timeout_used = true;
6403 if (!req->async_data && io_alloc_async_data(req))
6406 data = req->async_data;
6408 data->flags = flags;
6410 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6413 INIT_LIST_HEAD(&req->timeout.list);
6414 data->mode = io_translate_timeout_mode(flags);
6415 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6417 if (is_timeout_link) {
6418 struct io_submit_link *link = &req->ctx->submit_state.link;
6422 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6424 req->timeout.head = link->last;
6425 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6430 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6432 struct io_ring_ctx *ctx = req->ctx;
6433 struct io_timeout_data *data = req->async_data;
6434 struct list_head *entry;
6435 u32 tail, off = req->timeout.off;
6437 spin_lock_irq(&ctx->timeout_lock);
6440 * sqe->off holds how many events that need to occur for this
6441 * timeout event to be satisfied. If it isn't set, then this is
6442 * a pure timeout request, sequence isn't used.
6444 if (io_is_timeout_noseq(req)) {
6445 entry = ctx->timeout_list.prev;
6449 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6450 req->timeout.target_seq = tail + off;
6452 /* Update the last seq here in case io_flush_timeouts() hasn't.
6453 * This is safe because ->completion_lock is held, and submissions
6454 * and completions are never mixed in the same ->completion_lock section.
6456 ctx->cq_last_tm_flush = tail;
6459 * Insertion sort, ensuring the first entry in the list is always
6460 * the one we need first.
6462 list_for_each_prev(entry, &ctx->timeout_list) {
6463 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6466 if (io_is_timeout_noseq(nxt))
6468 /* nxt.seq is behind @tail, otherwise would've been completed */
6469 if (off >= nxt->timeout.target_seq - tail)
6473 list_add(&req->timeout.list, entry);
6474 data->timer.function = io_timeout_fn;
6475 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6476 spin_unlock_irq(&ctx->timeout_lock);
6480 struct io_cancel_data {
6481 struct io_ring_ctx *ctx;
6485 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6487 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6488 struct io_cancel_data *cd = data;
6490 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6493 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6494 struct io_ring_ctx *ctx)
6496 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6497 enum io_wq_cancel cancel_ret;
6500 if (!tctx || !tctx->io_wq)
6503 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6504 switch (cancel_ret) {
6505 case IO_WQ_CANCEL_OK:
6508 case IO_WQ_CANCEL_RUNNING:
6511 case IO_WQ_CANCEL_NOTFOUND:
6519 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6521 struct io_ring_ctx *ctx = req->ctx;
6524 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6526 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6530 spin_lock(&ctx->completion_lock);
6531 spin_lock_irq(&ctx->timeout_lock);
6532 ret = io_timeout_cancel(ctx, sqe_addr);
6533 spin_unlock_irq(&ctx->timeout_lock);
6536 ret = io_poll_cancel(ctx, sqe_addr, false);
6538 spin_unlock(&ctx->completion_lock);
6542 static int io_async_cancel_prep(struct io_kiocb *req,
6543 const struct io_uring_sqe *sqe)
6545 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6547 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6549 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6553 req->cancel.addr = READ_ONCE(sqe->addr);
6557 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6559 struct io_ring_ctx *ctx = req->ctx;
6560 u64 sqe_addr = req->cancel.addr;
6561 struct io_tctx_node *node;
6564 ret = io_try_cancel_userdata(req, sqe_addr);
6568 /* slow path, try all io-wq's */
6569 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6571 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6572 struct io_uring_task *tctx = node->task->io_uring;
6574 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6578 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6582 io_req_complete_post(req, ret, 0);
6586 static int io_rsrc_update_prep(struct io_kiocb *req,
6587 const struct io_uring_sqe *sqe)
6589 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6591 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6594 req->rsrc_update.offset = READ_ONCE(sqe->off);
6595 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6596 if (!req->rsrc_update.nr_args)
6598 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6602 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6604 struct io_ring_ctx *ctx = req->ctx;
6605 struct io_uring_rsrc_update2 up;
6608 up.offset = req->rsrc_update.offset;
6609 up.data = req->rsrc_update.arg;
6615 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6616 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6617 &up, req->rsrc_update.nr_args);
6618 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6622 __io_req_complete(req, issue_flags, ret, 0);
6626 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6628 switch (req->opcode) {
6631 case IORING_OP_READV:
6632 case IORING_OP_READ_FIXED:
6633 case IORING_OP_READ:
6634 return io_read_prep(req, sqe);
6635 case IORING_OP_WRITEV:
6636 case IORING_OP_WRITE_FIXED:
6637 case IORING_OP_WRITE:
6638 return io_write_prep(req, sqe);
6639 case IORING_OP_POLL_ADD:
6640 return io_poll_add_prep(req, sqe);
6641 case IORING_OP_POLL_REMOVE:
6642 return io_poll_update_prep(req, sqe);
6643 case IORING_OP_FSYNC:
6644 return io_fsync_prep(req, sqe);
6645 case IORING_OP_SYNC_FILE_RANGE:
6646 return io_sfr_prep(req, sqe);
6647 case IORING_OP_SENDMSG:
6648 case IORING_OP_SEND:
6649 return io_sendmsg_prep(req, sqe);
6650 case IORING_OP_RECVMSG:
6651 case IORING_OP_RECV:
6652 return io_recvmsg_prep(req, sqe);
6653 case IORING_OP_CONNECT:
6654 return io_connect_prep(req, sqe);
6655 case IORING_OP_TIMEOUT:
6656 return io_timeout_prep(req, sqe, false);
6657 case IORING_OP_TIMEOUT_REMOVE:
6658 return io_timeout_remove_prep(req, sqe);
6659 case IORING_OP_ASYNC_CANCEL:
6660 return io_async_cancel_prep(req, sqe);
6661 case IORING_OP_LINK_TIMEOUT:
6662 return io_timeout_prep(req, sqe, true);
6663 case IORING_OP_ACCEPT:
6664 return io_accept_prep(req, sqe);
6665 case IORING_OP_FALLOCATE:
6666 return io_fallocate_prep(req, sqe);
6667 case IORING_OP_OPENAT:
6668 return io_openat_prep(req, sqe);
6669 case IORING_OP_CLOSE:
6670 return io_close_prep(req, sqe);
6671 case IORING_OP_FILES_UPDATE:
6672 return io_rsrc_update_prep(req, sqe);
6673 case IORING_OP_STATX:
6674 return io_statx_prep(req, sqe);
6675 case IORING_OP_FADVISE:
6676 return io_fadvise_prep(req, sqe);
6677 case IORING_OP_MADVISE:
6678 return io_madvise_prep(req, sqe);
6679 case IORING_OP_OPENAT2:
6680 return io_openat2_prep(req, sqe);
6681 case IORING_OP_EPOLL_CTL:
6682 return io_epoll_ctl_prep(req, sqe);
6683 case IORING_OP_SPLICE:
6684 return io_splice_prep(req, sqe);
6685 case IORING_OP_PROVIDE_BUFFERS:
6686 return io_provide_buffers_prep(req, sqe);
6687 case IORING_OP_REMOVE_BUFFERS:
6688 return io_remove_buffers_prep(req, sqe);
6690 return io_tee_prep(req, sqe);
6691 case IORING_OP_SHUTDOWN:
6692 return io_shutdown_prep(req, sqe);
6693 case IORING_OP_RENAMEAT:
6694 return io_renameat_prep(req, sqe);
6695 case IORING_OP_UNLINKAT:
6696 return io_unlinkat_prep(req, sqe);
6697 case IORING_OP_MKDIRAT:
6698 return io_mkdirat_prep(req, sqe);
6699 case IORING_OP_SYMLINKAT:
6700 return io_symlinkat_prep(req, sqe);
6701 case IORING_OP_LINKAT:
6702 return io_linkat_prep(req, sqe);
6705 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6710 static int io_req_prep_async(struct io_kiocb *req)
6712 if (!io_op_defs[req->opcode].needs_async_setup)
6714 if (WARN_ON_ONCE(req->async_data))
6716 if (io_alloc_async_data(req))
6719 switch (req->opcode) {
6720 case IORING_OP_READV:
6721 return io_rw_prep_async(req, READ);
6722 case IORING_OP_WRITEV:
6723 return io_rw_prep_async(req, WRITE);
6724 case IORING_OP_SENDMSG:
6725 return io_sendmsg_prep_async(req);
6726 case IORING_OP_RECVMSG:
6727 return io_recvmsg_prep_async(req);
6728 case IORING_OP_CONNECT:
6729 return io_connect_prep_async(req);
6731 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6736 static u32 io_get_sequence(struct io_kiocb *req)
6738 u32 seq = req->ctx->cached_sq_head;
6740 /* need original cached_sq_head, but it was increased for each req */
6741 io_for_each_link(req, req)
6746 static bool io_drain_req(struct io_kiocb *req)
6748 struct io_kiocb *pos;
6749 struct io_ring_ctx *ctx = req->ctx;
6750 struct io_defer_entry *de;
6754 if (req->flags & REQ_F_FAIL) {
6755 io_req_complete_fail_submit(req);
6760 * If we need to drain a request in the middle of a link, drain the
6761 * head request and the next request/link after the current link.
6762 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6763 * maintained for every request of our link.
6765 if (ctx->drain_next) {
6766 req->flags |= REQ_F_IO_DRAIN;
6767 ctx->drain_next = false;
6769 /* not interested in head, start from the first linked */
6770 io_for_each_link(pos, req->link) {
6771 if (pos->flags & REQ_F_IO_DRAIN) {
6772 ctx->drain_next = true;
6773 req->flags |= REQ_F_IO_DRAIN;
6778 /* Still need defer if there is pending req in defer list. */
6779 spin_lock(&ctx->completion_lock);
6780 if (likely(list_empty_careful(&ctx->defer_list) &&
6781 !(req->flags & REQ_F_IO_DRAIN))) {
6782 spin_unlock(&ctx->completion_lock);
6783 ctx->drain_active = false;
6786 spin_unlock(&ctx->completion_lock);
6788 seq = io_get_sequence(req);
6789 /* Still a chance to pass the sequence check */
6790 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6793 ret = io_req_prep_async(req);
6796 io_prep_async_link(req);
6797 de = kmalloc(sizeof(*de), GFP_KERNEL);
6801 io_req_complete_failed(req, ret);
6805 spin_lock(&ctx->completion_lock);
6806 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6807 spin_unlock(&ctx->completion_lock);
6809 io_queue_async_work(req, NULL);
6813 trace_io_uring_defer(ctx, req, req->user_data);
6816 list_add_tail(&de->list, &ctx->defer_list);
6817 spin_unlock(&ctx->completion_lock);
6821 static void io_clean_op(struct io_kiocb *req)
6823 if (req->flags & REQ_F_BUFFER_SELECTED) {
6824 switch (req->opcode) {
6825 case IORING_OP_READV:
6826 case IORING_OP_READ_FIXED:
6827 case IORING_OP_READ:
6828 kfree((void *)(unsigned long)req->rw.addr);
6830 case IORING_OP_RECVMSG:
6831 case IORING_OP_RECV:
6832 kfree(req->sr_msg.kbuf);
6837 if (req->flags & REQ_F_NEED_CLEANUP) {
6838 switch (req->opcode) {
6839 case IORING_OP_READV:
6840 case IORING_OP_READ_FIXED:
6841 case IORING_OP_READ:
6842 case IORING_OP_WRITEV:
6843 case IORING_OP_WRITE_FIXED:
6844 case IORING_OP_WRITE: {
6845 struct io_async_rw *io = req->async_data;
6847 kfree(io->free_iovec);
6850 case IORING_OP_RECVMSG:
6851 case IORING_OP_SENDMSG: {
6852 struct io_async_msghdr *io = req->async_data;
6854 kfree(io->free_iov);
6857 case IORING_OP_OPENAT:
6858 case IORING_OP_OPENAT2:
6859 if (req->open.filename)
6860 putname(req->open.filename);
6862 case IORING_OP_RENAMEAT:
6863 putname(req->rename.oldpath);
6864 putname(req->rename.newpath);
6866 case IORING_OP_UNLINKAT:
6867 putname(req->unlink.filename);
6869 case IORING_OP_MKDIRAT:
6870 putname(req->mkdir.filename);
6872 case IORING_OP_SYMLINKAT:
6873 putname(req->symlink.oldpath);
6874 putname(req->symlink.newpath);
6876 case IORING_OP_LINKAT:
6877 putname(req->hardlink.oldpath);
6878 putname(req->hardlink.newpath);
6882 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6883 kfree(req->apoll->double_poll);
6887 if (req->flags & REQ_F_INFLIGHT) {
6888 struct io_uring_task *tctx = req->task->io_uring;
6890 atomic_dec(&tctx->inflight_tracked);
6892 if (req->flags & REQ_F_CREDS)
6893 put_cred(req->creds);
6895 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6898 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6900 struct io_ring_ctx *ctx = req->ctx;
6901 const struct cred *creds = NULL;
6904 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6905 creds = override_creds(req->creds);
6907 switch (req->opcode) {
6909 ret = io_nop(req, issue_flags);
6911 case IORING_OP_READV:
6912 case IORING_OP_READ_FIXED:
6913 case IORING_OP_READ:
6914 ret = io_read(req, issue_flags);
6916 case IORING_OP_WRITEV:
6917 case IORING_OP_WRITE_FIXED:
6918 case IORING_OP_WRITE:
6919 ret = io_write(req, issue_flags);
6921 case IORING_OP_FSYNC:
6922 ret = io_fsync(req, issue_flags);
6924 case IORING_OP_POLL_ADD:
6925 ret = io_poll_add(req, issue_flags);
6927 case IORING_OP_POLL_REMOVE:
6928 ret = io_poll_update(req, issue_flags);
6930 case IORING_OP_SYNC_FILE_RANGE:
6931 ret = io_sync_file_range(req, issue_flags);
6933 case IORING_OP_SENDMSG:
6934 ret = io_sendmsg(req, issue_flags);
6936 case IORING_OP_SEND:
6937 ret = io_send(req, issue_flags);
6939 case IORING_OP_RECVMSG:
6940 ret = io_recvmsg(req, issue_flags);
6942 case IORING_OP_RECV:
6943 ret = io_recv(req, issue_flags);
6945 case IORING_OP_TIMEOUT:
6946 ret = io_timeout(req, issue_flags);
6948 case IORING_OP_TIMEOUT_REMOVE:
6949 ret = io_timeout_remove(req, issue_flags);
6951 case IORING_OP_ACCEPT:
6952 ret = io_accept(req, issue_flags);
6954 case IORING_OP_CONNECT:
6955 ret = io_connect(req, issue_flags);
6957 case IORING_OP_ASYNC_CANCEL:
6958 ret = io_async_cancel(req, issue_flags);
6960 case IORING_OP_FALLOCATE:
6961 ret = io_fallocate(req, issue_flags);
6963 case IORING_OP_OPENAT:
6964 ret = io_openat(req, issue_flags);
6966 case IORING_OP_CLOSE:
6967 ret = io_close(req, issue_flags);
6969 case IORING_OP_FILES_UPDATE:
6970 ret = io_files_update(req, issue_flags);
6972 case IORING_OP_STATX:
6973 ret = io_statx(req, issue_flags);
6975 case IORING_OP_FADVISE:
6976 ret = io_fadvise(req, issue_flags);
6978 case IORING_OP_MADVISE:
6979 ret = io_madvise(req, issue_flags);
6981 case IORING_OP_OPENAT2:
6982 ret = io_openat2(req, issue_flags);
6984 case IORING_OP_EPOLL_CTL:
6985 ret = io_epoll_ctl(req, issue_flags);
6987 case IORING_OP_SPLICE:
6988 ret = io_splice(req, issue_flags);
6990 case IORING_OP_PROVIDE_BUFFERS:
6991 ret = io_provide_buffers(req, issue_flags);
6993 case IORING_OP_REMOVE_BUFFERS:
6994 ret = io_remove_buffers(req, issue_flags);
6997 ret = io_tee(req, issue_flags);
6999 case IORING_OP_SHUTDOWN:
7000 ret = io_shutdown(req, issue_flags);
7002 case IORING_OP_RENAMEAT:
7003 ret = io_renameat(req, issue_flags);
7005 case IORING_OP_UNLINKAT:
7006 ret = io_unlinkat(req, issue_flags);
7008 case IORING_OP_MKDIRAT:
7009 ret = io_mkdirat(req, issue_flags);
7011 case IORING_OP_SYMLINKAT:
7012 ret = io_symlinkat(req, issue_flags);
7014 case IORING_OP_LINKAT:
7015 ret = io_linkat(req, issue_flags);
7023 revert_creds(creds);
7026 /* If the op doesn't have a file, we're not polling for it */
7027 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7028 io_iopoll_req_issued(req);
7033 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7035 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7037 req = io_put_req_find_next(req);
7038 return req ? &req->work : NULL;
7041 static void io_wq_submit_work(struct io_wq_work *work)
7043 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7044 struct io_kiocb *timeout;
7047 /* one will be dropped by ->io_free_work() after returning to io-wq */
7048 if (!(req->flags & REQ_F_REFCOUNT))
7049 __io_req_set_refcount(req, 2);
7053 timeout = io_prep_linked_timeout(req);
7055 io_queue_linked_timeout(timeout);
7057 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7058 if (work->flags & IO_WQ_WORK_CANCEL)
7063 ret = io_issue_sqe(req, 0);
7065 * We can get EAGAIN for polled IO even though we're
7066 * forcing a sync submission from here, since we can't
7067 * wait for request slots on the block side.
7069 if (ret != -EAGAIN || !(req->ctx->flags & IORING_SETUP_IOPOLL))
7073 * If REQ_F_NOWAIT is set, then don't wait or retry with
7074 * poll. -EAGAIN is final for that case.
7076 if (req->flags & REQ_F_NOWAIT)
7083 /* avoid locking problems by failing it from a clean context */
7085 io_req_task_queue_fail(req, ret);
7088 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7091 return &table->files[i];
7094 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7097 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7099 return (struct file *) (slot->file_ptr & FFS_MASK);
7102 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7104 unsigned long file_ptr = (unsigned long) file;
7106 if (__io_file_supports_nowait(file, READ))
7107 file_ptr |= FFS_ASYNC_READ;
7108 if (__io_file_supports_nowait(file, WRITE))
7109 file_ptr |= FFS_ASYNC_WRITE;
7110 if (S_ISREG(file_inode(file)->i_mode))
7111 file_ptr |= FFS_ISREG;
7112 file_slot->file_ptr = file_ptr;
7115 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7116 struct io_kiocb *req, int fd,
7117 unsigned int issue_flags)
7119 struct file *file = NULL;
7120 unsigned long file_ptr;
7122 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
7124 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7126 fd = array_index_nospec(fd, ctx->nr_user_files);
7127 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7128 file = (struct file *) (file_ptr & FFS_MASK);
7129 file_ptr &= ~FFS_MASK;
7130 /* mask in overlapping REQ_F and FFS bits */
7131 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
7132 io_req_set_rsrc_node(req);
7134 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
7138 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7139 struct io_kiocb *req, int fd)
7141 struct file *file = fget(fd);
7143 trace_io_uring_file_get(ctx, fd);
7145 /* we don't allow fixed io_uring files */
7146 if (file && unlikely(file->f_op == &io_uring_fops))
7147 io_req_track_inflight(req);
7151 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7152 struct io_kiocb *req, int fd, bool fixed,
7153 unsigned int issue_flags)
7156 return io_file_get_fixed(ctx, req, fd, issue_flags);
7158 return io_file_get_normal(ctx, req, fd);
7161 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7163 struct io_kiocb *prev = req->timeout.prev;
7167 if (!(req->task->flags & PF_EXITING))
7168 ret = io_try_cancel_userdata(req, prev->user_data);
7169 io_req_complete_post(req, ret ?: -ETIME, 0);
7172 io_req_complete_post(req, -ETIME, 0);
7176 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7178 struct io_timeout_data *data = container_of(timer,
7179 struct io_timeout_data, timer);
7180 struct io_kiocb *prev, *req = data->req;
7181 struct io_ring_ctx *ctx = req->ctx;
7182 unsigned long flags;
7184 spin_lock_irqsave(&ctx->timeout_lock, flags);
7185 prev = req->timeout.head;
7186 req->timeout.head = NULL;
7189 * We don't expect the list to be empty, that will only happen if we
7190 * race with the completion of the linked work.
7193 io_remove_next_linked(prev);
7194 if (!req_ref_inc_not_zero(prev))
7197 list_del(&req->timeout.list);
7198 req->timeout.prev = prev;
7199 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7201 req->io_task_work.func = io_req_task_link_timeout;
7202 io_req_task_work_add(req);
7203 return HRTIMER_NORESTART;
7206 static void io_queue_linked_timeout(struct io_kiocb *req)
7208 struct io_ring_ctx *ctx = req->ctx;
7210 spin_lock_irq(&ctx->timeout_lock);
7212 * If the back reference is NULL, then our linked request finished
7213 * before we got a chance to setup the timer
7215 if (req->timeout.head) {
7216 struct io_timeout_data *data = req->async_data;
7218 data->timer.function = io_link_timeout_fn;
7219 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7221 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7223 spin_unlock_irq(&ctx->timeout_lock);
7224 /* drop submission reference */
7228 static void __io_queue_sqe(struct io_kiocb *req)
7229 __must_hold(&req->ctx->uring_lock)
7231 struct io_kiocb *linked_timeout;
7235 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7238 * We async punt it if the file wasn't marked NOWAIT, or if the file
7239 * doesn't support non-blocking read/write attempts
7242 if (req->flags & REQ_F_COMPLETE_INLINE) {
7243 struct io_ring_ctx *ctx = req->ctx;
7244 struct io_submit_state *state = &ctx->submit_state;
7246 state->compl_reqs[state->compl_nr++] = req;
7247 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
7248 io_submit_flush_completions(ctx);
7252 linked_timeout = io_prep_linked_timeout(req);
7254 io_queue_linked_timeout(linked_timeout);
7255 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7256 linked_timeout = io_prep_linked_timeout(req);
7258 switch (io_arm_poll_handler(req)) {
7259 case IO_APOLL_READY:
7261 io_queue_linked_timeout(linked_timeout);
7263 case IO_APOLL_ABORTED:
7265 * Queued up for async execution, worker will release
7266 * submit reference when the iocb is actually submitted.
7268 io_queue_async_work(req, NULL);
7273 io_queue_linked_timeout(linked_timeout);
7275 io_req_complete_failed(req, ret);
7279 static inline void io_queue_sqe(struct io_kiocb *req)
7280 __must_hold(&req->ctx->uring_lock)
7282 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
7285 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
7286 __io_queue_sqe(req);
7287 } else if (req->flags & REQ_F_FAIL) {
7288 io_req_complete_fail_submit(req);
7290 int ret = io_req_prep_async(req);
7293 io_req_complete_failed(req, ret);
7295 io_queue_async_work(req, NULL);
7300 * Check SQE restrictions (opcode and flags).
7302 * Returns 'true' if SQE is allowed, 'false' otherwise.
7304 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7305 struct io_kiocb *req,
7306 unsigned int sqe_flags)
7308 if (likely(!ctx->restricted))
7311 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7314 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7315 ctx->restrictions.sqe_flags_required)
7318 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7319 ctx->restrictions.sqe_flags_required))
7325 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7326 const struct io_uring_sqe *sqe)
7327 __must_hold(&ctx->uring_lock)
7329 struct io_submit_state *state;
7330 unsigned int sqe_flags;
7331 int personality, ret = 0;
7333 /* req is partially pre-initialised, see io_preinit_req() */
7334 req->opcode = READ_ONCE(sqe->opcode);
7335 /* same numerical values with corresponding REQ_F_*, safe to copy */
7336 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7337 req->user_data = READ_ONCE(sqe->user_data);
7339 req->fixed_rsrc_refs = NULL;
7340 req->task = current;
7342 /* enforce forwards compatibility on users */
7343 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
7345 if (unlikely(req->opcode >= IORING_OP_LAST))
7347 if (!io_check_restriction(ctx, req, sqe_flags))
7350 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7351 !io_op_defs[req->opcode].buffer_select)
7353 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
7354 ctx->drain_active = true;
7356 personality = READ_ONCE(sqe->personality);
7358 req->creds = xa_load(&ctx->personalities, personality);
7361 get_cred(req->creds);
7362 req->flags |= REQ_F_CREDS;
7364 state = &ctx->submit_state;
7367 * Plug now if we have more than 1 IO left after this, and the target
7368 * is potentially a read/write to block based storage.
7370 if (!state->plug_started && state->ios_left > 1 &&
7371 io_op_defs[req->opcode].plug) {
7372 blk_start_plug(&state->plug);
7373 state->plug_started = true;
7376 if (io_op_defs[req->opcode].needs_file) {
7377 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7378 (sqe_flags & IOSQE_FIXED_FILE),
7379 IO_URING_F_NONBLOCK);
7380 if (unlikely(!req->file))
7388 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7389 const struct io_uring_sqe *sqe)
7390 __must_hold(&ctx->uring_lock)
7392 struct io_submit_link *link = &ctx->submit_state.link;
7395 ret = io_init_req(ctx, req, sqe);
7396 if (unlikely(ret)) {
7398 /* fail even hard links since we don't submit */
7401 * we can judge a link req is failed or cancelled by if
7402 * REQ_F_FAIL is set, but the head is an exception since
7403 * it may be set REQ_F_FAIL because of other req's failure
7404 * so let's leverage req->result to distinguish if a head
7405 * is set REQ_F_FAIL because of its failure or other req's
7406 * failure so that we can set the correct ret code for it.
7407 * init result here to avoid affecting the normal path.
7409 if (!(link->head->flags & REQ_F_FAIL))
7410 req_fail_link_node(link->head, -ECANCELED);
7411 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7413 * the current req is a normal req, we should return
7414 * error and thus break the submittion loop.
7416 io_req_complete_failed(req, ret);
7419 req_fail_link_node(req, ret);
7421 ret = io_req_prep(req, sqe);
7426 /* don't need @sqe from now on */
7427 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7429 ctx->flags & IORING_SETUP_SQPOLL);
7432 * If we already have a head request, queue this one for async
7433 * submittal once the head completes. If we don't have a head but
7434 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7435 * submitted sync once the chain is complete. If none of those
7436 * conditions are true (normal request), then just queue it.
7439 struct io_kiocb *head = link->head;
7441 if (!(req->flags & REQ_F_FAIL)) {
7442 ret = io_req_prep_async(req);
7443 if (unlikely(ret)) {
7444 req_fail_link_node(req, ret);
7445 if (!(head->flags & REQ_F_FAIL))
7446 req_fail_link_node(head, -ECANCELED);
7449 trace_io_uring_link(ctx, req, head);
7450 link->last->link = req;
7453 /* last request of a link, enqueue the link */
7454 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7459 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7471 * Batched submission is done, ensure local IO is flushed out.
7473 static void io_submit_state_end(struct io_submit_state *state,
7474 struct io_ring_ctx *ctx)
7476 if (state->link.head)
7477 io_queue_sqe(state->link.head);
7478 if (state->compl_nr)
7479 io_submit_flush_completions(ctx);
7480 if (state->plug_started)
7481 blk_finish_plug(&state->plug);
7485 * Start submission side cache.
7487 static void io_submit_state_start(struct io_submit_state *state,
7488 unsigned int max_ios)
7490 state->plug_started = false;
7491 state->ios_left = max_ios;
7492 /* set only head, no need to init link_last in advance */
7493 state->link.head = NULL;
7496 static void io_commit_sqring(struct io_ring_ctx *ctx)
7498 struct io_rings *rings = ctx->rings;
7501 * Ensure any loads from the SQEs are done at this point,
7502 * since once we write the new head, the application could
7503 * write new data to them.
7505 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7509 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7510 * that is mapped by userspace. This means that care needs to be taken to
7511 * ensure that reads are stable, as we cannot rely on userspace always
7512 * being a good citizen. If members of the sqe are validated and then later
7513 * used, it's important that those reads are done through READ_ONCE() to
7514 * prevent a re-load down the line.
7516 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7518 unsigned head, mask = ctx->sq_entries - 1;
7519 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7522 * The cached sq head (or cq tail) serves two purposes:
7524 * 1) allows us to batch the cost of updating the user visible
7526 * 2) allows the kernel side to track the head on its own, even
7527 * though the application is the one updating it.
7529 head = READ_ONCE(ctx->sq_array[sq_idx]);
7530 if (likely(head < ctx->sq_entries))
7531 return &ctx->sq_sqes[head];
7533 /* drop invalid entries */
7535 WRITE_ONCE(ctx->rings->sq_dropped,
7536 READ_ONCE(ctx->rings->sq_dropped) + 1);
7540 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7541 __must_hold(&ctx->uring_lock)
7545 /* make sure SQ entry isn't read before tail */
7546 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7547 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7549 io_get_task_refs(nr);
7551 io_submit_state_start(&ctx->submit_state, nr);
7552 while (submitted < nr) {
7553 const struct io_uring_sqe *sqe;
7554 struct io_kiocb *req;
7556 req = io_alloc_req(ctx);
7557 if (unlikely(!req)) {
7559 submitted = -EAGAIN;
7562 sqe = io_get_sqe(ctx);
7563 if (unlikely(!sqe)) {
7564 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7567 /* will complete beyond this point, count as submitted */
7569 if (io_submit_sqe(ctx, req, sqe))
7573 if (unlikely(submitted != nr)) {
7574 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7575 int unused = nr - ref_used;
7577 current->io_uring->cached_refs += unused;
7578 percpu_ref_put_many(&ctx->refs, unused);
7581 io_submit_state_end(&ctx->submit_state, ctx);
7582 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7583 io_commit_sqring(ctx);
7588 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7590 return READ_ONCE(sqd->state);
7593 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7595 /* Tell userspace we may need a wakeup call */
7596 spin_lock(&ctx->completion_lock);
7597 WRITE_ONCE(ctx->rings->sq_flags,
7598 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7599 spin_unlock(&ctx->completion_lock);
7602 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7604 spin_lock(&ctx->completion_lock);
7605 WRITE_ONCE(ctx->rings->sq_flags,
7606 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7607 spin_unlock(&ctx->completion_lock);
7610 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7612 unsigned int to_submit;
7615 to_submit = io_sqring_entries(ctx);
7616 /* if we're handling multiple rings, cap submit size for fairness */
7617 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7618 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7620 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7621 unsigned nr_events = 0;
7622 const struct cred *creds = NULL;
7624 if (ctx->sq_creds != current_cred())
7625 creds = override_creds(ctx->sq_creds);
7627 mutex_lock(&ctx->uring_lock);
7628 if (!list_empty(&ctx->iopoll_list))
7629 io_do_iopoll(ctx, &nr_events, 0);
7632 * Don't submit if refs are dying, good for io_uring_register(),
7633 * but also it is relied upon by io_ring_exit_work()
7635 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7636 !(ctx->flags & IORING_SETUP_R_DISABLED))
7637 ret = io_submit_sqes(ctx, to_submit);
7638 mutex_unlock(&ctx->uring_lock);
7640 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7641 wake_up(&ctx->sqo_sq_wait);
7643 revert_creds(creds);
7649 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7651 struct io_ring_ctx *ctx;
7652 unsigned sq_thread_idle = 0;
7654 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7655 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7656 sqd->sq_thread_idle = sq_thread_idle;
7659 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7661 bool did_sig = false;
7662 struct ksignal ksig;
7664 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7665 signal_pending(current)) {
7666 mutex_unlock(&sqd->lock);
7667 if (signal_pending(current))
7668 did_sig = get_signal(&ksig);
7670 mutex_lock(&sqd->lock);
7672 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7675 static int io_sq_thread(void *data)
7677 struct io_sq_data *sqd = data;
7678 struct io_ring_ctx *ctx;
7679 unsigned long timeout = 0;
7680 char buf[TASK_COMM_LEN];
7683 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7684 set_task_comm(current, buf);
7686 if (sqd->sq_cpu != -1)
7687 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7689 set_cpus_allowed_ptr(current, cpu_online_mask);
7690 current->flags |= PF_NO_SETAFFINITY;
7692 mutex_lock(&sqd->lock);
7694 bool cap_entries, sqt_spin = false;
7696 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7697 if (io_sqd_handle_event(sqd))
7699 timeout = jiffies + sqd->sq_thread_idle;
7702 cap_entries = !list_is_singular(&sqd->ctx_list);
7703 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7704 int ret = __io_sq_thread(ctx, cap_entries);
7706 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7709 if (io_run_task_work())
7712 if (sqt_spin || !time_after(jiffies, timeout)) {
7715 timeout = jiffies + sqd->sq_thread_idle;
7719 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7720 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7721 bool needs_sched = true;
7723 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7724 io_ring_set_wakeup_flag(ctx);
7726 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7727 !list_empty_careful(&ctx->iopoll_list)) {
7728 needs_sched = false;
7731 if (io_sqring_entries(ctx)) {
7732 needs_sched = false;
7738 mutex_unlock(&sqd->lock);
7740 mutex_lock(&sqd->lock);
7742 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7743 io_ring_clear_wakeup_flag(ctx);
7746 finish_wait(&sqd->wait, &wait);
7747 timeout = jiffies + sqd->sq_thread_idle;
7750 io_uring_cancel_generic(true, sqd);
7752 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7753 io_ring_set_wakeup_flag(ctx);
7755 mutex_unlock(&sqd->lock);
7757 complete(&sqd->exited);
7761 struct io_wait_queue {
7762 struct wait_queue_entry wq;
7763 struct io_ring_ctx *ctx;
7765 unsigned nr_timeouts;
7768 static inline bool io_should_wake(struct io_wait_queue *iowq)
7770 struct io_ring_ctx *ctx = iowq->ctx;
7771 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7774 * Wake up if we have enough events, or if a timeout occurred since we
7775 * started waiting. For timeouts, we always want to return to userspace,
7776 * regardless of event count.
7778 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7781 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7782 int wake_flags, void *key)
7784 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7788 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7789 * the task, and the next invocation will do it.
7791 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7792 return autoremove_wake_function(curr, mode, wake_flags, key);
7796 static int io_run_task_work_sig(void)
7798 if (io_run_task_work())
7800 if (!signal_pending(current))
7802 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7803 return -ERESTARTSYS;
7807 static bool current_pending_io(void)
7809 struct io_uring_task *tctx = current->io_uring;
7813 return percpu_counter_read_positive(&tctx->inflight);
7816 /* when returns >0, the caller should retry */
7817 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7818 struct io_wait_queue *iowq,
7823 /* make sure we run task_work before checking for signals */
7824 ret = io_run_task_work_sig();
7825 if (ret || io_should_wake(iowq))
7827 /* let the caller flush overflows, retry */
7828 if (test_bit(0, &ctx->check_cq_overflow))
7832 * Mark us as being in io_wait if we have pending requests, so cpufreq
7833 * can take into account that the task is waiting for IO - turns out
7834 * to be important for low QD IO.
7836 io_wait = current->in_iowait;
7837 if (current_pending_io())
7838 current->in_iowait = 1;
7840 if (!schedule_hrtimeout(timeout, HRTIMER_MODE_ABS))
7842 current->in_iowait = io_wait;
7847 * Wait until events become available, if we don't already have some. The
7848 * application must reap them itself, as they reside on the shared cq ring.
7850 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7851 const sigset_t __user *sig, size_t sigsz,
7852 struct __kernel_timespec __user *uts)
7854 struct io_wait_queue iowq;
7855 struct io_rings *rings = ctx->rings;
7856 ktime_t timeout = KTIME_MAX;
7860 io_cqring_overflow_flush(ctx);
7861 if (io_cqring_events(ctx) >= min_events)
7863 if (!io_run_task_work())
7868 struct timespec64 ts;
7870 if (get_timespec64(&ts, uts))
7872 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7876 #ifdef CONFIG_COMPAT
7877 if (in_compat_syscall())
7878 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7882 ret = set_user_sigmask(sig, sigsz);
7888 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7889 iowq.wq.private = current;
7890 INIT_LIST_HEAD(&iowq.wq.entry);
7892 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7893 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7895 trace_io_uring_cqring_wait(ctx, min_events);
7897 /* if we can't even flush overflow, don't wait for more */
7898 if (!io_cqring_overflow_flush(ctx)) {
7902 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7903 TASK_INTERRUPTIBLE);
7904 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7905 finish_wait(&ctx->cq_wait, &iowq.wq);
7909 restore_saved_sigmask_unless(ret == -EINTR);
7911 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7914 static void io_free_page_table(void **table, size_t size)
7916 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7918 for (i = 0; i < nr_tables; i++)
7923 static void **io_alloc_page_table(size_t size)
7925 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7926 size_t init_size = size;
7929 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7933 for (i = 0; i < nr_tables; i++) {
7934 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7936 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7938 io_free_page_table(table, init_size);
7946 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7948 percpu_ref_exit(&ref_node->refs);
7952 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7954 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7955 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7956 unsigned long flags;
7957 bool first_add = false;
7958 unsigned long delay = HZ;
7960 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7963 /* if we are mid-quiesce then do not delay */
7964 if (node->rsrc_data->quiesce)
7967 while (!list_empty(&ctx->rsrc_ref_list)) {
7968 node = list_first_entry(&ctx->rsrc_ref_list,
7969 struct io_rsrc_node, node);
7970 /* recycle ref nodes in order */
7973 list_del(&node->node);
7974 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7976 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7979 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7982 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7984 struct io_rsrc_node *ref_node;
7986 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7990 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7995 INIT_LIST_HEAD(&ref_node->node);
7996 INIT_LIST_HEAD(&ref_node->rsrc_list);
7997 ref_node->done = false;
8001 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8002 struct io_rsrc_data *data_to_kill)
8004 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8005 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8008 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8010 rsrc_node->rsrc_data = data_to_kill;
8011 spin_lock_irq(&ctx->rsrc_ref_lock);
8012 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8013 spin_unlock_irq(&ctx->rsrc_ref_lock);
8015 atomic_inc(&data_to_kill->refs);
8016 percpu_ref_kill(&rsrc_node->refs);
8017 ctx->rsrc_node = NULL;
8020 if (!ctx->rsrc_node) {
8021 ctx->rsrc_node = ctx->rsrc_backup_node;
8022 ctx->rsrc_backup_node = NULL;
8026 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8028 if (ctx->rsrc_backup_node)
8030 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
8031 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8034 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
8038 /* As we may drop ->uring_lock, other task may have started quiesce */
8042 data->quiesce = true;
8044 ret = io_rsrc_node_switch_start(ctx);
8047 io_rsrc_node_switch(ctx, data);
8049 /* kill initial ref, already quiesced if zero */
8050 if (atomic_dec_and_test(&data->refs))
8052 mutex_unlock(&ctx->uring_lock);
8053 flush_delayed_work(&ctx->rsrc_put_work);
8054 ret = wait_for_completion_interruptible(&data->done);
8056 mutex_lock(&ctx->uring_lock);
8057 if (atomic_read(&data->refs) > 0) {
8059 * it has been revived by another thread while
8062 mutex_unlock(&ctx->uring_lock);
8068 atomic_inc(&data->refs);
8069 /* wait for all works potentially completing data->done */
8070 flush_delayed_work(&ctx->rsrc_put_work);
8071 reinit_completion(&data->done);
8073 ret = io_run_task_work_sig();
8074 mutex_lock(&ctx->uring_lock);
8076 data->quiesce = false;
8081 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8083 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8084 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8086 return &data->tags[table_idx][off];
8089 static void io_rsrc_data_free(struct io_rsrc_data *data)
8091 size_t size = data->nr * sizeof(data->tags[0][0]);
8094 io_free_page_table((void **)data->tags, size);
8098 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8099 u64 __user *utags, unsigned nr,
8100 struct io_rsrc_data **pdata)
8102 struct io_rsrc_data *data;
8106 data = kzalloc(sizeof(*data), GFP_KERNEL);
8109 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8117 data->do_put = do_put;
8120 for (i = 0; i < nr; i++) {
8121 u64 *tag_slot = io_get_tag_slot(data, i);
8123 if (copy_from_user(tag_slot, &utags[i],
8129 atomic_set(&data->refs, 1);
8130 init_completion(&data->done);
8134 io_rsrc_data_free(data);
8138 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8140 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8141 GFP_KERNEL_ACCOUNT);
8142 return !!table->files;
8145 static void io_free_file_tables(struct io_file_table *table)
8147 kvfree(table->files);
8148 table->files = NULL;
8151 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8153 #if defined(CONFIG_UNIX)
8154 if (ctx->ring_sock) {
8155 struct sock *sock = ctx->ring_sock->sk;
8156 struct sk_buff *skb;
8158 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8164 for (i = 0; i < ctx->nr_user_files; i++) {
8167 file = io_file_from_index(ctx, i);
8172 io_free_file_tables(&ctx->file_table);
8173 io_rsrc_data_free(ctx->file_data);
8174 ctx->file_data = NULL;
8175 ctx->nr_user_files = 0;
8178 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8180 unsigned nr = ctx->nr_user_files;
8183 if (!ctx->file_data)
8187 * Quiesce may unlock ->uring_lock, and while it's not held
8188 * prevent new requests using the table.
8190 ctx->nr_user_files = 0;
8191 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8192 ctx->nr_user_files = nr;
8194 __io_sqe_files_unregister(ctx);
8198 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8199 __releases(&sqd->lock)
8201 WARN_ON_ONCE(sqd->thread == current);
8204 * Do the dance but not conditional clear_bit() because it'd race with
8205 * other threads incrementing park_pending and setting the bit.
8207 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8208 if (atomic_dec_return(&sqd->park_pending))
8209 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8210 mutex_unlock(&sqd->lock);
8213 static void io_sq_thread_park(struct io_sq_data *sqd)
8214 __acquires(&sqd->lock)
8216 WARN_ON_ONCE(sqd->thread == current);
8218 atomic_inc(&sqd->park_pending);
8219 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8220 mutex_lock(&sqd->lock);
8222 wake_up_process(sqd->thread);
8225 static void io_sq_thread_stop(struct io_sq_data *sqd)
8227 WARN_ON_ONCE(sqd->thread == current);
8228 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8230 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8231 mutex_lock(&sqd->lock);
8233 wake_up_process(sqd->thread);
8234 mutex_unlock(&sqd->lock);
8235 wait_for_completion(&sqd->exited);
8238 static void io_put_sq_data(struct io_sq_data *sqd)
8240 if (refcount_dec_and_test(&sqd->refs)) {
8241 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8243 io_sq_thread_stop(sqd);
8248 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8250 struct io_sq_data *sqd = ctx->sq_data;
8253 io_sq_thread_park(sqd);
8254 list_del_init(&ctx->sqd_list);
8255 io_sqd_update_thread_idle(sqd);
8256 io_sq_thread_unpark(sqd);
8258 io_put_sq_data(sqd);
8259 ctx->sq_data = NULL;
8263 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8265 struct io_ring_ctx *ctx_attach;
8266 struct io_sq_data *sqd;
8269 f = fdget(p->wq_fd);
8271 return ERR_PTR(-ENXIO);
8272 if (f.file->f_op != &io_uring_fops) {
8274 return ERR_PTR(-EINVAL);
8277 ctx_attach = f.file->private_data;
8278 sqd = ctx_attach->sq_data;
8281 return ERR_PTR(-EINVAL);
8283 if (sqd->task_tgid != current->tgid) {
8285 return ERR_PTR(-EPERM);
8288 refcount_inc(&sqd->refs);
8293 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8296 struct io_sq_data *sqd;
8299 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8300 sqd = io_attach_sq_data(p);
8305 /* fall through for EPERM case, setup new sqd/task */
8306 if (PTR_ERR(sqd) != -EPERM)
8310 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8312 return ERR_PTR(-ENOMEM);
8314 atomic_set(&sqd->park_pending, 0);
8315 refcount_set(&sqd->refs, 1);
8316 INIT_LIST_HEAD(&sqd->ctx_list);
8317 mutex_init(&sqd->lock);
8318 init_waitqueue_head(&sqd->wait);
8319 init_completion(&sqd->exited);
8323 #if defined(CONFIG_UNIX)
8325 * Ensure the UNIX gc is aware of our file set, so we are certain that
8326 * the io_uring can be safely unregistered on process exit, even if we have
8327 * loops in the file referencing.
8329 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8331 struct sock *sk = ctx->ring_sock->sk;
8332 struct scm_fp_list *fpl;
8333 struct sk_buff *skb;
8336 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8340 skb = alloc_skb(0, GFP_KERNEL);
8347 skb->scm_io_uring = 1;
8350 fpl->user = get_uid(current_user());
8351 for (i = 0; i < nr; i++) {
8352 struct file *file = io_file_from_index(ctx, i + offset);
8356 fpl->fp[nr_files] = get_file(file);
8357 unix_inflight(fpl->user, fpl->fp[nr_files]);
8362 fpl->max = SCM_MAX_FD;
8363 fpl->count = nr_files;
8364 UNIXCB(skb).fp = fpl;
8365 skb->destructor = unix_destruct_scm;
8366 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8367 skb_queue_head(&sk->sk_receive_queue, skb);
8369 for (i = 0; i < nr; i++) {
8370 struct file *file = io_file_from_index(ctx, i + offset);
8377 free_uid(fpl->user);
8385 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8386 * causes regular reference counting to break down. We rely on the UNIX
8387 * garbage collection to take care of this problem for us.
8389 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8391 unsigned left, total;
8395 left = ctx->nr_user_files;
8397 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8399 ret = __io_sqe_files_scm(ctx, this_files, total);
8403 total += this_files;
8409 while (total < ctx->nr_user_files) {
8410 struct file *file = io_file_from_index(ctx, total);
8420 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8426 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8428 struct file *file = prsrc->file;
8429 #if defined(CONFIG_UNIX)
8430 struct sock *sock = ctx->ring_sock->sk;
8431 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8432 struct sk_buff *skb;
8435 __skb_queue_head_init(&list);
8438 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8439 * remove this entry and rearrange the file array.
8441 skb = skb_dequeue(head);
8443 struct scm_fp_list *fp;
8445 fp = UNIXCB(skb).fp;
8446 for (i = 0; i < fp->count; i++) {
8449 if (fp->fp[i] != file)
8452 unix_notinflight(fp->user, fp->fp[i]);
8453 left = fp->count - 1 - i;
8455 memmove(&fp->fp[i], &fp->fp[i + 1],
8456 left * sizeof(struct file *));
8463 __skb_queue_tail(&list, skb);
8473 __skb_queue_tail(&list, skb);
8475 skb = skb_dequeue(head);
8478 if (skb_peek(&list)) {
8479 spin_lock_irq(&head->lock);
8480 while ((skb = __skb_dequeue(&list)) != NULL)
8481 __skb_queue_tail(head, skb);
8482 spin_unlock_irq(&head->lock);
8489 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8491 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8492 struct io_ring_ctx *ctx = rsrc_data->ctx;
8493 struct io_rsrc_put *prsrc, *tmp;
8495 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8496 list_del(&prsrc->list);
8499 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8501 io_ring_submit_lock(ctx, lock_ring);
8502 spin_lock(&ctx->completion_lock);
8503 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8504 io_commit_cqring(ctx);
8505 spin_unlock(&ctx->completion_lock);
8506 io_cqring_ev_posted(ctx);
8507 io_ring_submit_unlock(ctx, lock_ring);
8510 rsrc_data->do_put(ctx, prsrc);
8514 io_rsrc_node_destroy(ref_node);
8515 if (atomic_dec_and_test(&rsrc_data->refs))
8516 complete(&rsrc_data->done);
8519 static void io_rsrc_put_work(struct work_struct *work)
8521 struct io_ring_ctx *ctx;
8522 struct llist_node *node;
8524 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8525 node = llist_del_all(&ctx->rsrc_put_llist);
8528 struct io_rsrc_node *ref_node;
8529 struct llist_node *next = node->next;
8531 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8532 __io_rsrc_put_work(ref_node);
8537 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8538 unsigned nr_args, u64 __user *tags)
8540 __s32 __user *fds = (__s32 __user *) arg;
8549 if (nr_args > IORING_MAX_FIXED_FILES)
8551 if (nr_args > rlimit(RLIMIT_NOFILE))
8553 ret = io_rsrc_node_switch_start(ctx);
8556 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8562 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8565 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8566 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8570 /* allow sparse sets */
8573 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8580 if (unlikely(!file))
8584 * Don't allow io_uring instances to be registered. If UNIX
8585 * isn't enabled, then this causes a reference cycle and this
8586 * instance can never get freed. If UNIX is enabled we'll
8587 * handle it just fine, but there's still no point in allowing
8588 * a ring fd as it doesn't support regular read/write anyway.
8590 if (file->f_op == &io_uring_fops) {
8594 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8597 ret = io_sqe_files_scm(ctx);
8599 __io_sqe_files_unregister(ctx);
8603 io_rsrc_node_switch(ctx, NULL);
8606 for (i = 0; i < ctx->nr_user_files; i++) {
8607 file = io_file_from_index(ctx, i);
8611 io_free_file_tables(&ctx->file_table);
8612 ctx->nr_user_files = 0;
8614 io_rsrc_data_free(ctx->file_data);
8615 ctx->file_data = NULL;
8619 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8622 #if defined(CONFIG_UNIX)
8623 struct sock *sock = ctx->ring_sock->sk;
8624 struct sk_buff_head *head = &sock->sk_receive_queue;
8625 struct sk_buff *skb;
8628 * See if we can merge this file into an existing skb SCM_RIGHTS
8629 * file set. If there's no room, fall back to allocating a new skb
8630 * and filling it in.
8632 spin_lock_irq(&head->lock);
8633 skb = skb_peek(head);
8635 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8637 if (fpl->count < SCM_MAX_FD) {
8638 __skb_unlink(skb, head);
8639 spin_unlock_irq(&head->lock);
8640 fpl->fp[fpl->count] = get_file(file);
8641 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8643 spin_lock_irq(&head->lock);
8644 __skb_queue_head(head, skb);
8649 spin_unlock_irq(&head->lock);
8656 return __io_sqe_files_scm(ctx, 1, index);
8662 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8663 struct io_rsrc_node *node, void *rsrc)
8665 u64 *tag_slot = io_get_tag_slot(data, idx);
8666 struct io_rsrc_put *prsrc;
8668 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8672 prsrc->tag = *tag_slot;
8675 list_add(&prsrc->list, &node->rsrc_list);
8679 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8680 unsigned int issue_flags, u32 slot_index)
8682 struct io_ring_ctx *ctx = req->ctx;
8683 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8684 bool needs_switch = false;
8685 struct io_fixed_file *file_slot;
8688 io_ring_submit_lock(ctx, !force_nonblock);
8689 if (file->f_op == &io_uring_fops)
8692 if (!ctx->file_data)
8695 if (slot_index >= ctx->nr_user_files)
8698 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8699 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8701 if (file_slot->file_ptr) {
8702 struct file *old_file;
8704 ret = io_rsrc_node_switch_start(ctx);
8708 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8709 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8710 ctx->rsrc_node, old_file);
8713 file_slot->file_ptr = 0;
8714 needs_switch = true;
8717 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8718 io_fixed_file_set(file_slot, file);
8719 ret = io_sqe_file_register(ctx, file, slot_index);
8721 file_slot->file_ptr = 0;
8728 io_rsrc_node_switch(ctx, ctx->file_data);
8729 io_ring_submit_unlock(ctx, !force_nonblock);
8735 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8737 unsigned int offset = req->close.file_slot - 1;
8738 struct io_ring_ctx *ctx = req->ctx;
8739 struct io_fixed_file *file_slot;
8743 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8745 if (unlikely(!ctx->file_data))
8748 if (offset >= ctx->nr_user_files)
8750 ret = io_rsrc_node_switch_start(ctx);
8754 offset = array_index_nospec(offset, ctx->nr_user_files);
8755 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8757 if (!file_slot->file_ptr)
8760 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8761 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8765 file_slot->file_ptr = 0;
8766 io_rsrc_node_switch(ctx, ctx->file_data);
8769 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8773 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8774 struct io_uring_rsrc_update2 *up,
8777 u64 __user *tags = u64_to_user_ptr(up->tags);
8778 __s32 __user *fds = u64_to_user_ptr(up->data);
8779 struct io_rsrc_data *data = ctx->file_data;
8780 struct io_fixed_file *file_slot;
8784 bool needs_switch = false;
8786 if (!ctx->file_data)
8788 if (up->offset + nr_args > ctx->nr_user_files)
8791 for (done = 0; done < nr_args; done++) {
8794 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8795 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8799 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8803 if (fd == IORING_REGISTER_FILES_SKIP)
8806 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8807 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8809 if (file_slot->file_ptr) {
8810 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8811 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8814 file_slot->file_ptr = 0;
8815 needs_switch = true;
8824 * Don't allow io_uring instances to be registered. If
8825 * UNIX isn't enabled, then this causes a reference
8826 * cycle and this instance can never get freed. If UNIX
8827 * is enabled we'll handle it just fine, but there's
8828 * still no point in allowing a ring fd as it doesn't
8829 * support regular read/write anyway.
8831 if (file->f_op == &io_uring_fops) {
8836 *io_get_tag_slot(data, i) = tag;
8837 io_fixed_file_set(file_slot, file);
8838 err = io_sqe_file_register(ctx, file, i);
8840 file_slot->file_ptr = 0;
8848 io_rsrc_node_switch(ctx, data);
8849 return done ? done : err;
8852 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8853 struct task_struct *task)
8855 struct io_wq_hash *hash;
8856 struct io_wq_data data;
8857 unsigned int concurrency;
8859 mutex_lock(&ctx->uring_lock);
8860 hash = ctx->hash_map;
8862 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8864 mutex_unlock(&ctx->uring_lock);
8865 return ERR_PTR(-ENOMEM);
8867 refcount_set(&hash->refs, 1);
8868 init_waitqueue_head(&hash->wait);
8869 ctx->hash_map = hash;
8871 mutex_unlock(&ctx->uring_lock);
8875 data.free_work = io_wq_free_work;
8876 data.do_work = io_wq_submit_work;
8878 /* Do QD, or 4 * CPUS, whatever is smallest */
8879 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8881 return io_wq_create(concurrency, &data);
8884 static int io_uring_alloc_task_context(struct task_struct *task,
8885 struct io_ring_ctx *ctx)
8887 struct io_uring_task *tctx;
8890 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8891 if (unlikely(!tctx))
8894 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8895 if (unlikely(ret)) {
8900 tctx->io_wq = io_init_wq_offload(ctx, task);
8901 if (IS_ERR(tctx->io_wq)) {
8902 ret = PTR_ERR(tctx->io_wq);
8903 percpu_counter_destroy(&tctx->inflight);
8909 init_waitqueue_head(&tctx->wait);
8910 atomic_set(&tctx->in_idle, 0);
8911 atomic_set(&tctx->inflight_tracked, 0);
8912 task->io_uring = tctx;
8913 spin_lock_init(&tctx->task_lock);
8914 INIT_WQ_LIST(&tctx->task_list);
8915 init_task_work(&tctx->task_work, tctx_task_work);
8919 void __io_uring_free(struct task_struct *tsk)
8921 struct io_uring_task *tctx = tsk->io_uring;
8923 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8924 WARN_ON_ONCE(tctx->io_wq);
8925 WARN_ON_ONCE(tctx->cached_refs);
8927 percpu_counter_destroy(&tctx->inflight);
8929 tsk->io_uring = NULL;
8932 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8933 struct io_uring_params *p)
8937 /* Retain compatibility with failing for an invalid attach attempt */
8938 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8939 IORING_SETUP_ATTACH_WQ) {
8942 f = fdget(p->wq_fd);
8945 if (f.file->f_op != &io_uring_fops) {
8951 if (ctx->flags & IORING_SETUP_SQPOLL) {
8952 struct task_struct *tsk;
8953 struct io_sq_data *sqd;
8956 sqd = io_get_sq_data(p, &attached);
8962 ctx->sq_creds = get_current_cred();
8964 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8965 if (!ctx->sq_thread_idle)
8966 ctx->sq_thread_idle = HZ;
8968 io_sq_thread_park(sqd);
8969 list_add(&ctx->sqd_list, &sqd->ctx_list);
8970 io_sqd_update_thread_idle(sqd);
8971 /* don't attach to a dying SQPOLL thread, would be racy */
8972 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8973 io_sq_thread_unpark(sqd);
8980 if (p->flags & IORING_SETUP_SQ_AFF) {
8981 int cpu = p->sq_thread_cpu;
8984 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8991 sqd->task_pid = current->pid;
8992 sqd->task_tgid = current->tgid;
8993 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9000 ret = io_uring_alloc_task_context(tsk, ctx);
9001 wake_up_new_task(tsk);
9004 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9005 /* Can't have SQ_AFF without SQPOLL */
9012 complete(&ctx->sq_data->exited);
9014 io_sq_thread_finish(ctx);
9018 static inline void __io_unaccount_mem(struct user_struct *user,
9019 unsigned long nr_pages)
9021 atomic_long_sub(nr_pages, &user->locked_vm);
9024 static inline int __io_account_mem(struct user_struct *user,
9025 unsigned long nr_pages)
9027 unsigned long page_limit, cur_pages, new_pages;
9029 /* Don't allow more pages than we can safely lock */
9030 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9033 cur_pages = atomic_long_read(&user->locked_vm);
9034 new_pages = cur_pages + nr_pages;
9035 if (new_pages > page_limit)
9037 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9038 new_pages) != cur_pages);
9043 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9046 __io_unaccount_mem(ctx->user, nr_pages);
9048 if (ctx->mm_account)
9049 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9052 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9057 ret = __io_account_mem(ctx->user, nr_pages);
9062 if (ctx->mm_account)
9063 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9068 static void io_mem_free(void *ptr)
9075 page = virt_to_head_page(ptr);
9076 if (put_page_testzero(page))
9077 free_compound_page(page);
9080 static void *io_mem_alloc(size_t size)
9082 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9084 return (void *) __get_free_pages(gfp, get_order(size));
9087 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9090 struct io_rings *rings;
9091 size_t off, sq_array_size;
9093 off = struct_size(rings, cqes, cq_entries);
9094 if (off == SIZE_MAX)
9098 off = ALIGN(off, SMP_CACHE_BYTES);
9106 sq_array_size = array_size(sizeof(u32), sq_entries);
9107 if (sq_array_size == SIZE_MAX)
9110 if (check_add_overflow(off, sq_array_size, &off))
9116 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9118 struct io_mapped_ubuf *imu = *slot;
9121 if (imu != ctx->dummy_ubuf) {
9122 for (i = 0; i < imu->nr_bvecs; i++)
9123 unpin_user_page(imu->bvec[i].bv_page);
9124 if (imu->acct_pages)
9125 io_unaccount_mem(ctx, imu->acct_pages);
9131 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9133 io_buffer_unmap(ctx, &prsrc->buf);
9137 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9141 for (i = 0; i < ctx->nr_user_bufs; i++)
9142 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9143 kfree(ctx->user_bufs);
9144 io_rsrc_data_free(ctx->buf_data);
9145 ctx->user_bufs = NULL;
9146 ctx->buf_data = NULL;
9147 ctx->nr_user_bufs = 0;
9150 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9152 unsigned nr = ctx->nr_user_bufs;
9159 * Quiesce may unlock ->uring_lock, and while it's not held
9160 * prevent new requests using the table.
9162 ctx->nr_user_bufs = 0;
9163 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9164 ctx->nr_user_bufs = nr;
9166 __io_sqe_buffers_unregister(ctx);
9170 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9171 void __user *arg, unsigned index)
9173 struct iovec __user *src;
9175 #ifdef CONFIG_COMPAT
9177 struct compat_iovec __user *ciovs;
9178 struct compat_iovec ciov;
9180 ciovs = (struct compat_iovec __user *) arg;
9181 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9184 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9185 dst->iov_len = ciov.iov_len;
9189 src = (struct iovec __user *) arg;
9190 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9196 * Not super efficient, but this is just a registration time. And we do cache
9197 * the last compound head, so generally we'll only do a full search if we don't
9200 * We check if the given compound head page has already been accounted, to
9201 * avoid double accounting it. This allows us to account the full size of the
9202 * page, not just the constituent pages of a huge page.
9204 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9205 int nr_pages, struct page *hpage)
9209 /* check current page array */
9210 for (i = 0; i < nr_pages; i++) {
9211 if (!PageCompound(pages[i]))
9213 if (compound_head(pages[i]) == hpage)
9217 /* check previously registered pages */
9218 for (i = 0; i < ctx->nr_user_bufs; i++) {
9219 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9221 for (j = 0; j < imu->nr_bvecs; j++) {
9222 if (!PageCompound(imu->bvec[j].bv_page))
9224 if (compound_head(imu->bvec[j].bv_page) == hpage)
9232 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9233 int nr_pages, struct io_mapped_ubuf *imu,
9234 struct page **last_hpage)
9238 imu->acct_pages = 0;
9239 for (i = 0; i < nr_pages; i++) {
9240 if (!PageCompound(pages[i])) {
9245 hpage = compound_head(pages[i]);
9246 if (hpage == *last_hpage)
9248 *last_hpage = hpage;
9249 if (headpage_already_acct(ctx, pages, i, hpage))
9251 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9255 if (!imu->acct_pages)
9258 ret = io_account_mem(ctx, imu->acct_pages);
9260 imu->acct_pages = 0;
9264 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9265 struct io_mapped_ubuf **pimu,
9266 struct page **last_hpage)
9268 struct io_mapped_ubuf *imu = NULL;
9269 struct vm_area_struct **vmas = NULL;
9270 struct page **pages = NULL;
9271 unsigned long off, start, end, ubuf;
9273 int ret, pret, nr_pages, i;
9275 if (!iov->iov_base) {
9276 *pimu = ctx->dummy_ubuf;
9280 ubuf = (unsigned long) iov->iov_base;
9281 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9282 start = ubuf >> PAGE_SHIFT;
9283 nr_pages = end - start;
9288 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9292 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9297 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9302 mmap_read_lock(current->mm);
9303 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9305 if (pret == nr_pages) {
9306 struct file *file = vmas[0]->vm_file;
9308 /* don't support file backed memory */
9309 for (i = 0; i < nr_pages; i++) {
9310 if (vmas[i]->vm_file != file) {
9316 if (!vma_is_shmem(vmas[i]) && !is_file_hugepages(file)) {
9322 ret = pret < 0 ? pret : -EFAULT;
9324 mmap_read_unlock(current->mm);
9327 * if we did partial map, or found file backed vmas,
9328 * release any pages we did get
9331 unpin_user_pages(pages, pret);
9335 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9337 unpin_user_pages(pages, pret);
9341 off = ubuf & ~PAGE_MASK;
9342 size = iov->iov_len;
9343 for (i = 0; i < nr_pages; i++) {
9346 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9347 imu->bvec[i].bv_page = pages[i];
9348 imu->bvec[i].bv_len = vec_len;
9349 imu->bvec[i].bv_offset = off;
9353 /* store original address for later verification */
9355 imu->ubuf_end = ubuf + iov->iov_len;
9356 imu->nr_bvecs = nr_pages;
9367 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9369 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9370 return ctx->user_bufs ? 0 : -ENOMEM;
9373 static int io_buffer_validate(struct iovec *iov)
9375 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9378 * Don't impose further limits on the size and buffer
9379 * constraints here, we'll -EINVAL later when IO is
9380 * submitted if they are wrong.
9383 return iov->iov_len ? -EFAULT : 0;
9387 /* arbitrary limit, but we need something */
9388 if (iov->iov_len > SZ_1G)
9391 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9397 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9398 unsigned int nr_args, u64 __user *tags)
9400 struct page *last_hpage = NULL;
9401 struct io_rsrc_data *data;
9407 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9409 ret = io_rsrc_node_switch_start(ctx);
9412 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9415 ret = io_buffers_map_alloc(ctx, nr_args);
9417 io_rsrc_data_free(data);
9421 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9422 ret = io_copy_iov(ctx, &iov, arg, i);
9425 ret = io_buffer_validate(&iov);
9428 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9433 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9439 WARN_ON_ONCE(ctx->buf_data);
9441 ctx->buf_data = data;
9443 __io_sqe_buffers_unregister(ctx);
9445 io_rsrc_node_switch(ctx, NULL);
9449 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9450 struct io_uring_rsrc_update2 *up,
9451 unsigned int nr_args)
9453 u64 __user *tags = u64_to_user_ptr(up->tags);
9454 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9455 struct page *last_hpage = NULL;
9456 bool needs_switch = false;
9462 if (up->offset + nr_args > ctx->nr_user_bufs)
9465 for (done = 0; done < nr_args; done++) {
9466 struct io_mapped_ubuf *imu;
9467 int offset = up->offset + done;
9470 err = io_copy_iov(ctx, &iov, iovs, done);
9473 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9477 err = io_buffer_validate(&iov);
9480 if (!iov.iov_base && tag) {
9484 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9488 i = array_index_nospec(offset, ctx->nr_user_bufs);
9489 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9490 err = io_queue_rsrc_removal(ctx->buf_data, i,
9491 ctx->rsrc_node, ctx->user_bufs[i]);
9492 if (unlikely(err)) {
9493 io_buffer_unmap(ctx, &imu);
9496 ctx->user_bufs[i] = NULL;
9497 needs_switch = true;
9500 ctx->user_bufs[i] = imu;
9501 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9505 io_rsrc_node_switch(ctx, ctx->buf_data);
9506 return done ? done : err;
9509 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9511 __s32 __user *fds = arg;
9517 if (copy_from_user(&fd, fds, sizeof(*fds)))
9520 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9521 if (IS_ERR(ctx->cq_ev_fd)) {
9522 int ret = PTR_ERR(ctx->cq_ev_fd);
9524 ctx->cq_ev_fd = NULL;
9531 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9533 if (ctx->cq_ev_fd) {
9534 eventfd_ctx_put(ctx->cq_ev_fd);
9535 ctx->cq_ev_fd = NULL;
9542 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9544 struct io_buffer *buf;
9545 unsigned long index;
9547 xa_for_each(&ctx->io_buffers, index, buf)
9548 __io_remove_buffers(ctx, buf, index, -1U);
9551 static void io_req_cache_free(struct list_head *list)
9553 struct io_kiocb *req, *nxt;
9555 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9556 list_del(&req->inflight_entry);
9557 kmem_cache_free(req_cachep, req);
9561 static void io_req_caches_free(struct io_ring_ctx *ctx)
9563 struct io_submit_state *state = &ctx->submit_state;
9565 mutex_lock(&ctx->uring_lock);
9567 if (state->free_reqs) {
9568 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9569 state->free_reqs = 0;
9572 io_flush_cached_locked_reqs(ctx, state);
9573 io_req_cache_free(&state->free_list);
9574 mutex_unlock(&ctx->uring_lock);
9577 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9579 if (data && !atomic_dec_and_test(&data->refs))
9580 wait_for_completion(&data->done);
9583 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9585 io_sq_thread_finish(ctx);
9587 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9588 io_wait_rsrc_data(ctx->buf_data);
9589 io_wait_rsrc_data(ctx->file_data);
9591 mutex_lock(&ctx->uring_lock);
9593 __io_sqe_buffers_unregister(ctx);
9595 __io_sqe_files_unregister(ctx);
9597 __io_cqring_overflow_flush(ctx, true);
9598 mutex_unlock(&ctx->uring_lock);
9599 io_eventfd_unregister(ctx);
9600 io_destroy_buffers(ctx);
9602 put_cred(ctx->sq_creds);
9604 /* there are no registered resources left, nobody uses it */
9606 io_rsrc_node_destroy(ctx->rsrc_node);
9607 if (ctx->rsrc_backup_node)
9608 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9609 flush_delayed_work(&ctx->rsrc_put_work);
9611 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9612 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9614 #if defined(CONFIG_UNIX)
9615 if (ctx->ring_sock) {
9616 ctx->ring_sock->file = NULL; /* so that iput() is called */
9617 sock_release(ctx->ring_sock);
9620 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9622 if (ctx->mm_account) {
9623 mmdrop(ctx->mm_account);
9624 ctx->mm_account = NULL;
9627 io_mem_free(ctx->rings);
9628 io_mem_free(ctx->sq_sqes);
9630 percpu_ref_exit(&ctx->refs);
9631 free_uid(ctx->user);
9632 io_req_caches_free(ctx);
9634 io_wq_put_hash(ctx->hash_map);
9635 kfree(ctx->cancel_hash);
9636 kfree(ctx->dummy_ubuf);
9640 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9642 struct io_ring_ctx *ctx = file->private_data;
9645 poll_wait(file, &ctx->poll_wait, wait);
9647 * synchronizes with barrier from wq_has_sleeper call in
9651 if (!io_sqring_full(ctx))
9652 mask |= EPOLLOUT | EPOLLWRNORM;
9655 * Don't flush cqring overflow list here, just do a simple check.
9656 * Otherwise there could possible be ABBA deadlock:
9659 * lock(&ctx->uring_lock);
9661 * lock(&ctx->uring_lock);
9664 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9665 * pushs them to do the flush.
9667 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9668 mask |= EPOLLIN | EPOLLRDNORM;
9673 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9675 const struct cred *creds;
9677 creds = xa_erase(&ctx->personalities, id);
9686 struct io_tctx_exit {
9687 struct callback_head task_work;
9688 struct completion completion;
9689 struct io_ring_ctx *ctx;
9692 static void io_tctx_exit_cb(struct callback_head *cb)
9694 struct io_uring_task *tctx = current->io_uring;
9695 struct io_tctx_exit *work;
9697 work = container_of(cb, struct io_tctx_exit, task_work);
9699 * When @in_idle, we're in cancellation and it's racy to remove the
9700 * node. It'll be removed by the end of cancellation, just ignore it.
9701 * tctx can be NULL if the queueing of this task_work raced with
9702 * work cancelation off the exec path.
9704 if (tctx && !atomic_read(&tctx->in_idle))
9705 io_uring_del_tctx_node((unsigned long)work->ctx);
9706 complete(&work->completion);
9709 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9711 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9713 return req->ctx == data;
9716 static void io_ring_exit_work(struct work_struct *work)
9718 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9719 unsigned long timeout = jiffies + HZ * 60 * 5;
9720 unsigned long interval = HZ / 20;
9721 struct io_tctx_exit exit;
9722 struct io_tctx_node *node;
9726 * If we're doing polled IO and end up having requests being
9727 * submitted async (out-of-line), then completions can come in while
9728 * we're waiting for refs to drop. We need to reap these manually,
9729 * as nobody else will be looking for them.
9732 io_uring_try_cancel_requests(ctx, NULL, true);
9734 struct io_sq_data *sqd = ctx->sq_data;
9735 struct task_struct *tsk;
9737 io_sq_thread_park(sqd);
9739 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9740 io_wq_cancel_cb(tsk->io_uring->io_wq,
9741 io_cancel_ctx_cb, ctx, true);
9742 io_sq_thread_unpark(sqd);
9745 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9746 /* there is little hope left, don't run it too often */
9750 * This is really an uninterruptible wait, as it has to be
9751 * complete. But it's also run from a kworker, which doesn't
9752 * take signals, so it's fine to make it interruptible. This
9753 * avoids scenarios where we knowingly can wait much longer
9754 * on completions, for example if someone does a SIGSTOP on
9755 * a task that needs to finish task_work to make this loop
9756 * complete. That's a synthetic situation that should not
9757 * cause a stuck task backtrace, and hence a potential panic
9758 * on stuck tasks if that is enabled.
9760 } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
9762 init_completion(&exit.completion);
9763 init_task_work(&exit.task_work, io_tctx_exit_cb);
9766 * Some may use context even when all refs and requests have been put,
9767 * and they are free to do so while still holding uring_lock or
9768 * completion_lock, see io_req_task_submit(). Apart from other work,
9769 * this lock/unlock section also waits them to finish.
9771 mutex_lock(&ctx->uring_lock);
9772 while (!list_empty(&ctx->tctx_list)) {
9773 WARN_ON_ONCE(time_after(jiffies, timeout));
9775 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9777 /* don't spin on a single task if cancellation failed */
9778 list_rotate_left(&ctx->tctx_list);
9779 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9780 if (WARN_ON_ONCE(ret))
9782 wake_up_process(node->task);
9784 mutex_unlock(&ctx->uring_lock);
9786 * See comment above for
9787 * wait_for_completion_interruptible_timeout() on why this
9788 * wait is marked as interruptible.
9790 wait_for_completion_interruptible(&exit.completion);
9791 mutex_lock(&ctx->uring_lock);
9793 mutex_unlock(&ctx->uring_lock);
9794 spin_lock(&ctx->completion_lock);
9795 spin_unlock(&ctx->completion_lock);
9797 io_ring_ctx_free(ctx);
9800 /* Returns true if we found and killed one or more timeouts */
9801 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9804 struct io_kiocb *req, *tmp;
9807 spin_lock(&ctx->completion_lock);
9808 spin_lock_irq(&ctx->timeout_lock);
9809 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9810 if (io_match_task(req, tsk, cancel_all)) {
9811 io_kill_timeout(req, -ECANCELED);
9815 spin_unlock_irq(&ctx->timeout_lock);
9817 io_commit_cqring(ctx);
9818 spin_unlock(&ctx->completion_lock);
9820 io_cqring_ev_posted(ctx);
9821 return canceled != 0;
9824 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9826 unsigned long index;
9827 struct creds *creds;
9829 mutex_lock(&ctx->uring_lock);
9830 percpu_ref_kill(&ctx->refs);
9832 __io_cqring_overflow_flush(ctx, true);
9833 xa_for_each(&ctx->personalities, index, creds)
9834 io_unregister_personality(ctx, index);
9835 mutex_unlock(&ctx->uring_lock);
9837 io_kill_timeouts(ctx, NULL, true);
9838 io_poll_remove_all(ctx, NULL, true);
9840 /* if we failed setting up the ctx, we might not have any rings */
9841 io_iopoll_try_reap_events(ctx);
9843 /* drop cached put refs after potentially doing completions */
9844 if (current->io_uring)
9845 io_uring_drop_tctx_refs(current);
9847 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9849 * Use system_unbound_wq to avoid spawning tons of event kworkers
9850 * if we're exiting a ton of rings at the same time. It just adds
9851 * noise and overhead, there's no discernable change in runtime
9852 * over using system_wq.
9854 queue_work(system_unbound_wq, &ctx->exit_work);
9857 static int io_uring_release(struct inode *inode, struct file *file)
9859 struct io_ring_ctx *ctx = file->private_data;
9861 file->private_data = NULL;
9862 io_ring_ctx_wait_and_kill(ctx);
9866 struct io_task_cancel {
9867 struct task_struct *task;
9871 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9873 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9874 struct io_task_cancel *cancel = data;
9876 return io_match_task_safe(req, cancel->task, cancel->all);
9879 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9880 struct task_struct *task, bool cancel_all)
9882 struct io_defer_entry *de;
9885 spin_lock(&ctx->completion_lock);
9886 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9887 if (io_match_task_safe(de->req, task, cancel_all)) {
9888 list_cut_position(&list, &ctx->defer_list, &de->list);
9892 spin_unlock(&ctx->completion_lock);
9893 if (list_empty(&list))
9896 while (!list_empty(&list)) {
9897 de = list_first_entry(&list, struct io_defer_entry, list);
9898 list_del_init(&de->list);
9899 io_req_complete_failed(de->req, -ECANCELED);
9905 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9907 struct io_tctx_node *node;
9908 enum io_wq_cancel cret;
9911 mutex_lock(&ctx->uring_lock);
9912 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9913 struct io_uring_task *tctx = node->task->io_uring;
9916 * io_wq will stay alive while we hold uring_lock, because it's
9917 * killed after ctx nodes, which requires to take the lock.
9919 if (!tctx || !tctx->io_wq)
9921 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9922 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9924 mutex_unlock(&ctx->uring_lock);
9929 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9930 struct task_struct *task,
9933 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9934 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9937 enum io_wq_cancel cret;
9941 ret |= io_uring_try_cancel_iowq(ctx);
9942 } else if (tctx && tctx->io_wq) {
9944 * Cancels requests of all rings, not only @ctx, but
9945 * it's fine as the task is in exit/exec.
9947 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9949 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9952 /* SQPOLL thread does its own polling */
9953 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9954 (ctx->sq_data && ctx->sq_data->thread == current)) {
9955 while (!list_empty_careful(&ctx->iopoll_list)) {
9956 io_iopoll_try_reap_events(ctx);
9962 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9963 ret |= io_poll_remove_all(ctx, task, cancel_all);
9964 ret |= io_kill_timeouts(ctx, task, cancel_all);
9966 ret |= io_run_task_work();
9973 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9975 struct io_uring_task *tctx = current->io_uring;
9976 struct io_tctx_node *node;
9979 if (unlikely(!tctx)) {
9980 ret = io_uring_alloc_task_context(current, ctx);
9984 tctx = current->io_uring;
9985 if (ctx->iowq_limits_set) {
9986 unsigned int limits[2] = { ctx->iowq_limits[0],
9987 ctx->iowq_limits[1], };
9989 ret = io_wq_max_workers(tctx->io_wq, limits);
9994 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9995 node = kmalloc(sizeof(*node), GFP_KERNEL);
9999 node->task = current;
10001 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10002 node, GFP_KERNEL));
10008 mutex_lock(&ctx->uring_lock);
10009 list_add(&node->ctx_node, &ctx->tctx_list);
10010 mutex_unlock(&ctx->uring_lock);
10017 * Note that this task has used io_uring. We use it for cancelation purposes.
10019 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10021 struct io_uring_task *tctx = current->io_uring;
10023 if (likely(tctx && tctx->last == ctx))
10025 return __io_uring_add_tctx_node(ctx);
10029 * Remove this io_uring_file -> task mapping.
10031 static void io_uring_del_tctx_node(unsigned long index)
10033 struct io_uring_task *tctx = current->io_uring;
10034 struct io_tctx_node *node;
10038 node = xa_erase(&tctx->xa, index);
10042 WARN_ON_ONCE(current != node->task);
10043 WARN_ON_ONCE(list_empty(&node->ctx_node));
10045 mutex_lock(&node->ctx->uring_lock);
10046 list_del(&node->ctx_node);
10047 mutex_unlock(&node->ctx->uring_lock);
10049 if (tctx->last == node->ctx)
10054 static void io_uring_clean_tctx(struct io_uring_task *tctx)
10056 struct io_wq *wq = tctx->io_wq;
10057 struct io_tctx_node *node;
10058 unsigned long index;
10060 xa_for_each(&tctx->xa, index, node) {
10061 io_uring_del_tctx_node(index);
10066 * Must be after io_uring_del_task_file() (removes nodes under
10067 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10069 io_wq_put_and_exit(wq);
10070 tctx->io_wq = NULL;
10074 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10077 return atomic_read(&tctx->inflight_tracked);
10078 return percpu_counter_sum(&tctx->inflight);
10082 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10083 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10085 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
10087 struct io_uring_task *tctx = current->io_uring;
10088 struct io_ring_ctx *ctx;
10092 WARN_ON_ONCE(sqd && sqd->thread != current);
10094 if (!current->io_uring)
10097 io_wq_exit_start(tctx->io_wq);
10099 atomic_inc(&tctx->in_idle);
10101 io_uring_drop_tctx_refs(current);
10102 /* read completions before cancelations */
10103 inflight = tctx_inflight(tctx, !cancel_all);
10108 struct io_tctx_node *node;
10109 unsigned long index;
10111 xa_for_each(&tctx->xa, index, node) {
10112 /* sqpoll task will cancel all its requests */
10113 if (node->ctx->sq_data)
10115 io_uring_try_cancel_requests(node->ctx, current,
10119 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10120 io_uring_try_cancel_requests(ctx, current,
10124 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10125 io_run_task_work();
10126 io_uring_drop_tctx_refs(current);
10129 * If we've seen completions, retry without waiting. This
10130 * avoids a race where a completion comes in before we did
10131 * prepare_to_wait().
10133 if (inflight == tctx_inflight(tctx, !cancel_all))
10135 finish_wait(&tctx->wait, &wait);
10138 io_uring_clean_tctx(tctx);
10141 * We shouldn't run task_works after cancel, so just leave
10142 * ->in_idle set for normal exit.
10144 atomic_dec(&tctx->in_idle);
10145 /* for exec all current's requests should be gone, kill tctx */
10146 __io_uring_free(current);
10150 void __io_uring_cancel(bool cancel_all)
10152 io_uring_cancel_generic(cancel_all, NULL);
10155 static void *io_uring_validate_mmap_request(struct file *file,
10156 loff_t pgoff, size_t sz)
10158 struct io_ring_ctx *ctx = file->private_data;
10159 loff_t offset = pgoff << PAGE_SHIFT;
10164 case IORING_OFF_SQ_RING:
10165 case IORING_OFF_CQ_RING:
10168 case IORING_OFF_SQES:
10169 ptr = ctx->sq_sqes;
10172 return ERR_PTR(-EINVAL);
10175 page = virt_to_head_page(ptr);
10176 if (sz > page_size(page))
10177 return ERR_PTR(-EINVAL);
10184 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10186 size_t sz = vma->vm_end - vma->vm_start;
10190 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10192 return PTR_ERR(ptr);
10194 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10195 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10198 #else /* !CONFIG_MMU */
10200 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10202 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10205 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10207 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10210 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10211 unsigned long addr, unsigned long len,
10212 unsigned long pgoff, unsigned long flags)
10216 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10218 return PTR_ERR(ptr);
10220 return (unsigned long) ptr;
10223 #endif /* !CONFIG_MMU */
10225 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10230 if (!io_sqring_full(ctx))
10232 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10234 if (!io_sqring_full(ctx))
10237 } while (!signal_pending(current));
10239 finish_wait(&ctx->sqo_sq_wait, &wait);
10243 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10244 struct __kernel_timespec __user **ts,
10245 const sigset_t __user **sig)
10247 struct io_uring_getevents_arg arg;
10250 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10251 * is just a pointer to the sigset_t.
10253 if (!(flags & IORING_ENTER_EXT_ARG)) {
10254 *sig = (const sigset_t __user *) argp;
10260 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10261 * timespec and sigset_t pointers if good.
10263 if (*argsz != sizeof(arg))
10265 if (copy_from_user(&arg, argp, sizeof(arg)))
10269 *sig = u64_to_user_ptr(arg.sigmask);
10270 *argsz = arg.sigmask_sz;
10271 *ts = u64_to_user_ptr(arg.ts);
10275 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10276 u32, min_complete, u32, flags, const void __user *, argp,
10279 struct io_ring_ctx *ctx;
10284 io_run_task_work();
10286 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10287 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10291 if (unlikely(!f.file))
10295 if (unlikely(f.file->f_op != &io_uring_fops))
10299 ctx = f.file->private_data;
10300 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10304 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10308 * For SQ polling, the thread will do all submissions and completions.
10309 * Just return the requested submit count, and wake the thread if
10310 * we were asked to.
10313 if (ctx->flags & IORING_SETUP_SQPOLL) {
10314 io_cqring_overflow_flush(ctx);
10316 if (unlikely(ctx->sq_data->thread == NULL)) {
10320 if (flags & IORING_ENTER_SQ_WAKEUP)
10321 wake_up(&ctx->sq_data->wait);
10322 if (flags & IORING_ENTER_SQ_WAIT) {
10323 ret = io_sqpoll_wait_sq(ctx);
10327 submitted = to_submit;
10328 } else if (to_submit) {
10329 ret = io_uring_add_tctx_node(ctx);
10332 mutex_lock(&ctx->uring_lock);
10333 submitted = io_submit_sqes(ctx, to_submit);
10334 mutex_unlock(&ctx->uring_lock);
10336 if (submitted != to_submit)
10339 if (flags & IORING_ENTER_GETEVENTS) {
10340 const sigset_t __user *sig;
10341 struct __kernel_timespec __user *ts;
10343 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10347 min_complete = min(min_complete, ctx->cq_entries);
10350 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10351 * space applications don't need to do io completion events
10352 * polling again, they can rely on io_sq_thread to do polling
10353 * work, which can reduce cpu usage and uring_lock contention.
10355 if (ctx->flags & IORING_SETUP_IOPOLL &&
10356 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10357 ret = io_iopoll_check(ctx, min_complete);
10359 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10364 percpu_ref_put(&ctx->refs);
10367 return submitted ? submitted : ret;
10370 #ifdef CONFIG_PROC_FS
10371 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
10372 const struct cred *cred)
10374 struct user_namespace *uns = seq_user_ns(m);
10375 struct group_info *gi;
10380 seq_printf(m, "%5d\n", id);
10381 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10382 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10383 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10384 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10385 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10386 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10387 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10388 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10389 seq_puts(m, "\n\tGroups:\t");
10390 gi = cred->group_info;
10391 for (g = 0; g < gi->ngroups; g++) {
10392 seq_put_decimal_ull(m, g ? " " : "",
10393 from_kgid_munged(uns, gi->gid[g]));
10395 seq_puts(m, "\n\tCapEff:\t");
10396 cap = cred->cap_effective;
10397 CAP_FOR_EACH_U32(__capi)
10398 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10403 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
10405 struct io_sq_data *sq = NULL;
10410 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10411 * since fdinfo case grabs it in the opposite direction of normal use
10412 * cases. If we fail to get the lock, we just don't iterate any
10413 * structures that could be going away outside the io_uring mutex.
10415 has_lock = mutex_trylock(&ctx->uring_lock);
10417 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10423 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10424 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10425 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10426 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10427 struct file *f = io_file_from_index(ctx, i);
10430 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10432 seq_printf(m, "%5u: <none>\n", i);
10434 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10435 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10436 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10437 unsigned int len = buf->ubuf_end - buf->ubuf;
10439 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10441 if (has_lock && !xa_empty(&ctx->personalities)) {
10442 unsigned long index;
10443 const struct cred *cred;
10445 seq_printf(m, "Personalities:\n");
10446 xa_for_each(&ctx->personalities, index, cred)
10447 io_uring_show_cred(m, index, cred);
10449 seq_printf(m, "PollList:\n");
10450 spin_lock(&ctx->completion_lock);
10451 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10452 struct hlist_head *list = &ctx->cancel_hash[i];
10453 struct io_kiocb *req;
10455 hlist_for_each_entry(req, list, hash_node)
10456 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10457 req->task->task_works != NULL);
10459 spin_unlock(&ctx->completion_lock);
10461 mutex_unlock(&ctx->uring_lock);
10464 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10466 struct io_ring_ctx *ctx = f->private_data;
10468 if (percpu_ref_tryget(&ctx->refs)) {
10469 __io_uring_show_fdinfo(ctx, m);
10470 percpu_ref_put(&ctx->refs);
10475 static const struct file_operations io_uring_fops = {
10476 .release = io_uring_release,
10477 .mmap = io_uring_mmap,
10479 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10480 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10482 .poll = io_uring_poll,
10483 #ifdef CONFIG_PROC_FS
10484 .show_fdinfo = io_uring_show_fdinfo,
10488 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10489 struct io_uring_params *p)
10491 struct io_rings *rings;
10492 size_t size, sq_array_offset;
10494 /* make sure these are sane, as we already accounted them */
10495 ctx->sq_entries = p->sq_entries;
10496 ctx->cq_entries = p->cq_entries;
10498 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10499 if (size == SIZE_MAX)
10502 rings = io_mem_alloc(size);
10506 ctx->rings = rings;
10507 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10508 rings->sq_ring_mask = p->sq_entries - 1;
10509 rings->cq_ring_mask = p->cq_entries - 1;
10510 rings->sq_ring_entries = p->sq_entries;
10511 rings->cq_ring_entries = p->cq_entries;
10513 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10514 if (size == SIZE_MAX) {
10515 io_mem_free(ctx->rings);
10520 ctx->sq_sqes = io_mem_alloc(size);
10521 if (!ctx->sq_sqes) {
10522 io_mem_free(ctx->rings);
10530 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10534 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10538 ret = io_uring_add_tctx_node(ctx);
10543 fd_install(fd, file);
10548 * Allocate an anonymous fd, this is what constitutes the application
10549 * visible backing of an io_uring instance. The application mmaps this
10550 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10551 * we have to tie this fd to a socket for file garbage collection purposes.
10553 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10556 #if defined(CONFIG_UNIX)
10559 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10562 return ERR_PTR(ret);
10565 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10566 O_RDWR | O_CLOEXEC);
10567 #if defined(CONFIG_UNIX)
10568 if (IS_ERR(file)) {
10569 sock_release(ctx->ring_sock);
10570 ctx->ring_sock = NULL;
10572 ctx->ring_sock->file = file;
10578 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10579 struct io_uring_params __user *params)
10581 struct io_ring_ctx *ctx;
10587 if (entries > IORING_MAX_ENTRIES) {
10588 if (!(p->flags & IORING_SETUP_CLAMP))
10590 entries = IORING_MAX_ENTRIES;
10594 * Use twice as many entries for the CQ ring. It's possible for the
10595 * application to drive a higher depth than the size of the SQ ring,
10596 * since the sqes are only used at submission time. This allows for
10597 * some flexibility in overcommitting a bit. If the application has
10598 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10599 * of CQ ring entries manually.
10601 p->sq_entries = roundup_pow_of_two(entries);
10602 if (p->flags & IORING_SETUP_CQSIZE) {
10604 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10605 * to a power-of-two, if it isn't already. We do NOT impose
10606 * any cq vs sq ring sizing.
10608 if (!p->cq_entries)
10610 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10611 if (!(p->flags & IORING_SETUP_CLAMP))
10613 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10615 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10616 if (p->cq_entries < p->sq_entries)
10619 p->cq_entries = 2 * p->sq_entries;
10622 ctx = io_ring_ctx_alloc(p);
10625 ctx->compat = in_compat_syscall();
10626 if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
10627 ctx->user = get_uid(current_user());
10630 * This is just grabbed for accounting purposes. When a process exits,
10631 * the mm is exited and dropped before the files, hence we need to hang
10632 * on to this mm purely for the purposes of being able to unaccount
10633 * memory (locked/pinned vm). It's not used for anything else.
10635 mmgrab(current->mm);
10636 ctx->mm_account = current->mm;
10638 ret = io_allocate_scq_urings(ctx, p);
10642 ret = io_sq_offload_create(ctx, p);
10645 /* always set a rsrc node */
10646 ret = io_rsrc_node_switch_start(ctx);
10649 io_rsrc_node_switch(ctx, NULL);
10651 memset(&p->sq_off, 0, sizeof(p->sq_off));
10652 p->sq_off.head = offsetof(struct io_rings, sq.head);
10653 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10654 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10655 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10656 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10657 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10658 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10660 memset(&p->cq_off, 0, sizeof(p->cq_off));
10661 p->cq_off.head = offsetof(struct io_rings, cq.head);
10662 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10663 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10664 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10665 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10666 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10667 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10669 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10670 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10671 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10672 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10673 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10674 IORING_FEAT_RSRC_TAGS;
10676 if (copy_to_user(params, p, sizeof(*p))) {
10681 file = io_uring_get_file(ctx);
10682 if (IS_ERR(file)) {
10683 ret = PTR_ERR(file);
10688 * Install ring fd as the very last thing, so we don't risk someone
10689 * having closed it before we finish setup
10691 ret = io_uring_install_fd(ctx, file);
10693 /* fput will clean it up */
10698 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10701 io_ring_ctx_wait_and_kill(ctx);
10706 * Sets up an aio uring context, and returns the fd. Applications asks for a
10707 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10708 * params structure passed in.
10710 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10712 struct io_uring_params p;
10715 if (copy_from_user(&p, params, sizeof(p)))
10717 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10722 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10723 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10724 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10725 IORING_SETUP_R_DISABLED))
10728 return io_uring_create(entries, &p, params);
10731 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10732 struct io_uring_params __user *, params)
10734 return io_uring_setup(entries, params);
10737 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10739 struct io_uring_probe *p;
10743 size = struct_size(p, ops, nr_args);
10744 if (size == SIZE_MAX)
10746 p = kzalloc(size, GFP_KERNEL);
10751 if (copy_from_user(p, arg, size))
10754 if (memchr_inv(p, 0, size))
10757 p->last_op = IORING_OP_LAST - 1;
10758 if (nr_args > IORING_OP_LAST)
10759 nr_args = IORING_OP_LAST;
10761 for (i = 0; i < nr_args; i++) {
10763 if (!io_op_defs[i].not_supported)
10764 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10769 if (copy_to_user(arg, p, size))
10776 static int io_register_personality(struct io_ring_ctx *ctx)
10778 const struct cred *creds;
10782 creds = get_current_cred();
10784 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10785 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10793 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10794 unsigned int nr_args)
10796 struct io_uring_restriction *res;
10800 /* Restrictions allowed only if rings started disabled */
10801 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10804 /* We allow only a single restrictions registration */
10805 if (ctx->restrictions.registered)
10808 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10811 size = array_size(nr_args, sizeof(*res));
10812 if (size == SIZE_MAX)
10815 res = memdup_user(arg, size);
10817 return PTR_ERR(res);
10821 for (i = 0; i < nr_args; i++) {
10822 switch (res[i].opcode) {
10823 case IORING_RESTRICTION_REGISTER_OP:
10824 if (res[i].register_op >= IORING_REGISTER_LAST) {
10829 __set_bit(res[i].register_op,
10830 ctx->restrictions.register_op);
10832 case IORING_RESTRICTION_SQE_OP:
10833 if (res[i].sqe_op >= IORING_OP_LAST) {
10838 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10840 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10841 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10843 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10844 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10853 /* Reset all restrictions if an error happened */
10855 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10857 ctx->restrictions.registered = true;
10863 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10865 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10868 if (ctx->restrictions.registered)
10869 ctx->restricted = 1;
10871 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10872 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10873 wake_up(&ctx->sq_data->wait);
10877 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10878 struct io_uring_rsrc_update2 *up,
10884 if (check_add_overflow(up->offset, nr_args, &tmp))
10886 err = io_rsrc_node_switch_start(ctx);
10891 case IORING_RSRC_FILE:
10892 return __io_sqe_files_update(ctx, up, nr_args);
10893 case IORING_RSRC_BUFFER:
10894 return __io_sqe_buffers_update(ctx, up, nr_args);
10899 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10902 struct io_uring_rsrc_update2 up;
10906 memset(&up, 0, sizeof(up));
10907 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10909 if (up.resv || up.resv2)
10911 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10914 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10915 unsigned size, unsigned type)
10917 struct io_uring_rsrc_update2 up;
10919 if (size != sizeof(up))
10921 if (copy_from_user(&up, arg, sizeof(up)))
10923 if (!up.nr || up.resv || up.resv2)
10925 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10928 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10929 unsigned int size, unsigned int type)
10931 struct io_uring_rsrc_register rr;
10933 /* keep it extendible */
10934 if (size != sizeof(rr))
10937 memset(&rr, 0, sizeof(rr));
10938 if (copy_from_user(&rr, arg, size))
10940 if (!rr.nr || rr.resv || rr.resv2)
10944 case IORING_RSRC_FILE:
10945 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10946 rr.nr, u64_to_user_ptr(rr.tags));
10947 case IORING_RSRC_BUFFER:
10948 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10949 rr.nr, u64_to_user_ptr(rr.tags));
10954 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10957 struct io_uring_task *tctx = current->io_uring;
10958 cpumask_var_t new_mask;
10961 if (!tctx || !tctx->io_wq)
10964 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10967 cpumask_clear(new_mask);
10968 if (len > cpumask_size())
10969 len = cpumask_size();
10971 if (in_compat_syscall()) {
10972 ret = compat_get_bitmap(cpumask_bits(new_mask),
10973 (const compat_ulong_t __user *)arg,
10974 len * 8 /* CHAR_BIT */);
10976 ret = copy_from_user(new_mask, arg, len);
10980 free_cpumask_var(new_mask);
10984 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10985 free_cpumask_var(new_mask);
10989 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10991 struct io_uring_task *tctx = current->io_uring;
10993 if (!tctx || !tctx->io_wq)
10996 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10999 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11001 __must_hold(&ctx->uring_lock)
11003 struct io_tctx_node *node;
11004 struct io_uring_task *tctx = NULL;
11005 struct io_sq_data *sqd = NULL;
11006 __u32 new_count[2];
11009 if (copy_from_user(new_count, arg, sizeof(new_count)))
11011 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11012 if (new_count[i] > INT_MAX)
11015 if (ctx->flags & IORING_SETUP_SQPOLL) {
11016 sqd = ctx->sq_data;
11019 * Observe the correct sqd->lock -> ctx->uring_lock
11020 * ordering. Fine to drop uring_lock here, we hold
11021 * a ref to the ctx.
11023 refcount_inc(&sqd->refs);
11024 mutex_unlock(&ctx->uring_lock);
11025 mutex_lock(&sqd->lock);
11026 mutex_lock(&ctx->uring_lock);
11028 tctx = sqd->thread->io_uring;
11031 tctx = current->io_uring;
11034 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11036 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11038 ctx->iowq_limits[i] = new_count[i];
11039 ctx->iowq_limits_set = true;
11042 if (tctx && tctx->io_wq) {
11043 ret = io_wq_max_workers(tctx->io_wq, new_count);
11047 memset(new_count, 0, sizeof(new_count));
11051 mutex_unlock(&sqd->lock);
11052 io_put_sq_data(sqd);
11055 if (copy_to_user(arg, new_count, sizeof(new_count)))
11058 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11062 /* now propagate the restriction to all registered users */
11063 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11064 struct io_uring_task *tctx = node->task->io_uring;
11066 if (WARN_ON_ONCE(!tctx->io_wq))
11069 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11070 new_count[i] = ctx->iowq_limits[i];
11071 /* ignore errors, it always returns zero anyway */
11072 (void)io_wq_max_workers(tctx->io_wq, new_count);
11077 mutex_unlock(&sqd->lock);
11078 io_put_sq_data(sqd);
11083 static bool io_register_op_must_quiesce(int op)
11086 case IORING_REGISTER_BUFFERS:
11087 case IORING_UNREGISTER_BUFFERS:
11088 case IORING_REGISTER_FILES:
11089 case IORING_UNREGISTER_FILES:
11090 case IORING_REGISTER_FILES_UPDATE:
11091 case IORING_REGISTER_PROBE:
11092 case IORING_REGISTER_PERSONALITY:
11093 case IORING_UNREGISTER_PERSONALITY:
11094 case IORING_REGISTER_FILES2:
11095 case IORING_REGISTER_FILES_UPDATE2:
11096 case IORING_REGISTER_BUFFERS2:
11097 case IORING_REGISTER_BUFFERS_UPDATE:
11098 case IORING_REGISTER_IOWQ_AFF:
11099 case IORING_UNREGISTER_IOWQ_AFF:
11100 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11107 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
11111 percpu_ref_kill(&ctx->refs);
11114 * Drop uring mutex before waiting for references to exit. If another
11115 * thread is currently inside io_uring_enter() it might need to grab the
11116 * uring_lock to make progress. If we hold it here across the drain
11117 * wait, then we can deadlock. It's safe to drop the mutex here, since
11118 * no new references will come in after we've killed the percpu ref.
11120 mutex_unlock(&ctx->uring_lock);
11122 ret = wait_for_completion_interruptible(&ctx->ref_comp);
11125 ret = io_run_task_work_sig();
11126 } while (ret >= 0);
11127 mutex_lock(&ctx->uring_lock);
11130 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
11134 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11135 void __user *arg, unsigned nr_args)
11136 __releases(ctx->uring_lock)
11137 __acquires(ctx->uring_lock)
11142 * We're inside the ring mutex, if the ref is already dying, then
11143 * someone else killed the ctx or is already going through
11144 * io_uring_register().
11146 if (percpu_ref_is_dying(&ctx->refs))
11149 if (ctx->restricted) {
11150 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11151 if (!test_bit(opcode, ctx->restrictions.register_op))
11155 if (io_register_op_must_quiesce(opcode)) {
11156 ret = io_ctx_quiesce(ctx);
11162 case IORING_REGISTER_BUFFERS:
11163 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11165 case IORING_UNREGISTER_BUFFERS:
11167 if (arg || nr_args)
11169 ret = io_sqe_buffers_unregister(ctx);
11171 case IORING_REGISTER_FILES:
11172 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11174 case IORING_UNREGISTER_FILES:
11176 if (arg || nr_args)
11178 ret = io_sqe_files_unregister(ctx);
11180 case IORING_REGISTER_FILES_UPDATE:
11181 ret = io_register_files_update(ctx, arg, nr_args);
11183 case IORING_REGISTER_EVENTFD:
11184 case IORING_REGISTER_EVENTFD_ASYNC:
11188 ret = io_eventfd_register(ctx, arg);
11191 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
11192 ctx->eventfd_async = 1;
11194 ctx->eventfd_async = 0;
11196 case IORING_UNREGISTER_EVENTFD:
11198 if (arg || nr_args)
11200 ret = io_eventfd_unregister(ctx);
11202 case IORING_REGISTER_PROBE:
11204 if (!arg || nr_args > 256)
11206 ret = io_probe(ctx, arg, nr_args);
11208 case IORING_REGISTER_PERSONALITY:
11210 if (arg || nr_args)
11212 ret = io_register_personality(ctx);
11214 case IORING_UNREGISTER_PERSONALITY:
11218 ret = io_unregister_personality(ctx, nr_args);
11220 case IORING_REGISTER_ENABLE_RINGS:
11222 if (arg || nr_args)
11224 ret = io_register_enable_rings(ctx);
11226 case IORING_REGISTER_RESTRICTIONS:
11227 ret = io_register_restrictions(ctx, arg, nr_args);
11229 case IORING_REGISTER_FILES2:
11230 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11232 case IORING_REGISTER_FILES_UPDATE2:
11233 ret = io_register_rsrc_update(ctx, arg, nr_args,
11236 case IORING_REGISTER_BUFFERS2:
11237 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11239 case IORING_REGISTER_BUFFERS_UPDATE:
11240 ret = io_register_rsrc_update(ctx, arg, nr_args,
11241 IORING_RSRC_BUFFER);
11243 case IORING_REGISTER_IOWQ_AFF:
11245 if (!arg || !nr_args)
11247 ret = io_register_iowq_aff(ctx, arg, nr_args);
11249 case IORING_UNREGISTER_IOWQ_AFF:
11251 if (arg || nr_args)
11253 ret = io_unregister_iowq_aff(ctx);
11255 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11257 if (!arg || nr_args != 2)
11259 ret = io_register_iowq_max_workers(ctx, arg);
11266 if (io_register_op_must_quiesce(opcode)) {
11267 /* bring the ctx back to life */
11268 percpu_ref_reinit(&ctx->refs);
11269 reinit_completion(&ctx->ref_comp);
11274 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11275 void __user *, arg, unsigned int, nr_args)
11277 struct io_ring_ctx *ctx;
11281 if (opcode >= IORING_REGISTER_LAST)
11289 if (f.file->f_op != &io_uring_fops)
11292 ctx = f.file->private_data;
11294 io_run_task_work();
11296 mutex_lock(&ctx->uring_lock);
11297 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11298 mutex_unlock(&ctx->uring_lock);
11299 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11300 ctx->cq_ev_fd != NULL, ret);
11306 static int __init io_uring_init(void)
11308 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11309 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11310 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11313 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11314 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11315 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11316 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11317 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11318 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11319 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11320 BUILD_BUG_SQE_ELEM(8, __u64, off);
11321 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11322 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11323 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11324 BUILD_BUG_SQE_ELEM(24, __u32, len);
11325 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11326 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11327 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11328 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11329 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11330 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11331 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11332 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11333 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11334 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11335 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11336 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11337 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11338 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11339 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11340 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11341 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11342 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11343 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11344 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11345 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11347 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11348 sizeof(struct io_uring_rsrc_update));
11349 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11350 sizeof(struct io_uring_rsrc_update2));
11352 /* ->buf_index is u16 */
11353 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11355 /* should fit into one byte */
11356 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11358 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11359 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11361 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11365 __initcall(io_uring_init);