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;
489 struct wait_queue_entry wait;
492 struct io_poll_update {
498 bool update_user_data;
507 struct io_timeout_data {
508 struct io_kiocb *req;
509 struct hrtimer timer;
510 struct timespec64 ts;
511 enum hrtimer_mode mode;
517 struct sockaddr __user *addr;
518 int __user *addr_len;
521 unsigned long nofile;
541 struct list_head list;
542 /* head of the link, used by linked timeouts only */
543 struct io_kiocb *head;
544 /* for linked completions */
545 struct io_kiocb *prev;
548 struct io_timeout_rem {
553 struct timespec64 ts;
559 /* NOTE: kiocb has the file as the first member, so don't do it here */
567 struct sockaddr __user *addr;
574 struct compat_msghdr __user *umsg_compat;
575 struct user_msghdr __user *umsg;
582 struct io_buffer *kbuf;
589 struct filename *filename;
591 unsigned long nofile;
594 struct io_rsrc_update {
620 struct epoll_event event;
624 struct file *file_out;
632 struct io_provide_buf {
646 const char __user *filename;
647 struct statx __user *buffer;
659 struct filename *oldpath;
660 struct filename *newpath;
668 struct filename *filename;
675 struct filename *filename;
681 struct filename *oldpath;
682 struct filename *newpath;
689 struct filename *oldpath;
690 struct filename *newpath;
694 struct io_completion {
699 struct io_async_connect {
700 struct sockaddr_storage address;
703 struct io_async_msghdr {
704 struct iovec fast_iov[UIO_FASTIOV];
705 /* points to an allocated iov, if NULL we use fast_iov instead */
706 struct iovec *free_iov;
707 struct sockaddr __user *uaddr;
709 struct sockaddr_storage addr;
713 struct iovec fast_iov[UIO_FASTIOV];
714 const struct iovec *free_iovec;
715 struct iov_iter iter;
716 struct iov_iter_state iter_state;
718 struct wait_page_queue wpq;
722 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
723 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
724 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
725 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
726 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
727 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
729 /* first byte is taken by user flags, shift it to not overlap */
734 REQ_F_LINK_TIMEOUT_BIT,
735 REQ_F_NEED_CLEANUP_BIT,
737 REQ_F_BUFFER_SELECTED_BIT,
738 REQ_F_COMPLETE_INLINE_BIT,
742 REQ_F_ARM_LTIMEOUT_BIT,
743 REQ_F_PARTIAL_IO_BIT,
744 /* keep async read/write and isreg together and in order */
745 REQ_F_NOWAIT_READ_BIT,
746 REQ_F_NOWAIT_WRITE_BIT,
749 /* not a real bit, just to check we're not overflowing the space */
755 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
756 /* drain existing IO first */
757 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
759 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
760 /* doesn't sever on completion < 0 */
761 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
763 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
764 /* IOSQE_BUFFER_SELECT */
765 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
767 /* fail rest of links */
768 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
769 /* on inflight list, should be cancelled and waited on exit reliably */
770 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
771 /* read/write uses file position */
772 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
773 /* must not punt to workers */
774 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
775 /* has or had linked timeout */
776 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
778 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
779 /* already went through poll handler */
780 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
781 /* buffer already selected */
782 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
783 /* completion is deferred through io_comp_state */
784 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
785 /* caller should reissue async */
786 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
787 /* supports async reads */
788 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
789 /* supports async writes */
790 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
792 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
793 /* has creds assigned */
794 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
795 /* skip refcounting if not set */
796 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
797 /* there is a linked timeout that has to be armed */
798 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
799 /* request has already done partial IO */
800 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
804 struct io_poll_iocb poll;
805 struct io_poll_iocb *double_poll;
808 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
810 struct io_task_work {
812 struct io_wq_work_node node;
813 struct llist_node fallback_node;
815 io_req_tw_func_t func;
819 IORING_RSRC_FILE = 0,
820 IORING_RSRC_BUFFER = 1,
824 * NOTE! Each of the iocb union members has the file pointer
825 * as the first entry in their struct definition. So you can
826 * access the file pointer through any of the sub-structs,
827 * or directly as just 'ki_filp' in this struct.
833 struct io_poll_iocb poll;
834 struct io_poll_update poll_update;
835 struct io_accept accept;
837 struct io_cancel cancel;
838 struct io_timeout timeout;
839 struct io_timeout_rem timeout_rem;
840 struct io_connect connect;
841 struct io_sr_msg sr_msg;
843 struct io_close close;
844 struct io_rsrc_update rsrc_update;
845 struct io_fadvise fadvise;
846 struct io_madvise madvise;
847 struct io_epoll epoll;
848 struct io_splice splice;
849 struct io_provide_buf pbuf;
850 struct io_statx statx;
851 struct io_shutdown shutdown;
852 struct io_rename rename;
853 struct io_unlink unlink;
854 struct io_mkdir mkdir;
855 struct io_symlink symlink;
856 struct io_hardlink hardlink;
857 /* use only after cleaning per-op data, see io_clean_op() */
858 struct io_completion compl;
861 /* opcode allocated if it needs to store data for async defer */
864 /* polled IO has completed */
870 struct io_ring_ctx *ctx;
873 struct task_struct *task;
876 struct io_kiocb *link;
877 struct percpu_ref *fixed_rsrc_refs;
879 /* used with ctx->iopoll_list with reads/writes */
880 struct list_head inflight_entry;
881 struct io_task_work io_task_work;
882 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
883 struct hlist_node hash_node;
884 struct async_poll *apoll;
885 struct io_wq_work work;
886 const struct cred *creds;
888 /* store used ubuf, so we can prevent reloading */
889 struct io_mapped_ubuf *imu;
890 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
891 struct io_buffer *kbuf;
895 struct io_tctx_node {
896 struct list_head ctx_node;
897 struct task_struct *task;
898 struct io_ring_ctx *ctx;
901 struct io_defer_entry {
902 struct list_head list;
903 struct io_kiocb *req;
908 /* needs req->file assigned */
909 unsigned needs_file : 1;
910 /* hash wq insertion if file is a regular file */
911 unsigned hash_reg_file : 1;
912 /* unbound wq insertion if file is a non-regular file */
913 unsigned unbound_nonreg_file : 1;
914 /* opcode is not supported by this kernel */
915 unsigned not_supported : 1;
916 /* set if opcode supports polled "wait" */
918 unsigned pollout : 1;
919 /* op supports buffer selection */
920 unsigned buffer_select : 1;
921 /* do prep async if is going to be punted */
922 unsigned needs_async_setup : 1;
923 /* should block plug */
925 /* size of async data needed, if any */
926 unsigned short async_size;
929 static const struct io_op_def io_op_defs[] = {
930 [IORING_OP_NOP] = {},
931 [IORING_OP_READV] = {
933 .unbound_nonreg_file = 1,
936 .needs_async_setup = 1,
938 .async_size = sizeof(struct io_async_rw),
940 [IORING_OP_WRITEV] = {
943 .unbound_nonreg_file = 1,
945 .needs_async_setup = 1,
947 .async_size = sizeof(struct io_async_rw),
949 [IORING_OP_FSYNC] = {
952 [IORING_OP_READ_FIXED] = {
954 .unbound_nonreg_file = 1,
957 .async_size = sizeof(struct io_async_rw),
959 [IORING_OP_WRITE_FIXED] = {
962 .unbound_nonreg_file = 1,
965 .async_size = sizeof(struct io_async_rw),
967 [IORING_OP_POLL_ADD] = {
969 .unbound_nonreg_file = 1,
971 [IORING_OP_POLL_REMOVE] = {},
972 [IORING_OP_SYNC_FILE_RANGE] = {
975 [IORING_OP_SENDMSG] = {
977 .unbound_nonreg_file = 1,
979 .needs_async_setup = 1,
980 .async_size = sizeof(struct io_async_msghdr),
982 [IORING_OP_RECVMSG] = {
984 .unbound_nonreg_file = 1,
987 .needs_async_setup = 1,
988 .async_size = sizeof(struct io_async_msghdr),
990 [IORING_OP_TIMEOUT] = {
991 .async_size = sizeof(struct io_timeout_data),
993 [IORING_OP_TIMEOUT_REMOVE] = {
994 /* used by timeout updates' prep() */
996 [IORING_OP_ACCEPT] = {
998 .unbound_nonreg_file = 1,
1001 [IORING_OP_ASYNC_CANCEL] = {},
1002 [IORING_OP_LINK_TIMEOUT] = {
1003 .async_size = sizeof(struct io_timeout_data),
1005 [IORING_OP_CONNECT] = {
1007 .unbound_nonreg_file = 1,
1009 .needs_async_setup = 1,
1010 .async_size = sizeof(struct io_async_connect),
1012 [IORING_OP_FALLOCATE] = {
1015 [IORING_OP_OPENAT] = {},
1016 [IORING_OP_CLOSE] = {},
1017 [IORING_OP_FILES_UPDATE] = {},
1018 [IORING_OP_STATX] = {},
1019 [IORING_OP_READ] = {
1021 .unbound_nonreg_file = 1,
1025 .async_size = sizeof(struct io_async_rw),
1027 [IORING_OP_WRITE] = {
1030 .unbound_nonreg_file = 1,
1033 .async_size = sizeof(struct io_async_rw),
1035 [IORING_OP_FADVISE] = {
1038 [IORING_OP_MADVISE] = {},
1039 [IORING_OP_SEND] = {
1041 .unbound_nonreg_file = 1,
1044 [IORING_OP_RECV] = {
1046 .unbound_nonreg_file = 1,
1050 [IORING_OP_OPENAT2] = {
1052 [IORING_OP_EPOLL_CTL] = {
1053 .unbound_nonreg_file = 1,
1055 [IORING_OP_SPLICE] = {
1058 .unbound_nonreg_file = 1,
1060 [IORING_OP_PROVIDE_BUFFERS] = {},
1061 [IORING_OP_REMOVE_BUFFERS] = {},
1065 .unbound_nonreg_file = 1,
1067 [IORING_OP_SHUTDOWN] = {
1070 [IORING_OP_RENAMEAT] = {},
1071 [IORING_OP_UNLINKAT] = {},
1072 [IORING_OP_MKDIRAT] = {},
1073 [IORING_OP_SYMLINKAT] = {},
1074 [IORING_OP_LINKAT] = {},
1077 /* requests with any of those set should undergo io_disarm_next() */
1078 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1080 static bool io_disarm_next(struct io_kiocb *req);
1081 static void io_uring_del_tctx_node(unsigned long index);
1082 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1083 struct task_struct *task,
1085 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1087 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1089 static void io_put_req(struct io_kiocb *req);
1090 static void io_put_req_deferred(struct io_kiocb *req);
1091 static void io_dismantle_req(struct io_kiocb *req);
1092 static void io_queue_linked_timeout(struct io_kiocb *req);
1093 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1094 struct io_uring_rsrc_update2 *up,
1096 static void io_clean_op(struct io_kiocb *req);
1097 static struct file *io_file_get(struct io_ring_ctx *ctx,
1098 struct io_kiocb *req, int fd, bool fixed);
1099 static void __io_queue_sqe(struct io_kiocb *req);
1100 static void io_rsrc_put_work(struct work_struct *work);
1102 static void io_req_task_queue(struct io_kiocb *req);
1103 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1104 static int io_req_prep_async(struct io_kiocb *req);
1106 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1107 unsigned int issue_flags, u32 slot_index);
1108 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1110 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1112 static struct kmem_cache *req_cachep;
1114 static const struct file_operations io_uring_fops;
1116 struct sock *io_uring_get_socket(struct file *file)
1118 #if defined(CONFIG_UNIX)
1119 if (file->f_op == &io_uring_fops) {
1120 struct io_ring_ctx *ctx = file->private_data;
1122 return ctx->ring_sock->sk;
1127 EXPORT_SYMBOL(io_uring_get_socket);
1129 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1132 mutex_lock(&ctx->uring_lock);
1137 #define io_for_each_link(pos, head) \
1138 for (pos = (head); pos; pos = pos->link)
1141 * Shamelessly stolen from the mm implementation of page reference checking,
1142 * see commit f958d7b528b1 for details.
1144 #define req_ref_zero_or_close_to_overflow(req) \
1145 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1147 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1149 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1150 return atomic_inc_not_zero(&req->refs);
1153 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1155 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1158 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1159 return atomic_dec_and_test(&req->refs);
1162 static inline void req_ref_get(struct io_kiocb *req)
1164 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1165 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1166 atomic_inc(&req->refs);
1169 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1171 if (!(req->flags & REQ_F_REFCOUNT)) {
1172 req->flags |= REQ_F_REFCOUNT;
1173 atomic_set(&req->refs, nr);
1177 static inline void io_req_set_refcount(struct io_kiocb *req)
1179 __io_req_set_refcount(req, 1);
1182 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1184 struct io_ring_ctx *ctx = req->ctx;
1186 if (!req->fixed_rsrc_refs) {
1187 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1188 percpu_ref_get(req->fixed_rsrc_refs);
1192 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1194 bool got = percpu_ref_tryget(ref);
1196 /* already at zero, wait for ->release() */
1198 wait_for_completion(compl);
1199 percpu_ref_resurrect(ref);
1201 percpu_ref_put(ref);
1204 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1206 __must_hold(&req->ctx->timeout_lock)
1208 struct io_kiocb *req;
1210 if (task && head->task != task)
1215 io_for_each_link(req, head) {
1216 if (req->flags & REQ_F_INFLIGHT)
1222 static bool io_match_linked(struct io_kiocb *head)
1224 struct io_kiocb *req;
1226 io_for_each_link(req, head) {
1227 if (req->flags & REQ_F_INFLIGHT)
1234 * As io_match_task() but protected against racing with linked timeouts.
1235 * User must not hold timeout_lock.
1237 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1242 if (task && head->task != task)
1247 if (head->flags & REQ_F_LINK_TIMEOUT) {
1248 struct io_ring_ctx *ctx = head->ctx;
1250 /* protect against races with linked timeouts */
1251 spin_lock_irq(&ctx->timeout_lock);
1252 matched = io_match_linked(head);
1253 spin_unlock_irq(&ctx->timeout_lock);
1255 matched = io_match_linked(head);
1260 static inline void req_set_fail(struct io_kiocb *req)
1262 req->flags |= REQ_F_FAIL;
1265 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1271 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1273 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1275 complete(&ctx->ref_comp);
1278 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1280 return !req->timeout.off;
1283 static void io_fallback_req_func(struct work_struct *work)
1285 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1286 fallback_work.work);
1287 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1288 struct io_kiocb *req, *tmp;
1289 bool locked = false;
1291 percpu_ref_get(&ctx->refs);
1292 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1293 req->io_task_work.func(req, &locked);
1296 if (ctx->submit_state.compl_nr)
1297 io_submit_flush_completions(ctx);
1298 mutex_unlock(&ctx->uring_lock);
1300 percpu_ref_put(&ctx->refs);
1304 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1306 struct io_ring_ctx *ctx;
1309 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1314 * Use 5 bits less than the max cq entries, that should give us around
1315 * 32 entries per hash list if totally full and uniformly spread.
1317 hash_bits = ilog2(p->cq_entries);
1321 ctx->cancel_hash_bits = hash_bits;
1322 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1324 if (!ctx->cancel_hash)
1326 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1328 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1329 if (!ctx->dummy_ubuf)
1331 /* set invalid range, so io_import_fixed() fails meeting it */
1332 ctx->dummy_ubuf->ubuf = -1UL;
1334 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1335 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1338 ctx->flags = p->flags;
1339 init_waitqueue_head(&ctx->sqo_sq_wait);
1340 INIT_LIST_HEAD(&ctx->sqd_list);
1341 init_waitqueue_head(&ctx->poll_wait);
1342 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1343 init_completion(&ctx->ref_comp);
1344 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1345 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1346 mutex_init(&ctx->uring_lock);
1347 init_waitqueue_head(&ctx->cq_wait);
1348 spin_lock_init(&ctx->completion_lock);
1349 spin_lock_init(&ctx->timeout_lock);
1350 INIT_LIST_HEAD(&ctx->iopoll_list);
1351 INIT_LIST_HEAD(&ctx->defer_list);
1352 INIT_LIST_HEAD(&ctx->timeout_list);
1353 INIT_LIST_HEAD(&ctx->ltimeout_list);
1354 spin_lock_init(&ctx->rsrc_ref_lock);
1355 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1356 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1357 init_llist_head(&ctx->rsrc_put_llist);
1358 INIT_LIST_HEAD(&ctx->tctx_list);
1359 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1360 INIT_LIST_HEAD(&ctx->locked_free_list);
1361 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1364 kfree(ctx->dummy_ubuf);
1365 kfree(ctx->cancel_hash);
1370 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1372 struct io_rings *r = ctx->rings;
1374 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1378 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1380 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1381 struct io_ring_ctx *ctx = req->ctx;
1383 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1389 #define FFS_ASYNC_READ 0x1UL
1390 #define FFS_ASYNC_WRITE 0x2UL
1392 #define FFS_ISREG 0x4UL
1394 #define FFS_ISREG 0x0UL
1396 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1398 static inline bool io_req_ffs_set(struct io_kiocb *req)
1400 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1403 static void io_req_track_inflight(struct io_kiocb *req)
1405 if (!(req->flags & REQ_F_INFLIGHT)) {
1406 req->flags |= REQ_F_INFLIGHT;
1407 atomic_inc(&req->task->io_uring->inflight_tracked);
1411 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1413 if (WARN_ON_ONCE(!req->link))
1416 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1417 req->flags |= REQ_F_LINK_TIMEOUT;
1419 /* linked timeouts should have two refs once prep'ed */
1420 io_req_set_refcount(req);
1421 __io_req_set_refcount(req->link, 2);
1425 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1427 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1429 return __io_prep_linked_timeout(req);
1432 static void io_prep_async_work(struct io_kiocb *req)
1434 const struct io_op_def *def = &io_op_defs[req->opcode];
1435 struct io_ring_ctx *ctx = req->ctx;
1437 if (!(req->flags & REQ_F_CREDS)) {
1438 req->flags |= REQ_F_CREDS;
1439 req->creds = get_current_cred();
1442 req->work.list.next = NULL;
1443 req->work.flags = 0;
1444 if (req->flags & REQ_F_FORCE_ASYNC)
1445 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1447 if (req->flags & REQ_F_ISREG) {
1448 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1449 io_wq_hash_work(&req->work, file_inode(req->file));
1450 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1451 if (def->unbound_nonreg_file)
1452 req->work.flags |= IO_WQ_WORK_UNBOUND;
1456 static void io_prep_async_link(struct io_kiocb *req)
1458 struct io_kiocb *cur;
1460 if (req->flags & REQ_F_LINK_TIMEOUT) {
1461 struct io_ring_ctx *ctx = req->ctx;
1463 spin_lock_irq(&ctx->timeout_lock);
1464 io_for_each_link(cur, req)
1465 io_prep_async_work(cur);
1466 spin_unlock_irq(&ctx->timeout_lock);
1468 io_for_each_link(cur, req)
1469 io_prep_async_work(cur);
1473 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1475 struct io_ring_ctx *ctx = req->ctx;
1476 struct io_kiocb *link = io_prep_linked_timeout(req);
1477 struct io_uring_task *tctx = req->task->io_uring;
1479 /* must not take the lock, NULL it as a precaution */
1483 BUG_ON(!tctx->io_wq);
1485 /* init ->work of the whole link before punting */
1486 io_prep_async_link(req);
1489 * Not expected to happen, but if we do have a bug where this _can_
1490 * happen, catch it here and ensure the request is marked as
1491 * canceled. That will make io-wq go through the usual work cancel
1492 * procedure rather than attempt to run this request (or create a new
1495 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1496 req->work.flags |= IO_WQ_WORK_CANCEL;
1498 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1499 &req->work, req->flags);
1500 io_wq_enqueue(tctx->io_wq, &req->work);
1502 io_queue_linked_timeout(link);
1505 static void io_kill_timeout(struct io_kiocb *req, int status)
1506 __must_hold(&req->ctx->completion_lock)
1507 __must_hold(&req->ctx->timeout_lock)
1509 struct io_timeout_data *io = req->async_data;
1511 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1514 atomic_set(&req->ctx->cq_timeouts,
1515 atomic_read(&req->ctx->cq_timeouts) + 1);
1516 list_del_init(&req->timeout.list);
1517 io_fill_cqe_req(req, status, 0);
1518 io_put_req_deferred(req);
1522 static void io_queue_deferred(struct io_ring_ctx *ctx)
1524 while (!list_empty(&ctx->defer_list)) {
1525 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1526 struct io_defer_entry, list);
1528 if (req_need_defer(de->req, de->seq))
1530 list_del_init(&de->list);
1531 io_req_task_queue(de->req);
1536 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1537 __must_hold(&ctx->completion_lock)
1539 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1540 struct io_kiocb *req, *tmp;
1542 spin_lock_irq(&ctx->timeout_lock);
1543 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1544 u32 events_needed, events_got;
1546 if (io_is_timeout_noseq(req))
1550 * Since seq can easily wrap around over time, subtract
1551 * the last seq at which timeouts were flushed before comparing.
1552 * Assuming not more than 2^31-1 events have happened since,
1553 * these subtractions won't have wrapped, so we can check if
1554 * target is in [last_seq, current_seq] by comparing the two.
1556 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1557 events_got = seq - ctx->cq_last_tm_flush;
1558 if (events_got < events_needed)
1561 io_kill_timeout(req, 0);
1563 ctx->cq_last_tm_flush = seq;
1564 spin_unlock_irq(&ctx->timeout_lock);
1567 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1569 if (ctx->off_timeout_used)
1570 io_flush_timeouts(ctx);
1571 if (ctx->drain_active)
1572 io_queue_deferred(ctx);
1575 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1577 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1578 __io_commit_cqring_flush(ctx);
1579 /* order cqe stores with ring update */
1580 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1583 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1585 struct io_rings *r = ctx->rings;
1587 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1590 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1592 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1595 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1597 struct io_rings *rings = ctx->rings;
1598 unsigned tail, mask = ctx->cq_entries - 1;
1601 * writes to the cq entry need to come after reading head; the
1602 * control dependency is enough as we're using WRITE_ONCE to
1605 if (__io_cqring_events(ctx) == ctx->cq_entries)
1608 tail = ctx->cached_cq_tail++;
1609 return &rings->cqes[tail & mask];
1612 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1614 if (likely(!ctx->cq_ev_fd))
1616 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1618 return !ctx->eventfd_async || io_wq_current_is_worker();
1622 * This should only get called when at least one event has been posted.
1623 * Some applications rely on the eventfd notification count only changing
1624 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1625 * 1:1 relationship between how many times this function is called (and
1626 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1628 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1631 * wake_up_all() may seem excessive, but io_wake_function() and
1632 * io_should_wake() handle the termination of the loop and only
1633 * wake as many waiters as we need to.
1635 if (wq_has_sleeper(&ctx->cq_wait))
1636 __wake_up(&ctx->cq_wait, TASK_NORMAL, 0,
1637 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1638 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1639 wake_up(&ctx->sq_data->wait);
1640 if (io_should_trigger_evfd(ctx))
1641 eventfd_signal_mask(ctx->cq_ev_fd, 1, EPOLL_URING_WAKE);
1642 if (waitqueue_active(&ctx->poll_wait))
1643 __wake_up(&ctx->poll_wait, TASK_INTERRUPTIBLE, 0,
1644 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1647 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1649 /* see waitqueue_active() comment */
1652 if (ctx->flags & IORING_SETUP_SQPOLL) {
1653 if (waitqueue_active(&ctx->cq_wait))
1654 __wake_up(&ctx->cq_wait, TASK_NORMAL, 0,
1655 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1657 if (io_should_trigger_evfd(ctx))
1658 eventfd_signal_mask(ctx->cq_ev_fd, 1, EPOLL_URING_WAKE);
1659 if (waitqueue_active(&ctx->poll_wait))
1660 __wake_up(&ctx->poll_wait, TASK_INTERRUPTIBLE, 0,
1661 poll_to_key(EPOLL_URING_WAKE | EPOLLIN));
1664 /* Returns true if there are no backlogged entries after the flush */
1665 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1667 bool all_flushed, posted;
1669 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1673 spin_lock(&ctx->completion_lock);
1674 while (!list_empty(&ctx->cq_overflow_list)) {
1675 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1676 struct io_overflow_cqe *ocqe;
1680 ocqe = list_first_entry(&ctx->cq_overflow_list,
1681 struct io_overflow_cqe, list);
1683 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1685 io_account_cq_overflow(ctx);
1688 list_del(&ocqe->list);
1692 all_flushed = list_empty(&ctx->cq_overflow_list);
1694 clear_bit(0, &ctx->check_cq_overflow);
1695 WRITE_ONCE(ctx->rings->sq_flags,
1696 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1700 io_commit_cqring(ctx);
1701 spin_unlock(&ctx->completion_lock);
1703 io_cqring_ev_posted(ctx);
1707 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1711 if (test_bit(0, &ctx->check_cq_overflow)) {
1712 /* iopoll syncs against uring_lock, not completion_lock */
1713 if (ctx->flags & IORING_SETUP_IOPOLL)
1714 mutex_lock(&ctx->uring_lock);
1715 ret = __io_cqring_overflow_flush(ctx, false);
1716 if (ctx->flags & IORING_SETUP_IOPOLL)
1717 mutex_unlock(&ctx->uring_lock);
1723 /* must to be called somewhat shortly after putting a request */
1724 static inline void io_put_task(struct task_struct *task, int nr)
1726 struct io_uring_task *tctx = task->io_uring;
1728 if (likely(task == current)) {
1729 tctx->cached_refs += nr;
1731 percpu_counter_sub(&tctx->inflight, nr);
1732 if (unlikely(atomic_read(&tctx->in_idle)))
1733 wake_up(&tctx->wait);
1734 put_task_struct_many(task, nr);
1738 static void io_task_refs_refill(struct io_uring_task *tctx)
1740 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1742 percpu_counter_add(&tctx->inflight, refill);
1743 refcount_add(refill, ¤t->usage);
1744 tctx->cached_refs += refill;
1747 static inline void io_get_task_refs(int nr)
1749 struct io_uring_task *tctx = current->io_uring;
1751 tctx->cached_refs -= nr;
1752 if (unlikely(tctx->cached_refs < 0))
1753 io_task_refs_refill(tctx);
1756 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1758 struct io_uring_task *tctx = task->io_uring;
1759 unsigned int refs = tctx->cached_refs;
1762 tctx->cached_refs = 0;
1763 percpu_counter_sub(&tctx->inflight, refs);
1764 put_task_struct_many(task, refs);
1768 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1769 s32 res, u32 cflags)
1771 struct io_overflow_cqe *ocqe;
1773 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1776 * If we're in ring overflow flush mode, or in task cancel mode,
1777 * or cannot allocate an overflow entry, then we need to drop it
1780 io_account_cq_overflow(ctx);
1783 if (list_empty(&ctx->cq_overflow_list)) {
1784 set_bit(0, &ctx->check_cq_overflow);
1785 WRITE_ONCE(ctx->rings->sq_flags,
1786 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1789 ocqe->cqe.user_data = user_data;
1790 ocqe->cqe.res = res;
1791 ocqe->cqe.flags = cflags;
1792 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1796 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
1797 s32 res, u32 cflags)
1799 struct io_uring_cqe *cqe;
1801 trace_io_uring_complete(ctx, user_data, res, cflags);
1804 * If we can't get a cq entry, userspace overflowed the
1805 * submission (by quite a lot). Increment the overflow count in
1808 cqe = io_get_cqe(ctx);
1810 WRITE_ONCE(cqe->user_data, user_data);
1811 WRITE_ONCE(cqe->res, res);
1812 WRITE_ONCE(cqe->flags, cflags);
1815 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1818 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
1820 __io_fill_cqe(req->ctx, req->user_data, res, cflags);
1823 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1824 s32 res, u32 cflags)
1827 return __io_fill_cqe(ctx, user_data, res, cflags);
1830 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1833 struct io_ring_ctx *ctx = req->ctx;
1835 spin_lock(&ctx->completion_lock);
1836 __io_fill_cqe(ctx, req->user_data, res, cflags);
1838 * If we're the last reference to this request, add to our locked
1841 if (req_ref_put_and_test(req)) {
1842 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1843 if (req->flags & IO_DISARM_MASK)
1844 io_disarm_next(req);
1846 io_req_task_queue(req->link);
1850 io_dismantle_req(req);
1851 io_put_task(req->task, 1);
1852 list_add(&req->inflight_entry, &ctx->locked_free_list);
1853 ctx->locked_free_nr++;
1855 if (!percpu_ref_tryget(&ctx->refs))
1858 io_commit_cqring(ctx);
1859 spin_unlock(&ctx->completion_lock);
1862 io_cqring_ev_posted(ctx);
1863 percpu_ref_put(&ctx->refs);
1867 static inline bool io_req_needs_clean(struct io_kiocb *req)
1869 return req->flags & IO_REQ_CLEAN_FLAGS;
1872 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1875 if (io_req_needs_clean(req))
1878 req->compl.cflags = cflags;
1879 req->flags |= REQ_F_COMPLETE_INLINE;
1882 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1883 s32 res, u32 cflags)
1885 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1886 io_req_complete_state(req, res, cflags);
1888 io_req_complete_post(req, res, cflags);
1891 static inline void io_req_complete(struct io_kiocb *req, s32 res)
1893 __io_req_complete(req, 0, res, 0);
1896 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1899 io_req_complete_post(req, res, 0);
1902 static void io_req_complete_fail_submit(struct io_kiocb *req)
1905 * We don't submit, fail them all, for that replace hardlinks with
1906 * normal links. Extra REQ_F_LINK is tolerated.
1908 req->flags &= ~REQ_F_HARDLINK;
1909 req->flags |= REQ_F_LINK;
1910 io_req_complete_failed(req, req->result);
1914 * Don't initialise the fields below on every allocation, but do that in
1915 * advance and keep them valid across allocations.
1917 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1921 req->async_data = NULL;
1922 /* not necessary, but safer to zero */
1926 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1927 struct io_submit_state *state)
1929 spin_lock(&ctx->completion_lock);
1930 list_splice_init(&ctx->locked_free_list, &state->free_list);
1931 ctx->locked_free_nr = 0;
1932 spin_unlock(&ctx->completion_lock);
1935 /* Returns true IFF there are requests in the cache */
1936 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1938 struct io_submit_state *state = &ctx->submit_state;
1942 * If we have more than a batch's worth of requests in our IRQ side
1943 * locked cache, grab the lock and move them over to our submission
1946 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1947 io_flush_cached_locked_reqs(ctx, state);
1949 nr = state->free_reqs;
1950 while (!list_empty(&state->free_list)) {
1951 struct io_kiocb *req = list_first_entry(&state->free_list,
1952 struct io_kiocb, inflight_entry);
1954 list_del(&req->inflight_entry);
1955 state->reqs[nr++] = req;
1956 if (nr == ARRAY_SIZE(state->reqs))
1960 state->free_reqs = nr;
1965 * A request might get retired back into the request caches even before opcode
1966 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1967 * Because of that, io_alloc_req() should be called only under ->uring_lock
1968 * and with extra caution to not get a request that is still worked on.
1970 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1971 __must_hold(&ctx->uring_lock)
1973 struct io_submit_state *state = &ctx->submit_state;
1974 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1977 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1979 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1982 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1986 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1987 * retry single alloc to be on the safe side.
1989 if (unlikely(ret <= 0)) {
1990 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1991 if (!state->reqs[0])
1996 for (i = 0; i < ret; i++)
1997 io_preinit_req(state->reqs[i], ctx);
1998 state->free_reqs = ret;
2001 return state->reqs[state->free_reqs];
2004 static inline void io_put_file(struct file *file)
2010 static void io_dismantle_req(struct io_kiocb *req)
2012 unsigned int flags = req->flags;
2014 if (io_req_needs_clean(req))
2016 if (!(flags & REQ_F_FIXED_FILE))
2017 io_put_file(req->file);
2018 if (req->fixed_rsrc_refs)
2019 percpu_ref_put(req->fixed_rsrc_refs);
2020 if (req->async_data) {
2021 kfree(req->async_data);
2022 req->async_data = NULL;
2026 static void __io_free_req(struct io_kiocb *req)
2028 struct io_ring_ctx *ctx = req->ctx;
2030 io_dismantle_req(req);
2031 io_put_task(req->task, 1);
2033 spin_lock(&ctx->completion_lock);
2034 list_add(&req->inflight_entry, &ctx->locked_free_list);
2035 ctx->locked_free_nr++;
2036 spin_unlock(&ctx->completion_lock);
2038 percpu_ref_put(&ctx->refs);
2041 static inline void io_remove_next_linked(struct io_kiocb *req)
2043 struct io_kiocb *nxt = req->link;
2045 req->link = nxt->link;
2049 static bool io_kill_linked_timeout(struct io_kiocb *req)
2050 __must_hold(&req->ctx->completion_lock)
2051 __must_hold(&req->ctx->timeout_lock)
2053 struct io_kiocb *link = req->link;
2055 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2056 struct io_timeout_data *io = link->async_data;
2058 io_remove_next_linked(req);
2059 link->timeout.head = NULL;
2060 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2061 list_del(&link->timeout.list);
2062 io_fill_cqe_req(link, -ECANCELED, 0);
2063 io_put_req_deferred(link);
2070 static void io_fail_links(struct io_kiocb *req)
2071 __must_hold(&req->ctx->completion_lock)
2073 struct io_kiocb *nxt, *link = req->link;
2077 long res = -ECANCELED;
2079 if (link->flags & REQ_F_FAIL)
2085 trace_io_uring_fail_link(req, link);
2086 io_fill_cqe_req(link, res, 0);
2087 io_put_req_deferred(link);
2092 static bool io_disarm_next(struct io_kiocb *req)
2093 __must_hold(&req->ctx->completion_lock)
2095 bool posted = false;
2097 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2098 struct io_kiocb *link = req->link;
2100 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2101 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2102 io_remove_next_linked(req);
2103 io_fill_cqe_req(link, -ECANCELED, 0);
2104 io_put_req_deferred(link);
2107 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2108 struct io_ring_ctx *ctx = req->ctx;
2110 spin_lock_irq(&ctx->timeout_lock);
2111 posted = io_kill_linked_timeout(req);
2112 spin_unlock_irq(&ctx->timeout_lock);
2114 if (unlikely((req->flags & REQ_F_FAIL) &&
2115 !(req->flags & REQ_F_HARDLINK))) {
2116 posted |= (req->link != NULL);
2122 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2124 struct io_kiocb *nxt;
2127 * If LINK is set, we have dependent requests in this chain. If we
2128 * didn't fail this request, queue the first one up, moving any other
2129 * dependencies to the next request. In case of failure, fail the rest
2132 if (req->flags & IO_DISARM_MASK) {
2133 struct io_ring_ctx *ctx = req->ctx;
2136 spin_lock(&ctx->completion_lock);
2137 posted = io_disarm_next(req);
2139 io_commit_cqring(req->ctx);
2140 spin_unlock(&ctx->completion_lock);
2142 io_cqring_ev_posted(ctx);
2149 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2151 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2153 return __io_req_find_next(req);
2156 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2161 if (ctx->submit_state.compl_nr)
2162 io_submit_flush_completions(ctx);
2163 mutex_unlock(&ctx->uring_lock);
2166 percpu_ref_put(&ctx->refs);
2169 static void tctx_task_work(struct callback_head *cb)
2171 bool locked = false;
2172 struct io_ring_ctx *ctx = NULL;
2173 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2177 struct io_wq_work_node *node;
2179 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2180 io_submit_flush_completions(ctx);
2182 spin_lock_irq(&tctx->task_lock);
2183 node = tctx->task_list.first;
2184 INIT_WQ_LIST(&tctx->task_list);
2186 tctx->task_running = false;
2187 spin_unlock_irq(&tctx->task_lock);
2192 struct io_wq_work_node *next = node->next;
2193 struct io_kiocb *req = container_of(node, struct io_kiocb,
2196 if (req->ctx != ctx) {
2197 ctx_flush_and_put(ctx, &locked);
2199 /* if not contended, grab and improve batching */
2200 locked = mutex_trylock(&ctx->uring_lock);
2201 percpu_ref_get(&ctx->refs);
2203 req->io_task_work.func(req, &locked);
2210 ctx_flush_and_put(ctx, &locked);
2212 /* relaxed read is enough as only the task itself sets ->in_idle */
2213 if (unlikely(atomic_read(&tctx->in_idle)))
2214 io_uring_drop_tctx_refs(current);
2217 static void io_req_task_work_add(struct io_kiocb *req)
2219 struct task_struct *tsk = req->task;
2220 struct io_uring_task *tctx = tsk->io_uring;
2221 enum task_work_notify_mode notify;
2222 struct io_wq_work_node *node;
2223 unsigned long flags;
2226 WARN_ON_ONCE(!tctx);
2228 spin_lock_irqsave(&tctx->task_lock, flags);
2229 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2230 running = tctx->task_running;
2232 tctx->task_running = true;
2233 spin_unlock_irqrestore(&tctx->task_lock, flags);
2235 /* task_work already pending, we're done */
2240 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2241 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2242 * processing task_work. There's no reliable way to tell if TWA_RESUME
2245 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2246 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2247 wake_up_process(tsk);
2251 spin_lock_irqsave(&tctx->task_lock, flags);
2252 tctx->task_running = false;
2253 node = tctx->task_list.first;
2254 INIT_WQ_LIST(&tctx->task_list);
2255 spin_unlock_irqrestore(&tctx->task_lock, flags);
2258 req = container_of(node, struct io_kiocb, io_task_work.node);
2260 if (llist_add(&req->io_task_work.fallback_node,
2261 &req->ctx->fallback_llist))
2262 schedule_delayed_work(&req->ctx->fallback_work, 1);
2266 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2268 struct io_ring_ctx *ctx = req->ctx;
2270 /* not needed for normal modes, but SQPOLL depends on it */
2271 io_tw_lock(ctx, locked);
2272 io_req_complete_failed(req, req->result);
2275 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2277 struct io_ring_ctx *ctx = req->ctx;
2279 io_tw_lock(ctx, locked);
2280 /* req->task == current here, checking PF_EXITING is safe */
2281 if (likely(!(req->task->flags & PF_EXITING)))
2282 __io_queue_sqe(req);
2284 io_req_complete_failed(req, -EFAULT);
2287 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2290 req->io_task_work.func = io_req_task_cancel;
2291 io_req_task_work_add(req);
2294 static void io_req_task_queue(struct io_kiocb *req)
2296 req->io_task_work.func = io_req_task_submit;
2297 io_req_task_work_add(req);
2300 static void io_req_task_queue_reissue(struct io_kiocb *req)
2302 req->io_task_work.func = io_queue_async_work;
2303 io_req_task_work_add(req);
2306 static inline void io_queue_next(struct io_kiocb *req)
2308 struct io_kiocb *nxt = io_req_find_next(req);
2311 io_req_task_queue(nxt);
2314 static void io_free_req(struct io_kiocb *req)
2320 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2326 struct task_struct *task;
2331 static inline void io_init_req_batch(struct req_batch *rb)
2338 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2339 struct req_batch *rb)
2342 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2344 io_put_task(rb->task, rb->task_refs);
2347 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2348 struct io_submit_state *state)
2351 io_dismantle_req(req);
2353 if (req->task != rb->task) {
2355 io_put_task(rb->task, rb->task_refs);
2356 rb->task = req->task;
2362 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2363 state->reqs[state->free_reqs++] = req;
2365 list_add(&req->inflight_entry, &state->free_list);
2368 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2369 __must_hold(&ctx->uring_lock)
2371 struct io_submit_state *state = &ctx->submit_state;
2372 int i, nr = state->compl_nr;
2373 struct req_batch rb;
2375 spin_lock(&ctx->completion_lock);
2376 for (i = 0; i < nr; i++) {
2377 struct io_kiocb *req = state->compl_reqs[i];
2379 __io_fill_cqe(ctx, req->user_data, req->result,
2382 io_commit_cqring(ctx);
2383 spin_unlock(&ctx->completion_lock);
2384 io_cqring_ev_posted(ctx);
2386 io_init_req_batch(&rb);
2387 for (i = 0; i < nr; i++) {
2388 struct io_kiocb *req = state->compl_reqs[i];
2390 if (req_ref_put_and_test(req))
2391 io_req_free_batch(&rb, req, &ctx->submit_state);
2394 io_req_free_batch_finish(ctx, &rb);
2395 state->compl_nr = 0;
2399 * Drop reference to request, return next in chain (if there is one) if this
2400 * was the last reference to this request.
2402 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2404 struct io_kiocb *nxt = NULL;
2406 if (req_ref_put_and_test(req)) {
2407 nxt = io_req_find_next(req);
2413 static inline void io_put_req(struct io_kiocb *req)
2415 if (req_ref_put_and_test(req))
2419 static inline void io_put_req_deferred(struct io_kiocb *req)
2421 if (req_ref_put_and_test(req)) {
2422 req->io_task_work.func = io_free_req_work;
2423 io_req_task_work_add(req);
2427 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2429 /* See comment at the top of this file */
2431 return __io_cqring_events(ctx);
2434 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2436 struct io_rings *rings = ctx->rings;
2438 /* make sure SQ entry isn't read before tail */
2439 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2442 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2444 unsigned int cflags;
2446 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2447 cflags |= IORING_CQE_F_BUFFER;
2448 req->flags &= ~REQ_F_BUFFER_SELECTED;
2453 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2455 struct io_buffer *kbuf;
2457 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2459 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2460 return io_put_kbuf(req, kbuf);
2463 static inline bool io_run_task_work(void)
2465 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2466 __set_current_state(TASK_RUNNING);
2467 tracehook_notify_signal();
2475 * Find and free completed poll iocbs
2477 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2478 struct list_head *done)
2480 struct req_batch rb;
2481 struct io_kiocb *req;
2483 /* order with ->result store in io_complete_rw_iopoll() */
2486 io_init_req_batch(&rb);
2487 while (!list_empty(done)) {
2488 struct io_uring_cqe *cqe;
2491 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2492 list_del(&req->inflight_entry);
2493 cflags = io_put_rw_kbuf(req);
2496 cqe = io_get_cqe(ctx);
2498 WRITE_ONCE(cqe->user_data, req->user_data);
2499 WRITE_ONCE(cqe->res, req->result);
2500 WRITE_ONCE(cqe->flags, cflags);
2502 spin_lock(&ctx->completion_lock);
2503 io_cqring_event_overflow(ctx, req->user_data,
2504 req->result, cflags);
2505 spin_unlock(&ctx->completion_lock);
2508 if (req_ref_put_and_test(req))
2509 io_req_free_batch(&rb, req, &ctx->submit_state);
2512 io_commit_cqring(ctx);
2513 io_cqring_ev_posted_iopoll(ctx);
2514 io_req_free_batch_finish(ctx, &rb);
2517 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2520 struct io_kiocb *req, *tmp;
2525 * Only spin for completions if we don't have multiple devices hanging
2526 * off our complete list, and we're under the requested amount.
2528 spin = !ctx->poll_multi_queue && *nr_events < min;
2530 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2531 struct kiocb *kiocb = &req->rw.kiocb;
2535 * Move completed and retryable entries to our local lists.
2536 * If we find a request that requires polling, break out
2537 * and complete those lists first, if we have entries there.
2539 if (READ_ONCE(req->iopoll_completed)) {
2540 list_move_tail(&req->inflight_entry, &done);
2543 if (!list_empty(&done))
2546 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2547 if (unlikely(ret < 0))
2552 /* iopoll may have completed current req */
2553 if (READ_ONCE(req->iopoll_completed))
2554 list_move_tail(&req->inflight_entry, &done);
2557 if (!list_empty(&done))
2558 io_iopoll_complete(ctx, nr_events, &done);
2564 * We can't just wait for polled events to come to us, we have to actively
2565 * find and complete them.
2567 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2569 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2572 mutex_lock(&ctx->uring_lock);
2573 while (!list_empty(&ctx->iopoll_list)) {
2574 unsigned int nr_events = 0;
2576 io_do_iopoll(ctx, &nr_events, 0);
2578 /* let it sleep and repeat later if can't complete a request */
2582 * Ensure we allow local-to-the-cpu processing to take place,
2583 * in this case we need to ensure that we reap all events.
2584 * Also let task_work, etc. to progress by releasing the mutex
2586 if (need_resched()) {
2587 mutex_unlock(&ctx->uring_lock);
2589 mutex_lock(&ctx->uring_lock);
2592 mutex_unlock(&ctx->uring_lock);
2595 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2597 unsigned int nr_events = 0;
2601 * We disallow the app entering submit/complete with polling, but we
2602 * still need to lock the ring to prevent racing with polled issue
2603 * that got punted to a workqueue.
2605 mutex_lock(&ctx->uring_lock);
2607 * Don't enter poll loop if we already have events pending.
2608 * If we do, we can potentially be spinning for commands that
2609 * already triggered a CQE (eg in error).
2611 if (test_bit(0, &ctx->check_cq_overflow))
2612 __io_cqring_overflow_flush(ctx, false);
2613 if (io_cqring_events(ctx))
2617 * If a submit got punted to a workqueue, we can have the
2618 * application entering polling for a command before it gets
2619 * issued. That app will hold the uring_lock for the duration
2620 * of the poll right here, so we need to take a breather every
2621 * now and then to ensure that the issue has a chance to add
2622 * the poll to the issued list. Otherwise we can spin here
2623 * forever, while the workqueue is stuck trying to acquire the
2626 if (list_empty(&ctx->iopoll_list)) {
2627 u32 tail = ctx->cached_cq_tail;
2629 mutex_unlock(&ctx->uring_lock);
2631 mutex_lock(&ctx->uring_lock);
2633 /* some requests don't go through iopoll_list */
2634 if (tail != ctx->cached_cq_tail ||
2635 list_empty(&ctx->iopoll_list))
2638 ret = io_do_iopoll(ctx, &nr_events, min);
2639 } while (!ret && nr_events < min && !need_resched());
2641 mutex_unlock(&ctx->uring_lock);
2645 static void kiocb_end_write(struct io_kiocb *req)
2648 * Tell lockdep we inherited freeze protection from submission
2651 if (req->flags & REQ_F_ISREG) {
2652 struct super_block *sb = file_inode(req->file)->i_sb;
2654 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2660 static bool io_resubmit_prep(struct io_kiocb *req)
2662 struct io_async_rw *rw = req->async_data;
2665 return !io_req_prep_async(req);
2666 iov_iter_restore(&rw->iter, &rw->iter_state);
2670 static bool io_rw_should_reissue(struct io_kiocb *req)
2672 umode_t mode = file_inode(req->file)->i_mode;
2673 struct io_ring_ctx *ctx = req->ctx;
2675 if (!S_ISBLK(mode) && !S_ISREG(mode))
2677 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2678 !(ctx->flags & IORING_SETUP_IOPOLL)))
2681 * If ref is dying, we might be running poll reap from the exit work.
2682 * Don't attempt to reissue from that path, just let it fail with
2685 if (percpu_ref_is_dying(&ctx->refs))
2688 * Play it safe and assume not safe to re-import and reissue if we're
2689 * not in the original thread group (or in task context).
2691 if (!same_thread_group(req->task, current) || !in_task())
2696 static bool io_resubmit_prep(struct io_kiocb *req)
2700 static bool io_rw_should_reissue(struct io_kiocb *req)
2707 * Trigger the notifications after having done some IO, and finish the write
2708 * accounting, if any.
2710 static void io_req_io_end(struct io_kiocb *req)
2712 struct io_rw *rw = &req->rw;
2714 if (rw->kiocb.ki_flags & IOCB_WRITE) {
2715 kiocb_end_write(req);
2716 fsnotify_modify(req->file);
2718 fsnotify_access(req->file);
2722 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2724 if (res != req->result) {
2725 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2726 io_rw_should_reissue(req)) {
2728 * Reissue will start accounting again, finish the
2732 req->flags |= REQ_F_REISSUE;
2741 static inline int io_fixup_rw_res(struct io_kiocb *req, long res)
2743 struct io_async_rw *io = req->async_data;
2745 /* add previously done IO, if any */
2746 if (io && io->bytes_done > 0) {
2748 res = io->bytes_done;
2750 res += io->bytes_done;
2755 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2757 unsigned int cflags = io_put_rw_kbuf(req);
2758 int res = req->result;
2761 struct io_ring_ctx *ctx = req->ctx;
2762 struct io_submit_state *state = &ctx->submit_state;
2764 io_req_complete_state(req, res, cflags);
2765 state->compl_reqs[state->compl_nr++] = req;
2766 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2767 io_submit_flush_completions(ctx);
2769 io_req_complete_post(req, res, cflags);
2773 static void io_req_rw_complete(struct io_kiocb *req, bool *locked)
2776 io_req_task_complete(req, locked);
2779 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2781 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2783 if (__io_complete_rw_common(req, res))
2785 req->result = io_fixup_rw_res(req, res);
2786 req->io_task_work.func = io_req_rw_complete;
2787 io_req_task_work_add(req);
2790 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2792 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2794 if (kiocb->ki_flags & IOCB_WRITE)
2795 kiocb_end_write(req);
2796 if (unlikely(res != req->result)) {
2797 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2798 req->flags |= REQ_F_REISSUE;
2803 WRITE_ONCE(req->result, res);
2804 /* order with io_iopoll_complete() checking ->result */
2806 WRITE_ONCE(req->iopoll_completed, 1);
2810 * After the iocb has been issued, it's safe to be found on the poll list.
2811 * Adding the kiocb to the list AFTER submission ensures that we don't
2812 * find it from a io_do_iopoll() thread before the issuer is done
2813 * accessing the kiocb cookie.
2815 static void io_iopoll_req_issued(struct io_kiocb *req)
2817 struct io_ring_ctx *ctx = req->ctx;
2818 const bool in_async = io_wq_current_is_worker();
2820 /* workqueue context doesn't hold uring_lock, grab it now */
2821 if (unlikely(in_async))
2822 mutex_lock(&ctx->uring_lock);
2825 * Track whether we have multiple files in our lists. This will impact
2826 * how we do polling eventually, not spinning if we're on potentially
2827 * different devices.
2829 if (list_empty(&ctx->iopoll_list)) {
2830 ctx->poll_multi_queue = false;
2831 } else if (!ctx->poll_multi_queue) {
2832 struct io_kiocb *list_req;
2833 unsigned int queue_num0, queue_num1;
2835 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2838 if (list_req->file != req->file) {
2839 ctx->poll_multi_queue = true;
2841 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2842 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2843 if (queue_num0 != queue_num1)
2844 ctx->poll_multi_queue = true;
2849 * For fast devices, IO may have already completed. If it has, add
2850 * it to the front so we find it first.
2852 if (READ_ONCE(req->iopoll_completed))
2853 list_add(&req->inflight_entry, &ctx->iopoll_list);
2855 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2857 if (unlikely(in_async)) {
2859 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2860 * in sq thread task context or in io worker task context. If
2861 * current task context is sq thread, we don't need to check
2862 * whether should wake up sq thread.
2864 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2865 wq_has_sleeper(&ctx->sq_data->wait))
2866 wake_up(&ctx->sq_data->wait);
2868 mutex_unlock(&ctx->uring_lock);
2872 static bool io_bdev_nowait(struct block_device *bdev)
2874 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2878 * If we tracked the file through the SCM inflight mechanism, we could support
2879 * any file. For now, just ensure that anything potentially problematic is done
2882 static bool __io_file_supports_nowait(struct file *file, int rw)
2884 umode_t mode = file_inode(file)->i_mode;
2886 if (S_ISBLK(mode)) {
2887 if (IS_ENABLED(CONFIG_BLOCK) &&
2888 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2894 if (S_ISREG(mode)) {
2895 if (IS_ENABLED(CONFIG_BLOCK) &&
2896 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2897 file->f_op != &io_uring_fops)
2902 /* any ->read/write should understand O_NONBLOCK */
2903 if (file->f_flags & O_NONBLOCK)
2906 if (!(file->f_mode & FMODE_NOWAIT))
2910 return file->f_op->read_iter != NULL;
2912 return file->f_op->write_iter != NULL;
2915 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2917 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2919 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2922 return __io_file_supports_nowait(req->file, rw);
2925 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2928 struct io_ring_ctx *ctx = req->ctx;
2929 struct kiocb *kiocb = &req->rw.kiocb;
2930 struct file *file = req->file;
2934 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2935 req->flags |= REQ_F_ISREG;
2937 kiocb->ki_pos = READ_ONCE(sqe->off);
2938 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2939 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2940 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2945 * If the file is marked O_NONBLOCK, still allow retry for it if it
2946 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2947 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2949 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2950 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req, rw)))
2951 req->flags |= REQ_F_NOWAIT;
2953 ioprio = READ_ONCE(sqe->ioprio);
2955 ret = ioprio_check_cap(ioprio);
2959 kiocb->ki_ioprio = ioprio;
2961 kiocb->ki_ioprio = get_current_ioprio();
2963 if (ctx->flags & IORING_SETUP_IOPOLL) {
2964 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2965 !kiocb->ki_filp->f_op->iopoll)
2968 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2969 kiocb->ki_complete = io_complete_rw_iopoll;
2970 req->iopoll_completed = 0;
2972 if (kiocb->ki_flags & IOCB_HIPRI)
2974 kiocb->ki_complete = io_complete_rw;
2977 /* used for fixed read/write too - just read unconditionally */
2978 req->buf_index = READ_ONCE(sqe->buf_index);
2981 if (req->opcode == IORING_OP_READ_FIXED ||
2982 req->opcode == IORING_OP_WRITE_FIXED) {
2983 struct io_ring_ctx *ctx = req->ctx;
2986 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2988 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2989 req->imu = ctx->user_bufs[index];
2990 io_req_set_rsrc_node(req);
2993 req->rw.addr = READ_ONCE(sqe->addr);
2994 req->rw.len = READ_ONCE(sqe->len);
2998 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3004 case -ERESTARTNOINTR:
3005 case -ERESTARTNOHAND:
3006 case -ERESTART_RESTARTBLOCK:
3008 * We can't just restart the syscall, since previously
3009 * submitted sqes may already be in progress. Just fail this
3015 kiocb->ki_complete(kiocb, ret, 0);
3019 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3021 struct kiocb *kiocb = &req->rw.kiocb;
3023 if (kiocb->ki_pos != -1)
3024 return &kiocb->ki_pos;
3026 if (!(req->file->f_mode & FMODE_STREAM)) {
3027 req->flags |= REQ_F_CUR_POS;
3028 kiocb->ki_pos = req->file->f_pos;
3029 return &kiocb->ki_pos;
3036 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
3037 unsigned int issue_flags)
3039 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3041 if (req->flags & REQ_F_CUR_POS)
3042 req->file->f_pos = kiocb->ki_pos;
3043 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw)) {
3044 if (!__io_complete_rw_common(req, ret)) {
3046 * Safe to call io_end from here as we're inline
3047 * from the submission path.
3050 __io_req_complete(req, issue_flags,
3051 io_fixup_rw_res(req, ret),
3052 io_put_rw_kbuf(req));
3055 io_rw_done(kiocb, ret);
3058 if (req->flags & REQ_F_REISSUE) {
3059 req->flags &= ~REQ_F_REISSUE;
3060 if (io_resubmit_prep(req)) {
3061 io_req_task_queue_reissue(req);
3063 unsigned int cflags = io_put_rw_kbuf(req);
3064 struct io_ring_ctx *ctx = req->ctx;
3066 ret = io_fixup_rw_res(req, ret);
3068 if (!(issue_flags & IO_URING_F_NONBLOCK)) {
3069 mutex_lock(&ctx->uring_lock);
3070 __io_req_complete(req, issue_flags, ret, cflags);
3071 mutex_unlock(&ctx->uring_lock);
3073 __io_req_complete(req, issue_flags, ret, cflags);
3079 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3080 struct io_mapped_ubuf *imu)
3082 size_t len = req->rw.len;
3083 u64 buf_end, buf_addr = req->rw.addr;
3086 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3088 /* not inside the mapped region */
3089 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3093 * May not be a start of buffer, set size appropriately
3094 * and advance us to the beginning.
3096 offset = buf_addr - imu->ubuf;
3097 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3101 * Don't use iov_iter_advance() here, as it's really slow for
3102 * using the latter parts of a big fixed buffer - it iterates
3103 * over each segment manually. We can cheat a bit here, because
3106 * 1) it's a BVEC iter, we set it up
3107 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3108 * first and last bvec
3110 * So just find our index, and adjust the iterator afterwards.
3111 * If the offset is within the first bvec (or the whole first
3112 * bvec, just use iov_iter_advance(). This makes it easier
3113 * since we can just skip the first segment, which may not
3114 * be PAGE_SIZE aligned.
3116 const struct bio_vec *bvec = imu->bvec;
3118 if (offset <= bvec->bv_len) {
3119 iov_iter_advance(iter, offset);
3121 unsigned long seg_skip;
3123 /* skip first vec */
3124 offset -= bvec->bv_len;
3125 seg_skip = 1 + (offset >> PAGE_SHIFT);
3127 iter->bvec = bvec + seg_skip;
3128 iter->nr_segs -= seg_skip;
3129 iter->count -= bvec->bv_len + offset;
3130 iter->iov_offset = offset & ~PAGE_MASK;
3137 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3139 if (WARN_ON_ONCE(!req->imu))
3141 return __io_import_fixed(req, rw, iter, req->imu);
3144 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3147 mutex_unlock(&ctx->uring_lock);
3150 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3153 * "Normal" inline submissions always hold the uring_lock, since we
3154 * grab it from the system call. Same is true for the SQPOLL offload.
3155 * The only exception is when we've detached the request and issue it
3156 * from an async worker thread, grab the lock for that case.
3159 mutex_lock(&ctx->uring_lock);
3162 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3163 int bgid, struct io_buffer *kbuf,
3166 struct io_buffer *head;
3168 if (req->flags & REQ_F_BUFFER_SELECTED)
3171 io_ring_submit_lock(req->ctx, needs_lock);
3173 lockdep_assert_held(&req->ctx->uring_lock);
3175 head = xa_load(&req->ctx->io_buffers, bgid);
3177 if (!list_empty(&head->list)) {
3178 kbuf = list_last_entry(&head->list, struct io_buffer,
3180 list_del(&kbuf->list);
3183 xa_erase(&req->ctx->io_buffers, bgid);
3185 if (*len > kbuf->len)
3188 kbuf = ERR_PTR(-ENOBUFS);
3191 io_ring_submit_unlock(req->ctx, needs_lock);
3196 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3199 struct io_buffer *kbuf;
3202 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3203 bgid = req->buf_index;
3204 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3207 req->rw.addr = (u64) (unsigned long) kbuf;
3208 req->flags |= REQ_F_BUFFER_SELECTED;
3209 return u64_to_user_ptr(kbuf->addr);
3212 #ifdef CONFIG_COMPAT
3213 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3216 struct compat_iovec __user *uiov;
3217 compat_ssize_t clen;
3221 uiov = u64_to_user_ptr(req->rw.addr);
3222 if (!access_ok(uiov, sizeof(*uiov)))
3224 if (__get_user(clen, &uiov->iov_len))
3230 buf = io_rw_buffer_select(req, &len, needs_lock);
3232 return PTR_ERR(buf);
3233 iov[0].iov_base = buf;
3234 iov[0].iov_len = (compat_size_t) len;
3239 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3242 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3246 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3249 len = iov[0].iov_len;
3252 buf = io_rw_buffer_select(req, &len, needs_lock);
3254 return PTR_ERR(buf);
3255 iov[0].iov_base = buf;
3256 iov[0].iov_len = len;
3260 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3263 if (req->flags & REQ_F_BUFFER_SELECTED) {
3264 struct io_buffer *kbuf;
3266 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3267 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3268 iov[0].iov_len = kbuf->len;
3271 if (req->rw.len != 1)
3274 #ifdef CONFIG_COMPAT
3275 if (req->ctx->compat)
3276 return io_compat_import(req, iov, needs_lock);
3279 return __io_iov_buffer_select(req, iov, needs_lock);
3282 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3283 struct iov_iter *iter, bool needs_lock)
3285 void __user *buf = u64_to_user_ptr(req->rw.addr);
3286 size_t sqe_len = req->rw.len;
3287 u8 opcode = req->opcode;
3290 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3292 return io_import_fixed(req, rw, iter);
3295 /* buffer index only valid with fixed read/write, or buffer select */
3296 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3299 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3300 if (req->flags & REQ_F_BUFFER_SELECT) {
3301 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3303 return PTR_ERR(buf);
3304 req->rw.len = sqe_len;
3307 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3312 if (req->flags & REQ_F_BUFFER_SELECT) {
3313 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3315 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3320 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3324 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3326 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3330 * For files that don't have ->read_iter() and ->write_iter(), handle them
3331 * by looping over ->read() or ->write() manually.
3333 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3335 struct kiocb *kiocb = &req->rw.kiocb;
3336 struct file *file = req->file;
3341 * Don't support polled IO through this interface, and we can't
3342 * support non-blocking either. For the latter, this just causes
3343 * the kiocb to be handled from an async context.
3345 if (kiocb->ki_flags & IOCB_HIPRI)
3347 if (kiocb->ki_flags & IOCB_NOWAIT)
3350 ppos = io_kiocb_ppos(kiocb);
3352 while (iov_iter_count(iter)) {
3356 if (!iov_iter_is_bvec(iter)) {
3357 iovec = iov_iter_iovec(iter);
3359 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3360 iovec.iov_len = req->rw.len;
3364 nr = file->f_op->read(file, iovec.iov_base,
3365 iovec.iov_len, ppos);
3367 nr = file->f_op->write(file, iovec.iov_base,
3368 iovec.iov_len, ppos);
3377 if (!iov_iter_is_bvec(iter)) {
3378 iov_iter_advance(iter, nr);
3385 if (nr != iovec.iov_len)
3392 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3393 const struct iovec *fast_iov, struct iov_iter *iter)
3395 struct io_async_rw *rw = req->async_data;
3397 memcpy(&rw->iter, iter, sizeof(*iter));
3398 rw->free_iovec = iovec;
3400 /* can only be fixed buffers, no need to do anything */
3401 if (iov_iter_is_bvec(iter))
3404 unsigned iov_off = 0;
3406 rw->iter.iov = rw->fast_iov;
3407 if (iter->iov != fast_iov) {
3408 iov_off = iter->iov - fast_iov;
3409 rw->iter.iov += iov_off;
3411 if (rw->fast_iov != fast_iov)
3412 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3413 sizeof(struct iovec) * iter->nr_segs);
3415 req->flags |= REQ_F_NEED_CLEANUP;
3419 static inline int io_alloc_async_data(struct io_kiocb *req)
3421 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3422 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3423 return req->async_data == NULL;
3426 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3427 const struct iovec *fast_iov,
3428 struct iov_iter *iter, bool force)
3430 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3432 if (!req->async_data) {
3433 struct io_async_rw *iorw;
3435 if (io_alloc_async_data(req)) {
3440 io_req_map_rw(req, iovec, fast_iov, iter);
3441 iorw = req->async_data;
3442 /* we've copied and mapped the iter, ensure state is saved */
3443 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3448 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3450 struct io_async_rw *iorw = req->async_data;
3451 struct iovec *iov = iorw->fast_iov;
3454 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3455 if (unlikely(ret < 0))
3458 iorw->bytes_done = 0;
3459 iorw->free_iovec = iov;
3461 req->flags |= REQ_F_NEED_CLEANUP;
3462 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3466 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3468 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3470 return io_prep_rw(req, sqe, READ);
3474 * This is our waitqueue callback handler, registered through lock_page_async()
3475 * when we initially tried to do the IO with the iocb armed our waitqueue.
3476 * This gets called when the page is unlocked, and we generally expect that to
3477 * happen when the page IO is completed and the page is now uptodate. This will
3478 * queue a task_work based retry of the operation, attempting to copy the data
3479 * again. If the latter fails because the page was NOT uptodate, then we will
3480 * do a thread based blocking retry of the operation. That's the unexpected
3483 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3484 int sync, void *arg)
3486 struct wait_page_queue *wpq;
3487 struct io_kiocb *req = wait->private;
3488 struct wait_page_key *key = arg;
3490 wpq = container_of(wait, struct wait_page_queue, wait);
3492 if (!wake_page_match(wpq, key))
3495 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3496 list_del_init(&wait->entry);
3497 io_req_task_queue(req);
3502 * This controls whether a given IO request should be armed for async page
3503 * based retry. If we return false here, the request is handed to the async
3504 * worker threads for retry. If we're doing buffered reads on a regular file,
3505 * we prepare a private wait_page_queue entry and retry the operation. This
3506 * will either succeed because the page is now uptodate and unlocked, or it
3507 * will register a callback when the page is unlocked at IO completion. Through
3508 * that callback, io_uring uses task_work to setup a retry of the operation.
3509 * That retry will attempt the buffered read again. The retry will generally
3510 * succeed, or in rare cases where it fails, we then fall back to using the
3511 * async worker threads for a blocking retry.
3513 static bool io_rw_should_retry(struct io_kiocb *req)
3515 struct io_async_rw *rw = req->async_data;
3516 struct wait_page_queue *wait = &rw->wpq;
3517 struct kiocb *kiocb = &req->rw.kiocb;
3519 /* never retry for NOWAIT, we just complete with -EAGAIN */
3520 if (req->flags & REQ_F_NOWAIT)
3523 /* Only for buffered IO */
3524 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3528 * just use poll if we can, and don't attempt if the fs doesn't
3529 * support callback based unlocks
3531 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3534 wait->wait.func = io_async_buf_func;
3535 wait->wait.private = req;
3536 wait->wait.flags = 0;
3537 INIT_LIST_HEAD(&wait->wait.entry);
3538 kiocb->ki_flags |= IOCB_WAITQ;
3539 kiocb->ki_flags &= ~IOCB_NOWAIT;
3540 kiocb->ki_waitq = wait;
3544 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3546 if (req->file->f_op->read_iter)
3547 return call_read_iter(req->file, &req->rw.kiocb, iter);
3548 else if (req->file->f_op->read)
3549 return loop_rw_iter(READ, req, iter);
3554 static bool need_read_all(struct io_kiocb *req)
3556 return req->flags & REQ_F_ISREG ||
3557 S_ISBLK(file_inode(req->file)->i_mode);
3560 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3562 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3563 struct kiocb *kiocb = &req->rw.kiocb;
3564 struct iov_iter __iter, *iter = &__iter;
3565 struct io_async_rw *rw = req->async_data;
3566 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3567 struct iov_iter_state __state, *state;
3573 state = &rw->iter_state;
3575 * We come here from an earlier attempt, restore our state to
3576 * match in case it doesn't. It's cheap enough that we don't
3577 * need to make this conditional.
3579 iov_iter_restore(iter, state);
3582 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3586 iov_iter_save_state(iter, state);
3588 req->result = iov_iter_count(iter);
3590 /* Ensure we clear previously set non-block flag */
3591 if (!force_nonblock)
3592 kiocb->ki_flags &= ~IOCB_NOWAIT;
3594 kiocb->ki_flags |= IOCB_NOWAIT;
3596 /* If the file doesn't support async, just async punt */
3597 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3598 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3599 return ret ?: -EAGAIN;
3602 ppos = io_kiocb_update_pos(req);
3604 ret = rw_verify_area(READ, req->file, ppos, req->result);
3605 if (unlikely(ret)) {
3610 ret = io_iter_do_read(req, iter);
3612 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3613 req->flags &= ~REQ_F_REISSUE;
3614 /* IOPOLL retry should happen for io-wq threads */
3615 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3617 /* no retry on NONBLOCK nor RWF_NOWAIT */
3618 if (req->flags & REQ_F_NOWAIT)
3621 } else if (ret == -EIOCBQUEUED) {
3623 } else if (ret <= 0 || ret == req->result || !force_nonblock ||
3624 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3625 /* read all, failed, already did sync or don't want to retry */
3630 * Don't depend on the iter state matching what was consumed, or being
3631 * untouched in case of error. Restore it and we'll advance it
3632 * manually if we need to.
3634 iov_iter_restore(iter, state);
3636 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3641 rw = req->async_data;
3643 * Now use our persistent iterator and state, if we aren't already.
3644 * We've restored and mapped the iter to match.
3646 if (iter != &rw->iter) {
3648 state = &rw->iter_state;
3653 * We end up here because of a partial read, either from
3654 * above or inside this loop. Advance the iter by the bytes
3655 * that were consumed.
3657 iov_iter_advance(iter, ret);
3658 if (!iov_iter_count(iter))
3660 rw->bytes_done += ret;
3661 iov_iter_save_state(iter, state);
3663 /* if we can retry, do so with the callbacks armed */
3664 if (!io_rw_should_retry(req)) {
3665 kiocb->ki_flags &= ~IOCB_WAITQ;
3669 req->result = iov_iter_count(iter);
3671 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3672 * we get -EIOCBQUEUED, then we'll get a notification when the
3673 * desired page gets unlocked. We can also get a partial read
3674 * here, and if we do, then just retry at the new offset.
3676 ret = io_iter_do_read(req, iter);
3677 if (ret == -EIOCBQUEUED)
3679 /* we got some bytes, but not all. retry. */
3680 kiocb->ki_flags &= ~IOCB_WAITQ;
3681 iov_iter_restore(iter, state);
3684 kiocb_done(kiocb, ret, issue_flags);
3686 /* it's faster to check here then delegate to kfree */
3692 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3694 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3696 return io_prep_rw(req, sqe, WRITE);
3699 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3701 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3702 struct kiocb *kiocb = &req->rw.kiocb;
3703 struct iov_iter __iter, *iter = &__iter;
3704 struct io_async_rw *rw = req->async_data;
3705 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3706 struct iov_iter_state __state, *state;
3712 state = &rw->iter_state;
3713 iov_iter_restore(iter, state);
3716 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3720 iov_iter_save_state(iter, state);
3722 req->result = iov_iter_count(iter);
3724 /* Ensure we clear previously set non-block flag */
3725 if (!force_nonblock)
3726 kiocb->ki_flags &= ~IOCB_NOWAIT;
3728 kiocb->ki_flags |= IOCB_NOWAIT;
3730 /* If the file doesn't support async, just async punt */
3731 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3734 /* file path doesn't support NOWAIT for non-direct_IO */
3735 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3736 (req->flags & REQ_F_ISREG))
3739 ppos = io_kiocb_update_pos(req);
3741 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3746 * Open-code file_start_write here to grab freeze protection,
3747 * which will be released by another thread in
3748 * io_complete_rw(). Fool lockdep by telling it the lock got
3749 * released so that it doesn't complain about the held lock when
3750 * we return to userspace.
3752 if (req->flags & REQ_F_ISREG) {
3753 sb_start_write(file_inode(req->file)->i_sb);
3754 __sb_writers_release(file_inode(req->file)->i_sb,
3757 kiocb->ki_flags |= IOCB_WRITE;
3759 if (req->file->f_op->write_iter)
3760 ret2 = call_write_iter(req->file, kiocb, iter);
3761 else if (req->file->f_op->write)
3762 ret2 = loop_rw_iter(WRITE, req, iter);
3766 if (req->flags & REQ_F_REISSUE) {
3767 req->flags &= ~REQ_F_REISSUE;
3772 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3773 * retry them without IOCB_NOWAIT.
3775 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3777 /* no retry on NONBLOCK nor RWF_NOWAIT */
3778 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3780 if (!force_nonblock || ret2 != -EAGAIN) {
3781 /* IOPOLL retry should happen for io-wq threads */
3782 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3785 kiocb_done(kiocb, ret2, issue_flags);
3788 iov_iter_restore(iter, state);
3789 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3791 if (kiocb->ki_flags & IOCB_WRITE)
3792 kiocb_end_write(req);
3798 /* it's reportedly faster than delegating the null check to kfree() */
3804 static int io_renameat_prep(struct io_kiocb *req,
3805 const struct io_uring_sqe *sqe)
3807 struct io_rename *ren = &req->rename;
3808 const char __user *oldf, *newf;
3810 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3812 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3814 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3817 ren->old_dfd = READ_ONCE(sqe->fd);
3818 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3819 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3820 ren->new_dfd = READ_ONCE(sqe->len);
3821 ren->flags = READ_ONCE(sqe->rename_flags);
3823 ren->oldpath = getname(oldf);
3824 if (IS_ERR(ren->oldpath))
3825 return PTR_ERR(ren->oldpath);
3827 ren->newpath = getname(newf);
3828 if (IS_ERR(ren->newpath)) {
3829 putname(ren->oldpath);
3830 return PTR_ERR(ren->newpath);
3833 req->flags |= REQ_F_NEED_CLEANUP;
3837 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3839 struct io_rename *ren = &req->rename;
3842 if (issue_flags & IO_URING_F_NONBLOCK)
3845 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3846 ren->newpath, ren->flags);
3848 req->flags &= ~REQ_F_NEED_CLEANUP;
3851 io_req_complete(req, ret);
3855 static int io_unlinkat_prep(struct io_kiocb *req,
3856 const struct io_uring_sqe *sqe)
3858 struct io_unlink *un = &req->unlink;
3859 const char __user *fname;
3861 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3863 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3866 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3869 un->dfd = READ_ONCE(sqe->fd);
3871 un->flags = READ_ONCE(sqe->unlink_flags);
3872 if (un->flags & ~AT_REMOVEDIR)
3875 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3876 un->filename = getname(fname);
3877 if (IS_ERR(un->filename))
3878 return PTR_ERR(un->filename);
3880 req->flags |= REQ_F_NEED_CLEANUP;
3884 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3886 struct io_unlink *un = &req->unlink;
3889 if (issue_flags & IO_URING_F_NONBLOCK)
3892 if (un->flags & AT_REMOVEDIR)
3893 ret = do_rmdir(un->dfd, un->filename);
3895 ret = do_unlinkat(un->dfd, un->filename);
3897 req->flags &= ~REQ_F_NEED_CLEANUP;
3900 io_req_complete(req, ret);
3904 static int io_mkdirat_prep(struct io_kiocb *req,
3905 const struct io_uring_sqe *sqe)
3907 struct io_mkdir *mkd = &req->mkdir;
3908 const char __user *fname;
3910 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3912 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3915 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3918 mkd->dfd = READ_ONCE(sqe->fd);
3919 mkd->mode = READ_ONCE(sqe->len);
3921 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3922 mkd->filename = getname(fname);
3923 if (IS_ERR(mkd->filename))
3924 return PTR_ERR(mkd->filename);
3926 req->flags |= REQ_F_NEED_CLEANUP;
3930 static int io_mkdirat(struct io_kiocb *req, int issue_flags)
3932 struct io_mkdir *mkd = &req->mkdir;
3935 if (issue_flags & IO_URING_F_NONBLOCK)
3938 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3940 req->flags &= ~REQ_F_NEED_CLEANUP;
3943 io_req_complete(req, ret);
3947 static int io_symlinkat_prep(struct io_kiocb *req,
3948 const struct io_uring_sqe *sqe)
3950 struct io_symlink *sl = &req->symlink;
3951 const char __user *oldpath, *newpath;
3953 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3955 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3958 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3961 sl->new_dfd = READ_ONCE(sqe->fd);
3962 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3963 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3965 sl->oldpath = getname(oldpath);
3966 if (IS_ERR(sl->oldpath))
3967 return PTR_ERR(sl->oldpath);
3969 sl->newpath = getname(newpath);
3970 if (IS_ERR(sl->newpath)) {
3971 putname(sl->oldpath);
3972 return PTR_ERR(sl->newpath);
3975 req->flags |= REQ_F_NEED_CLEANUP;
3979 static int io_symlinkat(struct io_kiocb *req, int issue_flags)
3981 struct io_symlink *sl = &req->symlink;
3984 if (issue_flags & IO_URING_F_NONBLOCK)
3987 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
3989 req->flags &= ~REQ_F_NEED_CLEANUP;
3992 io_req_complete(req, ret);
3996 static int io_linkat_prep(struct io_kiocb *req,
3997 const struct io_uring_sqe *sqe)
3999 struct io_hardlink *lnk = &req->hardlink;
4000 const char __user *oldf, *newf;
4002 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4004 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4006 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4009 lnk->old_dfd = READ_ONCE(sqe->fd);
4010 lnk->new_dfd = READ_ONCE(sqe->len);
4011 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4012 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4013 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4015 lnk->oldpath = getname(oldf);
4016 if (IS_ERR(lnk->oldpath))
4017 return PTR_ERR(lnk->oldpath);
4019 lnk->newpath = getname(newf);
4020 if (IS_ERR(lnk->newpath)) {
4021 putname(lnk->oldpath);
4022 return PTR_ERR(lnk->newpath);
4025 req->flags |= REQ_F_NEED_CLEANUP;
4029 static int io_linkat(struct io_kiocb *req, int issue_flags)
4031 struct io_hardlink *lnk = &req->hardlink;
4034 if (issue_flags & IO_URING_F_NONBLOCK)
4037 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4038 lnk->newpath, lnk->flags);
4040 req->flags &= ~REQ_F_NEED_CLEANUP;
4043 io_req_complete(req, ret);
4047 static int io_shutdown_prep(struct io_kiocb *req,
4048 const struct io_uring_sqe *sqe)
4050 #if defined(CONFIG_NET)
4051 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4053 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4054 sqe->buf_index || sqe->splice_fd_in))
4057 req->shutdown.how = READ_ONCE(sqe->len);
4064 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4066 #if defined(CONFIG_NET)
4067 struct socket *sock;
4070 if (issue_flags & IO_URING_F_NONBLOCK)
4073 sock = sock_from_file(req->file);
4074 if (unlikely(!sock))
4077 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4080 io_req_complete(req, ret);
4087 static int __io_splice_prep(struct io_kiocb *req,
4088 const struct io_uring_sqe *sqe)
4090 struct io_splice *sp = &req->splice;
4091 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4093 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4096 sp->len = READ_ONCE(sqe->len);
4097 sp->flags = READ_ONCE(sqe->splice_flags);
4098 if (unlikely(sp->flags & ~valid_flags))
4100 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4104 static int io_tee_prep(struct io_kiocb *req,
4105 const struct io_uring_sqe *sqe)
4107 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4109 return __io_splice_prep(req, sqe);
4112 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4114 struct io_splice *sp = &req->splice;
4115 struct file *out = sp->file_out;
4116 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4120 if (issue_flags & IO_URING_F_NONBLOCK)
4123 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4124 (sp->flags & SPLICE_F_FD_IN_FIXED));
4131 ret = do_tee(in, out, sp->len, flags);
4133 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4138 io_req_complete(req, ret);
4142 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4144 struct io_splice *sp = &req->splice;
4146 sp->off_in = READ_ONCE(sqe->splice_off_in);
4147 sp->off_out = READ_ONCE(sqe->off);
4148 return __io_splice_prep(req, sqe);
4151 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4153 struct io_splice *sp = &req->splice;
4154 struct file *out = sp->file_out;
4155 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4156 loff_t *poff_in, *poff_out;
4160 if (issue_flags & IO_URING_F_NONBLOCK)
4163 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4164 (sp->flags & SPLICE_F_FD_IN_FIXED));
4170 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4171 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4174 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4176 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4181 io_req_complete(req, ret);
4186 * IORING_OP_NOP just posts a completion event, nothing else.
4188 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4190 struct io_ring_ctx *ctx = req->ctx;
4192 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4195 __io_req_complete(req, issue_flags, 0, 0);
4199 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4201 struct io_ring_ctx *ctx = req->ctx;
4203 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4205 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4209 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4210 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4213 req->sync.off = READ_ONCE(sqe->off);
4214 req->sync.len = READ_ONCE(sqe->len);
4218 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4220 loff_t end = req->sync.off + req->sync.len;
4223 /* fsync always requires a blocking context */
4224 if (issue_flags & IO_URING_F_NONBLOCK)
4227 ret = vfs_fsync_range(req->file, req->sync.off,
4228 end > 0 ? end : LLONG_MAX,
4229 req->sync.flags & IORING_FSYNC_DATASYNC);
4232 io_req_complete(req, ret);
4236 static int io_fallocate_prep(struct io_kiocb *req,
4237 const struct io_uring_sqe *sqe)
4239 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4242 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4245 req->sync.off = READ_ONCE(sqe->off);
4246 req->sync.len = READ_ONCE(sqe->addr);
4247 req->sync.mode = READ_ONCE(sqe->len);
4251 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4255 /* fallocate always requiring blocking context */
4256 if (issue_flags & IO_URING_F_NONBLOCK)
4258 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4263 fsnotify_modify(req->file);
4264 io_req_complete(req, ret);
4268 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4270 const char __user *fname;
4273 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4275 if (unlikely(sqe->ioprio || sqe->buf_index))
4277 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4280 /* open.how should be already initialised */
4281 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4282 req->open.how.flags |= O_LARGEFILE;
4284 req->open.dfd = READ_ONCE(sqe->fd);
4285 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4286 req->open.filename = getname(fname);
4287 if (IS_ERR(req->open.filename)) {
4288 ret = PTR_ERR(req->open.filename);
4289 req->open.filename = NULL;
4293 req->open.file_slot = READ_ONCE(sqe->file_index);
4294 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4297 req->open.nofile = rlimit(RLIMIT_NOFILE);
4298 req->flags |= REQ_F_NEED_CLEANUP;
4302 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4304 u64 mode = READ_ONCE(sqe->len);
4305 u64 flags = READ_ONCE(sqe->open_flags);
4307 req->open.how = build_open_how(flags, mode);
4308 return __io_openat_prep(req, sqe);
4311 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4313 struct open_how __user *how;
4317 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4318 len = READ_ONCE(sqe->len);
4319 if (len < OPEN_HOW_SIZE_VER0)
4322 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4327 return __io_openat_prep(req, sqe);
4330 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4332 struct open_flags op;
4334 bool resolve_nonblock, nonblock_set;
4335 bool fixed = !!req->open.file_slot;
4338 ret = build_open_flags(&req->open.how, &op);
4341 nonblock_set = op.open_flag & O_NONBLOCK;
4342 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4343 if (issue_flags & IO_URING_F_NONBLOCK) {
4345 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4346 * it'll always -EAGAIN
4348 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4350 op.lookup_flags |= LOOKUP_CACHED;
4351 op.open_flag |= O_NONBLOCK;
4355 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4360 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4363 * We could hang on to this 'fd' on retrying, but seems like
4364 * marginal gain for something that is now known to be a slower
4365 * path. So just put it, and we'll get a new one when we retry.
4370 ret = PTR_ERR(file);
4371 /* only retry if RESOLVE_CACHED wasn't already set by application */
4372 if (ret == -EAGAIN &&
4373 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4378 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4379 file->f_flags &= ~O_NONBLOCK;
4380 fsnotify_open(file);
4383 fd_install(ret, file);
4385 ret = io_install_fixed_file(req, file, issue_flags,
4386 req->open.file_slot - 1);
4388 putname(req->open.filename);
4389 req->flags &= ~REQ_F_NEED_CLEANUP;
4392 __io_req_complete(req, issue_flags, ret, 0);
4396 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4398 return io_openat2(req, issue_flags);
4401 static int io_remove_buffers_prep(struct io_kiocb *req,
4402 const struct io_uring_sqe *sqe)
4404 struct io_provide_buf *p = &req->pbuf;
4407 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4411 tmp = READ_ONCE(sqe->fd);
4412 if (!tmp || tmp > USHRT_MAX)
4415 memset(p, 0, sizeof(*p));
4417 p->bgid = READ_ONCE(sqe->buf_group);
4421 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4422 int bgid, unsigned nbufs)
4426 /* shouldn't happen */
4430 /* the head kbuf is the list itself */
4431 while (!list_empty(&buf->list)) {
4432 struct io_buffer *nxt;
4434 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4435 list_del(&nxt->list);
4443 xa_erase(&ctx->io_buffers, bgid);
4448 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4450 struct io_provide_buf *p = &req->pbuf;
4451 struct io_ring_ctx *ctx = req->ctx;
4452 struct io_buffer *head;
4454 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4456 io_ring_submit_lock(ctx, !force_nonblock);
4458 lockdep_assert_held(&ctx->uring_lock);
4461 head = xa_load(&ctx->io_buffers, p->bgid);
4463 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4467 /* complete before unlock, IOPOLL may need the lock */
4468 __io_req_complete(req, issue_flags, ret, 0);
4469 io_ring_submit_unlock(ctx, !force_nonblock);
4473 static int io_provide_buffers_prep(struct io_kiocb *req,
4474 const struct io_uring_sqe *sqe)
4476 unsigned long size, tmp_check;
4477 struct io_provide_buf *p = &req->pbuf;
4480 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4483 tmp = READ_ONCE(sqe->fd);
4484 if (!tmp || tmp > USHRT_MAX)
4487 p->addr = READ_ONCE(sqe->addr);
4488 p->len = READ_ONCE(sqe->len);
4490 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4493 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4496 size = (unsigned long)p->len * p->nbufs;
4497 if (!access_ok(u64_to_user_ptr(p->addr), size))
4500 p->bgid = READ_ONCE(sqe->buf_group);
4501 tmp = READ_ONCE(sqe->off);
4502 if (tmp > USHRT_MAX)
4508 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4510 struct io_buffer *buf;
4511 u64 addr = pbuf->addr;
4512 int i, bid = pbuf->bid;
4514 for (i = 0; i < pbuf->nbufs; i++) {
4515 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4520 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4525 INIT_LIST_HEAD(&buf->list);
4528 list_add_tail(&buf->list, &(*head)->list);
4533 return i ? i : -ENOMEM;
4536 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4538 struct io_provide_buf *p = &req->pbuf;
4539 struct io_ring_ctx *ctx = req->ctx;
4540 struct io_buffer *head, *list;
4542 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4544 io_ring_submit_lock(ctx, !force_nonblock);
4546 lockdep_assert_held(&ctx->uring_lock);
4548 list = head = xa_load(&ctx->io_buffers, p->bgid);
4550 ret = io_add_buffers(p, &head);
4551 if (ret >= 0 && !list) {
4552 ret = xa_insert(&ctx->io_buffers, p->bgid, head,
4553 GFP_KERNEL_ACCOUNT);
4555 __io_remove_buffers(ctx, head, p->bgid, -1U);
4559 /* complete before unlock, IOPOLL may need the lock */
4560 __io_req_complete(req, issue_flags, ret, 0);
4561 io_ring_submit_unlock(ctx, !force_nonblock);
4565 static int io_epoll_ctl_prep(struct io_kiocb *req,
4566 const struct io_uring_sqe *sqe)
4568 #if defined(CONFIG_EPOLL)
4569 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4571 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4574 req->epoll.epfd = READ_ONCE(sqe->fd);
4575 req->epoll.op = READ_ONCE(sqe->len);
4576 req->epoll.fd = READ_ONCE(sqe->off);
4578 if (ep_op_has_event(req->epoll.op)) {
4579 struct epoll_event __user *ev;
4581 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4582 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4592 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4594 #if defined(CONFIG_EPOLL)
4595 struct io_epoll *ie = &req->epoll;
4597 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4599 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4600 if (force_nonblock && ret == -EAGAIN)
4605 __io_req_complete(req, issue_flags, ret, 0);
4612 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4614 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4615 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4617 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4620 req->madvise.addr = READ_ONCE(sqe->addr);
4621 req->madvise.len = READ_ONCE(sqe->len);
4622 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4629 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4631 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4632 struct io_madvise *ma = &req->madvise;
4635 if (issue_flags & IO_URING_F_NONBLOCK)
4638 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4641 io_req_complete(req, ret);
4648 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4650 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4652 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4655 req->fadvise.offset = READ_ONCE(sqe->off);
4656 req->fadvise.len = READ_ONCE(sqe->len);
4657 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4661 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4663 struct io_fadvise *fa = &req->fadvise;
4666 if (issue_flags & IO_URING_F_NONBLOCK) {
4667 switch (fa->advice) {
4668 case POSIX_FADV_NORMAL:
4669 case POSIX_FADV_RANDOM:
4670 case POSIX_FADV_SEQUENTIAL:
4677 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4680 __io_req_complete(req, issue_flags, ret, 0);
4684 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4686 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4688 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4690 if (req->flags & REQ_F_FIXED_FILE)
4693 req->statx.dfd = READ_ONCE(sqe->fd);
4694 req->statx.mask = READ_ONCE(sqe->len);
4695 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4696 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4697 req->statx.flags = READ_ONCE(sqe->statx_flags);
4702 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4704 struct io_statx *ctx = &req->statx;
4707 if (issue_flags & IO_URING_F_NONBLOCK)
4710 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4715 io_req_complete(req, ret);
4719 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4721 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4723 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4724 sqe->rw_flags || sqe->buf_index)
4726 if (req->flags & REQ_F_FIXED_FILE)
4729 req->close.fd = READ_ONCE(sqe->fd);
4730 req->close.file_slot = READ_ONCE(sqe->file_index);
4731 if (req->close.file_slot && req->close.fd)
4737 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4739 struct files_struct *files = current->files;
4740 struct io_close *close = &req->close;
4741 struct fdtable *fdt;
4742 struct file *file = NULL;
4745 if (req->close.file_slot) {
4746 ret = io_close_fixed(req, issue_flags);
4750 spin_lock(&files->file_lock);
4751 fdt = files_fdtable(files);
4752 if (close->fd >= fdt->max_fds) {
4753 spin_unlock(&files->file_lock);
4756 file = fdt->fd[close->fd];
4757 if (!file || file->f_op == &io_uring_fops) {
4758 spin_unlock(&files->file_lock);
4763 /* if the file has a flush method, be safe and punt to async */
4764 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4765 spin_unlock(&files->file_lock);
4769 ret = __close_fd_get_file(close->fd, &file);
4770 spin_unlock(&files->file_lock);
4777 /* No ->flush() or already async, safely close from here */
4778 ret = filp_close(file, current->files);
4784 __io_req_complete(req, issue_flags, ret, 0);
4788 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4790 struct io_ring_ctx *ctx = req->ctx;
4792 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4794 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4798 req->sync.off = READ_ONCE(sqe->off);
4799 req->sync.len = READ_ONCE(sqe->len);
4800 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4804 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4808 /* sync_file_range always requires a blocking context */
4809 if (issue_flags & IO_URING_F_NONBLOCK)
4812 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4816 io_req_complete(req, ret);
4820 #if defined(CONFIG_NET)
4821 static bool io_net_retry(struct socket *sock, int flags)
4823 if (!(flags & MSG_WAITALL))
4825 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
4828 static int io_setup_async_msg(struct io_kiocb *req,
4829 struct io_async_msghdr *kmsg)
4831 struct io_async_msghdr *async_msg = req->async_data;
4835 if (io_alloc_async_data(req)) {
4836 kfree(kmsg->free_iov);
4839 async_msg = req->async_data;
4840 req->flags |= REQ_F_NEED_CLEANUP;
4841 memcpy(async_msg, kmsg, sizeof(*kmsg));
4842 if (async_msg->msg.msg_name)
4843 async_msg->msg.msg_name = &async_msg->addr;
4844 /* if were using fast_iov, set it to the new one */
4845 if (!kmsg->free_iov) {
4846 size_t fast_idx = kmsg->msg.msg_iter.iov - kmsg->fast_iov;
4847 async_msg->msg.msg_iter.iov = &async_msg->fast_iov[fast_idx];
4853 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4854 struct io_async_msghdr *iomsg)
4856 iomsg->msg.msg_name = &iomsg->addr;
4857 iomsg->free_iov = iomsg->fast_iov;
4858 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4859 req->sr_msg.msg_flags, &iomsg->free_iov);
4862 static int io_sendmsg_prep_async(struct io_kiocb *req)
4866 ret = io_sendmsg_copy_hdr(req, req->async_data);
4868 req->flags |= REQ_F_NEED_CLEANUP;
4872 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4874 struct io_sr_msg *sr = &req->sr_msg;
4876 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4878 if (unlikely(sqe->addr2 || sqe->file_index))
4880 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
4883 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4884 sr->len = READ_ONCE(sqe->len);
4885 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4886 if (sr->msg_flags & MSG_DONTWAIT)
4887 req->flags |= REQ_F_NOWAIT;
4889 #ifdef CONFIG_COMPAT
4890 if (req->ctx->compat)
4891 sr->msg_flags |= MSG_CMSG_COMPAT;
4897 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4899 struct io_async_msghdr iomsg, *kmsg;
4900 struct io_sr_msg *sr = &req->sr_msg;
4901 struct socket *sock;
4906 sock = sock_from_file(req->file);
4907 if (unlikely(!sock))
4910 kmsg = req->async_data;
4912 ret = io_sendmsg_copy_hdr(req, &iomsg);
4918 flags = req->sr_msg.msg_flags;
4919 if (issue_flags & IO_URING_F_NONBLOCK)
4920 flags |= MSG_DONTWAIT;
4921 if (flags & MSG_WAITALL)
4922 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4924 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4926 if (ret < min_ret) {
4927 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4928 return io_setup_async_msg(req, kmsg);
4929 if (ret == -ERESTARTSYS)
4931 if (ret > 0 && io_net_retry(sock, flags)) {
4933 req->flags |= REQ_F_PARTIAL_IO;
4934 return io_setup_async_msg(req, kmsg);
4938 /* fast path, check for non-NULL to avoid function call */
4940 kfree(kmsg->free_iov);
4941 req->flags &= ~REQ_F_NEED_CLEANUP;
4944 else if (sr->done_io)
4946 __io_req_complete(req, issue_flags, ret, 0);
4950 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4952 struct io_sr_msg *sr = &req->sr_msg;
4955 struct socket *sock;
4960 sock = sock_from_file(req->file);
4961 if (unlikely(!sock))
4964 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4968 msg.msg_name = NULL;
4969 msg.msg_control = NULL;
4970 msg.msg_controllen = 0;
4971 msg.msg_namelen = 0;
4973 flags = req->sr_msg.msg_flags;
4974 if (issue_flags & IO_URING_F_NONBLOCK)
4975 flags |= MSG_DONTWAIT;
4976 if (flags & MSG_WAITALL)
4977 min_ret = iov_iter_count(&msg.msg_iter);
4979 msg.msg_flags = flags;
4980 ret = sock_sendmsg(sock, &msg);
4981 if (ret < min_ret) {
4982 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4984 if (ret == -ERESTARTSYS)
4986 if (ret > 0 && io_net_retry(sock, flags)) {
4990 req->flags |= REQ_F_PARTIAL_IO;
4997 else if (sr->done_io)
4999 __io_req_complete(req, issue_flags, ret, 0);
5003 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5004 struct io_async_msghdr *iomsg)
5006 struct io_sr_msg *sr = &req->sr_msg;
5007 struct iovec __user *uiov;
5011 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5012 &iomsg->uaddr, &uiov, &iov_len);
5016 if (req->flags & REQ_F_BUFFER_SELECT) {
5019 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5021 sr->len = iomsg->fast_iov[0].iov_len;
5022 iomsg->free_iov = NULL;
5024 iomsg->free_iov = iomsg->fast_iov;
5025 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5026 &iomsg->free_iov, &iomsg->msg.msg_iter,
5035 #ifdef CONFIG_COMPAT
5036 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5037 struct io_async_msghdr *iomsg)
5039 struct io_sr_msg *sr = &req->sr_msg;
5040 struct compat_iovec __user *uiov;
5045 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5050 uiov = compat_ptr(ptr);
5051 if (req->flags & REQ_F_BUFFER_SELECT) {
5052 compat_ssize_t clen;
5056 if (!access_ok(uiov, sizeof(*uiov)))
5058 if (__get_user(clen, &uiov->iov_len))
5063 iomsg->free_iov = NULL;
5065 iomsg->free_iov = iomsg->fast_iov;
5066 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5067 UIO_FASTIOV, &iomsg->free_iov,
5068 &iomsg->msg.msg_iter, true);
5077 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5078 struct io_async_msghdr *iomsg)
5080 iomsg->msg.msg_name = &iomsg->addr;
5082 #ifdef CONFIG_COMPAT
5083 if (req->ctx->compat)
5084 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5087 return __io_recvmsg_copy_hdr(req, iomsg);
5090 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5093 struct io_sr_msg *sr = &req->sr_msg;
5094 struct io_buffer *kbuf;
5096 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
5101 req->flags |= REQ_F_BUFFER_SELECTED;
5105 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
5107 return io_put_kbuf(req, req->sr_msg.kbuf);
5110 static int io_recvmsg_prep_async(struct io_kiocb *req)
5114 ret = io_recvmsg_copy_hdr(req, req->async_data);
5116 req->flags |= REQ_F_NEED_CLEANUP;
5120 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5122 struct io_sr_msg *sr = &req->sr_msg;
5124 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5126 if (unlikely(sqe->addr2 || sqe->file_index))
5128 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
5131 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5132 sr->len = READ_ONCE(sqe->len);
5133 sr->bgid = READ_ONCE(sqe->buf_group);
5134 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5135 if (sr->msg_flags & MSG_DONTWAIT)
5136 req->flags |= REQ_F_NOWAIT;
5138 #ifdef CONFIG_COMPAT
5139 if (req->ctx->compat)
5140 sr->msg_flags |= MSG_CMSG_COMPAT;
5146 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5148 struct io_async_msghdr iomsg, *kmsg;
5149 struct io_sr_msg *sr = &req->sr_msg;
5150 struct socket *sock;
5151 struct io_buffer *kbuf;
5154 int ret, cflags = 0;
5155 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5157 sock = sock_from_file(req->file);
5158 if (unlikely(!sock))
5161 kmsg = req->async_data;
5163 ret = io_recvmsg_copy_hdr(req, &iomsg);
5169 if (req->flags & REQ_F_BUFFER_SELECT) {
5170 kbuf = io_recv_buffer_select(req, !force_nonblock);
5172 return PTR_ERR(kbuf);
5173 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5174 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5175 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5176 1, req->sr_msg.len);
5179 flags = req->sr_msg.msg_flags;
5181 flags |= MSG_DONTWAIT;
5182 if (flags & MSG_WAITALL)
5183 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5185 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5186 kmsg->uaddr, flags);
5187 if (ret < min_ret) {
5188 if (ret == -EAGAIN && force_nonblock)
5189 return io_setup_async_msg(req, kmsg);
5190 if (ret == -ERESTARTSYS)
5192 if (ret > 0 && io_net_retry(sock, flags)) {
5194 req->flags |= REQ_F_PARTIAL_IO;
5195 return io_setup_async_msg(req, kmsg);
5198 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5202 if (req->flags & REQ_F_BUFFER_SELECTED)
5203 cflags = io_put_recv_kbuf(req);
5204 /* fast path, check for non-NULL to avoid function call */
5206 kfree(kmsg->free_iov);
5207 req->flags &= ~REQ_F_NEED_CLEANUP;
5210 else if (sr->done_io)
5212 __io_req_complete(req, issue_flags, ret, cflags);
5216 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5218 struct io_buffer *kbuf;
5219 struct io_sr_msg *sr = &req->sr_msg;
5221 void __user *buf = sr->buf;
5222 struct socket *sock;
5226 int ret, cflags = 0;
5227 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5229 sock = sock_from_file(req->file);
5230 if (unlikely(!sock))
5233 if (req->flags & REQ_F_BUFFER_SELECT) {
5234 kbuf = io_recv_buffer_select(req, !force_nonblock);
5236 return PTR_ERR(kbuf);
5237 buf = u64_to_user_ptr(kbuf->addr);
5240 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5244 msg.msg_name = NULL;
5245 msg.msg_control = NULL;
5246 msg.msg_controllen = 0;
5247 msg.msg_namelen = 0;
5248 msg.msg_iocb = NULL;
5251 flags = req->sr_msg.msg_flags;
5253 flags |= MSG_DONTWAIT;
5254 if (flags & MSG_WAITALL)
5255 min_ret = iov_iter_count(&msg.msg_iter);
5257 ret = sock_recvmsg(sock, &msg, flags);
5258 if (ret < min_ret) {
5259 if (ret == -EAGAIN && force_nonblock)
5261 if (ret == -ERESTARTSYS)
5263 if (ret > 0 && io_net_retry(sock, flags)) {
5267 req->flags |= REQ_F_PARTIAL_IO;
5271 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5275 if (req->flags & REQ_F_BUFFER_SELECTED)
5276 cflags = io_put_recv_kbuf(req);
5279 else if (sr->done_io)
5281 __io_req_complete(req, issue_flags, ret, cflags);
5285 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5287 struct io_accept *accept = &req->accept;
5289 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5291 if (sqe->ioprio || sqe->len || sqe->buf_index)
5294 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5295 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5296 accept->flags = READ_ONCE(sqe->accept_flags);
5297 accept->nofile = rlimit(RLIMIT_NOFILE);
5299 accept->file_slot = READ_ONCE(sqe->file_index);
5300 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5302 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5304 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5305 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5309 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5311 struct io_accept *accept = &req->accept;
5312 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5313 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5314 bool fixed = !!accept->file_slot;
5319 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5320 if (unlikely(fd < 0))
5323 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5328 ret = PTR_ERR(file);
5330 req->flags |= REQ_F_PARTIAL_IO;
5331 if (ret == -EAGAIN && force_nonblock)
5333 if (ret == -ERESTARTSYS)
5336 } else if (!fixed) {
5337 fd_install(fd, file);
5340 ret = io_install_fixed_file(req, file, issue_flags,
5341 accept->file_slot - 1);
5343 __io_req_complete(req, issue_flags, ret, 0);
5347 static int io_connect_prep_async(struct io_kiocb *req)
5349 struct io_async_connect *io = req->async_data;
5350 struct io_connect *conn = &req->connect;
5352 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5355 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5357 struct io_connect *conn = &req->connect;
5359 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5361 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5365 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5366 conn->addr_len = READ_ONCE(sqe->addr2);
5370 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5372 struct io_async_connect __io, *io;
5373 unsigned file_flags;
5375 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5377 if (req->async_data) {
5378 io = req->async_data;
5380 ret = move_addr_to_kernel(req->connect.addr,
5381 req->connect.addr_len,
5388 file_flags = force_nonblock ? O_NONBLOCK : 0;
5390 ret = __sys_connect_file(req->file, &io->address,
5391 req->connect.addr_len, file_flags);
5392 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5393 if (req->async_data)
5395 if (io_alloc_async_data(req)) {
5399 memcpy(req->async_data, &__io, sizeof(__io));
5402 if (ret == -ERESTARTSYS)
5407 __io_req_complete(req, issue_flags, ret, 0);
5410 #else /* !CONFIG_NET */
5411 #define IO_NETOP_FN(op) \
5412 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5414 return -EOPNOTSUPP; \
5417 #define IO_NETOP_PREP(op) \
5419 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5421 return -EOPNOTSUPP; \
5424 #define IO_NETOP_PREP_ASYNC(op) \
5426 static int io_##op##_prep_async(struct io_kiocb *req) \
5428 return -EOPNOTSUPP; \
5431 IO_NETOP_PREP_ASYNC(sendmsg);
5432 IO_NETOP_PREP_ASYNC(recvmsg);
5433 IO_NETOP_PREP_ASYNC(connect);
5434 IO_NETOP_PREP(accept);
5437 #endif /* CONFIG_NET */
5439 struct io_poll_table {
5440 struct poll_table_struct pt;
5441 struct io_kiocb *req;
5446 #define IO_POLL_CANCEL_FLAG BIT(31)
5447 #define IO_POLL_RETRY_FLAG BIT(30)
5448 #define IO_POLL_REF_MASK GENMASK(29, 0)
5451 * We usually have 1-2 refs taken, 128 is more than enough and we want to
5452 * maximise the margin between this amount and the moment when it overflows.
5454 #define IO_POLL_REF_BIAS 128
5456 static bool io_poll_get_ownership_slowpath(struct io_kiocb *req)
5461 * poll_refs are already elevated and we don't have much hope for
5462 * grabbing the ownership. Instead of incrementing set a retry flag
5463 * to notify the loop that there might have been some change.
5465 v = atomic_fetch_or(IO_POLL_RETRY_FLAG, &req->poll_refs);
5466 if (v & IO_POLL_REF_MASK)
5468 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5472 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5473 * bump it and acquire ownership. It's disallowed to modify requests while not
5474 * owning it, that prevents from races for enqueueing task_work's and b/w
5475 * arming poll and wakeups.
5477 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5479 if (unlikely(atomic_read(&req->poll_refs) >= IO_POLL_REF_BIAS))
5480 return io_poll_get_ownership_slowpath(req);
5481 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5484 static void io_poll_mark_cancelled(struct io_kiocb *req)
5486 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5489 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5491 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5492 if (req->opcode == IORING_OP_POLL_ADD)
5493 return req->async_data;
5494 return req->apoll->double_poll;
5497 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5499 if (req->opcode == IORING_OP_POLL_ADD)
5501 return &req->apoll->poll;
5504 static void io_poll_req_insert(struct io_kiocb *req)
5506 struct io_ring_ctx *ctx = req->ctx;
5507 struct hlist_head *list;
5509 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5510 hlist_add_head(&req->hash_node, list);
5513 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5514 wait_queue_func_t wake_func)
5517 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5518 /* mask in events that we always want/need */
5519 poll->events = events | IO_POLL_UNMASK;
5520 INIT_LIST_HEAD(&poll->wait.entry);
5521 init_waitqueue_func_entry(&poll->wait, wake_func);
5524 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5526 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5529 spin_lock_irq(&head->lock);
5530 list_del_init(&poll->wait.entry);
5532 spin_unlock_irq(&head->lock);
5536 static void io_poll_remove_entries(struct io_kiocb *req)
5538 struct io_poll_iocb *poll = io_poll_get_single(req);
5539 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5542 * While we hold the waitqueue lock and the waitqueue is nonempty,
5543 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5544 * lock in the first place can race with the waitqueue being freed.
5546 * We solve this as eventpoll does: by taking advantage of the fact that
5547 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5548 * we enter rcu_read_lock() and see that the pointer to the queue is
5549 * non-NULL, we can then lock it without the memory being freed out from
5552 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5553 * case the caller deletes the entry from the queue, leaving it empty.
5554 * In that case, only RCU prevents the queue memory from being freed.
5557 io_poll_remove_entry(poll);
5559 io_poll_remove_entry(poll_double);
5564 * All poll tw should go through this. Checks for poll events, manages
5565 * references, does rewait, etc.
5567 * Returns a negative error on failure. >0 when no action require, which is
5568 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5569 * the request, then the mask is stored in req->result.
5571 static int io_poll_check_events(struct io_kiocb *req)
5573 struct io_ring_ctx *ctx = req->ctx;
5574 struct io_poll_iocb *poll = io_poll_get_single(req);
5577 /* req->task == current here, checking PF_EXITING is safe */
5578 if (unlikely(req->task->flags & PF_EXITING))
5579 io_poll_mark_cancelled(req);
5582 v = atomic_read(&req->poll_refs);
5584 /* tw handler should be the owner, and so have some references */
5585 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5587 if (v & IO_POLL_CANCEL_FLAG)
5590 * cqe.res contains only events of the first wake up
5591 * and all others are be lost. Redo vfs_poll() to get
5594 if ((v & IO_POLL_REF_MASK) != 1)
5596 if (v & IO_POLL_RETRY_FLAG) {
5599 * We won't find new events that came in between
5600 * vfs_poll and the ref put unless we clear the
5603 atomic_andnot(IO_POLL_RETRY_FLAG, &req->poll_refs);
5604 v &= ~IO_POLL_RETRY_FLAG;
5608 struct poll_table_struct pt = { ._key = poll->events };
5610 req->result = vfs_poll(req->file, &pt) & poll->events;
5613 /* multishot, just fill an CQE and proceed */
5614 if (req->result && !(poll->events & EPOLLONESHOT)) {
5615 __poll_t mask = mangle_poll(req->result & poll->events);
5618 spin_lock(&ctx->completion_lock);
5619 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5621 io_commit_cqring(ctx);
5622 spin_unlock(&ctx->completion_lock);
5623 if (unlikely(!filled))
5625 io_cqring_ev_posted(ctx);
5626 } else if (req->result) {
5630 /* force the next iteration to vfs_poll() */
5634 * Release all references, retry if someone tried to restart
5635 * task_work while we were executing it.
5637 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs) &
5643 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5645 struct io_ring_ctx *ctx = req->ctx;
5648 ret = io_poll_check_events(req);
5653 req->result = mangle_poll(req->result & req->poll.events);
5659 io_poll_remove_entries(req);
5660 spin_lock(&ctx->completion_lock);
5661 hash_del(&req->hash_node);
5662 spin_unlock(&ctx->completion_lock);
5663 io_req_complete_post(req, req->result, 0);
5666 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5668 struct io_ring_ctx *ctx = req->ctx;
5671 ret = io_poll_check_events(req);
5675 io_poll_remove_entries(req);
5676 spin_lock(&ctx->completion_lock);
5677 hash_del(&req->hash_node);
5678 spin_unlock(&ctx->completion_lock);
5681 io_req_task_submit(req, locked);
5683 io_req_complete_failed(req, ret);
5686 static void __io_poll_execute(struct io_kiocb *req, int mask)
5689 if (req->opcode == IORING_OP_POLL_ADD)
5690 req->io_task_work.func = io_poll_task_func;
5692 req->io_task_work.func = io_apoll_task_func;
5694 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5695 io_req_task_work_add(req);
5698 static inline void io_poll_execute(struct io_kiocb *req, int res)
5700 if (io_poll_get_ownership(req))
5701 __io_poll_execute(req, res);
5704 static void io_poll_cancel_req(struct io_kiocb *req)
5706 io_poll_mark_cancelled(req);
5707 /* kick tw, which should complete the request */
5708 io_poll_execute(req, 0);
5711 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5714 struct io_kiocb *req = wait->private;
5715 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5717 __poll_t mask = key_to_poll(key);
5719 if (unlikely(mask & POLLFREE)) {
5720 io_poll_mark_cancelled(req);
5721 /* we have to kick tw in case it's not already */
5722 io_poll_execute(req, 0);
5725 * If the waitqueue is being freed early but someone is already
5726 * holds ownership over it, we have to tear down the request as
5727 * best we can. That means immediately removing the request from
5728 * its waitqueue and preventing all further accesses to the
5729 * waitqueue via the request.
5731 list_del_init(&poll->wait.entry);
5734 * Careful: this *must* be the last step, since as soon
5735 * as req->head is NULL'ed out, the request can be
5736 * completed and freed, since aio_poll_complete_work()
5737 * will no longer need to take the waitqueue lock.
5739 smp_store_release(&poll->head, NULL);
5743 /* for instances that support it check for an event match first */
5744 if (mask && !(mask & poll->events))
5747 if (io_poll_get_ownership(req)) {
5749 * If we trigger a multishot poll off our own wakeup path,
5750 * disable multishot as there is a circular dependency between
5751 * CQ posting and triggering the event.
5753 if (mask & EPOLL_URING_WAKE)
5754 poll->events |= EPOLLONESHOT;
5756 __io_poll_execute(req, mask);
5761 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5762 struct wait_queue_head *head,
5763 struct io_poll_iocb **poll_ptr)
5765 struct io_kiocb *req = pt->req;
5768 * The file being polled uses multiple waitqueues for poll handling
5769 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5772 if (unlikely(pt->nr_entries)) {
5773 struct io_poll_iocb *first = poll;
5775 /* double add on the same waitqueue head, ignore */
5776 if (first->head == head)
5778 /* already have a 2nd entry, fail a third attempt */
5780 if ((*poll_ptr)->head == head)
5782 pt->error = -EINVAL;
5786 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5788 pt->error = -ENOMEM;
5791 io_init_poll_iocb(poll, first->events, first->wait.func);
5797 poll->wait.private = req;
5799 if (poll->events & EPOLLEXCLUSIVE)
5800 add_wait_queue_exclusive(head, &poll->wait);
5802 add_wait_queue(head, &poll->wait);
5805 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5806 struct poll_table_struct *p)
5808 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5810 __io_queue_proc(&pt->req->poll, pt, head,
5811 (struct io_poll_iocb **) &pt->req->async_data);
5814 static int __io_arm_poll_handler(struct io_kiocb *req,
5815 struct io_poll_iocb *poll,
5816 struct io_poll_table *ipt, __poll_t mask)
5818 struct io_ring_ctx *ctx = req->ctx;
5820 INIT_HLIST_NODE(&req->hash_node);
5821 io_init_poll_iocb(poll, mask, io_poll_wake);
5822 poll->file = req->file;
5823 poll->wait.private = req;
5825 ipt->pt._key = mask;
5828 ipt->nr_entries = 0;
5831 * Take the ownership to delay any tw execution up until we're done
5832 * with poll arming. see io_poll_get_ownership().
5834 atomic_set(&req->poll_refs, 1);
5835 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5837 if (mask && (poll->events & EPOLLONESHOT)) {
5838 io_poll_remove_entries(req);
5839 /* no one else has access to the req, forget about the ref */
5842 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5843 io_poll_remove_entries(req);
5845 ipt->error = -EINVAL;
5849 spin_lock(&ctx->completion_lock);
5850 io_poll_req_insert(req);
5851 spin_unlock(&ctx->completion_lock);
5854 /* can't multishot if failed, just queue the event we've got */
5855 if (unlikely(ipt->error || !ipt->nr_entries)) {
5856 poll->events |= EPOLLONESHOT;
5859 __io_poll_execute(req, mask);
5864 * Try to release ownership. If we see a change of state, e.g.
5865 * poll was waken up, queue up a tw, it'll deal with it.
5867 if (atomic_cmpxchg(&req->poll_refs, 1, 0) != 1)
5868 __io_poll_execute(req, 0);
5872 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5873 struct poll_table_struct *p)
5875 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5876 struct async_poll *apoll = pt->req->apoll;
5878 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5887 static int io_arm_poll_handler(struct io_kiocb *req)
5889 const struct io_op_def *def = &io_op_defs[req->opcode];
5890 struct io_ring_ctx *ctx = req->ctx;
5891 struct async_poll *apoll;
5892 struct io_poll_table ipt;
5893 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5896 if (!req->file || !file_can_poll(req->file))
5897 return IO_APOLL_ABORTED;
5898 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
5899 return IO_APOLL_ABORTED;
5900 if (!def->pollin && !def->pollout)
5901 return IO_APOLL_ABORTED;
5904 mask |= POLLIN | POLLRDNORM;
5906 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5907 if ((req->opcode == IORING_OP_RECVMSG) &&
5908 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5911 mask |= POLLOUT | POLLWRNORM;
5914 if (req->flags & REQ_F_POLLED) {
5916 kfree(apoll->double_poll);
5918 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5920 if (unlikely(!apoll))
5921 return IO_APOLL_ABORTED;
5922 apoll->double_poll = NULL;
5924 req->flags |= REQ_F_POLLED;
5925 ipt.pt._qproc = io_async_queue_proc;
5927 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5928 if (ret || ipt.error)
5929 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5931 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5932 mask, apoll->poll.events);
5937 * Returns true if we found and killed one or more poll requests
5939 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5942 struct hlist_node *tmp;
5943 struct io_kiocb *req;
5947 spin_lock(&ctx->completion_lock);
5948 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5949 struct hlist_head *list;
5951 list = &ctx->cancel_hash[i];
5952 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5953 if (io_match_task_safe(req, tsk, cancel_all)) {
5954 hlist_del_init(&req->hash_node);
5955 io_poll_cancel_req(req);
5960 spin_unlock(&ctx->completion_lock);
5964 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5966 __must_hold(&ctx->completion_lock)
5968 struct hlist_head *list;
5969 struct io_kiocb *req;
5971 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5972 hlist_for_each_entry(req, list, hash_node) {
5973 if (sqe_addr != req->user_data)
5975 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5982 static bool io_poll_disarm(struct io_kiocb *req)
5983 __must_hold(&ctx->completion_lock)
5985 if (!io_poll_get_ownership(req))
5987 io_poll_remove_entries(req);
5988 hash_del(&req->hash_node);
5992 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5994 __must_hold(&ctx->completion_lock)
5996 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6000 io_poll_cancel_req(req);
6004 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6009 events = READ_ONCE(sqe->poll32_events);
6011 events = swahw32(events);
6013 if (!(flags & IORING_POLL_ADD_MULTI))
6014 events |= EPOLLONESHOT;
6015 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6018 static int io_poll_update_prep(struct io_kiocb *req,
6019 const struct io_uring_sqe *sqe)
6021 struct io_poll_update *upd = &req->poll_update;
6024 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6026 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6028 flags = READ_ONCE(sqe->len);
6029 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6030 IORING_POLL_ADD_MULTI))
6032 /* meaningless without update */
6033 if (flags == IORING_POLL_ADD_MULTI)
6036 upd->old_user_data = READ_ONCE(sqe->addr);
6037 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6038 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6040 upd->new_user_data = READ_ONCE(sqe->off);
6041 if (!upd->update_user_data && upd->new_user_data)
6043 if (upd->update_events)
6044 upd->events = io_poll_parse_events(sqe, flags);
6045 else if (sqe->poll32_events)
6051 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6053 struct io_poll_iocb *poll = &req->poll;
6056 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6058 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6060 flags = READ_ONCE(sqe->len);
6061 if (flags & ~IORING_POLL_ADD_MULTI)
6064 io_req_set_refcount(req);
6065 poll->events = io_poll_parse_events(sqe, flags);
6069 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6071 struct io_poll_iocb *poll = &req->poll;
6072 struct io_poll_table ipt;
6075 ipt.pt._qproc = io_poll_queue_proc;
6077 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6078 if (!ret && ipt.error)
6080 ret = ret ?: ipt.error;
6082 __io_req_complete(req, issue_flags, ret, 0);
6086 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6088 struct io_ring_ctx *ctx = req->ctx;
6089 struct io_kiocb *preq;
6092 spin_lock(&ctx->completion_lock);
6093 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6094 if (!preq || !io_poll_disarm(preq)) {
6095 spin_unlock(&ctx->completion_lock);
6096 ret = preq ? -EALREADY : -ENOENT;
6099 spin_unlock(&ctx->completion_lock);
6101 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6102 /* only mask one event flags, keep behavior flags */
6103 if (req->poll_update.update_events) {
6104 preq->poll.events &= ~0xffff;
6105 preq->poll.events |= req->poll_update.events & 0xffff;
6106 preq->poll.events |= IO_POLL_UNMASK;
6108 if (req->poll_update.update_user_data)
6109 preq->user_data = req->poll_update.new_user_data;
6111 ret2 = io_poll_add(preq, issue_flags);
6112 /* successfully updated, don't complete poll request */
6117 io_req_complete(preq, -ECANCELED);
6121 /* complete update request, we're done with it */
6122 io_req_complete(req, ret);
6126 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
6129 io_req_complete_post(req, -ETIME, 0);
6132 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6134 struct io_timeout_data *data = container_of(timer,
6135 struct io_timeout_data, timer);
6136 struct io_kiocb *req = data->req;
6137 struct io_ring_ctx *ctx = req->ctx;
6138 unsigned long flags;
6140 spin_lock_irqsave(&ctx->timeout_lock, flags);
6141 list_del_init(&req->timeout.list);
6142 atomic_set(&req->ctx->cq_timeouts,
6143 atomic_read(&req->ctx->cq_timeouts) + 1);
6144 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6146 req->io_task_work.func = io_req_task_timeout;
6147 io_req_task_work_add(req);
6148 return HRTIMER_NORESTART;
6151 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6153 __must_hold(&ctx->timeout_lock)
6155 struct io_timeout_data *io;
6156 struct io_kiocb *req;
6159 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6160 found = user_data == req->user_data;
6165 return ERR_PTR(-ENOENT);
6167 io = req->async_data;
6168 if (hrtimer_try_to_cancel(&io->timer) == -1)
6169 return ERR_PTR(-EALREADY);
6170 list_del_init(&req->timeout.list);
6174 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6175 __must_hold(&ctx->completion_lock)
6176 __must_hold(&ctx->timeout_lock)
6178 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6181 return PTR_ERR(req);
6184 io_fill_cqe_req(req, -ECANCELED, 0);
6185 io_put_req_deferred(req);
6189 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6191 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6192 case IORING_TIMEOUT_BOOTTIME:
6193 return CLOCK_BOOTTIME;
6194 case IORING_TIMEOUT_REALTIME:
6195 return CLOCK_REALTIME;
6197 /* can't happen, vetted at prep time */
6201 return CLOCK_MONOTONIC;
6205 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6206 struct timespec64 *ts, enum hrtimer_mode mode)
6207 __must_hold(&ctx->timeout_lock)
6209 struct io_timeout_data *io;
6210 struct io_kiocb *req;
6213 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6214 found = user_data == req->user_data;
6221 io = req->async_data;
6222 if (hrtimer_try_to_cancel(&io->timer) == -1)
6224 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6225 io->timer.function = io_link_timeout_fn;
6226 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6230 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6231 struct timespec64 *ts, enum hrtimer_mode mode)
6232 __must_hold(&ctx->timeout_lock)
6234 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6235 struct io_timeout_data *data;
6238 return PTR_ERR(req);
6240 req->timeout.off = 0; /* noseq */
6241 data = req->async_data;
6242 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6243 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6244 data->timer.function = io_timeout_fn;
6245 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6249 static int io_timeout_remove_prep(struct io_kiocb *req,
6250 const struct io_uring_sqe *sqe)
6252 struct io_timeout_rem *tr = &req->timeout_rem;
6254 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6256 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6258 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6261 tr->ltimeout = false;
6262 tr->addr = READ_ONCE(sqe->addr);
6263 tr->flags = READ_ONCE(sqe->timeout_flags);
6264 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6265 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6267 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6268 tr->ltimeout = true;
6269 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6271 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6273 } else if (tr->flags) {
6274 /* timeout removal doesn't support flags */
6281 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6283 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6288 * Remove or update an existing timeout command
6290 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6292 struct io_timeout_rem *tr = &req->timeout_rem;
6293 struct io_ring_ctx *ctx = req->ctx;
6296 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6297 spin_lock(&ctx->completion_lock);
6298 spin_lock_irq(&ctx->timeout_lock);
6299 ret = io_timeout_cancel(ctx, tr->addr);
6300 spin_unlock_irq(&ctx->timeout_lock);
6301 spin_unlock(&ctx->completion_lock);
6303 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6305 spin_lock_irq(&ctx->timeout_lock);
6307 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6309 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6310 spin_unlock_irq(&ctx->timeout_lock);
6315 io_req_complete_post(req, ret, 0);
6319 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6320 bool is_timeout_link)
6322 struct io_timeout_data *data;
6324 u32 off = READ_ONCE(sqe->off);
6326 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6328 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6331 if (off && is_timeout_link)
6333 flags = READ_ONCE(sqe->timeout_flags);
6334 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6336 /* more than one clock specified is invalid, obviously */
6337 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6340 INIT_LIST_HEAD(&req->timeout.list);
6341 req->timeout.off = off;
6342 if (unlikely(off && !req->ctx->off_timeout_used))
6343 req->ctx->off_timeout_used = true;
6345 if (!req->async_data && io_alloc_async_data(req))
6348 data = req->async_data;
6350 data->flags = flags;
6352 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6355 INIT_LIST_HEAD(&req->timeout.list);
6356 data->mode = io_translate_timeout_mode(flags);
6357 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6359 if (is_timeout_link) {
6360 struct io_submit_link *link = &req->ctx->submit_state.link;
6364 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6366 req->timeout.head = link->last;
6367 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6372 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6374 struct io_ring_ctx *ctx = req->ctx;
6375 struct io_timeout_data *data = req->async_data;
6376 struct list_head *entry;
6377 u32 tail, off = req->timeout.off;
6379 spin_lock_irq(&ctx->timeout_lock);
6382 * sqe->off holds how many events that need to occur for this
6383 * timeout event to be satisfied. If it isn't set, then this is
6384 * a pure timeout request, sequence isn't used.
6386 if (io_is_timeout_noseq(req)) {
6387 entry = ctx->timeout_list.prev;
6391 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6392 req->timeout.target_seq = tail + off;
6394 /* Update the last seq here in case io_flush_timeouts() hasn't.
6395 * This is safe because ->completion_lock is held, and submissions
6396 * and completions are never mixed in the same ->completion_lock section.
6398 ctx->cq_last_tm_flush = tail;
6401 * Insertion sort, ensuring the first entry in the list is always
6402 * the one we need first.
6404 list_for_each_prev(entry, &ctx->timeout_list) {
6405 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6408 if (io_is_timeout_noseq(nxt))
6410 /* nxt.seq is behind @tail, otherwise would've been completed */
6411 if (off >= nxt->timeout.target_seq - tail)
6415 list_add(&req->timeout.list, entry);
6416 data->timer.function = io_timeout_fn;
6417 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6418 spin_unlock_irq(&ctx->timeout_lock);
6422 struct io_cancel_data {
6423 struct io_ring_ctx *ctx;
6427 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6429 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6430 struct io_cancel_data *cd = data;
6432 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6435 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6436 struct io_ring_ctx *ctx)
6438 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6439 enum io_wq_cancel cancel_ret;
6442 if (!tctx || !tctx->io_wq)
6445 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6446 switch (cancel_ret) {
6447 case IO_WQ_CANCEL_OK:
6450 case IO_WQ_CANCEL_RUNNING:
6453 case IO_WQ_CANCEL_NOTFOUND:
6461 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6463 struct io_ring_ctx *ctx = req->ctx;
6466 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6468 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6472 spin_lock(&ctx->completion_lock);
6473 spin_lock_irq(&ctx->timeout_lock);
6474 ret = io_timeout_cancel(ctx, sqe_addr);
6475 spin_unlock_irq(&ctx->timeout_lock);
6478 ret = io_poll_cancel(ctx, sqe_addr, false);
6480 spin_unlock(&ctx->completion_lock);
6484 static int io_async_cancel_prep(struct io_kiocb *req,
6485 const struct io_uring_sqe *sqe)
6487 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6489 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6491 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6495 req->cancel.addr = READ_ONCE(sqe->addr);
6499 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6501 struct io_ring_ctx *ctx = req->ctx;
6502 u64 sqe_addr = req->cancel.addr;
6503 struct io_tctx_node *node;
6506 ret = io_try_cancel_userdata(req, sqe_addr);
6510 /* slow path, try all io-wq's */
6511 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6513 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6514 struct io_uring_task *tctx = node->task->io_uring;
6516 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6520 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6524 io_req_complete_post(req, ret, 0);
6528 static int io_rsrc_update_prep(struct io_kiocb *req,
6529 const struct io_uring_sqe *sqe)
6531 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6533 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6536 req->rsrc_update.offset = READ_ONCE(sqe->off);
6537 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6538 if (!req->rsrc_update.nr_args)
6540 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6544 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6546 struct io_ring_ctx *ctx = req->ctx;
6547 struct io_uring_rsrc_update2 up;
6550 up.offset = req->rsrc_update.offset;
6551 up.data = req->rsrc_update.arg;
6557 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6558 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6559 &up, req->rsrc_update.nr_args);
6560 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6564 __io_req_complete(req, issue_flags, ret, 0);
6568 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6570 switch (req->opcode) {
6573 case IORING_OP_READV:
6574 case IORING_OP_READ_FIXED:
6575 case IORING_OP_READ:
6576 return io_read_prep(req, sqe);
6577 case IORING_OP_WRITEV:
6578 case IORING_OP_WRITE_FIXED:
6579 case IORING_OP_WRITE:
6580 return io_write_prep(req, sqe);
6581 case IORING_OP_POLL_ADD:
6582 return io_poll_add_prep(req, sqe);
6583 case IORING_OP_POLL_REMOVE:
6584 return io_poll_update_prep(req, sqe);
6585 case IORING_OP_FSYNC:
6586 return io_fsync_prep(req, sqe);
6587 case IORING_OP_SYNC_FILE_RANGE:
6588 return io_sfr_prep(req, sqe);
6589 case IORING_OP_SENDMSG:
6590 case IORING_OP_SEND:
6591 return io_sendmsg_prep(req, sqe);
6592 case IORING_OP_RECVMSG:
6593 case IORING_OP_RECV:
6594 return io_recvmsg_prep(req, sqe);
6595 case IORING_OP_CONNECT:
6596 return io_connect_prep(req, sqe);
6597 case IORING_OP_TIMEOUT:
6598 return io_timeout_prep(req, sqe, false);
6599 case IORING_OP_TIMEOUT_REMOVE:
6600 return io_timeout_remove_prep(req, sqe);
6601 case IORING_OP_ASYNC_CANCEL:
6602 return io_async_cancel_prep(req, sqe);
6603 case IORING_OP_LINK_TIMEOUT:
6604 return io_timeout_prep(req, sqe, true);
6605 case IORING_OP_ACCEPT:
6606 return io_accept_prep(req, sqe);
6607 case IORING_OP_FALLOCATE:
6608 return io_fallocate_prep(req, sqe);
6609 case IORING_OP_OPENAT:
6610 return io_openat_prep(req, sqe);
6611 case IORING_OP_CLOSE:
6612 return io_close_prep(req, sqe);
6613 case IORING_OP_FILES_UPDATE:
6614 return io_rsrc_update_prep(req, sqe);
6615 case IORING_OP_STATX:
6616 return io_statx_prep(req, sqe);
6617 case IORING_OP_FADVISE:
6618 return io_fadvise_prep(req, sqe);
6619 case IORING_OP_MADVISE:
6620 return io_madvise_prep(req, sqe);
6621 case IORING_OP_OPENAT2:
6622 return io_openat2_prep(req, sqe);
6623 case IORING_OP_EPOLL_CTL:
6624 return io_epoll_ctl_prep(req, sqe);
6625 case IORING_OP_SPLICE:
6626 return io_splice_prep(req, sqe);
6627 case IORING_OP_PROVIDE_BUFFERS:
6628 return io_provide_buffers_prep(req, sqe);
6629 case IORING_OP_REMOVE_BUFFERS:
6630 return io_remove_buffers_prep(req, sqe);
6632 return io_tee_prep(req, sqe);
6633 case IORING_OP_SHUTDOWN:
6634 return io_shutdown_prep(req, sqe);
6635 case IORING_OP_RENAMEAT:
6636 return io_renameat_prep(req, sqe);
6637 case IORING_OP_UNLINKAT:
6638 return io_unlinkat_prep(req, sqe);
6639 case IORING_OP_MKDIRAT:
6640 return io_mkdirat_prep(req, sqe);
6641 case IORING_OP_SYMLINKAT:
6642 return io_symlinkat_prep(req, sqe);
6643 case IORING_OP_LINKAT:
6644 return io_linkat_prep(req, sqe);
6647 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6652 static int io_req_prep_async(struct io_kiocb *req)
6654 if (!io_op_defs[req->opcode].needs_async_setup)
6656 if (WARN_ON_ONCE(req->async_data))
6658 if (io_alloc_async_data(req))
6661 switch (req->opcode) {
6662 case IORING_OP_READV:
6663 return io_rw_prep_async(req, READ);
6664 case IORING_OP_WRITEV:
6665 return io_rw_prep_async(req, WRITE);
6666 case IORING_OP_SENDMSG:
6667 return io_sendmsg_prep_async(req);
6668 case IORING_OP_RECVMSG:
6669 return io_recvmsg_prep_async(req);
6670 case IORING_OP_CONNECT:
6671 return io_connect_prep_async(req);
6673 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6678 static u32 io_get_sequence(struct io_kiocb *req)
6680 u32 seq = req->ctx->cached_sq_head;
6682 /* need original cached_sq_head, but it was increased for each req */
6683 io_for_each_link(req, req)
6688 static bool io_drain_req(struct io_kiocb *req)
6690 struct io_kiocb *pos;
6691 struct io_ring_ctx *ctx = req->ctx;
6692 struct io_defer_entry *de;
6696 if (req->flags & REQ_F_FAIL) {
6697 io_req_complete_fail_submit(req);
6702 * If we need to drain a request in the middle of a link, drain the
6703 * head request and the next request/link after the current link.
6704 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6705 * maintained for every request of our link.
6707 if (ctx->drain_next) {
6708 req->flags |= REQ_F_IO_DRAIN;
6709 ctx->drain_next = false;
6711 /* not interested in head, start from the first linked */
6712 io_for_each_link(pos, req->link) {
6713 if (pos->flags & REQ_F_IO_DRAIN) {
6714 ctx->drain_next = true;
6715 req->flags |= REQ_F_IO_DRAIN;
6720 /* Still need defer if there is pending req in defer list. */
6721 spin_lock(&ctx->completion_lock);
6722 if (likely(list_empty_careful(&ctx->defer_list) &&
6723 !(req->flags & REQ_F_IO_DRAIN))) {
6724 spin_unlock(&ctx->completion_lock);
6725 ctx->drain_active = false;
6728 spin_unlock(&ctx->completion_lock);
6730 seq = io_get_sequence(req);
6731 /* Still a chance to pass the sequence check */
6732 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6735 ret = io_req_prep_async(req);
6738 io_prep_async_link(req);
6739 de = kmalloc(sizeof(*de), GFP_KERNEL);
6743 io_req_complete_failed(req, ret);
6747 spin_lock(&ctx->completion_lock);
6748 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6749 spin_unlock(&ctx->completion_lock);
6751 io_queue_async_work(req, NULL);
6755 trace_io_uring_defer(ctx, req, req->user_data);
6758 list_add_tail(&de->list, &ctx->defer_list);
6759 spin_unlock(&ctx->completion_lock);
6763 static void io_clean_op(struct io_kiocb *req)
6765 if (req->flags & REQ_F_BUFFER_SELECTED) {
6766 switch (req->opcode) {
6767 case IORING_OP_READV:
6768 case IORING_OP_READ_FIXED:
6769 case IORING_OP_READ:
6770 kfree((void *)(unsigned long)req->rw.addr);
6772 case IORING_OP_RECVMSG:
6773 case IORING_OP_RECV:
6774 kfree(req->sr_msg.kbuf);
6779 if (req->flags & REQ_F_NEED_CLEANUP) {
6780 switch (req->opcode) {
6781 case IORING_OP_READV:
6782 case IORING_OP_READ_FIXED:
6783 case IORING_OP_READ:
6784 case IORING_OP_WRITEV:
6785 case IORING_OP_WRITE_FIXED:
6786 case IORING_OP_WRITE: {
6787 struct io_async_rw *io = req->async_data;
6789 kfree(io->free_iovec);
6792 case IORING_OP_RECVMSG:
6793 case IORING_OP_SENDMSG: {
6794 struct io_async_msghdr *io = req->async_data;
6796 kfree(io->free_iov);
6799 case IORING_OP_OPENAT:
6800 case IORING_OP_OPENAT2:
6801 if (req->open.filename)
6802 putname(req->open.filename);
6804 case IORING_OP_RENAMEAT:
6805 putname(req->rename.oldpath);
6806 putname(req->rename.newpath);
6808 case IORING_OP_UNLINKAT:
6809 putname(req->unlink.filename);
6811 case IORING_OP_MKDIRAT:
6812 putname(req->mkdir.filename);
6814 case IORING_OP_SYMLINKAT:
6815 putname(req->symlink.oldpath);
6816 putname(req->symlink.newpath);
6818 case IORING_OP_LINKAT:
6819 putname(req->hardlink.oldpath);
6820 putname(req->hardlink.newpath);
6824 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6825 kfree(req->apoll->double_poll);
6829 if (req->flags & REQ_F_INFLIGHT) {
6830 struct io_uring_task *tctx = req->task->io_uring;
6832 atomic_dec(&tctx->inflight_tracked);
6834 if (req->flags & REQ_F_CREDS)
6835 put_cred(req->creds);
6837 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6840 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6842 struct io_ring_ctx *ctx = req->ctx;
6843 const struct cred *creds = NULL;
6846 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6847 creds = override_creds(req->creds);
6849 switch (req->opcode) {
6851 ret = io_nop(req, issue_flags);
6853 case IORING_OP_READV:
6854 case IORING_OP_READ_FIXED:
6855 case IORING_OP_READ:
6856 ret = io_read(req, issue_flags);
6858 case IORING_OP_WRITEV:
6859 case IORING_OP_WRITE_FIXED:
6860 case IORING_OP_WRITE:
6861 ret = io_write(req, issue_flags);
6863 case IORING_OP_FSYNC:
6864 ret = io_fsync(req, issue_flags);
6866 case IORING_OP_POLL_ADD:
6867 ret = io_poll_add(req, issue_flags);
6869 case IORING_OP_POLL_REMOVE:
6870 ret = io_poll_update(req, issue_flags);
6872 case IORING_OP_SYNC_FILE_RANGE:
6873 ret = io_sync_file_range(req, issue_flags);
6875 case IORING_OP_SENDMSG:
6876 ret = io_sendmsg(req, issue_flags);
6878 case IORING_OP_SEND:
6879 ret = io_send(req, issue_flags);
6881 case IORING_OP_RECVMSG:
6882 ret = io_recvmsg(req, issue_flags);
6884 case IORING_OP_RECV:
6885 ret = io_recv(req, issue_flags);
6887 case IORING_OP_TIMEOUT:
6888 ret = io_timeout(req, issue_flags);
6890 case IORING_OP_TIMEOUT_REMOVE:
6891 ret = io_timeout_remove(req, issue_flags);
6893 case IORING_OP_ACCEPT:
6894 ret = io_accept(req, issue_flags);
6896 case IORING_OP_CONNECT:
6897 ret = io_connect(req, issue_flags);
6899 case IORING_OP_ASYNC_CANCEL:
6900 ret = io_async_cancel(req, issue_flags);
6902 case IORING_OP_FALLOCATE:
6903 ret = io_fallocate(req, issue_flags);
6905 case IORING_OP_OPENAT:
6906 ret = io_openat(req, issue_flags);
6908 case IORING_OP_CLOSE:
6909 ret = io_close(req, issue_flags);
6911 case IORING_OP_FILES_UPDATE:
6912 ret = io_files_update(req, issue_flags);
6914 case IORING_OP_STATX:
6915 ret = io_statx(req, issue_flags);
6917 case IORING_OP_FADVISE:
6918 ret = io_fadvise(req, issue_flags);
6920 case IORING_OP_MADVISE:
6921 ret = io_madvise(req, issue_flags);
6923 case IORING_OP_OPENAT2:
6924 ret = io_openat2(req, issue_flags);
6926 case IORING_OP_EPOLL_CTL:
6927 ret = io_epoll_ctl(req, issue_flags);
6929 case IORING_OP_SPLICE:
6930 ret = io_splice(req, issue_flags);
6932 case IORING_OP_PROVIDE_BUFFERS:
6933 ret = io_provide_buffers(req, issue_flags);
6935 case IORING_OP_REMOVE_BUFFERS:
6936 ret = io_remove_buffers(req, issue_flags);
6939 ret = io_tee(req, issue_flags);
6941 case IORING_OP_SHUTDOWN:
6942 ret = io_shutdown(req, issue_flags);
6944 case IORING_OP_RENAMEAT:
6945 ret = io_renameat(req, issue_flags);
6947 case IORING_OP_UNLINKAT:
6948 ret = io_unlinkat(req, issue_flags);
6950 case IORING_OP_MKDIRAT:
6951 ret = io_mkdirat(req, issue_flags);
6953 case IORING_OP_SYMLINKAT:
6954 ret = io_symlinkat(req, issue_flags);
6956 case IORING_OP_LINKAT:
6957 ret = io_linkat(req, issue_flags);
6965 revert_creds(creds);
6968 /* If the op doesn't have a file, we're not polling for it */
6969 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6970 io_iopoll_req_issued(req);
6975 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6977 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6979 req = io_put_req_find_next(req);
6980 return req ? &req->work : NULL;
6983 static void io_wq_submit_work(struct io_wq_work *work)
6985 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6986 struct io_kiocb *timeout;
6989 /* one will be dropped by ->io_free_work() after returning to io-wq */
6990 if (!(req->flags & REQ_F_REFCOUNT))
6991 __io_req_set_refcount(req, 2);
6995 timeout = io_prep_linked_timeout(req);
6997 io_queue_linked_timeout(timeout);
6999 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7000 if (work->flags & IO_WQ_WORK_CANCEL)
7005 ret = io_issue_sqe(req, 0);
7007 * We can get EAGAIN for polled IO even though we're
7008 * forcing a sync submission from here, since we can't
7009 * wait for request slots on the block side.
7011 if (ret != -EAGAIN || !(req->ctx->flags & IORING_SETUP_IOPOLL))
7017 /* avoid locking problems by failing it from a clean context */
7019 io_req_task_queue_fail(req, ret);
7022 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7025 return &table->files[i];
7028 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7031 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7033 return (struct file *) (slot->file_ptr & FFS_MASK);
7036 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7038 unsigned long file_ptr = (unsigned long) file;
7040 if (__io_file_supports_nowait(file, READ))
7041 file_ptr |= FFS_ASYNC_READ;
7042 if (__io_file_supports_nowait(file, WRITE))
7043 file_ptr |= FFS_ASYNC_WRITE;
7044 if (S_ISREG(file_inode(file)->i_mode))
7045 file_ptr |= FFS_ISREG;
7046 file_slot->file_ptr = file_ptr;
7049 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7050 struct io_kiocb *req, int fd)
7053 unsigned long file_ptr;
7055 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7057 fd = array_index_nospec(fd, ctx->nr_user_files);
7058 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7059 file = (struct file *) (file_ptr & FFS_MASK);
7060 file_ptr &= ~FFS_MASK;
7061 /* mask in overlapping REQ_F and FFS bits */
7062 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
7063 io_req_set_rsrc_node(req);
7067 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7068 struct io_kiocb *req, int fd)
7070 struct file *file = fget(fd);
7072 trace_io_uring_file_get(ctx, fd);
7074 /* we don't allow fixed io_uring files */
7075 if (file && unlikely(file->f_op == &io_uring_fops))
7076 io_req_track_inflight(req);
7080 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7081 struct io_kiocb *req, int fd, bool fixed)
7084 return io_file_get_fixed(ctx, req, fd);
7086 return io_file_get_normal(ctx, req, fd);
7089 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7091 struct io_kiocb *prev = req->timeout.prev;
7095 if (!(req->task->flags & PF_EXITING))
7096 ret = io_try_cancel_userdata(req, prev->user_data);
7097 io_req_complete_post(req, ret ?: -ETIME, 0);
7100 io_req_complete_post(req, -ETIME, 0);
7104 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7106 struct io_timeout_data *data = container_of(timer,
7107 struct io_timeout_data, timer);
7108 struct io_kiocb *prev, *req = data->req;
7109 struct io_ring_ctx *ctx = req->ctx;
7110 unsigned long flags;
7112 spin_lock_irqsave(&ctx->timeout_lock, flags);
7113 prev = req->timeout.head;
7114 req->timeout.head = NULL;
7117 * We don't expect the list to be empty, that will only happen if we
7118 * race with the completion of the linked work.
7121 io_remove_next_linked(prev);
7122 if (!req_ref_inc_not_zero(prev))
7125 list_del(&req->timeout.list);
7126 req->timeout.prev = prev;
7127 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7129 req->io_task_work.func = io_req_task_link_timeout;
7130 io_req_task_work_add(req);
7131 return HRTIMER_NORESTART;
7134 static void io_queue_linked_timeout(struct io_kiocb *req)
7136 struct io_ring_ctx *ctx = req->ctx;
7138 spin_lock_irq(&ctx->timeout_lock);
7140 * If the back reference is NULL, then our linked request finished
7141 * before we got a chance to setup the timer
7143 if (req->timeout.head) {
7144 struct io_timeout_data *data = req->async_data;
7146 data->timer.function = io_link_timeout_fn;
7147 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7149 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7151 spin_unlock_irq(&ctx->timeout_lock);
7152 /* drop submission reference */
7156 static void __io_queue_sqe(struct io_kiocb *req)
7157 __must_hold(&req->ctx->uring_lock)
7159 struct io_kiocb *linked_timeout;
7163 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7166 * We async punt it if the file wasn't marked NOWAIT, or if the file
7167 * doesn't support non-blocking read/write attempts
7170 if (req->flags & REQ_F_COMPLETE_INLINE) {
7171 struct io_ring_ctx *ctx = req->ctx;
7172 struct io_submit_state *state = &ctx->submit_state;
7174 state->compl_reqs[state->compl_nr++] = req;
7175 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
7176 io_submit_flush_completions(ctx);
7180 linked_timeout = io_prep_linked_timeout(req);
7182 io_queue_linked_timeout(linked_timeout);
7183 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7184 linked_timeout = io_prep_linked_timeout(req);
7186 switch (io_arm_poll_handler(req)) {
7187 case IO_APOLL_READY:
7189 io_queue_linked_timeout(linked_timeout);
7191 case IO_APOLL_ABORTED:
7193 * Queued up for async execution, worker will release
7194 * submit reference when the iocb is actually submitted.
7196 io_queue_async_work(req, NULL);
7201 io_queue_linked_timeout(linked_timeout);
7203 io_req_complete_failed(req, ret);
7207 static inline void io_queue_sqe(struct io_kiocb *req)
7208 __must_hold(&req->ctx->uring_lock)
7210 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
7213 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
7214 __io_queue_sqe(req);
7215 } else if (req->flags & REQ_F_FAIL) {
7216 io_req_complete_fail_submit(req);
7218 int ret = io_req_prep_async(req);
7221 io_req_complete_failed(req, ret);
7223 io_queue_async_work(req, NULL);
7228 * Check SQE restrictions (opcode and flags).
7230 * Returns 'true' if SQE is allowed, 'false' otherwise.
7232 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7233 struct io_kiocb *req,
7234 unsigned int sqe_flags)
7236 if (likely(!ctx->restricted))
7239 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7242 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7243 ctx->restrictions.sqe_flags_required)
7246 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7247 ctx->restrictions.sqe_flags_required))
7253 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7254 const struct io_uring_sqe *sqe)
7255 __must_hold(&ctx->uring_lock)
7257 struct io_submit_state *state;
7258 unsigned int sqe_flags;
7259 int personality, ret = 0;
7261 /* req is partially pre-initialised, see io_preinit_req() */
7262 req->opcode = READ_ONCE(sqe->opcode);
7263 /* same numerical values with corresponding REQ_F_*, safe to copy */
7264 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7265 req->user_data = READ_ONCE(sqe->user_data);
7267 req->fixed_rsrc_refs = NULL;
7268 req->task = current;
7270 /* enforce forwards compatibility on users */
7271 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
7273 if (unlikely(req->opcode >= IORING_OP_LAST))
7275 if (!io_check_restriction(ctx, req, sqe_flags))
7278 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7279 !io_op_defs[req->opcode].buffer_select)
7281 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
7282 ctx->drain_active = true;
7284 personality = READ_ONCE(sqe->personality);
7286 req->creds = xa_load(&ctx->personalities, personality);
7289 get_cred(req->creds);
7290 req->flags |= REQ_F_CREDS;
7292 state = &ctx->submit_state;
7295 * Plug now if we have more than 1 IO left after this, and the target
7296 * is potentially a read/write to block based storage.
7298 if (!state->plug_started && state->ios_left > 1 &&
7299 io_op_defs[req->opcode].plug) {
7300 blk_start_plug(&state->plug);
7301 state->plug_started = true;
7304 if (io_op_defs[req->opcode].needs_file) {
7305 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7306 (sqe_flags & IOSQE_FIXED_FILE));
7307 if (unlikely(!req->file))
7315 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7316 const struct io_uring_sqe *sqe)
7317 __must_hold(&ctx->uring_lock)
7319 struct io_submit_link *link = &ctx->submit_state.link;
7322 ret = io_init_req(ctx, req, sqe);
7323 if (unlikely(ret)) {
7325 /* fail even hard links since we don't submit */
7328 * we can judge a link req is failed or cancelled by if
7329 * REQ_F_FAIL is set, but the head is an exception since
7330 * it may be set REQ_F_FAIL because of other req's failure
7331 * so let's leverage req->result to distinguish if a head
7332 * is set REQ_F_FAIL because of its failure or other req's
7333 * failure so that we can set the correct ret code for it.
7334 * init result here to avoid affecting the normal path.
7336 if (!(link->head->flags & REQ_F_FAIL))
7337 req_fail_link_node(link->head, -ECANCELED);
7338 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7340 * the current req is a normal req, we should return
7341 * error and thus break the submittion loop.
7343 io_req_complete_failed(req, ret);
7346 req_fail_link_node(req, ret);
7348 ret = io_req_prep(req, sqe);
7353 /* don't need @sqe from now on */
7354 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7356 ctx->flags & IORING_SETUP_SQPOLL);
7359 * If we already have a head request, queue this one for async
7360 * submittal once the head completes. If we don't have a head but
7361 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7362 * submitted sync once the chain is complete. If none of those
7363 * conditions are true (normal request), then just queue it.
7366 struct io_kiocb *head = link->head;
7368 if (!(req->flags & REQ_F_FAIL)) {
7369 ret = io_req_prep_async(req);
7370 if (unlikely(ret)) {
7371 req_fail_link_node(req, ret);
7372 if (!(head->flags & REQ_F_FAIL))
7373 req_fail_link_node(head, -ECANCELED);
7376 trace_io_uring_link(ctx, req, head);
7377 link->last->link = req;
7380 /* last request of a link, enqueue the link */
7381 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7386 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7398 * Batched submission is done, ensure local IO is flushed out.
7400 static void io_submit_state_end(struct io_submit_state *state,
7401 struct io_ring_ctx *ctx)
7403 if (state->link.head)
7404 io_queue_sqe(state->link.head);
7405 if (state->compl_nr)
7406 io_submit_flush_completions(ctx);
7407 if (state->plug_started)
7408 blk_finish_plug(&state->plug);
7412 * Start submission side cache.
7414 static void io_submit_state_start(struct io_submit_state *state,
7415 unsigned int max_ios)
7417 state->plug_started = false;
7418 state->ios_left = max_ios;
7419 /* set only head, no need to init link_last in advance */
7420 state->link.head = NULL;
7423 static void io_commit_sqring(struct io_ring_ctx *ctx)
7425 struct io_rings *rings = ctx->rings;
7428 * Ensure any loads from the SQEs are done at this point,
7429 * since once we write the new head, the application could
7430 * write new data to them.
7432 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7436 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7437 * that is mapped by userspace. This means that care needs to be taken to
7438 * ensure that reads are stable, as we cannot rely on userspace always
7439 * being a good citizen. If members of the sqe are validated and then later
7440 * used, it's important that those reads are done through READ_ONCE() to
7441 * prevent a re-load down the line.
7443 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7445 unsigned head, mask = ctx->sq_entries - 1;
7446 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7449 * The cached sq head (or cq tail) serves two purposes:
7451 * 1) allows us to batch the cost of updating the user visible
7453 * 2) allows the kernel side to track the head on its own, even
7454 * though the application is the one updating it.
7456 head = READ_ONCE(ctx->sq_array[sq_idx]);
7457 if (likely(head < ctx->sq_entries))
7458 return &ctx->sq_sqes[head];
7460 /* drop invalid entries */
7462 WRITE_ONCE(ctx->rings->sq_dropped,
7463 READ_ONCE(ctx->rings->sq_dropped) + 1);
7467 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7468 __must_hold(&ctx->uring_lock)
7472 /* make sure SQ entry isn't read before tail */
7473 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7474 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7476 io_get_task_refs(nr);
7478 io_submit_state_start(&ctx->submit_state, nr);
7479 while (submitted < nr) {
7480 const struct io_uring_sqe *sqe;
7481 struct io_kiocb *req;
7483 req = io_alloc_req(ctx);
7484 if (unlikely(!req)) {
7486 submitted = -EAGAIN;
7489 sqe = io_get_sqe(ctx);
7490 if (unlikely(!sqe)) {
7491 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7494 /* will complete beyond this point, count as submitted */
7496 if (io_submit_sqe(ctx, req, sqe))
7500 if (unlikely(submitted != nr)) {
7501 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7502 int unused = nr - ref_used;
7504 current->io_uring->cached_refs += unused;
7505 percpu_ref_put_many(&ctx->refs, unused);
7508 io_submit_state_end(&ctx->submit_state, ctx);
7509 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7510 io_commit_sqring(ctx);
7515 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7517 return READ_ONCE(sqd->state);
7520 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7522 /* Tell userspace we may need a wakeup call */
7523 spin_lock(&ctx->completion_lock);
7524 WRITE_ONCE(ctx->rings->sq_flags,
7525 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7526 spin_unlock(&ctx->completion_lock);
7529 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7531 spin_lock(&ctx->completion_lock);
7532 WRITE_ONCE(ctx->rings->sq_flags,
7533 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7534 spin_unlock(&ctx->completion_lock);
7537 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7539 unsigned int to_submit;
7542 to_submit = io_sqring_entries(ctx);
7543 /* if we're handling multiple rings, cap submit size for fairness */
7544 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7545 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7547 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7548 unsigned nr_events = 0;
7549 const struct cred *creds = NULL;
7551 if (ctx->sq_creds != current_cred())
7552 creds = override_creds(ctx->sq_creds);
7554 mutex_lock(&ctx->uring_lock);
7555 if (!list_empty(&ctx->iopoll_list))
7556 io_do_iopoll(ctx, &nr_events, 0);
7559 * Don't submit if refs are dying, good for io_uring_register(),
7560 * but also it is relied upon by io_ring_exit_work()
7562 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7563 !(ctx->flags & IORING_SETUP_R_DISABLED))
7564 ret = io_submit_sqes(ctx, to_submit);
7565 mutex_unlock(&ctx->uring_lock);
7567 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7568 wake_up(&ctx->sqo_sq_wait);
7570 revert_creds(creds);
7576 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7578 struct io_ring_ctx *ctx;
7579 unsigned sq_thread_idle = 0;
7581 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7582 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7583 sqd->sq_thread_idle = sq_thread_idle;
7586 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7588 bool did_sig = false;
7589 struct ksignal ksig;
7591 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7592 signal_pending(current)) {
7593 mutex_unlock(&sqd->lock);
7594 if (signal_pending(current))
7595 did_sig = get_signal(&ksig);
7597 mutex_lock(&sqd->lock);
7599 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7602 static int io_sq_thread(void *data)
7604 struct io_sq_data *sqd = data;
7605 struct io_ring_ctx *ctx;
7606 unsigned long timeout = 0;
7607 char buf[TASK_COMM_LEN];
7610 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7611 set_task_comm(current, buf);
7613 if (sqd->sq_cpu != -1)
7614 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7616 set_cpus_allowed_ptr(current, cpu_online_mask);
7617 current->flags |= PF_NO_SETAFFINITY;
7619 mutex_lock(&sqd->lock);
7621 bool cap_entries, sqt_spin = false;
7623 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7624 if (io_sqd_handle_event(sqd))
7626 timeout = jiffies + sqd->sq_thread_idle;
7629 cap_entries = !list_is_singular(&sqd->ctx_list);
7630 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7631 int ret = __io_sq_thread(ctx, cap_entries);
7633 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7636 if (io_run_task_work())
7639 if (sqt_spin || !time_after(jiffies, timeout)) {
7642 timeout = jiffies + sqd->sq_thread_idle;
7646 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7647 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7648 bool needs_sched = true;
7650 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7651 io_ring_set_wakeup_flag(ctx);
7653 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7654 !list_empty_careful(&ctx->iopoll_list)) {
7655 needs_sched = false;
7658 if (io_sqring_entries(ctx)) {
7659 needs_sched = false;
7665 mutex_unlock(&sqd->lock);
7667 mutex_lock(&sqd->lock);
7669 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7670 io_ring_clear_wakeup_flag(ctx);
7673 finish_wait(&sqd->wait, &wait);
7674 timeout = jiffies + sqd->sq_thread_idle;
7677 io_uring_cancel_generic(true, sqd);
7679 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7680 io_ring_set_wakeup_flag(ctx);
7682 mutex_unlock(&sqd->lock);
7684 complete(&sqd->exited);
7688 struct io_wait_queue {
7689 struct wait_queue_entry wq;
7690 struct io_ring_ctx *ctx;
7692 unsigned nr_timeouts;
7695 static inline bool io_should_wake(struct io_wait_queue *iowq)
7697 struct io_ring_ctx *ctx = iowq->ctx;
7698 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7701 * Wake up if we have enough events, or if a timeout occurred since we
7702 * started waiting. For timeouts, we always want to return to userspace,
7703 * regardless of event count.
7705 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7708 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7709 int wake_flags, void *key)
7711 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7715 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7716 * the task, and the next invocation will do it.
7718 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7719 return autoremove_wake_function(curr, mode, wake_flags, key);
7723 static int io_run_task_work_sig(void)
7725 if (io_run_task_work())
7727 if (!signal_pending(current))
7729 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7730 return -ERESTARTSYS;
7734 /* when returns >0, the caller should retry */
7735 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7736 struct io_wait_queue *iowq,
7741 /* make sure we run task_work before checking for signals */
7742 ret = io_run_task_work_sig();
7743 if (ret || io_should_wake(iowq))
7745 /* let the caller flush overflows, retry */
7746 if (test_bit(0, &ctx->check_cq_overflow))
7749 if (!schedule_hrtimeout(timeout, HRTIMER_MODE_ABS))
7755 * Wait until events become available, if we don't already have some. The
7756 * application must reap them itself, as they reside on the shared cq ring.
7758 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7759 const sigset_t __user *sig, size_t sigsz,
7760 struct __kernel_timespec __user *uts)
7762 struct io_wait_queue iowq;
7763 struct io_rings *rings = ctx->rings;
7764 ktime_t timeout = KTIME_MAX;
7768 io_cqring_overflow_flush(ctx);
7769 if (io_cqring_events(ctx) >= min_events)
7771 if (!io_run_task_work())
7776 struct timespec64 ts;
7778 if (get_timespec64(&ts, uts))
7780 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7784 #ifdef CONFIG_COMPAT
7785 if (in_compat_syscall())
7786 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7790 ret = set_user_sigmask(sig, sigsz);
7796 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7797 iowq.wq.private = current;
7798 INIT_LIST_HEAD(&iowq.wq.entry);
7800 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7801 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7803 trace_io_uring_cqring_wait(ctx, min_events);
7805 /* if we can't even flush overflow, don't wait for more */
7806 if (!io_cqring_overflow_flush(ctx)) {
7810 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7811 TASK_INTERRUPTIBLE);
7812 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7813 finish_wait(&ctx->cq_wait, &iowq.wq);
7817 restore_saved_sigmask_unless(ret == -EINTR);
7819 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7822 static void io_free_page_table(void **table, size_t size)
7824 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7826 for (i = 0; i < nr_tables; i++)
7831 static void **io_alloc_page_table(size_t size)
7833 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7834 size_t init_size = size;
7837 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7841 for (i = 0; i < nr_tables; i++) {
7842 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7844 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7846 io_free_page_table(table, init_size);
7854 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7856 percpu_ref_exit(&ref_node->refs);
7860 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7862 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7863 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7864 unsigned long flags;
7865 bool first_add = false;
7866 unsigned long delay = HZ;
7868 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7871 /* if we are mid-quiesce then do not delay */
7872 if (node->rsrc_data->quiesce)
7875 while (!list_empty(&ctx->rsrc_ref_list)) {
7876 node = list_first_entry(&ctx->rsrc_ref_list,
7877 struct io_rsrc_node, node);
7878 /* recycle ref nodes in order */
7881 list_del(&node->node);
7882 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7884 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7887 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7890 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7892 struct io_rsrc_node *ref_node;
7894 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7898 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7903 INIT_LIST_HEAD(&ref_node->node);
7904 INIT_LIST_HEAD(&ref_node->rsrc_list);
7905 ref_node->done = false;
7909 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7910 struct io_rsrc_data *data_to_kill)
7912 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7913 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7916 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7918 rsrc_node->rsrc_data = data_to_kill;
7919 spin_lock_irq(&ctx->rsrc_ref_lock);
7920 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7921 spin_unlock_irq(&ctx->rsrc_ref_lock);
7923 atomic_inc(&data_to_kill->refs);
7924 percpu_ref_kill(&rsrc_node->refs);
7925 ctx->rsrc_node = NULL;
7928 if (!ctx->rsrc_node) {
7929 ctx->rsrc_node = ctx->rsrc_backup_node;
7930 ctx->rsrc_backup_node = NULL;
7934 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7936 if (ctx->rsrc_backup_node)
7938 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7939 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7942 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7946 /* As we may drop ->uring_lock, other task may have started quiesce */
7950 data->quiesce = true;
7952 ret = io_rsrc_node_switch_start(ctx);
7955 io_rsrc_node_switch(ctx, data);
7957 /* kill initial ref, already quiesced if zero */
7958 if (atomic_dec_and_test(&data->refs))
7960 mutex_unlock(&ctx->uring_lock);
7961 flush_delayed_work(&ctx->rsrc_put_work);
7962 ret = wait_for_completion_interruptible(&data->done);
7964 mutex_lock(&ctx->uring_lock);
7965 if (atomic_read(&data->refs) > 0) {
7967 * it has been revived by another thread while
7970 mutex_unlock(&ctx->uring_lock);
7976 atomic_inc(&data->refs);
7977 /* wait for all works potentially completing data->done */
7978 flush_delayed_work(&ctx->rsrc_put_work);
7979 reinit_completion(&data->done);
7981 ret = io_run_task_work_sig();
7982 mutex_lock(&ctx->uring_lock);
7984 data->quiesce = false;
7989 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7991 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7992 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7994 return &data->tags[table_idx][off];
7997 static void io_rsrc_data_free(struct io_rsrc_data *data)
7999 size_t size = data->nr * sizeof(data->tags[0][0]);
8002 io_free_page_table((void **)data->tags, size);
8006 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8007 u64 __user *utags, unsigned nr,
8008 struct io_rsrc_data **pdata)
8010 struct io_rsrc_data *data;
8014 data = kzalloc(sizeof(*data), GFP_KERNEL);
8017 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8025 data->do_put = do_put;
8028 for (i = 0; i < nr; i++) {
8029 u64 *tag_slot = io_get_tag_slot(data, i);
8031 if (copy_from_user(tag_slot, &utags[i],
8037 atomic_set(&data->refs, 1);
8038 init_completion(&data->done);
8042 io_rsrc_data_free(data);
8046 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8048 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8049 GFP_KERNEL_ACCOUNT);
8050 return !!table->files;
8053 static void io_free_file_tables(struct io_file_table *table)
8055 kvfree(table->files);
8056 table->files = NULL;
8059 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8061 #if defined(CONFIG_UNIX)
8062 if (ctx->ring_sock) {
8063 struct sock *sock = ctx->ring_sock->sk;
8064 struct sk_buff *skb;
8066 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8072 for (i = 0; i < ctx->nr_user_files; i++) {
8075 file = io_file_from_index(ctx, i);
8080 io_free_file_tables(&ctx->file_table);
8081 io_rsrc_data_free(ctx->file_data);
8082 ctx->file_data = NULL;
8083 ctx->nr_user_files = 0;
8086 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8088 unsigned nr = ctx->nr_user_files;
8091 if (!ctx->file_data)
8095 * Quiesce may unlock ->uring_lock, and while it's not held
8096 * prevent new requests using the table.
8098 ctx->nr_user_files = 0;
8099 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8100 ctx->nr_user_files = nr;
8102 __io_sqe_files_unregister(ctx);
8106 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8107 __releases(&sqd->lock)
8109 WARN_ON_ONCE(sqd->thread == current);
8112 * Do the dance but not conditional clear_bit() because it'd race with
8113 * other threads incrementing park_pending and setting the bit.
8115 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8116 if (atomic_dec_return(&sqd->park_pending))
8117 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8118 mutex_unlock(&sqd->lock);
8121 static void io_sq_thread_park(struct io_sq_data *sqd)
8122 __acquires(&sqd->lock)
8124 WARN_ON_ONCE(sqd->thread == current);
8126 atomic_inc(&sqd->park_pending);
8127 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8128 mutex_lock(&sqd->lock);
8130 wake_up_process(sqd->thread);
8133 static void io_sq_thread_stop(struct io_sq_data *sqd)
8135 WARN_ON_ONCE(sqd->thread == current);
8136 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8138 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8139 mutex_lock(&sqd->lock);
8141 wake_up_process(sqd->thread);
8142 mutex_unlock(&sqd->lock);
8143 wait_for_completion(&sqd->exited);
8146 static void io_put_sq_data(struct io_sq_data *sqd)
8148 if (refcount_dec_and_test(&sqd->refs)) {
8149 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8151 io_sq_thread_stop(sqd);
8156 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8158 struct io_sq_data *sqd = ctx->sq_data;
8161 io_sq_thread_park(sqd);
8162 list_del_init(&ctx->sqd_list);
8163 io_sqd_update_thread_idle(sqd);
8164 io_sq_thread_unpark(sqd);
8166 io_put_sq_data(sqd);
8167 ctx->sq_data = NULL;
8171 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8173 struct io_ring_ctx *ctx_attach;
8174 struct io_sq_data *sqd;
8177 f = fdget(p->wq_fd);
8179 return ERR_PTR(-ENXIO);
8180 if (f.file->f_op != &io_uring_fops) {
8182 return ERR_PTR(-EINVAL);
8185 ctx_attach = f.file->private_data;
8186 sqd = ctx_attach->sq_data;
8189 return ERR_PTR(-EINVAL);
8191 if (sqd->task_tgid != current->tgid) {
8193 return ERR_PTR(-EPERM);
8196 refcount_inc(&sqd->refs);
8201 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8204 struct io_sq_data *sqd;
8207 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8208 sqd = io_attach_sq_data(p);
8213 /* fall through for EPERM case, setup new sqd/task */
8214 if (PTR_ERR(sqd) != -EPERM)
8218 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8220 return ERR_PTR(-ENOMEM);
8222 atomic_set(&sqd->park_pending, 0);
8223 refcount_set(&sqd->refs, 1);
8224 INIT_LIST_HEAD(&sqd->ctx_list);
8225 mutex_init(&sqd->lock);
8226 init_waitqueue_head(&sqd->wait);
8227 init_completion(&sqd->exited);
8231 #if defined(CONFIG_UNIX)
8233 * Ensure the UNIX gc is aware of our file set, so we are certain that
8234 * the io_uring can be safely unregistered on process exit, even if we have
8235 * loops in the file referencing.
8237 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8239 struct sock *sk = ctx->ring_sock->sk;
8240 struct scm_fp_list *fpl;
8241 struct sk_buff *skb;
8244 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8248 skb = alloc_skb(0, GFP_KERNEL);
8255 skb->scm_io_uring = 1;
8258 fpl->user = get_uid(current_user());
8259 for (i = 0; i < nr; i++) {
8260 struct file *file = io_file_from_index(ctx, i + offset);
8264 fpl->fp[nr_files] = get_file(file);
8265 unix_inflight(fpl->user, fpl->fp[nr_files]);
8270 fpl->max = SCM_MAX_FD;
8271 fpl->count = nr_files;
8272 UNIXCB(skb).fp = fpl;
8273 skb->destructor = unix_destruct_scm;
8274 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8275 skb_queue_head(&sk->sk_receive_queue, skb);
8277 for (i = 0; i < nr; i++) {
8278 struct file *file = io_file_from_index(ctx, i + offset);
8285 free_uid(fpl->user);
8293 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8294 * causes regular reference counting to break down. We rely on the UNIX
8295 * garbage collection to take care of this problem for us.
8297 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8299 unsigned left, total;
8303 left = ctx->nr_user_files;
8305 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8307 ret = __io_sqe_files_scm(ctx, this_files, total);
8311 total += this_files;
8317 while (total < ctx->nr_user_files) {
8318 struct file *file = io_file_from_index(ctx, total);
8328 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8334 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8336 struct file *file = prsrc->file;
8337 #if defined(CONFIG_UNIX)
8338 struct sock *sock = ctx->ring_sock->sk;
8339 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8340 struct sk_buff *skb;
8343 __skb_queue_head_init(&list);
8346 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8347 * remove this entry and rearrange the file array.
8349 skb = skb_dequeue(head);
8351 struct scm_fp_list *fp;
8353 fp = UNIXCB(skb).fp;
8354 for (i = 0; i < fp->count; i++) {
8357 if (fp->fp[i] != file)
8360 unix_notinflight(fp->user, fp->fp[i]);
8361 left = fp->count - 1 - i;
8363 memmove(&fp->fp[i], &fp->fp[i + 1],
8364 left * sizeof(struct file *));
8371 __skb_queue_tail(&list, skb);
8381 __skb_queue_tail(&list, skb);
8383 skb = skb_dequeue(head);
8386 if (skb_peek(&list)) {
8387 spin_lock_irq(&head->lock);
8388 while ((skb = __skb_dequeue(&list)) != NULL)
8389 __skb_queue_tail(head, skb);
8390 spin_unlock_irq(&head->lock);
8397 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8399 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8400 struct io_ring_ctx *ctx = rsrc_data->ctx;
8401 struct io_rsrc_put *prsrc, *tmp;
8403 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8404 list_del(&prsrc->list);
8407 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8409 io_ring_submit_lock(ctx, lock_ring);
8410 spin_lock(&ctx->completion_lock);
8411 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8412 io_commit_cqring(ctx);
8413 spin_unlock(&ctx->completion_lock);
8414 io_cqring_ev_posted(ctx);
8415 io_ring_submit_unlock(ctx, lock_ring);
8418 rsrc_data->do_put(ctx, prsrc);
8422 io_rsrc_node_destroy(ref_node);
8423 if (atomic_dec_and_test(&rsrc_data->refs))
8424 complete(&rsrc_data->done);
8427 static void io_rsrc_put_work(struct work_struct *work)
8429 struct io_ring_ctx *ctx;
8430 struct llist_node *node;
8432 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8433 node = llist_del_all(&ctx->rsrc_put_llist);
8436 struct io_rsrc_node *ref_node;
8437 struct llist_node *next = node->next;
8439 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8440 __io_rsrc_put_work(ref_node);
8445 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8446 unsigned nr_args, u64 __user *tags)
8448 __s32 __user *fds = (__s32 __user *) arg;
8457 if (nr_args > IORING_MAX_FIXED_FILES)
8459 if (nr_args > rlimit(RLIMIT_NOFILE))
8461 ret = io_rsrc_node_switch_start(ctx);
8464 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8470 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8473 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8474 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8478 /* allow sparse sets */
8481 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8488 if (unlikely(!file))
8492 * Don't allow io_uring instances to be registered. If UNIX
8493 * isn't enabled, then this causes a reference cycle and this
8494 * instance can never get freed. If UNIX is enabled we'll
8495 * handle it just fine, but there's still no point in allowing
8496 * a ring fd as it doesn't support regular read/write anyway.
8498 if (file->f_op == &io_uring_fops) {
8502 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8505 ret = io_sqe_files_scm(ctx);
8507 __io_sqe_files_unregister(ctx);
8511 io_rsrc_node_switch(ctx, NULL);
8514 for (i = 0; i < ctx->nr_user_files; i++) {
8515 file = io_file_from_index(ctx, i);
8519 io_free_file_tables(&ctx->file_table);
8520 ctx->nr_user_files = 0;
8522 io_rsrc_data_free(ctx->file_data);
8523 ctx->file_data = NULL;
8527 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8530 #if defined(CONFIG_UNIX)
8531 struct sock *sock = ctx->ring_sock->sk;
8532 struct sk_buff_head *head = &sock->sk_receive_queue;
8533 struct sk_buff *skb;
8536 * See if we can merge this file into an existing skb SCM_RIGHTS
8537 * file set. If there's no room, fall back to allocating a new skb
8538 * and filling it in.
8540 spin_lock_irq(&head->lock);
8541 skb = skb_peek(head);
8543 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8545 if (fpl->count < SCM_MAX_FD) {
8546 __skb_unlink(skb, head);
8547 spin_unlock_irq(&head->lock);
8548 fpl->fp[fpl->count] = get_file(file);
8549 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8551 spin_lock_irq(&head->lock);
8552 __skb_queue_head(head, skb);
8557 spin_unlock_irq(&head->lock);
8564 return __io_sqe_files_scm(ctx, 1, index);
8570 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8571 struct io_rsrc_node *node, void *rsrc)
8573 u64 *tag_slot = io_get_tag_slot(data, idx);
8574 struct io_rsrc_put *prsrc;
8576 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8580 prsrc->tag = *tag_slot;
8583 list_add(&prsrc->list, &node->rsrc_list);
8587 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8588 unsigned int issue_flags, u32 slot_index)
8590 struct io_ring_ctx *ctx = req->ctx;
8591 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8592 bool needs_switch = false;
8593 struct io_fixed_file *file_slot;
8596 io_ring_submit_lock(ctx, !force_nonblock);
8597 if (file->f_op == &io_uring_fops)
8600 if (!ctx->file_data)
8603 if (slot_index >= ctx->nr_user_files)
8606 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8607 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8609 if (file_slot->file_ptr) {
8610 struct file *old_file;
8612 ret = io_rsrc_node_switch_start(ctx);
8616 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8617 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8618 ctx->rsrc_node, old_file);
8621 file_slot->file_ptr = 0;
8622 needs_switch = true;
8625 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8626 io_fixed_file_set(file_slot, file);
8627 ret = io_sqe_file_register(ctx, file, slot_index);
8629 file_slot->file_ptr = 0;
8636 io_rsrc_node_switch(ctx, ctx->file_data);
8637 io_ring_submit_unlock(ctx, !force_nonblock);
8643 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8645 unsigned int offset = req->close.file_slot - 1;
8646 struct io_ring_ctx *ctx = req->ctx;
8647 struct io_fixed_file *file_slot;
8651 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8653 if (unlikely(!ctx->file_data))
8656 if (offset >= ctx->nr_user_files)
8658 ret = io_rsrc_node_switch_start(ctx);
8662 offset = array_index_nospec(offset, ctx->nr_user_files);
8663 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8665 if (!file_slot->file_ptr)
8668 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8669 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8673 file_slot->file_ptr = 0;
8674 io_rsrc_node_switch(ctx, ctx->file_data);
8677 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8681 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8682 struct io_uring_rsrc_update2 *up,
8685 u64 __user *tags = u64_to_user_ptr(up->tags);
8686 __s32 __user *fds = u64_to_user_ptr(up->data);
8687 struct io_rsrc_data *data = ctx->file_data;
8688 struct io_fixed_file *file_slot;
8692 bool needs_switch = false;
8694 if (!ctx->file_data)
8696 if (up->offset + nr_args > ctx->nr_user_files)
8699 for (done = 0; done < nr_args; done++) {
8702 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8703 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8707 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8711 if (fd == IORING_REGISTER_FILES_SKIP)
8714 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8715 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8717 if (file_slot->file_ptr) {
8718 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8719 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8722 file_slot->file_ptr = 0;
8723 needs_switch = true;
8732 * Don't allow io_uring instances to be registered. If
8733 * UNIX isn't enabled, then this causes a reference
8734 * cycle and this instance can never get freed. If UNIX
8735 * is enabled we'll handle it just fine, but there's
8736 * still no point in allowing a ring fd as it doesn't
8737 * support regular read/write anyway.
8739 if (file->f_op == &io_uring_fops) {
8744 *io_get_tag_slot(data, i) = tag;
8745 io_fixed_file_set(file_slot, file);
8746 err = io_sqe_file_register(ctx, file, i);
8748 file_slot->file_ptr = 0;
8756 io_rsrc_node_switch(ctx, data);
8757 return done ? done : err;
8760 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8761 struct task_struct *task)
8763 struct io_wq_hash *hash;
8764 struct io_wq_data data;
8765 unsigned int concurrency;
8767 mutex_lock(&ctx->uring_lock);
8768 hash = ctx->hash_map;
8770 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8772 mutex_unlock(&ctx->uring_lock);
8773 return ERR_PTR(-ENOMEM);
8775 refcount_set(&hash->refs, 1);
8776 init_waitqueue_head(&hash->wait);
8777 ctx->hash_map = hash;
8779 mutex_unlock(&ctx->uring_lock);
8783 data.free_work = io_wq_free_work;
8784 data.do_work = io_wq_submit_work;
8786 /* Do QD, or 4 * CPUS, whatever is smallest */
8787 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8789 return io_wq_create(concurrency, &data);
8792 static int io_uring_alloc_task_context(struct task_struct *task,
8793 struct io_ring_ctx *ctx)
8795 struct io_uring_task *tctx;
8798 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8799 if (unlikely(!tctx))
8802 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8803 if (unlikely(ret)) {
8808 tctx->io_wq = io_init_wq_offload(ctx, task);
8809 if (IS_ERR(tctx->io_wq)) {
8810 ret = PTR_ERR(tctx->io_wq);
8811 percpu_counter_destroy(&tctx->inflight);
8817 init_waitqueue_head(&tctx->wait);
8818 atomic_set(&tctx->in_idle, 0);
8819 atomic_set(&tctx->inflight_tracked, 0);
8820 task->io_uring = tctx;
8821 spin_lock_init(&tctx->task_lock);
8822 INIT_WQ_LIST(&tctx->task_list);
8823 init_task_work(&tctx->task_work, tctx_task_work);
8827 void __io_uring_free(struct task_struct *tsk)
8829 struct io_uring_task *tctx = tsk->io_uring;
8831 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8832 WARN_ON_ONCE(tctx->io_wq);
8833 WARN_ON_ONCE(tctx->cached_refs);
8835 percpu_counter_destroy(&tctx->inflight);
8837 tsk->io_uring = NULL;
8840 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8841 struct io_uring_params *p)
8845 /* Retain compatibility with failing for an invalid attach attempt */
8846 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8847 IORING_SETUP_ATTACH_WQ) {
8850 f = fdget(p->wq_fd);
8853 if (f.file->f_op != &io_uring_fops) {
8859 if (ctx->flags & IORING_SETUP_SQPOLL) {
8860 struct task_struct *tsk;
8861 struct io_sq_data *sqd;
8864 sqd = io_get_sq_data(p, &attached);
8870 ctx->sq_creds = get_current_cred();
8872 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8873 if (!ctx->sq_thread_idle)
8874 ctx->sq_thread_idle = HZ;
8876 io_sq_thread_park(sqd);
8877 list_add(&ctx->sqd_list, &sqd->ctx_list);
8878 io_sqd_update_thread_idle(sqd);
8879 /* don't attach to a dying SQPOLL thread, would be racy */
8880 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8881 io_sq_thread_unpark(sqd);
8888 if (p->flags & IORING_SETUP_SQ_AFF) {
8889 int cpu = p->sq_thread_cpu;
8892 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8899 sqd->task_pid = current->pid;
8900 sqd->task_tgid = current->tgid;
8901 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8908 ret = io_uring_alloc_task_context(tsk, ctx);
8909 wake_up_new_task(tsk);
8912 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8913 /* Can't have SQ_AFF without SQPOLL */
8920 complete(&ctx->sq_data->exited);
8922 io_sq_thread_finish(ctx);
8926 static inline void __io_unaccount_mem(struct user_struct *user,
8927 unsigned long nr_pages)
8929 atomic_long_sub(nr_pages, &user->locked_vm);
8932 static inline int __io_account_mem(struct user_struct *user,
8933 unsigned long nr_pages)
8935 unsigned long page_limit, cur_pages, new_pages;
8937 /* Don't allow more pages than we can safely lock */
8938 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8941 cur_pages = atomic_long_read(&user->locked_vm);
8942 new_pages = cur_pages + nr_pages;
8943 if (new_pages > page_limit)
8945 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8946 new_pages) != cur_pages);
8951 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8954 __io_unaccount_mem(ctx->user, nr_pages);
8956 if (ctx->mm_account)
8957 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8960 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8965 ret = __io_account_mem(ctx->user, nr_pages);
8970 if (ctx->mm_account)
8971 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8976 static void io_mem_free(void *ptr)
8983 page = virt_to_head_page(ptr);
8984 if (put_page_testzero(page))
8985 free_compound_page(page);
8988 static void *io_mem_alloc(size_t size)
8990 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8992 return (void *) __get_free_pages(gfp, get_order(size));
8995 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8998 struct io_rings *rings;
8999 size_t off, sq_array_size;
9001 off = struct_size(rings, cqes, cq_entries);
9002 if (off == SIZE_MAX)
9006 off = ALIGN(off, SMP_CACHE_BYTES);
9014 sq_array_size = array_size(sizeof(u32), sq_entries);
9015 if (sq_array_size == SIZE_MAX)
9018 if (check_add_overflow(off, sq_array_size, &off))
9024 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9026 struct io_mapped_ubuf *imu = *slot;
9029 if (imu != ctx->dummy_ubuf) {
9030 for (i = 0; i < imu->nr_bvecs; i++)
9031 unpin_user_page(imu->bvec[i].bv_page);
9032 if (imu->acct_pages)
9033 io_unaccount_mem(ctx, imu->acct_pages);
9039 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9041 io_buffer_unmap(ctx, &prsrc->buf);
9045 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9049 for (i = 0; i < ctx->nr_user_bufs; i++)
9050 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9051 kfree(ctx->user_bufs);
9052 io_rsrc_data_free(ctx->buf_data);
9053 ctx->user_bufs = NULL;
9054 ctx->buf_data = NULL;
9055 ctx->nr_user_bufs = 0;
9058 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9060 unsigned nr = ctx->nr_user_bufs;
9067 * Quiesce may unlock ->uring_lock, and while it's not held
9068 * prevent new requests using the table.
9070 ctx->nr_user_bufs = 0;
9071 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9072 ctx->nr_user_bufs = nr;
9074 __io_sqe_buffers_unregister(ctx);
9078 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9079 void __user *arg, unsigned index)
9081 struct iovec __user *src;
9083 #ifdef CONFIG_COMPAT
9085 struct compat_iovec __user *ciovs;
9086 struct compat_iovec ciov;
9088 ciovs = (struct compat_iovec __user *) arg;
9089 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9092 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9093 dst->iov_len = ciov.iov_len;
9097 src = (struct iovec __user *) arg;
9098 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9104 * Not super efficient, but this is just a registration time. And we do cache
9105 * the last compound head, so generally we'll only do a full search if we don't
9108 * We check if the given compound head page has already been accounted, to
9109 * avoid double accounting it. This allows us to account the full size of the
9110 * page, not just the constituent pages of a huge page.
9112 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9113 int nr_pages, struct page *hpage)
9117 /* check current page array */
9118 for (i = 0; i < nr_pages; i++) {
9119 if (!PageCompound(pages[i]))
9121 if (compound_head(pages[i]) == hpage)
9125 /* check previously registered pages */
9126 for (i = 0; i < ctx->nr_user_bufs; i++) {
9127 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9129 for (j = 0; j < imu->nr_bvecs; j++) {
9130 if (!PageCompound(imu->bvec[j].bv_page))
9132 if (compound_head(imu->bvec[j].bv_page) == hpage)
9140 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9141 int nr_pages, struct io_mapped_ubuf *imu,
9142 struct page **last_hpage)
9146 imu->acct_pages = 0;
9147 for (i = 0; i < nr_pages; i++) {
9148 if (!PageCompound(pages[i])) {
9153 hpage = compound_head(pages[i]);
9154 if (hpage == *last_hpage)
9156 *last_hpage = hpage;
9157 if (headpage_already_acct(ctx, pages, i, hpage))
9159 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9163 if (!imu->acct_pages)
9166 ret = io_account_mem(ctx, imu->acct_pages);
9168 imu->acct_pages = 0;
9172 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9173 struct io_mapped_ubuf **pimu,
9174 struct page **last_hpage)
9176 struct io_mapped_ubuf *imu = NULL;
9177 struct vm_area_struct **vmas = NULL;
9178 struct page **pages = NULL;
9179 unsigned long off, start, end, ubuf;
9181 int ret, pret, nr_pages, i;
9183 if (!iov->iov_base) {
9184 *pimu = ctx->dummy_ubuf;
9188 ubuf = (unsigned long) iov->iov_base;
9189 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9190 start = ubuf >> PAGE_SHIFT;
9191 nr_pages = end - start;
9196 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9200 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9205 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9210 mmap_read_lock(current->mm);
9211 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9213 if (pret == nr_pages) {
9214 /* don't support file backed memory */
9215 for (i = 0; i < nr_pages; i++) {
9216 struct vm_area_struct *vma = vmas[i];
9218 if (vma_is_shmem(vma))
9221 !is_file_hugepages(vma->vm_file)) {
9227 ret = pret < 0 ? pret : -EFAULT;
9229 mmap_read_unlock(current->mm);
9232 * if we did partial map, or found file backed vmas,
9233 * release any pages we did get
9236 unpin_user_pages(pages, pret);
9240 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9242 unpin_user_pages(pages, pret);
9246 off = ubuf & ~PAGE_MASK;
9247 size = iov->iov_len;
9248 for (i = 0; i < nr_pages; i++) {
9251 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9252 imu->bvec[i].bv_page = pages[i];
9253 imu->bvec[i].bv_len = vec_len;
9254 imu->bvec[i].bv_offset = off;
9258 /* store original address for later verification */
9260 imu->ubuf_end = ubuf + iov->iov_len;
9261 imu->nr_bvecs = nr_pages;
9272 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9274 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9275 return ctx->user_bufs ? 0 : -ENOMEM;
9278 static int io_buffer_validate(struct iovec *iov)
9280 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9283 * Don't impose further limits on the size and buffer
9284 * constraints here, we'll -EINVAL later when IO is
9285 * submitted if they are wrong.
9288 return iov->iov_len ? -EFAULT : 0;
9292 /* arbitrary limit, but we need something */
9293 if (iov->iov_len > SZ_1G)
9296 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9302 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9303 unsigned int nr_args, u64 __user *tags)
9305 struct page *last_hpage = NULL;
9306 struct io_rsrc_data *data;
9312 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9314 ret = io_rsrc_node_switch_start(ctx);
9317 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9320 ret = io_buffers_map_alloc(ctx, nr_args);
9322 io_rsrc_data_free(data);
9326 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9327 ret = io_copy_iov(ctx, &iov, arg, i);
9330 ret = io_buffer_validate(&iov);
9333 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9338 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9344 WARN_ON_ONCE(ctx->buf_data);
9346 ctx->buf_data = data;
9348 __io_sqe_buffers_unregister(ctx);
9350 io_rsrc_node_switch(ctx, NULL);
9354 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9355 struct io_uring_rsrc_update2 *up,
9356 unsigned int nr_args)
9358 u64 __user *tags = u64_to_user_ptr(up->tags);
9359 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9360 struct page *last_hpage = NULL;
9361 bool needs_switch = false;
9367 if (up->offset + nr_args > ctx->nr_user_bufs)
9370 for (done = 0; done < nr_args; done++) {
9371 struct io_mapped_ubuf *imu;
9372 int offset = up->offset + done;
9375 err = io_copy_iov(ctx, &iov, iovs, done);
9378 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9382 err = io_buffer_validate(&iov);
9385 if (!iov.iov_base && tag) {
9389 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9393 i = array_index_nospec(offset, ctx->nr_user_bufs);
9394 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9395 err = io_queue_rsrc_removal(ctx->buf_data, i,
9396 ctx->rsrc_node, ctx->user_bufs[i]);
9397 if (unlikely(err)) {
9398 io_buffer_unmap(ctx, &imu);
9401 ctx->user_bufs[i] = NULL;
9402 needs_switch = true;
9405 ctx->user_bufs[i] = imu;
9406 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9410 io_rsrc_node_switch(ctx, ctx->buf_data);
9411 return done ? done : err;
9414 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9416 __s32 __user *fds = arg;
9422 if (copy_from_user(&fd, fds, sizeof(*fds)))
9425 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9426 if (IS_ERR(ctx->cq_ev_fd)) {
9427 int ret = PTR_ERR(ctx->cq_ev_fd);
9429 ctx->cq_ev_fd = NULL;
9436 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9438 if (ctx->cq_ev_fd) {
9439 eventfd_ctx_put(ctx->cq_ev_fd);
9440 ctx->cq_ev_fd = NULL;
9447 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9449 struct io_buffer *buf;
9450 unsigned long index;
9452 xa_for_each(&ctx->io_buffers, index, buf)
9453 __io_remove_buffers(ctx, buf, index, -1U);
9456 static void io_req_cache_free(struct list_head *list)
9458 struct io_kiocb *req, *nxt;
9460 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9461 list_del(&req->inflight_entry);
9462 kmem_cache_free(req_cachep, req);
9466 static void io_req_caches_free(struct io_ring_ctx *ctx)
9468 struct io_submit_state *state = &ctx->submit_state;
9470 mutex_lock(&ctx->uring_lock);
9472 if (state->free_reqs) {
9473 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9474 state->free_reqs = 0;
9477 io_flush_cached_locked_reqs(ctx, state);
9478 io_req_cache_free(&state->free_list);
9479 mutex_unlock(&ctx->uring_lock);
9482 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9484 if (data && !atomic_dec_and_test(&data->refs))
9485 wait_for_completion(&data->done);
9488 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9490 io_sq_thread_finish(ctx);
9492 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9493 io_wait_rsrc_data(ctx->buf_data);
9494 io_wait_rsrc_data(ctx->file_data);
9496 mutex_lock(&ctx->uring_lock);
9498 __io_sqe_buffers_unregister(ctx);
9500 __io_sqe_files_unregister(ctx);
9502 __io_cqring_overflow_flush(ctx, true);
9503 mutex_unlock(&ctx->uring_lock);
9504 io_eventfd_unregister(ctx);
9505 io_destroy_buffers(ctx);
9507 put_cred(ctx->sq_creds);
9509 /* there are no registered resources left, nobody uses it */
9511 io_rsrc_node_destroy(ctx->rsrc_node);
9512 if (ctx->rsrc_backup_node)
9513 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9514 flush_delayed_work(&ctx->rsrc_put_work);
9516 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9517 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9519 #if defined(CONFIG_UNIX)
9520 if (ctx->ring_sock) {
9521 ctx->ring_sock->file = NULL; /* so that iput() is called */
9522 sock_release(ctx->ring_sock);
9525 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9527 if (ctx->mm_account) {
9528 mmdrop(ctx->mm_account);
9529 ctx->mm_account = NULL;
9532 io_mem_free(ctx->rings);
9533 io_mem_free(ctx->sq_sqes);
9535 percpu_ref_exit(&ctx->refs);
9536 free_uid(ctx->user);
9537 io_req_caches_free(ctx);
9539 io_wq_put_hash(ctx->hash_map);
9540 kfree(ctx->cancel_hash);
9541 kfree(ctx->dummy_ubuf);
9545 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9547 struct io_ring_ctx *ctx = file->private_data;
9550 poll_wait(file, &ctx->poll_wait, wait);
9552 * synchronizes with barrier from wq_has_sleeper call in
9556 if (!io_sqring_full(ctx))
9557 mask |= EPOLLOUT | EPOLLWRNORM;
9560 * Don't flush cqring overflow list here, just do a simple check.
9561 * Otherwise there could possible be ABBA deadlock:
9564 * lock(&ctx->uring_lock);
9566 * lock(&ctx->uring_lock);
9569 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9570 * pushs them to do the flush.
9572 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9573 mask |= EPOLLIN | EPOLLRDNORM;
9578 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9580 const struct cred *creds;
9582 creds = xa_erase(&ctx->personalities, id);
9591 struct io_tctx_exit {
9592 struct callback_head task_work;
9593 struct completion completion;
9594 struct io_ring_ctx *ctx;
9597 static void io_tctx_exit_cb(struct callback_head *cb)
9599 struct io_uring_task *tctx = current->io_uring;
9600 struct io_tctx_exit *work;
9602 work = container_of(cb, struct io_tctx_exit, task_work);
9604 * When @in_idle, we're in cancellation and it's racy to remove the
9605 * node. It'll be removed by the end of cancellation, just ignore it.
9606 * tctx can be NULL if the queueing of this task_work raced with
9607 * work cancelation off the exec path.
9609 if (tctx && !atomic_read(&tctx->in_idle))
9610 io_uring_del_tctx_node((unsigned long)work->ctx);
9611 complete(&work->completion);
9614 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9616 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9618 return req->ctx == data;
9621 static void io_ring_exit_work(struct work_struct *work)
9623 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9624 unsigned long timeout = jiffies + HZ * 60 * 5;
9625 unsigned long interval = HZ / 20;
9626 struct io_tctx_exit exit;
9627 struct io_tctx_node *node;
9631 * If we're doing polled IO and end up having requests being
9632 * submitted async (out-of-line), then completions can come in while
9633 * we're waiting for refs to drop. We need to reap these manually,
9634 * as nobody else will be looking for them.
9637 io_uring_try_cancel_requests(ctx, NULL, true);
9639 struct io_sq_data *sqd = ctx->sq_data;
9640 struct task_struct *tsk;
9642 io_sq_thread_park(sqd);
9644 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9645 io_wq_cancel_cb(tsk->io_uring->io_wq,
9646 io_cancel_ctx_cb, ctx, true);
9647 io_sq_thread_unpark(sqd);
9650 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9651 /* there is little hope left, don't run it too often */
9654 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9656 init_completion(&exit.completion);
9657 init_task_work(&exit.task_work, io_tctx_exit_cb);
9660 * Some may use context even when all refs and requests have been put,
9661 * and they are free to do so while still holding uring_lock or
9662 * completion_lock, see io_req_task_submit(). Apart from other work,
9663 * this lock/unlock section also waits them to finish.
9665 mutex_lock(&ctx->uring_lock);
9666 while (!list_empty(&ctx->tctx_list)) {
9667 WARN_ON_ONCE(time_after(jiffies, timeout));
9669 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9671 /* don't spin on a single task if cancellation failed */
9672 list_rotate_left(&ctx->tctx_list);
9673 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9674 if (WARN_ON_ONCE(ret))
9676 wake_up_process(node->task);
9678 mutex_unlock(&ctx->uring_lock);
9679 wait_for_completion(&exit.completion);
9680 mutex_lock(&ctx->uring_lock);
9682 mutex_unlock(&ctx->uring_lock);
9683 spin_lock(&ctx->completion_lock);
9684 spin_unlock(&ctx->completion_lock);
9686 io_ring_ctx_free(ctx);
9689 /* Returns true if we found and killed one or more timeouts */
9690 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9693 struct io_kiocb *req, *tmp;
9696 spin_lock(&ctx->completion_lock);
9697 spin_lock_irq(&ctx->timeout_lock);
9698 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9699 if (io_match_task(req, tsk, cancel_all)) {
9700 io_kill_timeout(req, -ECANCELED);
9704 spin_unlock_irq(&ctx->timeout_lock);
9706 io_commit_cqring(ctx);
9707 spin_unlock(&ctx->completion_lock);
9709 io_cqring_ev_posted(ctx);
9710 return canceled != 0;
9713 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9715 unsigned long index;
9716 struct creds *creds;
9718 mutex_lock(&ctx->uring_lock);
9719 percpu_ref_kill(&ctx->refs);
9721 __io_cqring_overflow_flush(ctx, true);
9722 xa_for_each(&ctx->personalities, index, creds)
9723 io_unregister_personality(ctx, index);
9724 mutex_unlock(&ctx->uring_lock);
9726 io_kill_timeouts(ctx, NULL, true);
9727 io_poll_remove_all(ctx, NULL, true);
9729 /* if we failed setting up the ctx, we might not have any rings */
9730 io_iopoll_try_reap_events(ctx);
9732 /* drop cached put refs after potentially doing completions */
9733 if (current->io_uring)
9734 io_uring_drop_tctx_refs(current);
9736 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9738 * Use system_unbound_wq to avoid spawning tons of event kworkers
9739 * if we're exiting a ton of rings at the same time. It just adds
9740 * noise and overhead, there's no discernable change in runtime
9741 * over using system_wq.
9743 queue_work(system_unbound_wq, &ctx->exit_work);
9746 static int io_uring_release(struct inode *inode, struct file *file)
9748 struct io_ring_ctx *ctx = file->private_data;
9750 file->private_data = NULL;
9751 io_ring_ctx_wait_and_kill(ctx);
9755 struct io_task_cancel {
9756 struct task_struct *task;
9760 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9762 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9763 struct io_task_cancel *cancel = data;
9765 return io_match_task_safe(req, cancel->task, cancel->all);
9768 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9769 struct task_struct *task, bool cancel_all)
9771 struct io_defer_entry *de;
9774 spin_lock(&ctx->completion_lock);
9775 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9776 if (io_match_task_safe(de->req, task, cancel_all)) {
9777 list_cut_position(&list, &ctx->defer_list, &de->list);
9781 spin_unlock(&ctx->completion_lock);
9782 if (list_empty(&list))
9785 while (!list_empty(&list)) {
9786 de = list_first_entry(&list, struct io_defer_entry, list);
9787 list_del_init(&de->list);
9788 io_req_complete_failed(de->req, -ECANCELED);
9794 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9796 struct io_tctx_node *node;
9797 enum io_wq_cancel cret;
9800 mutex_lock(&ctx->uring_lock);
9801 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9802 struct io_uring_task *tctx = node->task->io_uring;
9805 * io_wq will stay alive while we hold uring_lock, because it's
9806 * killed after ctx nodes, which requires to take the lock.
9808 if (!tctx || !tctx->io_wq)
9810 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9811 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9813 mutex_unlock(&ctx->uring_lock);
9818 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9819 struct task_struct *task,
9822 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9823 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9826 enum io_wq_cancel cret;
9830 ret |= io_uring_try_cancel_iowq(ctx);
9831 } else if (tctx && tctx->io_wq) {
9833 * Cancels requests of all rings, not only @ctx, but
9834 * it's fine as the task is in exit/exec.
9836 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9838 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9841 /* SQPOLL thread does its own polling */
9842 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9843 (ctx->sq_data && ctx->sq_data->thread == current)) {
9844 while (!list_empty_careful(&ctx->iopoll_list)) {
9845 io_iopoll_try_reap_events(ctx);
9850 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9851 ret |= io_poll_remove_all(ctx, task, cancel_all);
9852 ret |= io_kill_timeouts(ctx, task, cancel_all);
9854 ret |= io_run_task_work();
9861 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9863 struct io_uring_task *tctx = current->io_uring;
9864 struct io_tctx_node *node;
9867 if (unlikely(!tctx)) {
9868 ret = io_uring_alloc_task_context(current, ctx);
9872 tctx = current->io_uring;
9873 if (ctx->iowq_limits_set) {
9874 unsigned int limits[2] = { ctx->iowq_limits[0],
9875 ctx->iowq_limits[1], };
9877 ret = io_wq_max_workers(tctx->io_wq, limits);
9882 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9883 node = kmalloc(sizeof(*node), GFP_KERNEL);
9887 node->task = current;
9889 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9896 mutex_lock(&ctx->uring_lock);
9897 list_add(&node->ctx_node, &ctx->tctx_list);
9898 mutex_unlock(&ctx->uring_lock);
9905 * Note that this task has used io_uring. We use it for cancelation purposes.
9907 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9909 struct io_uring_task *tctx = current->io_uring;
9911 if (likely(tctx && tctx->last == ctx))
9913 return __io_uring_add_tctx_node(ctx);
9917 * Remove this io_uring_file -> task mapping.
9919 static void io_uring_del_tctx_node(unsigned long index)
9921 struct io_uring_task *tctx = current->io_uring;
9922 struct io_tctx_node *node;
9926 node = xa_erase(&tctx->xa, index);
9930 WARN_ON_ONCE(current != node->task);
9931 WARN_ON_ONCE(list_empty(&node->ctx_node));
9933 mutex_lock(&node->ctx->uring_lock);
9934 list_del(&node->ctx_node);
9935 mutex_unlock(&node->ctx->uring_lock);
9937 if (tctx->last == node->ctx)
9942 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9944 struct io_wq *wq = tctx->io_wq;
9945 struct io_tctx_node *node;
9946 unsigned long index;
9948 xa_for_each(&tctx->xa, index, node) {
9949 io_uring_del_tctx_node(index);
9954 * Must be after io_uring_del_task_file() (removes nodes under
9955 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9957 io_wq_put_and_exit(wq);
9962 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9965 return atomic_read(&tctx->inflight_tracked);
9966 return percpu_counter_sum(&tctx->inflight);
9970 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9971 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9973 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9975 struct io_uring_task *tctx = current->io_uring;
9976 struct io_ring_ctx *ctx;
9980 WARN_ON_ONCE(sqd && sqd->thread != current);
9982 if (!current->io_uring)
9985 io_wq_exit_start(tctx->io_wq);
9987 atomic_inc(&tctx->in_idle);
9989 io_uring_drop_tctx_refs(current);
9990 /* read completions before cancelations */
9991 inflight = tctx_inflight(tctx, !cancel_all);
9996 struct io_tctx_node *node;
9997 unsigned long index;
9999 xa_for_each(&tctx->xa, index, node) {
10000 /* sqpoll task will cancel all its requests */
10001 if (node->ctx->sq_data)
10003 io_uring_try_cancel_requests(node->ctx, current,
10007 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10008 io_uring_try_cancel_requests(ctx, current,
10012 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10013 io_run_task_work();
10014 io_uring_drop_tctx_refs(current);
10017 * If we've seen completions, retry without waiting. This
10018 * avoids a race where a completion comes in before we did
10019 * prepare_to_wait().
10021 if (inflight == tctx_inflight(tctx, !cancel_all))
10023 finish_wait(&tctx->wait, &wait);
10026 io_uring_clean_tctx(tctx);
10029 * We shouldn't run task_works after cancel, so just leave
10030 * ->in_idle set for normal exit.
10032 atomic_dec(&tctx->in_idle);
10033 /* for exec all current's requests should be gone, kill tctx */
10034 __io_uring_free(current);
10038 void __io_uring_cancel(bool cancel_all)
10040 io_uring_cancel_generic(cancel_all, NULL);
10043 static void *io_uring_validate_mmap_request(struct file *file,
10044 loff_t pgoff, size_t sz)
10046 struct io_ring_ctx *ctx = file->private_data;
10047 loff_t offset = pgoff << PAGE_SHIFT;
10052 case IORING_OFF_SQ_RING:
10053 case IORING_OFF_CQ_RING:
10056 case IORING_OFF_SQES:
10057 ptr = ctx->sq_sqes;
10060 return ERR_PTR(-EINVAL);
10063 page = virt_to_head_page(ptr);
10064 if (sz > page_size(page))
10065 return ERR_PTR(-EINVAL);
10072 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10074 size_t sz = vma->vm_end - vma->vm_start;
10078 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10080 return PTR_ERR(ptr);
10082 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10083 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10086 #else /* !CONFIG_MMU */
10088 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10090 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10093 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10095 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10098 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10099 unsigned long addr, unsigned long len,
10100 unsigned long pgoff, unsigned long flags)
10104 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10106 return PTR_ERR(ptr);
10108 return (unsigned long) ptr;
10111 #endif /* !CONFIG_MMU */
10113 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10118 if (!io_sqring_full(ctx))
10120 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10122 if (!io_sqring_full(ctx))
10125 } while (!signal_pending(current));
10127 finish_wait(&ctx->sqo_sq_wait, &wait);
10131 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10132 struct __kernel_timespec __user **ts,
10133 const sigset_t __user **sig)
10135 struct io_uring_getevents_arg arg;
10138 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10139 * is just a pointer to the sigset_t.
10141 if (!(flags & IORING_ENTER_EXT_ARG)) {
10142 *sig = (const sigset_t __user *) argp;
10148 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10149 * timespec and sigset_t pointers if good.
10151 if (*argsz != sizeof(arg))
10153 if (copy_from_user(&arg, argp, sizeof(arg)))
10157 *sig = u64_to_user_ptr(arg.sigmask);
10158 *argsz = arg.sigmask_sz;
10159 *ts = u64_to_user_ptr(arg.ts);
10163 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10164 u32, min_complete, u32, flags, const void __user *, argp,
10167 struct io_ring_ctx *ctx;
10172 io_run_task_work();
10174 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10175 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10179 if (unlikely(!f.file))
10183 if (unlikely(f.file->f_op != &io_uring_fops))
10187 ctx = f.file->private_data;
10188 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10192 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10196 * For SQ polling, the thread will do all submissions and completions.
10197 * Just return the requested submit count, and wake the thread if
10198 * we were asked to.
10201 if (ctx->flags & IORING_SETUP_SQPOLL) {
10202 io_cqring_overflow_flush(ctx);
10204 if (unlikely(ctx->sq_data->thread == NULL)) {
10208 if (flags & IORING_ENTER_SQ_WAKEUP)
10209 wake_up(&ctx->sq_data->wait);
10210 if (flags & IORING_ENTER_SQ_WAIT) {
10211 ret = io_sqpoll_wait_sq(ctx);
10215 submitted = to_submit;
10216 } else if (to_submit) {
10217 ret = io_uring_add_tctx_node(ctx);
10220 mutex_lock(&ctx->uring_lock);
10221 submitted = io_submit_sqes(ctx, to_submit);
10222 mutex_unlock(&ctx->uring_lock);
10224 if (submitted != to_submit)
10227 if (flags & IORING_ENTER_GETEVENTS) {
10228 const sigset_t __user *sig;
10229 struct __kernel_timespec __user *ts;
10231 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10235 min_complete = min(min_complete, ctx->cq_entries);
10238 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10239 * space applications don't need to do io completion events
10240 * polling again, they can rely on io_sq_thread to do polling
10241 * work, which can reduce cpu usage and uring_lock contention.
10243 if (ctx->flags & IORING_SETUP_IOPOLL &&
10244 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10245 ret = io_iopoll_check(ctx, min_complete);
10247 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10252 percpu_ref_put(&ctx->refs);
10255 return submitted ? submitted : ret;
10258 #ifdef CONFIG_PROC_FS
10259 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
10260 const struct cred *cred)
10262 struct user_namespace *uns = seq_user_ns(m);
10263 struct group_info *gi;
10268 seq_printf(m, "%5d\n", id);
10269 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10270 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10271 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10272 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10273 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10274 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10275 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10276 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10277 seq_puts(m, "\n\tGroups:\t");
10278 gi = cred->group_info;
10279 for (g = 0; g < gi->ngroups; g++) {
10280 seq_put_decimal_ull(m, g ? " " : "",
10281 from_kgid_munged(uns, gi->gid[g]));
10283 seq_puts(m, "\n\tCapEff:\t");
10284 cap = cred->cap_effective;
10285 CAP_FOR_EACH_U32(__capi)
10286 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10291 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
10293 struct io_sq_data *sq = NULL;
10298 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10299 * since fdinfo case grabs it in the opposite direction of normal use
10300 * cases. If we fail to get the lock, we just don't iterate any
10301 * structures that could be going away outside the io_uring mutex.
10303 has_lock = mutex_trylock(&ctx->uring_lock);
10305 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10311 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10312 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10313 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10314 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10315 struct file *f = io_file_from_index(ctx, i);
10318 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10320 seq_printf(m, "%5u: <none>\n", i);
10322 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10323 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10324 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10325 unsigned int len = buf->ubuf_end - buf->ubuf;
10327 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10329 if (has_lock && !xa_empty(&ctx->personalities)) {
10330 unsigned long index;
10331 const struct cred *cred;
10333 seq_printf(m, "Personalities:\n");
10334 xa_for_each(&ctx->personalities, index, cred)
10335 io_uring_show_cred(m, index, cred);
10337 seq_printf(m, "PollList:\n");
10338 spin_lock(&ctx->completion_lock);
10339 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10340 struct hlist_head *list = &ctx->cancel_hash[i];
10341 struct io_kiocb *req;
10343 hlist_for_each_entry(req, list, hash_node)
10344 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10345 req->task->task_works != NULL);
10347 spin_unlock(&ctx->completion_lock);
10349 mutex_unlock(&ctx->uring_lock);
10352 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10354 struct io_ring_ctx *ctx = f->private_data;
10356 if (percpu_ref_tryget(&ctx->refs)) {
10357 __io_uring_show_fdinfo(ctx, m);
10358 percpu_ref_put(&ctx->refs);
10363 static const struct file_operations io_uring_fops = {
10364 .release = io_uring_release,
10365 .mmap = io_uring_mmap,
10367 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10368 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10370 .poll = io_uring_poll,
10371 #ifdef CONFIG_PROC_FS
10372 .show_fdinfo = io_uring_show_fdinfo,
10376 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10377 struct io_uring_params *p)
10379 struct io_rings *rings;
10380 size_t size, sq_array_offset;
10382 /* make sure these are sane, as we already accounted them */
10383 ctx->sq_entries = p->sq_entries;
10384 ctx->cq_entries = p->cq_entries;
10386 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10387 if (size == SIZE_MAX)
10390 rings = io_mem_alloc(size);
10394 ctx->rings = rings;
10395 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10396 rings->sq_ring_mask = p->sq_entries - 1;
10397 rings->cq_ring_mask = p->cq_entries - 1;
10398 rings->sq_ring_entries = p->sq_entries;
10399 rings->cq_ring_entries = p->cq_entries;
10401 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10402 if (size == SIZE_MAX) {
10403 io_mem_free(ctx->rings);
10408 ctx->sq_sqes = io_mem_alloc(size);
10409 if (!ctx->sq_sqes) {
10410 io_mem_free(ctx->rings);
10418 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10422 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10426 ret = io_uring_add_tctx_node(ctx);
10431 fd_install(fd, file);
10436 * Allocate an anonymous fd, this is what constitutes the application
10437 * visible backing of an io_uring instance. The application mmaps this
10438 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10439 * we have to tie this fd to a socket for file garbage collection purposes.
10441 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10444 #if defined(CONFIG_UNIX)
10447 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10450 return ERR_PTR(ret);
10453 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10454 O_RDWR | O_CLOEXEC);
10455 #if defined(CONFIG_UNIX)
10456 if (IS_ERR(file)) {
10457 sock_release(ctx->ring_sock);
10458 ctx->ring_sock = NULL;
10460 ctx->ring_sock->file = file;
10466 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10467 struct io_uring_params __user *params)
10469 struct io_ring_ctx *ctx;
10475 if (entries > IORING_MAX_ENTRIES) {
10476 if (!(p->flags & IORING_SETUP_CLAMP))
10478 entries = IORING_MAX_ENTRIES;
10482 * Use twice as many entries for the CQ ring. It's possible for the
10483 * application to drive a higher depth than the size of the SQ ring,
10484 * since the sqes are only used at submission time. This allows for
10485 * some flexibility in overcommitting a bit. If the application has
10486 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10487 * of CQ ring entries manually.
10489 p->sq_entries = roundup_pow_of_two(entries);
10490 if (p->flags & IORING_SETUP_CQSIZE) {
10492 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10493 * to a power-of-two, if it isn't already. We do NOT impose
10494 * any cq vs sq ring sizing.
10496 if (!p->cq_entries)
10498 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10499 if (!(p->flags & IORING_SETUP_CLAMP))
10501 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10503 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10504 if (p->cq_entries < p->sq_entries)
10507 p->cq_entries = 2 * p->sq_entries;
10510 ctx = io_ring_ctx_alloc(p);
10513 ctx->compat = in_compat_syscall();
10514 if (!capable(CAP_IPC_LOCK))
10515 ctx->user = get_uid(current_user());
10518 * This is just grabbed for accounting purposes. When a process exits,
10519 * the mm is exited and dropped before the files, hence we need to hang
10520 * on to this mm purely for the purposes of being able to unaccount
10521 * memory (locked/pinned vm). It's not used for anything else.
10523 mmgrab(current->mm);
10524 ctx->mm_account = current->mm;
10526 ret = io_allocate_scq_urings(ctx, p);
10530 ret = io_sq_offload_create(ctx, p);
10533 /* always set a rsrc node */
10534 ret = io_rsrc_node_switch_start(ctx);
10537 io_rsrc_node_switch(ctx, NULL);
10539 memset(&p->sq_off, 0, sizeof(p->sq_off));
10540 p->sq_off.head = offsetof(struct io_rings, sq.head);
10541 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10542 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10543 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10544 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10545 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10546 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10548 memset(&p->cq_off, 0, sizeof(p->cq_off));
10549 p->cq_off.head = offsetof(struct io_rings, cq.head);
10550 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10551 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10552 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10553 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10554 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10555 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10557 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10558 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10559 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10560 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10561 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10562 IORING_FEAT_RSRC_TAGS;
10564 if (copy_to_user(params, p, sizeof(*p))) {
10569 file = io_uring_get_file(ctx);
10570 if (IS_ERR(file)) {
10571 ret = PTR_ERR(file);
10576 * Install ring fd as the very last thing, so we don't risk someone
10577 * having closed it before we finish setup
10579 ret = io_uring_install_fd(ctx, file);
10581 /* fput will clean it up */
10586 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10589 io_ring_ctx_wait_and_kill(ctx);
10594 * Sets up an aio uring context, and returns the fd. Applications asks for a
10595 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10596 * params structure passed in.
10598 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10600 struct io_uring_params p;
10603 if (copy_from_user(&p, params, sizeof(p)))
10605 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10610 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10611 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10612 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10613 IORING_SETUP_R_DISABLED))
10616 return io_uring_create(entries, &p, params);
10619 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10620 struct io_uring_params __user *, params)
10622 return io_uring_setup(entries, params);
10625 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10627 struct io_uring_probe *p;
10631 size = struct_size(p, ops, nr_args);
10632 if (size == SIZE_MAX)
10634 p = kzalloc(size, GFP_KERNEL);
10639 if (copy_from_user(p, arg, size))
10642 if (memchr_inv(p, 0, size))
10645 p->last_op = IORING_OP_LAST - 1;
10646 if (nr_args > IORING_OP_LAST)
10647 nr_args = IORING_OP_LAST;
10649 for (i = 0; i < nr_args; i++) {
10651 if (!io_op_defs[i].not_supported)
10652 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10657 if (copy_to_user(arg, p, size))
10664 static int io_register_personality(struct io_ring_ctx *ctx)
10666 const struct cred *creds;
10670 creds = get_current_cred();
10672 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10673 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10681 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10682 unsigned int nr_args)
10684 struct io_uring_restriction *res;
10688 /* Restrictions allowed only if rings started disabled */
10689 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10692 /* We allow only a single restrictions registration */
10693 if (ctx->restrictions.registered)
10696 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10699 size = array_size(nr_args, sizeof(*res));
10700 if (size == SIZE_MAX)
10703 res = memdup_user(arg, size);
10705 return PTR_ERR(res);
10709 for (i = 0; i < nr_args; i++) {
10710 switch (res[i].opcode) {
10711 case IORING_RESTRICTION_REGISTER_OP:
10712 if (res[i].register_op >= IORING_REGISTER_LAST) {
10717 __set_bit(res[i].register_op,
10718 ctx->restrictions.register_op);
10720 case IORING_RESTRICTION_SQE_OP:
10721 if (res[i].sqe_op >= IORING_OP_LAST) {
10726 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10728 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10729 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10731 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10732 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10741 /* Reset all restrictions if an error happened */
10743 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10745 ctx->restrictions.registered = true;
10751 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10753 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10756 if (ctx->restrictions.registered)
10757 ctx->restricted = 1;
10759 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10760 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10761 wake_up(&ctx->sq_data->wait);
10765 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10766 struct io_uring_rsrc_update2 *up,
10772 if (check_add_overflow(up->offset, nr_args, &tmp))
10774 err = io_rsrc_node_switch_start(ctx);
10779 case IORING_RSRC_FILE:
10780 return __io_sqe_files_update(ctx, up, nr_args);
10781 case IORING_RSRC_BUFFER:
10782 return __io_sqe_buffers_update(ctx, up, nr_args);
10787 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10790 struct io_uring_rsrc_update2 up;
10794 memset(&up, 0, sizeof(up));
10795 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10797 if (up.resv || up.resv2)
10799 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10802 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10803 unsigned size, unsigned type)
10805 struct io_uring_rsrc_update2 up;
10807 if (size != sizeof(up))
10809 if (copy_from_user(&up, arg, sizeof(up)))
10811 if (!up.nr || up.resv || up.resv2)
10813 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10816 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10817 unsigned int size, unsigned int type)
10819 struct io_uring_rsrc_register rr;
10821 /* keep it extendible */
10822 if (size != sizeof(rr))
10825 memset(&rr, 0, sizeof(rr));
10826 if (copy_from_user(&rr, arg, size))
10828 if (!rr.nr || rr.resv || rr.resv2)
10832 case IORING_RSRC_FILE:
10833 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10834 rr.nr, u64_to_user_ptr(rr.tags));
10835 case IORING_RSRC_BUFFER:
10836 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10837 rr.nr, u64_to_user_ptr(rr.tags));
10842 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10845 struct io_uring_task *tctx = current->io_uring;
10846 cpumask_var_t new_mask;
10849 if (!tctx || !tctx->io_wq)
10852 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10855 cpumask_clear(new_mask);
10856 if (len > cpumask_size())
10857 len = cpumask_size();
10859 if (in_compat_syscall()) {
10860 ret = compat_get_bitmap(cpumask_bits(new_mask),
10861 (const compat_ulong_t __user *)arg,
10862 len * 8 /* CHAR_BIT */);
10864 ret = copy_from_user(new_mask, arg, len);
10868 free_cpumask_var(new_mask);
10872 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10873 free_cpumask_var(new_mask);
10877 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10879 struct io_uring_task *tctx = current->io_uring;
10881 if (!tctx || !tctx->io_wq)
10884 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10887 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10889 __must_hold(&ctx->uring_lock)
10891 struct io_tctx_node *node;
10892 struct io_uring_task *tctx = NULL;
10893 struct io_sq_data *sqd = NULL;
10894 __u32 new_count[2];
10897 if (copy_from_user(new_count, arg, sizeof(new_count)))
10899 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10900 if (new_count[i] > INT_MAX)
10903 if (ctx->flags & IORING_SETUP_SQPOLL) {
10904 sqd = ctx->sq_data;
10907 * Observe the correct sqd->lock -> ctx->uring_lock
10908 * ordering. Fine to drop uring_lock here, we hold
10909 * a ref to the ctx.
10911 refcount_inc(&sqd->refs);
10912 mutex_unlock(&ctx->uring_lock);
10913 mutex_lock(&sqd->lock);
10914 mutex_lock(&ctx->uring_lock);
10916 tctx = sqd->thread->io_uring;
10919 tctx = current->io_uring;
10922 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10924 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10926 ctx->iowq_limits[i] = new_count[i];
10927 ctx->iowq_limits_set = true;
10930 if (tctx && tctx->io_wq) {
10931 ret = io_wq_max_workers(tctx->io_wq, new_count);
10935 memset(new_count, 0, sizeof(new_count));
10939 mutex_unlock(&sqd->lock);
10940 io_put_sq_data(sqd);
10943 if (copy_to_user(arg, new_count, sizeof(new_count)))
10946 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10950 /* now propagate the restriction to all registered users */
10951 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10952 struct io_uring_task *tctx = node->task->io_uring;
10954 if (WARN_ON_ONCE(!tctx->io_wq))
10957 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10958 new_count[i] = ctx->iowq_limits[i];
10959 /* ignore errors, it always returns zero anyway */
10960 (void)io_wq_max_workers(tctx->io_wq, new_count);
10965 mutex_unlock(&sqd->lock);
10966 io_put_sq_data(sqd);
10971 static bool io_register_op_must_quiesce(int op)
10974 case IORING_REGISTER_BUFFERS:
10975 case IORING_UNREGISTER_BUFFERS:
10976 case IORING_REGISTER_FILES:
10977 case IORING_UNREGISTER_FILES:
10978 case IORING_REGISTER_FILES_UPDATE:
10979 case IORING_REGISTER_PROBE:
10980 case IORING_REGISTER_PERSONALITY:
10981 case IORING_UNREGISTER_PERSONALITY:
10982 case IORING_REGISTER_FILES2:
10983 case IORING_REGISTER_FILES_UPDATE2:
10984 case IORING_REGISTER_BUFFERS2:
10985 case IORING_REGISTER_BUFFERS_UPDATE:
10986 case IORING_REGISTER_IOWQ_AFF:
10987 case IORING_UNREGISTER_IOWQ_AFF:
10988 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10995 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10999 percpu_ref_kill(&ctx->refs);
11002 * Drop uring mutex before waiting for references to exit. If another
11003 * thread is currently inside io_uring_enter() it might need to grab the
11004 * uring_lock to make progress. If we hold it here across the drain
11005 * wait, then we can deadlock. It's safe to drop the mutex here, since
11006 * no new references will come in after we've killed the percpu ref.
11008 mutex_unlock(&ctx->uring_lock);
11010 ret = wait_for_completion_interruptible(&ctx->ref_comp);
11013 ret = io_run_task_work_sig();
11014 } while (ret >= 0);
11015 mutex_lock(&ctx->uring_lock);
11018 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
11022 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11023 void __user *arg, unsigned nr_args)
11024 __releases(ctx->uring_lock)
11025 __acquires(ctx->uring_lock)
11030 * We're inside the ring mutex, if the ref is already dying, then
11031 * someone else killed the ctx or is already going through
11032 * io_uring_register().
11034 if (percpu_ref_is_dying(&ctx->refs))
11037 if (ctx->restricted) {
11038 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11039 if (!test_bit(opcode, ctx->restrictions.register_op))
11043 if (io_register_op_must_quiesce(opcode)) {
11044 ret = io_ctx_quiesce(ctx);
11050 case IORING_REGISTER_BUFFERS:
11051 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11053 case IORING_UNREGISTER_BUFFERS:
11055 if (arg || nr_args)
11057 ret = io_sqe_buffers_unregister(ctx);
11059 case IORING_REGISTER_FILES:
11060 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11062 case IORING_UNREGISTER_FILES:
11064 if (arg || nr_args)
11066 ret = io_sqe_files_unregister(ctx);
11068 case IORING_REGISTER_FILES_UPDATE:
11069 ret = io_register_files_update(ctx, arg, nr_args);
11071 case IORING_REGISTER_EVENTFD:
11072 case IORING_REGISTER_EVENTFD_ASYNC:
11076 ret = io_eventfd_register(ctx, arg);
11079 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
11080 ctx->eventfd_async = 1;
11082 ctx->eventfd_async = 0;
11084 case IORING_UNREGISTER_EVENTFD:
11086 if (arg || nr_args)
11088 ret = io_eventfd_unregister(ctx);
11090 case IORING_REGISTER_PROBE:
11092 if (!arg || nr_args > 256)
11094 ret = io_probe(ctx, arg, nr_args);
11096 case IORING_REGISTER_PERSONALITY:
11098 if (arg || nr_args)
11100 ret = io_register_personality(ctx);
11102 case IORING_UNREGISTER_PERSONALITY:
11106 ret = io_unregister_personality(ctx, nr_args);
11108 case IORING_REGISTER_ENABLE_RINGS:
11110 if (arg || nr_args)
11112 ret = io_register_enable_rings(ctx);
11114 case IORING_REGISTER_RESTRICTIONS:
11115 ret = io_register_restrictions(ctx, arg, nr_args);
11117 case IORING_REGISTER_FILES2:
11118 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11120 case IORING_REGISTER_FILES_UPDATE2:
11121 ret = io_register_rsrc_update(ctx, arg, nr_args,
11124 case IORING_REGISTER_BUFFERS2:
11125 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11127 case IORING_REGISTER_BUFFERS_UPDATE:
11128 ret = io_register_rsrc_update(ctx, arg, nr_args,
11129 IORING_RSRC_BUFFER);
11131 case IORING_REGISTER_IOWQ_AFF:
11133 if (!arg || !nr_args)
11135 ret = io_register_iowq_aff(ctx, arg, nr_args);
11137 case IORING_UNREGISTER_IOWQ_AFF:
11139 if (arg || nr_args)
11141 ret = io_unregister_iowq_aff(ctx);
11143 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11145 if (!arg || nr_args != 2)
11147 ret = io_register_iowq_max_workers(ctx, arg);
11154 if (io_register_op_must_quiesce(opcode)) {
11155 /* bring the ctx back to life */
11156 percpu_ref_reinit(&ctx->refs);
11157 reinit_completion(&ctx->ref_comp);
11162 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11163 void __user *, arg, unsigned int, nr_args)
11165 struct io_ring_ctx *ctx;
11169 if (opcode >= IORING_REGISTER_LAST)
11177 if (f.file->f_op != &io_uring_fops)
11180 ctx = f.file->private_data;
11182 io_run_task_work();
11184 mutex_lock(&ctx->uring_lock);
11185 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11186 mutex_unlock(&ctx->uring_lock);
11187 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11188 ctx->cq_ev_fd != NULL, ret);
11194 static int __init io_uring_init(void)
11196 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11197 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11198 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11201 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11202 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11203 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11204 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11205 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11206 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11207 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11208 BUILD_BUG_SQE_ELEM(8, __u64, off);
11209 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11210 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11211 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11212 BUILD_BUG_SQE_ELEM(24, __u32, len);
11213 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11214 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11215 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11216 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11217 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11218 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11219 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11220 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11221 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11222 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11223 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11224 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11225 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11226 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11227 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11228 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11229 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11230 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11231 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11232 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11233 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11235 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11236 sizeof(struct io_uring_rsrc_update));
11237 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11238 sizeof(struct io_uring_rsrc_update2));
11240 /* ->buf_index is u16 */
11241 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11243 /* should fit into one byte */
11244 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11246 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11247 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11249 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11253 __initcall(io_uring_init);