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/blk-mq.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/audit.h>
82 #include <linux/security.h>
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
87 #include <uapi/linux/io_uring.h>
92 #define IORING_MAX_ENTRIES 32768
93 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
97 #define IORING_MAX_FIXED_FILES (1U << 20)
98 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
99 IORING_REGISTER_LAST + IORING_OP_LAST)
101 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
102 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
103 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
105 #define IORING_MAX_REG_BUFFERS (1U << 14)
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_CREDS | REQ_F_ASYNC_DATA)
116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
119 #define IO_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
121 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
124 u32 head ____cacheline_aligned_in_smp;
125 u32 tail ____cacheline_aligned_in_smp;
129 * This data is shared with the application through the mmap at offsets
130 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
132 * The offsets to the member fields are published through struct
133 * io_sqring_offsets when calling io_uring_setup.
137 * Head and tail offsets into the ring; the offsets need to be
138 * masked to get valid indices.
140 * The kernel controls head of the sq ring and the tail of the cq ring,
141 * and the application controls tail of the sq ring and the head of the
144 struct io_uring sq, cq;
146 * Bitmasks to apply to head and tail offsets (constant, equals
149 u32 sq_ring_mask, cq_ring_mask;
150 /* Ring sizes (constant, power of 2) */
151 u32 sq_ring_entries, cq_ring_entries;
153 * Number of invalid entries dropped by the kernel due to
154 * invalid index stored in array
156 * Written by the kernel, shouldn't be modified by the
157 * application (i.e. get number of "new events" by comparing to
160 * After a new SQ head value was read by the application this
161 * counter includes all submissions that were dropped reaching
162 * the new SQ head (and possibly more).
168 * Written by the kernel, shouldn't be modified by the
171 * The application needs a full memory barrier before checking
172 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
178 * Written by the application, shouldn't be modified by the
183 * Number of completion events lost because the queue was full;
184 * this should be avoided by the application by making sure
185 * there are not more requests pending than there is space in
186 * the completion queue.
188 * Written by the kernel, shouldn't be modified by the
189 * application (i.e. get number of "new events" by comparing to
192 * As completion events come in out of order this counter is not
193 * ordered with any other data.
197 * Ring buffer of completion events.
199 * The kernel writes completion events fresh every time they are
200 * produced, so the application is allowed to modify pending
203 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
206 enum io_uring_cmd_flags {
207 IO_URING_F_COMPLETE_DEFER = 1,
208 IO_URING_F_UNLOCKED = 2,
209 /* int's last bit, sign checks are usually faster than a bit test */
210 IO_URING_F_NONBLOCK = INT_MIN,
213 struct io_mapped_ubuf {
216 unsigned int nr_bvecs;
217 unsigned long acct_pages;
218 struct bio_vec bvec[];
223 struct io_overflow_cqe {
224 struct io_uring_cqe cqe;
225 struct list_head list;
229 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
230 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
231 * can't safely always dereference the file when the task has exited and ring
232 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
233 * process exit may reap it before __io_sqe_files_unregister() is run.
235 #define FFS_NOWAIT 0x1UL
236 #define FFS_ISREG 0x2UL
237 #if defined(CONFIG_64BIT)
238 #define FFS_SCM 0x4UL
240 #define IO_URING_SCM_ALL
241 #define FFS_SCM 0x0UL
243 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
245 struct io_fixed_file {
246 /* file * with additional FFS_* flags */
247 unsigned long file_ptr;
251 struct list_head list;
256 struct io_mapped_ubuf *buf;
260 struct io_file_table {
261 struct io_fixed_file *files;
262 unsigned long *bitmap;
263 unsigned int alloc_hint;
266 struct io_rsrc_node {
267 struct percpu_ref refs;
268 struct list_head node;
269 struct list_head rsrc_list;
270 struct io_rsrc_data *rsrc_data;
271 struct llist_node llist;
275 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
277 struct io_rsrc_data {
278 struct io_ring_ctx *ctx;
284 struct completion done;
288 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
289 struct io_buffer_list {
291 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
292 * then these are classic provided buffers and ->buf_list is used.
295 struct list_head buf_list;
297 struct page **buf_pages;
298 struct io_uring_buf_ring *buf_ring;
303 /* below is for ring provided buffers */
311 struct list_head list;
318 struct io_restriction {
319 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
320 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
321 u8 sqe_flags_allowed;
322 u8 sqe_flags_required;
327 IO_SQ_THREAD_SHOULD_STOP = 0,
328 IO_SQ_THREAD_SHOULD_PARK,
333 atomic_t park_pending;
336 /* ctx's that are using this sqd */
337 struct list_head ctx_list;
339 struct task_struct *thread;
340 struct wait_queue_head wait;
342 unsigned sq_thread_idle;
348 struct completion exited;
351 #define IO_COMPL_BATCH 32
352 #define IO_REQ_CACHE_SIZE 32
353 #define IO_REQ_ALLOC_BATCH 8
355 struct io_submit_link {
356 struct io_kiocb *head;
357 struct io_kiocb *last;
360 struct io_submit_state {
361 /* inline/task_work completion list, under ->uring_lock */
362 struct io_wq_work_node free_list;
363 /* batch completion logic */
364 struct io_wq_work_list compl_reqs;
365 struct io_submit_link link;
370 unsigned short submit_nr;
371 struct blk_plug plug;
375 struct eventfd_ctx *cq_ev_fd;
376 unsigned int eventfd_async: 1;
380 #define BGID_ARRAY 64
383 /* const or read-mostly hot data */
385 struct percpu_ref refs;
387 struct io_rings *rings;
389 enum task_work_notify_mode notify_method;
390 unsigned int compat: 1;
391 unsigned int drain_next: 1;
392 unsigned int restricted: 1;
393 unsigned int off_timeout_used: 1;
394 unsigned int drain_active: 1;
395 unsigned int drain_disabled: 1;
396 unsigned int has_evfd: 1;
397 unsigned int syscall_iopoll: 1;
398 } ____cacheline_aligned_in_smp;
400 /* submission data */
402 struct mutex uring_lock;
405 * Ring buffer of indices into array of io_uring_sqe, which is
406 * mmapped by the application using the IORING_OFF_SQES offset.
408 * This indirection could e.g. be used to assign fixed
409 * io_uring_sqe entries to operations and only submit them to
410 * the queue when needed.
412 * The kernel modifies neither the indices array nor the entries
416 struct io_uring_sqe *sq_sqes;
417 unsigned cached_sq_head;
419 struct list_head defer_list;
422 * Fixed resources fast path, should be accessed only under
423 * uring_lock, and updated through io_uring_register(2)
425 struct io_rsrc_node *rsrc_node;
426 int rsrc_cached_refs;
428 struct io_file_table file_table;
429 unsigned nr_user_files;
430 unsigned nr_user_bufs;
431 struct io_mapped_ubuf **user_bufs;
433 struct io_submit_state submit_state;
435 struct io_buffer_list *io_bl;
436 struct xarray io_bl_xa;
437 struct list_head io_buffers_cache;
439 struct list_head timeout_list;
440 struct list_head ltimeout_list;
441 struct list_head cq_overflow_list;
442 struct list_head apoll_cache;
443 struct xarray personalities;
445 unsigned sq_thread_idle;
446 } ____cacheline_aligned_in_smp;
448 /* IRQ completion list, under ->completion_lock */
449 struct io_wq_work_list locked_free_list;
450 unsigned int locked_free_nr;
452 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
453 struct io_sq_data *sq_data; /* if using sq thread polling */
455 struct wait_queue_head sqo_sq_wait;
456 struct list_head sqd_list;
458 unsigned long check_cq;
462 * We cache a range of free CQEs we can use, once exhausted it
463 * should go through a slower range setup, see __io_get_cqe()
465 struct io_uring_cqe *cqe_cached;
466 struct io_uring_cqe *cqe_sentinel;
468 unsigned cached_cq_tail;
470 struct io_ev_fd __rcu *io_ev_fd;
471 struct wait_queue_head cq_wait;
473 atomic_t cq_timeouts;
474 unsigned cq_last_tm_flush;
475 } ____cacheline_aligned_in_smp;
478 spinlock_t completion_lock;
480 spinlock_t timeout_lock;
483 * ->iopoll_list is protected by the ctx->uring_lock for
484 * io_uring instances that don't use IORING_SETUP_SQPOLL.
485 * For SQPOLL, only the single threaded io_sq_thread() will
486 * manipulate the list, hence no extra locking is needed there.
488 struct io_wq_work_list iopoll_list;
489 struct hlist_head *cancel_hash;
490 unsigned cancel_hash_bits;
491 bool poll_multi_queue;
493 struct list_head io_buffers_comp;
494 } ____cacheline_aligned_in_smp;
496 struct io_restriction restrictions;
498 /* slow path rsrc auxilary data, used by update/register */
500 struct io_rsrc_node *rsrc_backup_node;
501 struct io_mapped_ubuf *dummy_ubuf;
502 struct io_rsrc_data *file_data;
503 struct io_rsrc_data *buf_data;
505 struct delayed_work rsrc_put_work;
506 struct llist_head rsrc_put_llist;
507 struct list_head rsrc_ref_list;
508 spinlock_t rsrc_ref_lock;
510 struct list_head io_buffers_pages;
513 /* Keep this last, we don't need it for the fast path */
515 #if defined(CONFIG_UNIX)
516 struct socket *ring_sock;
518 /* hashed buffered write serialization */
519 struct io_wq_hash *hash_map;
521 /* Only used for accounting purposes */
522 struct user_struct *user;
523 struct mm_struct *mm_account;
525 /* ctx exit and cancelation */
526 struct llist_head fallback_llist;
527 struct delayed_work fallback_work;
528 struct work_struct exit_work;
529 struct list_head tctx_list;
530 struct completion ref_comp;
532 bool iowq_limits_set;
537 * Arbitrary limit, can be raised if need be
539 #define IO_RINGFD_REG_MAX 16
541 struct io_uring_task {
542 /* submission side */
545 struct wait_queue_head wait;
546 const struct io_ring_ctx *last;
548 struct percpu_counter inflight;
551 spinlock_t task_lock;
552 struct io_wq_work_list task_list;
553 struct io_wq_work_list prior_task_list;
554 struct callback_head task_work;
555 struct file **registered_rings;
560 * First field must be the file pointer in all the
561 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
563 struct io_poll_iocb {
565 struct wait_queue_head *head;
567 struct wait_queue_entry wait;
570 struct io_poll_update {
576 bool update_user_data;
585 struct io_timeout_data {
586 struct io_kiocb *req;
587 struct hrtimer timer;
588 struct timespec64 ts;
589 enum hrtimer_mode mode;
595 struct sockaddr __user *addr;
596 int __user *addr_len;
599 unsigned long nofile;
621 struct list_head list;
622 /* head of the link, used by linked timeouts only */
623 struct io_kiocb *head;
624 /* for linked completions */
625 struct io_kiocb *prev;
628 struct io_timeout_rem {
633 struct timespec64 ts;
639 /* NOTE: kiocb has the file as the first member, so don't do it here */
648 struct sockaddr __user *addr;
655 struct compat_msghdr __user *umsg_compat;
656 struct user_msghdr __user *umsg;
669 struct filename *filename;
671 unsigned long nofile;
674 struct io_rsrc_update {
700 struct epoll_event event;
704 struct file *file_out;
712 struct io_provide_buf {
726 struct filename *filename;
727 struct statx __user *buffer;
739 struct filename *oldpath;
740 struct filename *newpath;
748 struct filename *filename;
755 struct filename *filename;
761 struct filename *oldpath;
762 struct filename *newpath;
769 struct filename *oldpath;
770 struct filename *newpath;
780 struct io_async_connect {
781 struct sockaddr_storage address;
784 struct io_async_msghdr {
785 struct iovec fast_iov[UIO_FASTIOV];
786 /* points to an allocated iov, if NULL we use fast_iov instead */
787 struct iovec *free_iov;
788 struct sockaddr __user *uaddr;
790 struct sockaddr_storage addr;
794 struct iov_iter iter;
795 struct iov_iter_state iter_state;
796 struct iovec fast_iov[UIO_FASTIOV];
800 struct io_rw_state s;
801 const struct iovec *free_iovec;
803 struct wait_page_queue wpq;
807 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
808 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
809 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
810 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
811 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
812 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
813 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
815 /* first byte is taken by user flags, shift it to not overlap */
820 REQ_F_LINK_TIMEOUT_BIT,
821 REQ_F_NEED_CLEANUP_BIT,
823 REQ_F_BUFFER_SELECTED_BIT,
824 REQ_F_BUFFER_RING_BIT,
825 REQ_F_COMPLETE_INLINE_BIT,
829 REQ_F_ARM_LTIMEOUT_BIT,
830 REQ_F_ASYNC_DATA_BIT,
831 REQ_F_SKIP_LINK_CQES_BIT,
832 REQ_F_SINGLE_POLL_BIT,
833 REQ_F_DOUBLE_POLL_BIT,
834 REQ_F_PARTIAL_IO_BIT,
835 REQ_F_APOLL_MULTISHOT_BIT,
836 /* keep async read/write and isreg together and in order */
837 REQ_F_SUPPORT_NOWAIT_BIT,
840 /* not a real bit, just to check we're not overflowing the space */
846 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
847 /* drain existing IO first */
848 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
850 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
851 /* doesn't sever on completion < 0 */
852 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
854 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
855 /* IOSQE_BUFFER_SELECT */
856 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
857 /* IOSQE_CQE_SKIP_SUCCESS */
858 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
860 /* fail rest of links */
861 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
862 /* on inflight list, should be cancelled and waited on exit reliably */
863 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
864 /* read/write uses file position */
865 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
866 /* must not punt to workers */
867 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
868 /* has or had linked timeout */
869 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
871 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
872 /* already went through poll handler */
873 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
874 /* buffer already selected */
875 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
876 /* buffer selected from ring, needs commit */
877 REQ_F_BUFFER_RING = BIT(REQ_F_BUFFER_RING_BIT),
878 /* completion is deferred through io_comp_state */
879 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
880 /* caller should reissue async */
881 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
882 /* supports async reads/writes */
883 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
885 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
886 /* has creds assigned */
887 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
888 /* skip refcounting if not set */
889 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
890 /* there is a linked timeout that has to be armed */
891 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
892 /* ->async_data allocated */
893 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
894 /* don't post CQEs while failing linked requests */
895 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
896 /* single poll may be active */
897 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
898 /* double poll may active */
899 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
900 /* request has already done partial IO */
901 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
902 /* fast poll multishot mode */
903 REQ_F_APOLL_MULTISHOT = BIT(REQ_F_APOLL_MULTISHOT_BIT),
907 struct io_poll_iocb poll;
908 struct io_poll_iocb *double_poll;
911 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
913 struct io_task_work {
915 struct io_wq_work_node node;
916 struct llist_node fallback_node;
918 io_req_tw_func_t func;
922 IORING_RSRC_FILE = 0,
923 IORING_RSRC_BUFFER = 1,
929 /* fd initially, then cflags for completion */
937 IO_CHECK_CQ_OVERFLOW_BIT,
938 IO_CHECK_CQ_DROPPED_BIT,
942 * NOTE! Each of the iocb union members has the file pointer
943 * as the first entry in their struct definition. So you can
944 * access the file pointer through any of the sub-structs,
945 * or directly as just 'file' in this struct.
951 struct io_poll_iocb poll;
952 struct io_poll_update poll_update;
953 struct io_accept accept;
955 struct io_cancel cancel;
956 struct io_timeout timeout;
957 struct io_timeout_rem timeout_rem;
958 struct io_connect connect;
959 struct io_sr_msg sr_msg;
961 struct io_close close;
962 struct io_rsrc_update rsrc_update;
963 struct io_fadvise fadvise;
964 struct io_madvise madvise;
965 struct io_epoll epoll;
966 struct io_splice splice;
967 struct io_provide_buf pbuf;
968 struct io_statx statx;
969 struct io_shutdown shutdown;
970 struct io_rename rename;
971 struct io_unlink unlink;
972 struct io_mkdir mkdir;
973 struct io_symlink symlink;
974 struct io_hardlink hardlink;
979 /* polled IO has completed */
982 * Can be either a fixed buffer index, or used with provided buffers.
983 * For the latter, before issue it points to the buffer group ID,
984 * and after selection it points to the buffer ID itself.
991 struct io_ring_ctx *ctx;
992 struct task_struct *task;
994 struct io_rsrc_node *rsrc_node;
997 /* store used ubuf, so we can prevent reloading */
998 struct io_mapped_ubuf *imu;
1000 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1001 struct io_buffer *kbuf;
1004 * stores buffer ID for ring provided buffers, valid IFF
1005 * REQ_F_BUFFER_RING is set.
1007 struct io_buffer_list *buf_list;
1011 /* used by request caches, completion batching and iopoll */
1012 struct io_wq_work_node comp_list;
1013 /* cache ->apoll->events */
1018 struct io_task_work io_task_work;
1019 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1020 struct hlist_node hash_node;
1021 /* internal polling, see IORING_FEAT_FAST_POLL */
1022 struct async_poll *apoll;
1023 /* opcode allocated if it needs to store data for async defer */
1025 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1026 struct io_kiocb *link;
1027 /* custom credentials, valid IFF REQ_F_CREDS is set */
1028 const struct cred *creds;
1029 struct io_wq_work work;
1032 struct io_tctx_node {
1033 struct list_head ctx_node;
1034 struct task_struct *task;
1035 struct io_ring_ctx *ctx;
1038 struct io_defer_entry {
1039 struct list_head list;
1040 struct io_kiocb *req;
1044 struct io_cancel_data {
1045 struct io_ring_ctx *ctx;
1055 /* needs req->file assigned */
1056 unsigned needs_file : 1;
1057 /* should block plug */
1059 /* hash wq insertion if file is a regular file */
1060 unsigned hash_reg_file : 1;
1061 /* unbound wq insertion if file is a non-regular file */
1062 unsigned unbound_nonreg_file : 1;
1063 /* set if opcode supports polled "wait" */
1064 unsigned pollin : 1;
1065 unsigned pollout : 1;
1066 unsigned poll_exclusive : 1;
1067 /* op supports buffer selection */
1068 unsigned buffer_select : 1;
1069 /* do prep async if is going to be punted */
1070 unsigned needs_async_setup : 1;
1071 /* opcode is not supported by this kernel */
1072 unsigned not_supported : 1;
1074 unsigned audit_skip : 1;
1075 /* supports ioprio */
1076 unsigned ioprio : 1;
1077 /* supports iopoll */
1078 unsigned iopoll : 1;
1079 /* size of async data needed, if any */
1080 unsigned short async_size;
1083 static const struct io_op_def io_op_defs[] = {
1089 [IORING_OP_READV] = {
1091 .unbound_nonreg_file = 1,
1094 .needs_async_setup = 1,
1099 .async_size = sizeof(struct io_async_rw),
1101 [IORING_OP_WRITEV] = {
1104 .unbound_nonreg_file = 1,
1106 .needs_async_setup = 1,
1111 .async_size = sizeof(struct io_async_rw),
1113 [IORING_OP_FSYNC] = {
1117 [IORING_OP_READ_FIXED] = {
1119 .unbound_nonreg_file = 1,
1125 .async_size = sizeof(struct io_async_rw),
1127 [IORING_OP_WRITE_FIXED] = {
1130 .unbound_nonreg_file = 1,
1136 .async_size = sizeof(struct io_async_rw),
1138 [IORING_OP_POLL_ADD] = {
1140 .unbound_nonreg_file = 1,
1143 [IORING_OP_POLL_REMOVE] = {
1146 [IORING_OP_SYNC_FILE_RANGE] = {
1150 [IORING_OP_SENDMSG] = {
1152 .unbound_nonreg_file = 1,
1154 .needs_async_setup = 1,
1155 .async_size = sizeof(struct io_async_msghdr),
1157 [IORING_OP_RECVMSG] = {
1159 .unbound_nonreg_file = 1,
1162 .needs_async_setup = 1,
1163 .async_size = sizeof(struct io_async_msghdr),
1165 [IORING_OP_TIMEOUT] = {
1167 .async_size = sizeof(struct io_timeout_data),
1169 [IORING_OP_TIMEOUT_REMOVE] = {
1170 /* used by timeout updates' prep() */
1173 [IORING_OP_ACCEPT] = {
1175 .unbound_nonreg_file = 1,
1177 .poll_exclusive = 1,
1178 .ioprio = 1, /* used for flags */
1180 [IORING_OP_ASYNC_CANCEL] = {
1183 [IORING_OP_LINK_TIMEOUT] = {
1185 .async_size = sizeof(struct io_timeout_data),
1187 [IORING_OP_CONNECT] = {
1189 .unbound_nonreg_file = 1,
1191 .needs_async_setup = 1,
1192 .async_size = sizeof(struct io_async_connect),
1194 [IORING_OP_FALLOCATE] = {
1197 [IORING_OP_OPENAT] = {},
1198 [IORING_OP_CLOSE] = {},
1199 [IORING_OP_FILES_UPDATE] = {
1203 [IORING_OP_STATX] = {
1206 [IORING_OP_READ] = {
1208 .unbound_nonreg_file = 1,
1215 .async_size = sizeof(struct io_async_rw),
1217 [IORING_OP_WRITE] = {
1220 .unbound_nonreg_file = 1,
1226 .async_size = sizeof(struct io_async_rw),
1228 [IORING_OP_FADVISE] = {
1232 [IORING_OP_MADVISE] = {},
1233 [IORING_OP_SEND] = {
1235 .unbound_nonreg_file = 1,
1239 [IORING_OP_RECV] = {
1241 .unbound_nonreg_file = 1,
1246 [IORING_OP_OPENAT2] = {
1248 [IORING_OP_EPOLL_CTL] = {
1249 .unbound_nonreg_file = 1,
1252 [IORING_OP_SPLICE] = {
1255 .unbound_nonreg_file = 1,
1258 [IORING_OP_PROVIDE_BUFFERS] = {
1262 [IORING_OP_REMOVE_BUFFERS] = {
1269 .unbound_nonreg_file = 1,
1272 [IORING_OP_SHUTDOWN] = {
1275 [IORING_OP_RENAMEAT] = {},
1276 [IORING_OP_UNLINKAT] = {},
1277 [IORING_OP_MKDIRAT] = {},
1278 [IORING_OP_SYMLINKAT] = {},
1279 [IORING_OP_LINKAT] = {},
1280 [IORING_OP_MSG_RING] = {
1286 /* requests with any of those set should undergo io_disarm_next() */
1287 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1288 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1290 static bool io_disarm_next(struct io_kiocb *req);
1291 static void io_uring_del_tctx_node(unsigned long index);
1292 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1293 struct task_struct *task,
1295 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1297 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1298 static void io_dismantle_req(struct io_kiocb *req);
1299 static void io_queue_linked_timeout(struct io_kiocb *req);
1300 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1301 struct io_uring_rsrc_update2 *up,
1303 static void io_clean_op(struct io_kiocb *req);
1304 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1305 unsigned issue_flags);
1306 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1307 static void io_drop_inflight_file(struct io_kiocb *req);
1308 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1309 static void io_queue_sqe(struct io_kiocb *req);
1310 static void io_rsrc_put_work(struct work_struct *work);
1312 static void io_req_task_queue(struct io_kiocb *req);
1313 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1314 static int io_req_prep_async(struct io_kiocb *req);
1316 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1317 unsigned int issue_flags, u32 slot_index);
1318 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1320 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1321 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1322 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1324 static struct kmem_cache *req_cachep;
1326 static const struct file_operations io_uring_fops;
1328 struct sock *io_uring_get_socket(struct file *file)
1330 #if defined(CONFIG_UNIX)
1331 if (file->f_op == &io_uring_fops) {
1332 struct io_ring_ctx *ctx = file->private_data;
1334 return ctx->ring_sock->sk;
1339 EXPORT_SYMBOL(io_uring_get_socket);
1341 #if defined(CONFIG_UNIX)
1342 static inline bool io_file_need_scm(struct file *filp)
1344 #if defined(IO_URING_SCM_ALL)
1347 return !!unix_get_socket(filp);
1351 static inline bool io_file_need_scm(struct file *filp)
1357 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1359 lockdep_assert_held(&ctx->uring_lock);
1360 if (issue_flags & IO_URING_F_UNLOCKED)
1361 mutex_unlock(&ctx->uring_lock);
1364 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1367 * "Normal" inline submissions always hold the uring_lock, since we
1368 * grab it from the system call. Same is true for the SQPOLL offload.
1369 * The only exception is when we've detached the request and issue it
1370 * from an async worker thread, grab the lock for that case.
1372 if (issue_flags & IO_URING_F_UNLOCKED)
1373 mutex_lock(&ctx->uring_lock);
1374 lockdep_assert_held(&ctx->uring_lock);
1377 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1380 mutex_lock(&ctx->uring_lock);
1385 #define io_for_each_link(pos, head) \
1386 for (pos = (head); pos; pos = pos->link)
1389 * Shamelessly stolen from the mm implementation of page reference checking,
1390 * see commit f958d7b528b1 for details.
1392 #define req_ref_zero_or_close_to_overflow(req) \
1393 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1395 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1397 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1398 return atomic_inc_not_zero(&req->refs);
1401 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1403 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1406 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1407 return atomic_dec_and_test(&req->refs);
1410 static inline void req_ref_get(struct io_kiocb *req)
1412 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1413 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1414 atomic_inc(&req->refs);
1417 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1419 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1420 __io_submit_flush_completions(ctx);
1423 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1425 if (!(req->flags & REQ_F_REFCOUNT)) {
1426 req->flags |= REQ_F_REFCOUNT;
1427 atomic_set(&req->refs, nr);
1431 static inline void io_req_set_refcount(struct io_kiocb *req)
1433 __io_req_set_refcount(req, 1);
1436 #define IO_RSRC_REF_BATCH 100
1438 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1440 percpu_ref_put_many(&node->refs, nr);
1443 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1444 struct io_ring_ctx *ctx)
1445 __must_hold(&ctx->uring_lock)
1447 struct io_rsrc_node *node = req->rsrc_node;
1450 if (node == ctx->rsrc_node)
1451 ctx->rsrc_cached_refs++;
1453 io_rsrc_put_node(node, 1);
1457 static inline void io_req_put_rsrc(struct io_kiocb *req)
1460 io_rsrc_put_node(req->rsrc_node, 1);
1463 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1464 __must_hold(&ctx->uring_lock)
1466 if (ctx->rsrc_cached_refs) {
1467 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1468 ctx->rsrc_cached_refs = 0;
1472 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1473 __must_hold(&ctx->uring_lock)
1475 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1476 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1479 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1480 struct io_ring_ctx *ctx,
1481 unsigned int issue_flags)
1483 if (!req->rsrc_node) {
1484 req->rsrc_node = ctx->rsrc_node;
1486 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1487 lockdep_assert_held(&ctx->uring_lock);
1488 ctx->rsrc_cached_refs--;
1489 if (unlikely(ctx->rsrc_cached_refs < 0))
1490 io_rsrc_refs_refill(ctx);
1492 percpu_ref_get(&req->rsrc_node->refs);
1497 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1499 if (req->flags & REQ_F_BUFFER_RING) {
1501 req->buf_list->head++;
1502 req->flags &= ~REQ_F_BUFFER_RING;
1504 list_add(&req->kbuf->list, list);
1505 req->flags &= ~REQ_F_BUFFER_SELECTED;
1508 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1511 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1513 lockdep_assert_held(&req->ctx->completion_lock);
1515 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1517 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1520 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1521 unsigned issue_flags)
1523 unsigned int cflags;
1525 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1529 * We can add this buffer back to two lists:
1531 * 1) The io_buffers_cache list. This one is protected by the
1532 * ctx->uring_lock. If we already hold this lock, add back to this
1533 * list as we can grab it from issue as well.
1534 * 2) The io_buffers_comp list. This one is protected by the
1535 * ctx->completion_lock.
1537 * We migrate buffers from the comp_list to the issue cache list
1540 if (req->flags & REQ_F_BUFFER_RING) {
1541 /* no buffers to recycle for this case */
1542 cflags = __io_put_kbuf(req, NULL);
1543 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1544 struct io_ring_ctx *ctx = req->ctx;
1546 spin_lock(&ctx->completion_lock);
1547 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1548 spin_unlock(&ctx->completion_lock);
1550 lockdep_assert_held(&req->ctx->uring_lock);
1552 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1558 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1561 if (ctx->io_bl && bgid < BGID_ARRAY)
1562 return &ctx->io_bl[bgid];
1564 return xa_load(&ctx->io_bl_xa, bgid);
1567 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1569 struct io_ring_ctx *ctx = req->ctx;
1570 struct io_buffer_list *bl;
1571 struct io_buffer *buf;
1573 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1575 /* don't recycle if we already did IO to this buffer */
1576 if (req->flags & REQ_F_PARTIAL_IO)
1579 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1580 * the flag and hence ensure that bl->head doesn't get incremented.
1581 * If the tail has already been incremented, hang on to it.
1583 if (req->flags & REQ_F_BUFFER_RING) {
1584 if (req->buf_list) {
1585 req->buf_index = req->buf_list->bgid;
1586 req->flags &= ~REQ_F_BUFFER_RING;
1591 io_ring_submit_lock(ctx, issue_flags);
1594 bl = io_buffer_get_list(ctx, buf->bgid);
1595 list_add(&buf->list, &bl->buf_list);
1596 req->flags &= ~REQ_F_BUFFER_SELECTED;
1597 req->buf_index = buf->bgid;
1599 io_ring_submit_unlock(ctx, issue_flags);
1602 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1604 __must_hold(&req->ctx->timeout_lock)
1606 if (task && head->task != task)
1612 * As io_match_task() but protected against racing with linked timeouts.
1613 * User must not hold timeout_lock.
1615 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1618 if (task && head->task != task)
1623 static inline bool req_has_async_data(struct io_kiocb *req)
1625 return req->flags & REQ_F_ASYNC_DATA;
1628 static inline void req_set_fail(struct io_kiocb *req)
1630 req->flags |= REQ_F_FAIL;
1631 if (req->flags & REQ_F_CQE_SKIP) {
1632 req->flags &= ~REQ_F_CQE_SKIP;
1633 req->flags |= REQ_F_SKIP_LINK_CQES;
1637 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1643 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1645 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1648 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1650 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1652 complete(&ctx->ref_comp);
1655 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1657 return !req->timeout.off;
1660 static __cold void io_fallback_req_func(struct work_struct *work)
1662 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1663 fallback_work.work);
1664 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1665 struct io_kiocb *req, *tmp;
1666 bool locked = false;
1668 percpu_ref_get(&ctx->refs);
1669 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1670 req->io_task_work.func(req, &locked);
1673 io_submit_flush_completions(ctx);
1674 mutex_unlock(&ctx->uring_lock);
1676 percpu_ref_put(&ctx->refs);
1679 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1681 struct io_ring_ctx *ctx;
1684 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1688 xa_init(&ctx->io_bl_xa);
1691 * Use 5 bits less than the max cq entries, that should give us around
1692 * 32 entries per hash list if totally full and uniformly spread.
1694 hash_bits = ilog2(p->cq_entries);
1698 ctx->cancel_hash_bits = hash_bits;
1699 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1701 if (!ctx->cancel_hash)
1703 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1705 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1706 if (!ctx->dummy_ubuf)
1708 /* set invalid range, so io_import_fixed() fails meeting it */
1709 ctx->dummy_ubuf->ubuf = -1UL;
1711 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1712 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1715 ctx->flags = p->flags;
1716 init_waitqueue_head(&ctx->sqo_sq_wait);
1717 INIT_LIST_HEAD(&ctx->sqd_list);
1718 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1719 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1720 INIT_LIST_HEAD(&ctx->apoll_cache);
1721 init_completion(&ctx->ref_comp);
1722 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1723 mutex_init(&ctx->uring_lock);
1724 init_waitqueue_head(&ctx->cq_wait);
1725 spin_lock_init(&ctx->completion_lock);
1726 spin_lock_init(&ctx->timeout_lock);
1727 INIT_WQ_LIST(&ctx->iopoll_list);
1728 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1729 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1730 INIT_LIST_HEAD(&ctx->defer_list);
1731 INIT_LIST_HEAD(&ctx->timeout_list);
1732 INIT_LIST_HEAD(&ctx->ltimeout_list);
1733 spin_lock_init(&ctx->rsrc_ref_lock);
1734 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1735 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1736 init_llist_head(&ctx->rsrc_put_llist);
1737 INIT_LIST_HEAD(&ctx->tctx_list);
1738 ctx->submit_state.free_list.next = NULL;
1739 INIT_WQ_LIST(&ctx->locked_free_list);
1740 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1741 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1744 kfree(ctx->dummy_ubuf);
1745 kfree(ctx->cancel_hash);
1747 xa_destroy(&ctx->io_bl_xa);
1752 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1754 struct io_rings *r = ctx->rings;
1756 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1760 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1762 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1763 struct io_ring_ctx *ctx = req->ctx;
1765 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1771 static inline bool io_req_ffs_set(struct io_kiocb *req)
1773 return req->flags & REQ_F_FIXED_FILE;
1776 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1778 if (WARN_ON_ONCE(!req->link))
1781 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1782 req->flags |= REQ_F_LINK_TIMEOUT;
1784 /* linked timeouts should have two refs once prep'ed */
1785 io_req_set_refcount(req);
1786 __io_req_set_refcount(req->link, 2);
1790 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1792 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1794 return __io_prep_linked_timeout(req);
1797 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1799 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1802 static inline void io_arm_ltimeout(struct io_kiocb *req)
1804 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1805 __io_arm_ltimeout(req);
1808 static void io_prep_async_work(struct io_kiocb *req)
1810 const struct io_op_def *def = &io_op_defs[req->opcode];
1811 struct io_ring_ctx *ctx = req->ctx;
1813 if (!(req->flags & REQ_F_CREDS)) {
1814 req->flags |= REQ_F_CREDS;
1815 req->creds = get_current_cred();
1818 req->work.list.next = NULL;
1819 req->work.flags = 0;
1820 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1821 if (req->flags & REQ_F_FORCE_ASYNC)
1822 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1824 if (req->flags & REQ_F_ISREG) {
1825 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1826 io_wq_hash_work(&req->work, file_inode(req->file));
1827 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1828 if (def->unbound_nonreg_file)
1829 req->work.flags |= IO_WQ_WORK_UNBOUND;
1833 static void io_prep_async_link(struct io_kiocb *req)
1835 struct io_kiocb *cur;
1837 if (req->flags & REQ_F_LINK_TIMEOUT) {
1838 struct io_ring_ctx *ctx = req->ctx;
1840 spin_lock_irq(&ctx->timeout_lock);
1841 io_for_each_link(cur, req)
1842 io_prep_async_work(cur);
1843 spin_unlock_irq(&ctx->timeout_lock);
1845 io_for_each_link(cur, req)
1846 io_prep_async_work(cur);
1850 static inline void io_req_add_compl_list(struct io_kiocb *req)
1852 struct io_submit_state *state = &req->ctx->submit_state;
1854 if (!(req->flags & REQ_F_CQE_SKIP))
1855 state->flush_cqes = true;
1856 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1859 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1861 struct io_kiocb *link = io_prep_linked_timeout(req);
1862 struct io_uring_task *tctx = req->task->io_uring;
1865 BUG_ON(!tctx->io_wq);
1867 /* init ->work of the whole link before punting */
1868 io_prep_async_link(req);
1871 * Not expected to happen, but if we do have a bug where this _can_
1872 * happen, catch it here and ensure the request is marked as
1873 * canceled. That will make io-wq go through the usual work cancel
1874 * procedure rather than attempt to run this request (or create a new
1877 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1878 req->work.flags |= IO_WQ_WORK_CANCEL;
1880 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1881 req->opcode, req->flags, &req->work,
1882 io_wq_is_hashed(&req->work));
1883 io_wq_enqueue(tctx->io_wq, &req->work);
1885 io_queue_linked_timeout(link);
1888 static void io_kill_timeout(struct io_kiocb *req, int status)
1889 __must_hold(&req->ctx->completion_lock)
1890 __must_hold(&req->ctx->timeout_lock)
1892 struct io_timeout_data *io = req->async_data;
1894 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1897 atomic_set(&req->ctx->cq_timeouts,
1898 atomic_read(&req->ctx->cq_timeouts) + 1);
1899 list_del_init(&req->timeout.list);
1900 io_req_tw_post_queue(req, status, 0);
1904 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1906 while (!list_empty(&ctx->defer_list)) {
1907 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1908 struct io_defer_entry, list);
1910 if (req_need_defer(de->req, de->seq))
1912 list_del_init(&de->list);
1913 io_req_task_queue(de->req);
1918 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1919 __must_hold(&ctx->completion_lock)
1921 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1922 struct io_kiocb *req, *tmp;
1924 spin_lock_irq(&ctx->timeout_lock);
1925 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1926 u32 events_needed, events_got;
1928 if (io_is_timeout_noseq(req))
1932 * Since seq can easily wrap around over time, subtract
1933 * the last seq at which timeouts were flushed before comparing.
1934 * Assuming not more than 2^31-1 events have happened since,
1935 * these subtractions won't have wrapped, so we can check if
1936 * target is in [last_seq, current_seq] by comparing the two.
1938 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1939 events_got = seq - ctx->cq_last_tm_flush;
1940 if (events_got < events_needed)
1943 io_kill_timeout(req, 0);
1945 ctx->cq_last_tm_flush = seq;
1946 spin_unlock_irq(&ctx->timeout_lock);
1949 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1951 /* order cqe stores with ring update */
1952 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1955 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1957 if (ctx->off_timeout_used || ctx->drain_active) {
1958 spin_lock(&ctx->completion_lock);
1959 if (ctx->off_timeout_used)
1960 io_flush_timeouts(ctx);
1961 if (ctx->drain_active)
1962 io_queue_deferred(ctx);
1963 io_commit_cqring(ctx);
1964 spin_unlock(&ctx->completion_lock);
1967 io_eventfd_signal(ctx);
1970 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1972 struct io_rings *r = ctx->rings;
1974 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1977 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1979 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1983 * writes to the cq entry need to come after reading head; the
1984 * control dependency is enough as we're using WRITE_ONCE to
1987 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1989 struct io_rings *rings = ctx->rings;
1990 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1991 unsigned int free, queued, len;
1993 /* userspace may cheat modifying the tail, be safe and do min */
1994 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1995 free = ctx->cq_entries - queued;
1996 /* we need a contiguous range, limit based on the current array offset */
1997 len = min(free, ctx->cq_entries - off);
2001 ctx->cached_cq_tail++;
2002 ctx->cqe_cached = &rings->cqes[off];
2003 ctx->cqe_sentinel = ctx->cqe_cached + len;
2004 return ctx->cqe_cached++;
2007 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2009 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2010 ctx->cached_cq_tail++;
2011 return ctx->cqe_cached++;
2013 return __io_get_cqe(ctx);
2016 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2018 struct io_ev_fd *ev_fd;
2022 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2023 * and eventfd_signal
2025 ev_fd = rcu_dereference(ctx->io_ev_fd);
2028 * Check again if ev_fd exists incase an io_eventfd_unregister call
2029 * completed between the NULL check of ctx->io_ev_fd at the start of
2030 * the function and rcu_read_lock.
2032 if (unlikely(!ev_fd))
2034 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2037 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2038 eventfd_signal(ev_fd->cq_ev_fd, 1);
2043 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2046 * wake_up_all() may seem excessive, but io_wake_function() and
2047 * io_should_wake() handle the termination of the loop and only
2048 * wake as many waiters as we need to.
2050 if (wq_has_sleeper(&ctx->cq_wait))
2051 wake_up_all(&ctx->cq_wait);
2055 * This should only get called when at least one event has been posted.
2056 * Some applications rely on the eventfd notification count only changing
2057 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2058 * 1:1 relationship between how many times this function is called (and
2059 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2061 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2063 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2065 __io_commit_cqring_flush(ctx);
2067 io_cqring_wake(ctx);
2070 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2072 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2074 __io_commit_cqring_flush(ctx);
2076 if (ctx->flags & IORING_SETUP_SQPOLL)
2077 io_cqring_wake(ctx);
2080 /* Returns true if there are no backlogged entries after the flush */
2081 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2083 bool all_flushed, posted;
2085 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2089 spin_lock(&ctx->completion_lock);
2090 while (!list_empty(&ctx->cq_overflow_list)) {
2091 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2092 struct io_overflow_cqe *ocqe;
2096 ocqe = list_first_entry(&ctx->cq_overflow_list,
2097 struct io_overflow_cqe, list);
2099 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
2101 io_account_cq_overflow(ctx);
2104 list_del(&ocqe->list);
2108 all_flushed = list_empty(&ctx->cq_overflow_list);
2110 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2111 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2114 io_commit_cqring(ctx);
2115 spin_unlock(&ctx->completion_lock);
2117 io_cqring_ev_posted(ctx);
2121 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2125 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2126 /* iopoll syncs against uring_lock, not completion_lock */
2127 if (ctx->flags & IORING_SETUP_IOPOLL)
2128 mutex_lock(&ctx->uring_lock);
2129 ret = __io_cqring_overflow_flush(ctx, false);
2130 if (ctx->flags & IORING_SETUP_IOPOLL)
2131 mutex_unlock(&ctx->uring_lock);
2137 static void __io_put_task(struct task_struct *task, int nr)
2139 struct io_uring_task *tctx = task->io_uring;
2141 percpu_counter_sub(&tctx->inflight, nr);
2142 if (unlikely(atomic_read(&tctx->in_idle)))
2143 wake_up(&tctx->wait);
2144 put_task_struct_many(task, nr);
2147 /* must to be called somewhat shortly after putting a request */
2148 static inline void io_put_task(struct task_struct *task, int nr)
2150 if (likely(task == current))
2151 task->io_uring->cached_refs += nr;
2153 __io_put_task(task, nr);
2156 static void io_task_refs_refill(struct io_uring_task *tctx)
2158 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2160 percpu_counter_add(&tctx->inflight, refill);
2161 refcount_add(refill, ¤t->usage);
2162 tctx->cached_refs += refill;
2165 static inline void io_get_task_refs(int nr)
2167 struct io_uring_task *tctx = current->io_uring;
2169 tctx->cached_refs -= nr;
2170 if (unlikely(tctx->cached_refs < 0))
2171 io_task_refs_refill(tctx);
2174 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2176 struct io_uring_task *tctx = task->io_uring;
2177 unsigned int refs = tctx->cached_refs;
2180 tctx->cached_refs = 0;
2181 percpu_counter_sub(&tctx->inflight, refs);
2182 put_task_struct_many(task, refs);
2186 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2187 s32 res, u32 cflags)
2189 struct io_overflow_cqe *ocqe;
2191 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2192 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2195 * If we're in ring overflow flush mode, or in task cancel mode,
2196 * or cannot allocate an overflow entry, then we need to drop it
2199 io_account_cq_overflow(ctx);
2200 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2203 if (list_empty(&ctx->cq_overflow_list)) {
2204 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2205 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2208 ocqe->cqe.user_data = user_data;
2209 ocqe->cqe.res = res;
2210 ocqe->cqe.flags = cflags;
2211 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2215 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2216 s32 res, u32 cflags)
2218 struct io_uring_cqe *cqe;
2221 * If we can't get a cq entry, userspace overflowed the
2222 * submission (by quite a lot). Increment the overflow count in
2225 cqe = io_get_cqe(ctx);
2227 WRITE_ONCE(cqe->user_data, user_data);
2228 WRITE_ONCE(cqe->res, res);
2229 WRITE_ONCE(cqe->flags, cflags);
2232 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2235 static inline bool __io_fill_cqe_req_filled(struct io_ring_ctx *ctx,
2236 struct io_kiocb *req)
2238 struct io_uring_cqe *cqe;
2240 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2241 req->cqe.res, req->cqe.flags);
2244 * If we can't get a cq entry, userspace overflowed the
2245 * submission (by quite a lot). Increment the overflow count in
2248 cqe = io_get_cqe(ctx);
2250 memcpy(cqe, &req->cqe, sizeof(*cqe));
2253 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2254 req->cqe.res, req->cqe.flags);
2257 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2259 trace_io_uring_complete(req->ctx, req, req->cqe.user_data, res, cflags);
2260 return __io_fill_cqe(req->ctx, req->cqe.user_data, res, cflags);
2263 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2264 s32 res, u32 cflags)
2267 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2268 return __io_fill_cqe(ctx, user_data, res, cflags);
2271 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2274 struct io_ring_ctx *ctx = req->ctx;
2276 if (!(req->flags & REQ_F_CQE_SKIP))
2277 __io_fill_cqe_req(req, res, cflags);
2279 * If we're the last reference to this request, add to our locked
2282 if (req_ref_put_and_test(req)) {
2283 if (req->flags & IO_REQ_LINK_FLAGS) {
2284 if (req->flags & IO_DISARM_MASK)
2285 io_disarm_next(req);
2287 io_req_task_queue(req->link);
2291 io_req_put_rsrc(req);
2293 * Selected buffer deallocation in io_clean_op() assumes that
2294 * we don't hold ->completion_lock. Clean them here to avoid
2297 io_put_kbuf_comp(req);
2298 io_dismantle_req(req);
2299 io_put_task(req->task, 1);
2300 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2301 ctx->locked_free_nr++;
2305 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2308 struct io_ring_ctx *ctx = req->ctx;
2310 spin_lock(&ctx->completion_lock);
2311 __io_req_complete_post(req, res, cflags);
2312 io_commit_cqring(ctx);
2313 spin_unlock(&ctx->completion_lock);
2314 io_cqring_ev_posted(ctx);
2317 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2321 req->cqe.flags = cflags;
2322 req->flags |= REQ_F_COMPLETE_INLINE;
2325 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2326 s32 res, u32 cflags)
2328 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2329 io_req_complete_state(req, res, cflags);
2331 io_req_complete_post(req, res, cflags);
2334 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2336 __io_req_complete(req, 0, res, 0);
2339 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2342 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2346 * Don't initialise the fields below on every allocation, but do that in
2347 * advance and keep them valid across allocations.
2349 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2353 req->async_data = NULL;
2354 /* not necessary, but safer to zero */
2358 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2359 struct io_submit_state *state)
2361 spin_lock(&ctx->completion_lock);
2362 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2363 ctx->locked_free_nr = 0;
2364 spin_unlock(&ctx->completion_lock);
2367 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2369 return !ctx->submit_state.free_list.next;
2373 * A request might get retired back into the request caches even before opcode
2374 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2375 * Because of that, io_alloc_req() should be called only under ->uring_lock
2376 * and with extra caution to not get a request that is still worked on.
2378 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2379 __must_hold(&ctx->uring_lock)
2381 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2382 void *reqs[IO_REQ_ALLOC_BATCH];
2386 * If we have more than a batch's worth of requests in our IRQ side
2387 * locked cache, grab the lock and move them over to our submission
2390 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2391 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2392 if (!io_req_cache_empty(ctx))
2396 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2399 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2400 * retry single alloc to be on the safe side.
2402 if (unlikely(ret <= 0)) {
2403 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2409 percpu_ref_get_many(&ctx->refs, ret);
2410 for (i = 0; i < ret; i++) {
2411 struct io_kiocb *req = reqs[i];
2413 io_preinit_req(req, ctx);
2414 io_req_add_to_cache(req, ctx);
2419 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2421 if (unlikely(io_req_cache_empty(ctx)))
2422 return __io_alloc_req_refill(ctx);
2426 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2428 struct io_wq_work_node *node;
2430 node = wq_stack_extract(&ctx->submit_state.free_list);
2431 return container_of(node, struct io_kiocb, comp_list);
2434 static inline void io_put_file(struct file *file)
2440 static inline void io_dismantle_req(struct io_kiocb *req)
2442 unsigned int flags = req->flags;
2444 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2446 if (!(flags & REQ_F_FIXED_FILE))
2447 io_put_file(req->file);
2450 static __cold void io_free_req(struct io_kiocb *req)
2452 struct io_ring_ctx *ctx = req->ctx;
2454 io_req_put_rsrc(req);
2455 io_dismantle_req(req);
2456 io_put_task(req->task, 1);
2458 spin_lock(&ctx->completion_lock);
2459 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2460 ctx->locked_free_nr++;
2461 spin_unlock(&ctx->completion_lock);
2464 static inline void io_remove_next_linked(struct io_kiocb *req)
2466 struct io_kiocb *nxt = req->link;
2468 req->link = nxt->link;
2472 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2473 __must_hold(&req->ctx->completion_lock)
2474 __must_hold(&req->ctx->timeout_lock)
2476 struct io_kiocb *link = req->link;
2478 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2479 struct io_timeout_data *io = link->async_data;
2481 io_remove_next_linked(req);
2482 link->timeout.head = NULL;
2483 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2484 list_del(&link->timeout.list);
2491 static void io_fail_links(struct io_kiocb *req)
2492 __must_hold(&req->ctx->completion_lock)
2494 struct io_kiocb *nxt, *link = req->link;
2495 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2499 long res = -ECANCELED;
2501 if (link->flags & REQ_F_FAIL)
2502 res = link->cqe.res;
2507 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2511 link->flags |= REQ_F_CQE_SKIP;
2513 link->flags &= ~REQ_F_CQE_SKIP;
2514 __io_req_complete_post(link, res, 0);
2519 static bool io_disarm_next(struct io_kiocb *req)
2520 __must_hold(&req->ctx->completion_lock)
2522 struct io_kiocb *link = NULL;
2523 bool posted = false;
2525 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2527 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2528 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2529 io_remove_next_linked(req);
2530 io_req_tw_post_queue(link, -ECANCELED, 0);
2533 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2534 struct io_ring_ctx *ctx = req->ctx;
2536 spin_lock_irq(&ctx->timeout_lock);
2537 link = io_disarm_linked_timeout(req);
2538 spin_unlock_irq(&ctx->timeout_lock);
2541 io_req_tw_post_queue(link, -ECANCELED, 0);
2544 if (unlikely((req->flags & REQ_F_FAIL) &&
2545 !(req->flags & REQ_F_HARDLINK))) {
2546 posted |= (req->link != NULL);
2552 static void __io_req_find_next_prep(struct io_kiocb *req)
2554 struct io_ring_ctx *ctx = req->ctx;
2557 spin_lock(&ctx->completion_lock);
2558 posted = io_disarm_next(req);
2559 io_commit_cqring(ctx);
2560 spin_unlock(&ctx->completion_lock);
2562 io_cqring_ev_posted(ctx);
2565 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2567 struct io_kiocb *nxt;
2570 * If LINK is set, we have dependent requests in this chain. If we
2571 * didn't fail this request, queue the first one up, moving any other
2572 * dependencies to the next request. In case of failure, fail the rest
2575 if (unlikely(req->flags & IO_DISARM_MASK))
2576 __io_req_find_next_prep(req);
2582 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2586 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2587 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2589 io_submit_flush_completions(ctx);
2590 mutex_unlock(&ctx->uring_lock);
2593 percpu_ref_put(&ctx->refs);
2596 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2598 io_commit_cqring(ctx);
2599 spin_unlock(&ctx->completion_lock);
2600 io_cqring_ev_posted(ctx);
2603 static void handle_prev_tw_list(struct io_wq_work_node *node,
2604 struct io_ring_ctx **ctx, bool *uring_locked)
2606 if (*ctx && !*uring_locked)
2607 spin_lock(&(*ctx)->completion_lock);
2610 struct io_wq_work_node *next = node->next;
2611 struct io_kiocb *req = container_of(node, struct io_kiocb,
2614 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2616 if (req->ctx != *ctx) {
2617 if (unlikely(!*uring_locked && *ctx))
2618 ctx_commit_and_unlock(*ctx);
2620 ctx_flush_and_put(*ctx, uring_locked);
2622 /* if not contended, grab and improve batching */
2623 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2624 percpu_ref_get(&(*ctx)->refs);
2625 if (unlikely(!*uring_locked))
2626 spin_lock(&(*ctx)->completion_lock);
2628 if (likely(*uring_locked))
2629 req->io_task_work.func(req, uring_locked);
2631 __io_req_complete_post(req, req->cqe.res,
2632 io_put_kbuf_comp(req));
2636 if (unlikely(!*uring_locked))
2637 ctx_commit_and_unlock(*ctx);
2640 static void handle_tw_list(struct io_wq_work_node *node,
2641 struct io_ring_ctx **ctx, bool *locked)
2644 struct io_wq_work_node *next = node->next;
2645 struct io_kiocb *req = container_of(node, struct io_kiocb,
2648 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2650 if (req->ctx != *ctx) {
2651 ctx_flush_and_put(*ctx, locked);
2653 /* if not contended, grab and improve batching */
2654 *locked = mutex_trylock(&(*ctx)->uring_lock);
2655 percpu_ref_get(&(*ctx)->refs);
2657 req->io_task_work.func(req, locked);
2662 static void tctx_task_work(struct callback_head *cb)
2664 bool uring_locked = false;
2665 struct io_ring_ctx *ctx = NULL;
2666 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2670 struct io_wq_work_node *node1, *node2;
2672 spin_lock_irq(&tctx->task_lock);
2673 node1 = tctx->prior_task_list.first;
2674 node2 = tctx->task_list.first;
2675 INIT_WQ_LIST(&tctx->task_list);
2676 INIT_WQ_LIST(&tctx->prior_task_list);
2677 if (!node2 && !node1)
2678 tctx->task_running = false;
2679 spin_unlock_irq(&tctx->task_lock);
2680 if (!node2 && !node1)
2684 handle_prev_tw_list(node1, &ctx, &uring_locked);
2686 handle_tw_list(node2, &ctx, &uring_locked);
2689 if (data_race(!tctx->task_list.first) &&
2690 data_race(!tctx->prior_task_list.first) && uring_locked)
2691 io_submit_flush_completions(ctx);
2694 ctx_flush_and_put(ctx, &uring_locked);
2696 /* relaxed read is enough as only the task itself sets ->in_idle */
2697 if (unlikely(atomic_read(&tctx->in_idle)))
2698 io_uring_drop_tctx_refs(current);
2701 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2703 struct task_struct *tsk = req->task;
2704 struct io_ring_ctx *ctx = req->ctx;
2705 struct io_uring_task *tctx = tsk->io_uring;
2706 struct io_wq_work_node *node;
2707 unsigned long flags;
2710 WARN_ON_ONCE(!tctx);
2712 io_drop_inflight_file(req);
2714 spin_lock_irqsave(&tctx->task_lock, flags);
2716 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2718 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2719 running = tctx->task_running;
2721 tctx->task_running = true;
2722 spin_unlock_irqrestore(&tctx->task_lock, flags);
2724 /* task_work already pending, we're done */
2728 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2729 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2731 if (likely(!task_work_add(tsk, &tctx->task_work, ctx->notify_method)))
2734 spin_lock_irqsave(&tctx->task_lock, flags);
2735 tctx->task_running = false;
2736 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2737 spin_unlock_irqrestore(&tctx->task_lock, flags);
2740 req = container_of(node, struct io_kiocb, io_task_work.node);
2742 if (llist_add(&req->io_task_work.fallback_node,
2743 &req->ctx->fallback_llist))
2744 schedule_delayed_work(&req->ctx->fallback_work, 1);
2748 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2750 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2753 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2756 req->cqe.flags = cflags;
2757 req->io_task_work.func = io_req_tw_post;
2758 io_req_task_work_add(req, false);
2761 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2763 /* not needed for normal modes, but SQPOLL depends on it */
2764 io_tw_lock(req->ctx, locked);
2765 io_req_complete_failed(req, req->cqe.res);
2768 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2770 io_tw_lock(req->ctx, locked);
2771 /* req->task == current here, checking PF_EXITING is safe */
2772 if (likely(!(req->task->flags & PF_EXITING)))
2775 io_req_complete_failed(req, -EFAULT);
2778 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2781 req->io_task_work.func = io_req_task_cancel;
2782 io_req_task_work_add(req, false);
2785 static void io_req_task_queue(struct io_kiocb *req)
2787 req->io_task_work.func = io_req_task_submit;
2788 io_req_task_work_add(req, false);
2791 static void io_req_task_queue_reissue(struct io_kiocb *req)
2793 req->io_task_work.func = io_queue_iowq;
2794 io_req_task_work_add(req, false);
2797 static void io_queue_next(struct io_kiocb *req)
2799 struct io_kiocb *nxt = io_req_find_next(req);
2802 io_req_task_queue(nxt);
2805 static void io_free_batch_list(struct io_ring_ctx *ctx,
2806 struct io_wq_work_node *node)
2807 __must_hold(&ctx->uring_lock)
2809 struct task_struct *task = NULL;
2813 struct io_kiocb *req = container_of(node, struct io_kiocb,
2816 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2817 if (req->flags & REQ_F_REFCOUNT) {
2818 node = req->comp_list.next;
2819 if (!req_ref_put_and_test(req))
2822 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2823 struct async_poll *apoll = req->apoll;
2825 if (apoll->double_poll)
2826 kfree(apoll->double_poll);
2827 list_add(&apoll->poll.wait.entry,
2829 req->flags &= ~REQ_F_POLLED;
2831 if (req->flags & IO_REQ_LINK_FLAGS)
2833 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2836 if (!(req->flags & REQ_F_FIXED_FILE))
2837 io_put_file(req->file);
2839 io_req_put_rsrc_locked(req, ctx);
2841 if (req->task != task) {
2843 io_put_task(task, task_refs);
2848 node = req->comp_list.next;
2849 io_req_add_to_cache(req, ctx);
2853 io_put_task(task, task_refs);
2856 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2857 __must_hold(&ctx->uring_lock)
2859 struct io_wq_work_node *node, *prev;
2860 struct io_submit_state *state = &ctx->submit_state;
2862 if (state->flush_cqes) {
2863 spin_lock(&ctx->completion_lock);
2864 wq_list_for_each(node, prev, &state->compl_reqs) {
2865 struct io_kiocb *req = container_of(node, struct io_kiocb,
2868 if (!(req->flags & REQ_F_CQE_SKIP))
2869 __io_fill_cqe_req_filled(ctx, req);
2872 io_commit_cqring(ctx);
2873 spin_unlock(&ctx->completion_lock);
2874 io_cqring_ev_posted(ctx);
2875 state->flush_cqes = false;
2878 io_free_batch_list(ctx, state->compl_reqs.first);
2879 INIT_WQ_LIST(&state->compl_reqs);
2883 * Drop reference to request, return next in chain (if there is one) if this
2884 * was the last reference to this request.
2886 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2888 struct io_kiocb *nxt = NULL;
2890 if (req_ref_put_and_test(req)) {
2891 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2892 nxt = io_req_find_next(req);
2898 static inline void io_put_req(struct io_kiocb *req)
2900 if (req_ref_put_and_test(req)) {
2906 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2908 /* See comment at the top of this file */
2910 return __io_cqring_events(ctx);
2913 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2915 struct io_rings *rings = ctx->rings;
2917 /* make sure SQ entry isn't read before tail */
2918 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2921 static inline bool io_run_task_work(void)
2923 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2924 __set_current_state(TASK_RUNNING);
2925 clear_notify_signal();
2926 if (task_work_pending(current))
2934 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2936 struct io_wq_work_node *pos, *start, *prev;
2937 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2938 DEFINE_IO_COMP_BATCH(iob);
2942 * Only spin for completions if we don't have multiple devices hanging
2943 * off our complete list.
2945 if (ctx->poll_multi_queue || force_nonspin)
2946 poll_flags |= BLK_POLL_ONESHOT;
2948 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2949 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2950 struct kiocb *kiocb = &req->rw.kiocb;
2954 * Move completed and retryable entries to our local lists.
2955 * If we find a request that requires polling, break out
2956 * and complete those lists first, if we have entries there.
2958 if (READ_ONCE(req->iopoll_completed))
2961 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2962 if (unlikely(ret < 0))
2965 poll_flags |= BLK_POLL_ONESHOT;
2967 /* iopoll may have completed current req */
2968 if (!rq_list_empty(iob.req_list) ||
2969 READ_ONCE(req->iopoll_completed))
2973 if (!rq_list_empty(iob.req_list))
2979 wq_list_for_each_resume(pos, prev) {
2980 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2982 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2983 if (!smp_load_acquire(&req->iopoll_completed))
2986 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2988 __io_fill_cqe_req(req, req->cqe.res, io_put_kbuf(req, 0));
2991 if (unlikely(!nr_events))
2994 io_commit_cqring(ctx);
2995 io_cqring_ev_posted_iopoll(ctx);
2996 pos = start ? start->next : ctx->iopoll_list.first;
2997 wq_list_cut(&ctx->iopoll_list, prev, start);
2998 io_free_batch_list(ctx, pos);
3003 * We can't just wait for polled events to come to us, we have to actively
3004 * find and complete them.
3006 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3008 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3011 mutex_lock(&ctx->uring_lock);
3012 while (!wq_list_empty(&ctx->iopoll_list)) {
3013 /* let it sleep and repeat later if can't complete a request */
3014 if (io_do_iopoll(ctx, true) == 0)
3017 * Ensure we allow local-to-the-cpu processing to take place,
3018 * in this case we need to ensure that we reap all events.
3019 * Also let task_work, etc. to progress by releasing the mutex
3021 if (need_resched()) {
3022 mutex_unlock(&ctx->uring_lock);
3024 mutex_lock(&ctx->uring_lock);
3027 mutex_unlock(&ctx->uring_lock);
3030 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3032 unsigned int nr_events = 0;
3034 unsigned long check_cq;
3037 * Don't enter poll loop if we already have events pending.
3038 * If we do, we can potentially be spinning for commands that
3039 * already triggered a CQE (eg in error).
3041 check_cq = READ_ONCE(ctx->check_cq);
3042 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3043 __io_cqring_overflow_flush(ctx, false);
3044 if (io_cqring_events(ctx))
3048 * Similarly do not spin if we have not informed the user of any
3051 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3056 * If a submit got punted to a workqueue, we can have the
3057 * application entering polling for a command before it gets
3058 * issued. That app will hold the uring_lock for the duration
3059 * of the poll right here, so we need to take a breather every
3060 * now and then to ensure that the issue has a chance to add
3061 * the poll to the issued list. Otherwise we can spin here
3062 * forever, while the workqueue is stuck trying to acquire the
3065 if (wq_list_empty(&ctx->iopoll_list)) {
3066 u32 tail = ctx->cached_cq_tail;
3068 mutex_unlock(&ctx->uring_lock);
3070 mutex_lock(&ctx->uring_lock);
3072 /* some requests don't go through iopoll_list */
3073 if (tail != ctx->cached_cq_tail ||
3074 wq_list_empty(&ctx->iopoll_list))
3077 ret = io_do_iopoll(ctx, !min);
3082 } while (nr_events < min && !need_resched());
3087 static void kiocb_end_write(struct io_kiocb *req)
3090 * Tell lockdep we inherited freeze protection from submission
3093 if (req->flags & REQ_F_ISREG) {
3094 struct super_block *sb = file_inode(req->file)->i_sb;
3096 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3102 static bool io_resubmit_prep(struct io_kiocb *req)
3104 struct io_async_rw *rw = req->async_data;
3106 if (!req_has_async_data(req))
3107 return !io_req_prep_async(req);
3108 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3112 static bool io_rw_should_reissue(struct io_kiocb *req)
3114 umode_t mode = file_inode(req->file)->i_mode;
3115 struct io_ring_ctx *ctx = req->ctx;
3117 if (!S_ISBLK(mode) && !S_ISREG(mode))
3119 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3120 !(ctx->flags & IORING_SETUP_IOPOLL)))
3123 * If ref is dying, we might be running poll reap from the exit work.
3124 * Don't attempt to reissue from that path, just let it fail with
3127 if (percpu_ref_is_dying(&ctx->refs))
3130 * Play it safe and assume not safe to re-import and reissue if we're
3131 * not in the original thread group (or in task context).
3133 if (!same_thread_group(req->task, current) || !in_task())
3138 static bool io_resubmit_prep(struct io_kiocb *req)
3142 static bool io_rw_should_reissue(struct io_kiocb *req)
3148 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3150 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3151 kiocb_end_write(req);
3152 fsnotify_modify(req->file);
3154 fsnotify_access(req->file);
3156 if (unlikely(res != req->cqe.res)) {
3157 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3158 io_rw_should_reissue(req)) {
3159 req->flags |= REQ_F_REISSUE;
3168 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3170 int res = req->cqe.res;
3173 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3174 io_req_add_compl_list(req);
3176 io_req_complete_post(req, res,
3177 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3181 static void __io_complete_rw(struct io_kiocb *req, long res,
3182 unsigned int issue_flags)
3184 if (__io_complete_rw_common(req, res))
3186 __io_req_complete(req, issue_flags, req->cqe.res,
3187 io_put_kbuf(req, issue_flags));
3190 static void io_complete_rw(struct kiocb *kiocb, long res)
3192 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3194 if (__io_complete_rw_common(req, res))
3197 req->io_task_work.func = io_req_task_complete;
3198 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3201 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3203 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3205 if (kiocb->ki_flags & IOCB_WRITE)
3206 kiocb_end_write(req);
3207 if (unlikely(res != req->cqe.res)) {
3208 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3209 req->flags |= REQ_F_REISSUE;
3215 /* order with io_iopoll_complete() checking ->iopoll_completed */
3216 smp_store_release(&req->iopoll_completed, 1);
3220 * After the iocb has been issued, it's safe to be found on the poll list.
3221 * Adding the kiocb to the list AFTER submission ensures that we don't
3222 * find it from a io_do_iopoll() thread before the issuer is done
3223 * accessing the kiocb cookie.
3225 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3227 struct io_ring_ctx *ctx = req->ctx;
3228 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3230 /* workqueue context doesn't hold uring_lock, grab it now */
3231 if (unlikely(needs_lock))
3232 mutex_lock(&ctx->uring_lock);
3235 * Track whether we have multiple files in our lists. This will impact
3236 * how we do polling eventually, not spinning if we're on potentially
3237 * different devices.
3239 if (wq_list_empty(&ctx->iopoll_list)) {
3240 ctx->poll_multi_queue = false;
3241 } else if (!ctx->poll_multi_queue) {
3242 struct io_kiocb *list_req;
3244 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3246 if (list_req->file != req->file)
3247 ctx->poll_multi_queue = true;
3251 * For fast devices, IO may have already completed. If it has, add
3252 * it to the front so we find it first.
3254 if (READ_ONCE(req->iopoll_completed))
3255 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3257 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3259 if (unlikely(needs_lock)) {
3261 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3262 * in sq thread task context or in io worker task context. If
3263 * current task context is sq thread, we don't need to check
3264 * whether should wake up sq thread.
3266 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3267 wq_has_sleeper(&ctx->sq_data->wait))
3268 wake_up(&ctx->sq_data->wait);
3270 mutex_unlock(&ctx->uring_lock);
3274 static bool io_bdev_nowait(struct block_device *bdev)
3276 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3280 * If we tracked the file through the SCM inflight mechanism, we could support
3281 * any file. For now, just ensure that anything potentially problematic is done
3284 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3286 if (S_ISBLK(mode)) {
3287 if (IS_ENABLED(CONFIG_BLOCK) &&
3288 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3294 if (S_ISREG(mode)) {
3295 if (IS_ENABLED(CONFIG_BLOCK) &&
3296 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3297 file->f_op != &io_uring_fops)
3302 /* any ->read/write should understand O_NONBLOCK */
3303 if (file->f_flags & O_NONBLOCK)
3305 return file->f_mode & FMODE_NOWAIT;
3309 * If we tracked the file through the SCM inflight mechanism, we could support
3310 * any file. For now, just ensure that anything potentially problematic is done
3313 static unsigned int io_file_get_flags(struct file *file)
3315 umode_t mode = file_inode(file)->i_mode;
3316 unsigned int res = 0;
3320 if (__io_file_supports_nowait(file, mode))
3322 if (io_file_need_scm(file))
3327 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3329 return req->flags & REQ_F_SUPPORT_NOWAIT;
3332 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3334 struct kiocb *kiocb = &req->rw.kiocb;
3338 kiocb->ki_pos = READ_ONCE(sqe->off);
3340 ioprio = READ_ONCE(sqe->ioprio);
3342 ret = ioprio_check_cap(ioprio);
3346 kiocb->ki_ioprio = ioprio;
3348 kiocb->ki_ioprio = get_current_ioprio();
3352 req->rw.addr = READ_ONCE(sqe->addr);
3353 req->rw.len = READ_ONCE(sqe->len);
3354 req->rw.flags = READ_ONCE(sqe->rw_flags);
3355 /* used for fixed read/write too - just read unconditionally */
3356 req->buf_index = READ_ONCE(sqe->buf_index);
3360 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3366 case -ERESTARTNOINTR:
3367 case -ERESTARTNOHAND:
3368 case -ERESTART_RESTARTBLOCK:
3370 * We can't just restart the syscall, since previously
3371 * submitted sqes may already be in progress. Just fail this
3377 kiocb->ki_complete(kiocb, ret);
3381 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3383 struct kiocb *kiocb = &req->rw.kiocb;
3385 if (kiocb->ki_pos != -1)
3386 return &kiocb->ki_pos;
3388 if (!(req->file->f_mode & FMODE_STREAM)) {
3389 req->flags |= REQ_F_CUR_POS;
3390 kiocb->ki_pos = req->file->f_pos;
3391 return &kiocb->ki_pos;
3398 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3399 unsigned int issue_flags)
3401 struct io_async_rw *io = req->async_data;
3403 /* add previously done IO, if any */
3404 if (req_has_async_data(req) && io->bytes_done > 0) {
3406 ret = io->bytes_done;
3408 ret += io->bytes_done;
3411 if (req->flags & REQ_F_CUR_POS)
3412 req->file->f_pos = req->rw.kiocb.ki_pos;
3413 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3414 __io_complete_rw(req, ret, issue_flags);
3416 io_rw_done(&req->rw.kiocb, ret);
3418 if (req->flags & REQ_F_REISSUE) {
3419 req->flags &= ~REQ_F_REISSUE;
3420 if (io_resubmit_prep(req))
3421 io_req_task_queue_reissue(req);
3423 io_req_task_queue_fail(req, ret);
3427 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3428 struct io_mapped_ubuf *imu)
3430 size_t len = req->rw.len;
3431 u64 buf_end, buf_addr = req->rw.addr;
3434 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3436 /* not inside the mapped region */
3437 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3441 * May not be a start of buffer, set size appropriately
3442 * and advance us to the beginning.
3444 offset = buf_addr - imu->ubuf;
3445 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3449 * Don't use iov_iter_advance() here, as it's really slow for
3450 * using the latter parts of a big fixed buffer - it iterates
3451 * over each segment manually. We can cheat a bit here, because
3454 * 1) it's a BVEC iter, we set it up
3455 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3456 * first and last bvec
3458 * So just find our index, and adjust the iterator afterwards.
3459 * If the offset is within the first bvec (or the whole first
3460 * bvec, just use iov_iter_advance(). This makes it easier
3461 * since we can just skip the first segment, which may not
3462 * be PAGE_SIZE aligned.
3464 const struct bio_vec *bvec = imu->bvec;
3466 if (offset <= bvec->bv_len) {
3467 iov_iter_advance(iter, offset);
3469 unsigned long seg_skip;
3471 /* skip first vec */
3472 offset -= bvec->bv_len;
3473 seg_skip = 1 + (offset >> PAGE_SHIFT);
3475 iter->bvec = bvec + seg_skip;
3476 iter->nr_segs -= seg_skip;
3477 iter->count -= bvec->bv_len + offset;
3478 iter->iov_offset = offset & ~PAGE_MASK;
3485 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3486 unsigned int issue_flags)
3488 struct io_mapped_ubuf *imu = req->imu;
3489 u16 index, buf_index = req->buf_index;
3492 struct io_ring_ctx *ctx = req->ctx;
3494 if (unlikely(buf_index >= ctx->nr_user_bufs))
3496 io_req_set_rsrc_node(req, ctx, issue_flags);
3497 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3498 imu = READ_ONCE(ctx->user_bufs[index]);
3501 return __io_import_fixed(req, rw, iter, imu);
3504 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3505 struct io_buffer_list *bl, unsigned int bgid)
3508 if (bgid < BGID_ARRAY)
3511 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3514 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3515 struct io_buffer_list *bl)
3517 if (!list_empty(&bl->buf_list)) {
3518 struct io_buffer *kbuf;
3520 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3521 list_del(&kbuf->list);
3522 if (*len > kbuf->len)
3524 req->flags |= REQ_F_BUFFER_SELECTED;
3526 req->buf_index = kbuf->bid;
3527 return u64_to_user_ptr(kbuf->addr);
3532 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3533 struct io_buffer_list *bl,
3534 unsigned int issue_flags)
3536 struct io_uring_buf_ring *br = bl->buf_ring;
3537 struct io_uring_buf *buf;
3538 __u32 head = bl->head;
3540 if (unlikely(smp_load_acquire(&br->tail) == head)) {
3541 io_ring_submit_unlock(req->ctx, issue_flags);
3546 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3547 buf = &br->bufs[head];
3549 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3550 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE - 1;
3551 buf = page_address(bl->buf_pages[index]);
3554 if (*len > buf->len)
3556 req->flags |= REQ_F_BUFFER_RING;
3558 req->buf_index = buf->bid;
3560 if (issue_flags & IO_URING_F_UNLOCKED) {
3562 * If we came in unlocked, we have no choice but to consume the
3563 * buffer here. This does mean it'll be pinned until the IO
3564 * completes. But coming in unlocked means we're in io-wq
3565 * context, hence there should be no further retry. For the
3566 * locked case, the caller must ensure to call the commit when
3567 * the transfer completes (or if we get -EAGAIN and must poll
3570 req->buf_list = NULL;
3573 return u64_to_user_ptr(buf->addr);
3576 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3577 unsigned int issue_flags)
3579 struct io_ring_ctx *ctx = req->ctx;
3580 struct io_buffer_list *bl;
3581 void __user *ret = NULL;
3583 io_ring_submit_lock(req->ctx, issue_flags);
3585 bl = io_buffer_get_list(ctx, req->buf_index);
3587 if (bl->buf_nr_pages)
3588 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3590 ret = io_provided_buffer_select(req, len, bl);
3592 io_ring_submit_unlock(req->ctx, issue_flags);
3596 #ifdef CONFIG_COMPAT
3597 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3598 unsigned int issue_flags)
3600 struct compat_iovec __user *uiov;
3601 compat_ssize_t clen;
3605 uiov = u64_to_user_ptr(req->rw.addr);
3606 if (!access_ok(uiov, sizeof(*uiov)))
3608 if (__get_user(clen, &uiov->iov_len))
3614 buf = io_buffer_select(req, &len, issue_flags);
3617 req->rw.addr = (unsigned long) buf;
3618 iov[0].iov_base = buf;
3619 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3624 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3625 unsigned int issue_flags)
3627 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3631 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3634 len = iov[0].iov_len;
3637 buf = io_buffer_select(req, &len, issue_flags);
3640 req->rw.addr = (unsigned long) buf;
3641 iov[0].iov_base = buf;
3642 req->rw.len = iov[0].iov_len = len;
3646 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3647 unsigned int issue_flags)
3649 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3650 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3651 iov[0].iov_len = req->rw.len;
3654 if (req->rw.len != 1)
3657 #ifdef CONFIG_COMPAT
3658 if (req->ctx->compat)
3659 return io_compat_import(req, iov, issue_flags);
3662 return __io_iov_buffer_select(req, iov, issue_flags);
3665 static inline bool io_do_buffer_select(struct io_kiocb *req)
3667 if (!(req->flags & REQ_F_BUFFER_SELECT))
3669 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3672 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3673 struct io_rw_state *s,
3674 unsigned int issue_flags)
3676 struct iov_iter *iter = &s->iter;
3677 u8 opcode = req->opcode;
3678 struct iovec *iovec;
3683 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3684 ret = io_import_fixed(req, rw, iter, issue_flags);
3686 return ERR_PTR(ret);
3690 buf = u64_to_user_ptr(req->rw.addr);
3691 sqe_len = req->rw.len;
3693 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3694 if (io_do_buffer_select(req)) {
3695 buf = io_buffer_select(req, &sqe_len, issue_flags);
3697 return ERR_PTR(-ENOBUFS);
3698 req->rw.addr = (unsigned long) buf;
3699 req->rw.len = sqe_len;
3702 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3704 return ERR_PTR(ret);
3708 iovec = s->fast_iov;
3709 if (req->flags & REQ_F_BUFFER_SELECT) {
3710 ret = io_iov_buffer_select(req, iovec, issue_flags);
3712 return ERR_PTR(ret);
3713 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3717 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3719 if (unlikely(ret < 0))
3720 return ERR_PTR(ret);
3724 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3725 struct iovec **iovec, struct io_rw_state *s,
3726 unsigned int issue_flags)
3728 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3729 if (unlikely(IS_ERR(*iovec)))
3730 return PTR_ERR(*iovec);
3732 iov_iter_save_state(&s->iter, &s->iter_state);
3736 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3738 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3742 * For files that don't have ->read_iter() and ->write_iter(), handle them
3743 * by looping over ->read() or ->write() manually.
3745 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3747 struct kiocb *kiocb = &req->rw.kiocb;
3748 struct file *file = req->file;
3753 * Don't support polled IO through this interface, and we can't
3754 * support non-blocking either. For the latter, this just causes
3755 * the kiocb to be handled from an async context.
3757 if (kiocb->ki_flags & IOCB_HIPRI)
3759 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3760 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3763 ppos = io_kiocb_ppos(kiocb);
3765 while (iov_iter_count(iter)) {
3769 if (!iov_iter_is_bvec(iter)) {
3770 iovec = iov_iter_iovec(iter);
3772 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3773 iovec.iov_len = req->rw.len;
3777 nr = file->f_op->read(file, iovec.iov_base,
3778 iovec.iov_len, ppos);
3780 nr = file->f_op->write(file, iovec.iov_base,
3781 iovec.iov_len, ppos);
3790 if (!iov_iter_is_bvec(iter)) {
3791 iov_iter_advance(iter, nr);
3798 if (nr != iovec.iov_len)
3805 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3806 const struct iovec *fast_iov, struct iov_iter *iter)
3808 struct io_async_rw *rw = req->async_data;
3810 memcpy(&rw->s.iter, iter, sizeof(*iter));
3811 rw->free_iovec = iovec;
3813 /* can only be fixed buffers, no need to do anything */
3814 if (iov_iter_is_bvec(iter))
3817 unsigned iov_off = 0;
3819 rw->s.iter.iov = rw->s.fast_iov;
3820 if (iter->iov != fast_iov) {
3821 iov_off = iter->iov - fast_iov;
3822 rw->s.iter.iov += iov_off;
3824 if (rw->s.fast_iov != fast_iov)
3825 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3826 sizeof(struct iovec) * iter->nr_segs);
3828 req->flags |= REQ_F_NEED_CLEANUP;
3832 static inline bool io_alloc_async_data(struct io_kiocb *req)
3834 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3835 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3836 if (req->async_data) {
3837 req->flags |= REQ_F_ASYNC_DATA;
3843 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3844 struct io_rw_state *s, bool force)
3846 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3848 if (!req_has_async_data(req)) {
3849 struct io_async_rw *iorw;
3851 if (io_alloc_async_data(req)) {
3856 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3857 iorw = req->async_data;
3858 /* we've copied and mapped the iter, ensure state is saved */
3859 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3864 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3866 struct io_async_rw *iorw = req->async_data;
3870 /* submission path, ->uring_lock should already be taken */
3871 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3872 if (unlikely(ret < 0))
3875 iorw->bytes_done = 0;
3876 iorw->free_iovec = iov;
3878 req->flags |= REQ_F_NEED_CLEANUP;
3883 * This is our waitqueue callback handler, registered through __folio_lock_async()
3884 * when we initially tried to do the IO with the iocb armed our waitqueue.
3885 * This gets called when the page is unlocked, and we generally expect that to
3886 * happen when the page IO is completed and the page is now uptodate. This will
3887 * queue a task_work based retry of the operation, attempting to copy the data
3888 * again. If the latter fails because the page was NOT uptodate, then we will
3889 * do a thread based blocking retry of the operation. That's the unexpected
3892 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3893 int sync, void *arg)
3895 struct wait_page_queue *wpq;
3896 struct io_kiocb *req = wait->private;
3897 struct wait_page_key *key = arg;
3899 wpq = container_of(wait, struct wait_page_queue, wait);
3901 if (!wake_page_match(wpq, key))
3904 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3905 list_del_init(&wait->entry);
3906 io_req_task_queue(req);
3911 * This controls whether a given IO request should be armed for async page
3912 * based retry. If we return false here, the request is handed to the async
3913 * worker threads for retry. If we're doing buffered reads on a regular file,
3914 * we prepare a private wait_page_queue entry and retry the operation. This
3915 * will either succeed because the page is now uptodate and unlocked, or it
3916 * will register a callback when the page is unlocked at IO completion. Through
3917 * that callback, io_uring uses task_work to setup a retry of the operation.
3918 * That retry will attempt the buffered read again. The retry will generally
3919 * succeed, or in rare cases where it fails, we then fall back to using the
3920 * async worker threads for a blocking retry.
3922 static bool io_rw_should_retry(struct io_kiocb *req)
3924 struct io_async_rw *rw = req->async_data;
3925 struct wait_page_queue *wait = &rw->wpq;
3926 struct kiocb *kiocb = &req->rw.kiocb;
3928 /* never retry for NOWAIT, we just complete with -EAGAIN */
3929 if (req->flags & REQ_F_NOWAIT)
3932 /* Only for buffered IO */
3933 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3937 * just use poll if we can, and don't attempt if the fs doesn't
3938 * support callback based unlocks
3940 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3943 wait->wait.func = io_async_buf_func;
3944 wait->wait.private = req;
3945 wait->wait.flags = 0;
3946 INIT_LIST_HEAD(&wait->wait.entry);
3947 kiocb->ki_flags |= IOCB_WAITQ;
3948 kiocb->ki_flags &= ~IOCB_NOWAIT;
3949 kiocb->ki_waitq = wait;
3953 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3955 if (likely(req->file->f_op->read_iter))
3956 return call_read_iter(req->file, &req->rw.kiocb, iter);
3957 else if (req->file->f_op->read)
3958 return loop_rw_iter(READ, req, iter);
3963 static bool need_read_all(struct io_kiocb *req)
3965 return req->flags & REQ_F_ISREG ||
3966 S_ISBLK(file_inode(req->file)->i_mode);
3969 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3971 struct kiocb *kiocb = &req->rw.kiocb;
3972 struct io_ring_ctx *ctx = req->ctx;
3973 struct file *file = req->file;
3976 if (unlikely(!file || !(file->f_mode & mode)))
3979 if (!io_req_ffs_set(req))
3980 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3982 kiocb->ki_flags = iocb_flags(file);
3983 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
3988 * If the file is marked O_NONBLOCK, still allow retry for it if it
3989 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3990 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3992 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3993 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3994 req->flags |= REQ_F_NOWAIT;
3996 if (ctx->flags & IORING_SETUP_IOPOLL) {
3997 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4000 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4001 kiocb->ki_complete = io_complete_rw_iopoll;
4002 req->iopoll_completed = 0;
4004 if (kiocb->ki_flags & IOCB_HIPRI)
4006 kiocb->ki_complete = io_complete_rw;
4012 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4014 struct io_rw_state __s, *s = &__s;
4015 struct iovec *iovec;
4016 struct kiocb *kiocb = &req->rw.kiocb;
4017 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4018 struct io_async_rw *rw;
4022 if (!req_has_async_data(req)) {
4023 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4024 if (unlikely(ret < 0))
4028 * Safe and required to re-import if we're using provided
4029 * buffers, as we dropped the selected one before retry.
4031 if (req->flags & REQ_F_BUFFER_SELECT) {
4032 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4033 if (unlikely(ret < 0))
4037 rw = req->async_data;
4040 * We come here from an earlier attempt, restore our state to
4041 * match in case it doesn't. It's cheap enough that we don't
4042 * need to make this conditional.
4044 iov_iter_restore(&s->iter, &s->iter_state);
4047 ret = io_rw_init_file(req, FMODE_READ);
4048 if (unlikely(ret)) {
4052 req->cqe.res = iov_iter_count(&s->iter);
4054 if (force_nonblock) {
4055 /* If the file doesn't support async, just async punt */
4056 if (unlikely(!io_file_supports_nowait(req))) {
4057 ret = io_setup_async_rw(req, iovec, s, true);
4058 return ret ?: -EAGAIN;
4060 kiocb->ki_flags |= IOCB_NOWAIT;
4062 /* Ensure we clear previously set non-block flag */
4063 kiocb->ki_flags &= ~IOCB_NOWAIT;
4066 ppos = io_kiocb_update_pos(req);
4068 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4069 if (unlikely(ret)) {
4074 ret = io_iter_do_read(req, &s->iter);
4076 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4077 req->flags &= ~REQ_F_REISSUE;
4078 /* if we can poll, just do that */
4079 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4081 /* IOPOLL retry should happen for io-wq threads */
4082 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4084 /* no retry on NONBLOCK nor RWF_NOWAIT */
4085 if (req->flags & REQ_F_NOWAIT)
4088 } else if (ret == -EIOCBQUEUED) {
4090 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4091 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4092 /* read all, failed, already did sync or don't want to retry */
4097 * Don't depend on the iter state matching what was consumed, or being
4098 * untouched in case of error. Restore it and we'll advance it
4099 * manually if we need to.
4101 iov_iter_restore(&s->iter, &s->iter_state);
4103 ret2 = io_setup_async_rw(req, iovec, s, true);
4108 rw = req->async_data;
4111 * Now use our persistent iterator and state, if we aren't already.
4112 * We've restored and mapped the iter to match.
4117 * We end up here because of a partial read, either from
4118 * above or inside this loop. Advance the iter by the bytes
4119 * that were consumed.
4121 iov_iter_advance(&s->iter, ret);
4122 if (!iov_iter_count(&s->iter))
4124 rw->bytes_done += ret;
4125 iov_iter_save_state(&s->iter, &s->iter_state);
4127 /* if we can retry, do so with the callbacks armed */
4128 if (!io_rw_should_retry(req)) {
4129 kiocb->ki_flags &= ~IOCB_WAITQ;
4134 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4135 * we get -EIOCBQUEUED, then we'll get a notification when the
4136 * desired page gets unlocked. We can also get a partial read
4137 * here, and if we do, then just retry at the new offset.
4139 ret = io_iter_do_read(req, &s->iter);
4140 if (ret == -EIOCBQUEUED)
4142 /* we got some bytes, but not all. retry. */
4143 kiocb->ki_flags &= ~IOCB_WAITQ;
4144 iov_iter_restore(&s->iter, &s->iter_state);
4147 kiocb_done(req, ret, issue_flags);
4149 /* it's faster to check here then delegate to kfree */
4155 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4157 struct io_rw_state __s, *s = &__s;
4158 struct iovec *iovec;
4159 struct kiocb *kiocb = &req->rw.kiocb;
4160 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4164 if (!req_has_async_data(req)) {
4165 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4166 if (unlikely(ret < 0))
4169 struct io_async_rw *rw = req->async_data;
4172 iov_iter_restore(&s->iter, &s->iter_state);
4175 ret = io_rw_init_file(req, FMODE_WRITE);
4176 if (unlikely(ret)) {
4180 req->cqe.res = iov_iter_count(&s->iter);
4182 if (force_nonblock) {
4183 /* If the file doesn't support async, just async punt */
4184 if (unlikely(!io_file_supports_nowait(req)))
4187 /* file path doesn't support NOWAIT for non-direct_IO */
4188 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4189 (req->flags & REQ_F_ISREG))
4192 kiocb->ki_flags |= IOCB_NOWAIT;
4194 /* Ensure we clear previously set non-block flag */
4195 kiocb->ki_flags &= ~IOCB_NOWAIT;
4198 ppos = io_kiocb_update_pos(req);
4200 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4205 * Open-code file_start_write here to grab freeze protection,
4206 * which will be released by another thread in
4207 * io_complete_rw(). Fool lockdep by telling it the lock got
4208 * released so that it doesn't complain about the held lock when
4209 * we return to userspace.
4211 if (req->flags & REQ_F_ISREG) {
4212 sb_start_write(file_inode(req->file)->i_sb);
4213 __sb_writers_release(file_inode(req->file)->i_sb,
4216 kiocb->ki_flags |= IOCB_WRITE;
4218 if (likely(req->file->f_op->write_iter))
4219 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4220 else if (req->file->f_op->write)
4221 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4225 if (req->flags & REQ_F_REISSUE) {
4226 req->flags &= ~REQ_F_REISSUE;
4231 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4232 * retry them without IOCB_NOWAIT.
4234 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4236 /* no retry on NONBLOCK nor RWF_NOWAIT */
4237 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4239 if (!force_nonblock || ret2 != -EAGAIN) {
4240 /* IOPOLL retry should happen for io-wq threads */
4241 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4244 kiocb_done(req, ret2, issue_flags);
4247 iov_iter_restore(&s->iter, &s->iter_state);
4248 ret = io_setup_async_rw(req, iovec, s, false);
4249 return ret ?: -EAGAIN;
4252 /* it's reportedly faster than delegating the null check to kfree() */
4258 static int io_renameat_prep(struct io_kiocb *req,
4259 const struct io_uring_sqe *sqe)
4261 struct io_rename *ren = &req->rename;
4262 const char __user *oldf, *newf;
4264 if (sqe->buf_index || sqe->splice_fd_in)
4266 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4269 ren->old_dfd = READ_ONCE(sqe->fd);
4270 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4271 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4272 ren->new_dfd = READ_ONCE(sqe->len);
4273 ren->flags = READ_ONCE(sqe->rename_flags);
4275 ren->oldpath = getname(oldf);
4276 if (IS_ERR(ren->oldpath))
4277 return PTR_ERR(ren->oldpath);
4279 ren->newpath = getname(newf);
4280 if (IS_ERR(ren->newpath)) {
4281 putname(ren->oldpath);
4282 return PTR_ERR(ren->newpath);
4285 req->flags |= REQ_F_NEED_CLEANUP;
4289 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4291 struct io_rename *ren = &req->rename;
4294 if (issue_flags & IO_URING_F_NONBLOCK)
4297 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4298 ren->newpath, ren->flags);
4300 req->flags &= ~REQ_F_NEED_CLEANUP;
4303 io_req_complete(req, ret);
4307 static int io_unlinkat_prep(struct io_kiocb *req,
4308 const struct io_uring_sqe *sqe)
4310 struct io_unlink *un = &req->unlink;
4311 const char __user *fname;
4313 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4315 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4318 un->dfd = READ_ONCE(sqe->fd);
4320 un->flags = READ_ONCE(sqe->unlink_flags);
4321 if (un->flags & ~AT_REMOVEDIR)
4324 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4325 un->filename = getname(fname);
4326 if (IS_ERR(un->filename))
4327 return PTR_ERR(un->filename);
4329 req->flags |= REQ_F_NEED_CLEANUP;
4333 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4335 struct io_unlink *un = &req->unlink;
4338 if (issue_flags & IO_URING_F_NONBLOCK)
4341 if (un->flags & AT_REMOVEDIR)
4342 ret = do_rmdir(un->dfd, un->filename);
4344 ret = do_unlinkat(un->dfd, un->filename);
4346 req->flags &= ~REQ_F_NEED_CLEANUP;
4349 io_req_complete(req, ret);
4353 static int io_mkdirat_prep(struct io_kiocb *req,
4354 const struct io_uring_sqe *sqe)
4356 struct io_mkdir *mkd = &req->mkdir;
4357 const char __user *fname;
4359 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4361 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4364 mkd->dfd = READ_ONCE(sqe->fd);
4365 mkd->mode = READ_ONCE(sqe->len);
4367 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4368 mkd->filename = getname(fname);
4369 if (IS_ERR(mkd->filename))
4370 return PTR_ERR(mkd->filename);
4372 req->flags |= REQ_F_NEED_CLEANUP;
4376 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4378 struct io_mkdir *mkd = &req->mkdir;
4381 if (issue_flags & IO_URING_F_NONBLOCK)
4384 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4386 req->flags &= ~REQ_F_NEED_CLEANUP;
4389 io_req_complete(req, ret);
4393 static int io_symlinkat_prep(struct io_kiocb *req,
4394 const struct io_uring_sqe *sqe)
4396 struct io_symlink *sl = &req->symlink;
4397 const char __user *oldpath, *newpath;
4399 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4401 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4404 sl->new_dfd = READ_ONCE(sqe->fd);
4405 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4406 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4408 sl->oldpath = getname(oldpath);
4409 if (IS_ERR(sl->oldpath))
4410 return PTR_ERR(sl->oldpath);
4412 sl->newpath = getname(newpath);
4413 if (IS_ERR(sl->newpath)) {
4414 putname(sl->oldpath);
4415 return PTR_ERR(sl->newpath);
4418 req->flags |= REQ_F_NEED_CLEANUP;
4422 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4424 struct io_symlink *sl = &req->symlink;
4427 if (issue_flags & IO_URING_F_NONBLOCK)
4430 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4432 req->flags &= ~REQ_F_NEED_CLEANUP;
4435 io_req_complete(req, ret);
4439 static int io_linkat_prep(struct io_kiocb *req,
4440 const struct io_uring_sqe *sqe)
4442 struct io_hardlink *lnk = &req->hardlink;
4443 const char __user *oldf, *newf;
4445 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4447 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4450 lnk->old_dfd = READ_ONCE(sqe->fd);
4451 lnk->new_dfd = READ_ONCE(sqe->len);
4452 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4453 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4454 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4456 lnk->oldpath = getname(oldf);
4457 if (IS_ERR(lnk->oldpath))
4458 return PTR_ERR(lnk->oldpath);
4460 lnk->newpath = getname(newf);
4461 if (IS_ERR(lnk->newpath)) {
4462 putname(lnk->oldpath);
4463 return PTR_ERR(lnk->newpath);
4466 req->flags |= REQ_F_NEED_CLEANUP;
4470 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4472 struct io_hardlink *lnk = &req->hardlink;
4475 if (issue_flags & IO_URING_F_NONBLOCK)
4478 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4479 lnk->newpath, lnk->flags);
4481 req->flags &= ~REQ_F_NEED_CLEANUP;
4484 io_req_complete(req, ret);
4488 static int io_shutdown_prep(struct io_kiocb *req,
4489 const struct io_uring_sqe *sqe)
4491 #if defined(CONFIG_NET)
4492 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
4493 sqe->buf_index || sqe->splice_fd_in))
4496 req->shutdown.how = READ_ONCE(sqe->len);
4503 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4505 #if defined(CONFIG_NET)
4506 struct socket *sock;
4509 if (issue_flags & IO_URING_F_NONBLOCK)
4512 sock = sock_from_file(req->file);
4513 if (unlikely(!sock))
4516 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4519 io_req_complete(req, ret);
4526 static int __io_splice_prep(struct io_kiocb *req,
4527 const struct io_uring_sqe *sqe)
4529 struct io_splice *sp = &req->splice;
4530 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4532 sp->len = READ_ONCE(sqe->len);
4533 sp->flags = READ_ONCE(sqe->splice_flags);
4534 if (unlikely(sp->flags & ~valid_flags))
4536 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4540 static int io_tee_prep(struct io_kiocb *req,
4541 const struct io_uring_sqe *sqe)
4543 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4545 return __io_splice_prep(req, sqe);
4548 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4550 struct io_splice *sp = &req->splice;
4551 struct file *out = sp->file_out;
4552 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4556 if (issue_flags & IO_URING_F_NONBLOCK)
4559 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4560 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4562 in = io_file_get_normal(req, sp->splice_fd_in);
4569 ret = do_tee(in, out, sp->len, flags);
4571 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4576 io_req_complete(req, ret);
4580 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4582 struct io_splice *sp = &req->splice;
4584 sp->off_in = READ_ONCE(sqe->splice_off_in);
4585 sp->off_out = READ_ONCE(sqe->off);
4586 return __io_splice_prep(req, sqe);
4589 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4591 struct io_splice *sp = &req->splice;
4592 struct file *out = sp->file_out;
4593 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4594 loff_t *poff_in, *poff_out;
4598 if (issue_flags & IO_URING_F_NONBLOCK)
4601 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4602 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4604 in = io_file_get_normal(req, sp->splice_fd_in);
4610 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4611 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4614 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4616 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4621 io_req_complete(req, ret);
4626 * IORING_OP_NOP just posts a completion event, nothing else.
4628 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4632 if (req->flags & REQ_F_BUFFER_SELECT) {
4635 buf = io_buffer_select(req, &len, issue_flags);
4640 __io_req_complete(req, issue_flags, 0, io_put_kbuf(req, issue_flags));
4644 static int io_msg_ring_prep(struct io_kiocb *req,
4645 const struct io_uring_sqe *sqe)
4647 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
4648 sqe->buf_index || sqe->personality))
4651 req->msg.user_data = READ_ONCE(sqe->off);
4652 req->msg.len = READ_ONCE(sqe->len);
4656 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4658 struct io_ring_ctx *target_ctx;
4659 struct io_msg *msg = &req->msg;
4664 if (req->file->f_op != &io_uring_fops)
4668 target_ctx = req->file->private_data;
4670 spin_lock(&target_ctx->completion_lock);
4671 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4672 io_commit_cqring(target_ctx);
4673 spin_unlock(&target_ctx->completion_lock);
4676 io_cqring_ev_posted(target_ctx);
4683 __io_req_complete(req, issue_flags, ret, 0);
4687 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4689 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
4692 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4693 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4696 req->sync.off = READ_ONCE(sqe->off);
4697 req->sync.len = READ_ONCE(sqe->len);
4701 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4703 loff_t end = req->sync.off + req->sync.len;
4706 /* fsync always requires a blocking context */
4707 if (issue_flags & IO_URING_F_NONBLOCK)
4710 ret = vfs_fsync_range(req->file, req->sync.off,
4711 end > 0 ? end : LLONG_MAX,
4712 req->sync.flags & IORING_FSYNC_DATASYNC);
4715 io_req_complete(req, ret);
4719 static int io_fallocate_prep(struct io_kiocb *req,
4720 const struct io_uring_sqe *sqe)
4722 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
4725 req->sync.off = READ_ONCE(sqe->off);
4726 req->sync.len = READ_ONCE(sqe->addr);
4727 req->sync.mode = READ_ONCE(sqe->len);
4731 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4735 /* fallocate always requiring blocking context */
4736 if (issue_flags & IO_URING_F_NONBLOCK)
4738 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4743 fsnotify_modify(req->file);
4744 io_req_complete(req, ret);
4748 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4750 const char __user *fname;
4753 if (unlikely(sqe->buf_index))
4755 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4758 /* open.how should be already initialised */
4759 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4760 req->open.how.flags |= O_LARGEFILE;
4762 req->open.dfd = READ_ONCE(sqe->fd);
4763 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4764 req->open.filename = getname(fname);
4765 if (IS_ERR(req->open.filename)) {
4766 ret = PTR_ERR(req->open.filename);
4767 req->open.filename = NULL;
4771 req->open.file_slot = READ_ONCE(sqe->file_index);
4772 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4775 req->open.nofile = rlimit(RLIMIT_NOFILE);
4776 req->flags |= REQ_F_NEED_CLEANUP;
4780 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4782 u64 mode = READ_ONCE(sqe->len);
4783 u64 flags = READ_ONCE(sqe->open_flags);
4785 req->open.how = build_open_how(flags, mode);
4786 return __io_openat_prep(req, sqe);
4789 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4791 struct open_how __user *how;
4795 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4796 len = READ_ONCE(sqe->len);
4797 if (len < OPEN_HOW_SIZE_VER0)
4800 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4805 return __io_openat_prep(req, sqe);
4808 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
4810 struct io_file_table *table = &ctx->file_table;
4811 unsigned long nr = ctx->nr_user_files;
4814 if (table->alloc_hint >= nr)
4815 table->alloc_hint = 0;
4818 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
4820 table->alloc_hint = ret + 1;
4823 if (!table->alloc_hint)
4826 nr = table->alloc_hint;
4827 table->alloc_hint = 0;
4833 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
4834 struct file *file, unsigned int file_slot)
4836 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
4837 struct io_ring_ctx *ctx = req->ctx;
4841 io_ring_submit_lock(ctx, issue_flags);
4842 ret = io_file_bitmap_get(ctx);
4843 if (unlikely(ret < 0)) {
4844 io_ring_submit_unlock(ctx, issue_flags);
4853 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
4855 io_ring_submit_unlock(ctx, issue_flags);
4863 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4865 struct open_flags op;
4867 bool resolve_nonblock, nonblock_set;
4868 bool fixed = !!req->open.file_slot;
4871 ret = build_open_flags(&req->open.how, &op);
4874 nonblock_set = op.open_flag & O_NONBLOCK;
4875 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4876 if (issue_flags & IO_URING_F_NONBLOCK) {
4878 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4879 * it'll always -EAGAIN
4881 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4883 op.lookup_flags |= LOOKUP_CACHED;
4884 op.open_flag |= O_NONBLOCK;
4888 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4893 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4896 * We could hang on to this 'fd' on retrying, but seems like
4897 * marginal gain for something that is now known to be a slower
4898 * path. So just put it, and we'll get a new one when we retry.
4903 ret = PTR_ERR(file);
4904 /* only retry if RESOLVE_CACHED wasn't already set by application */
4905 if (ret == -EAGAIN &&
4906 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4911 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4912 file->f_flags &= ~O_NONBLOCK;
4913 fsnotify_open(file);
4916 fd_install(ret, file);
4918 ret = io_fixed_fd_install(req, issue_flags, file,
4919 req->open.file_slot);
4921 putname(req->open.filename);
4922 req->flags &= ~REQ_F_NEED_CLEANUP;
4925 __io_req_complete(req, issue_flags, ret, 0);
4929 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4931 return io_openat2(req, issue_flags);
4934 static int io_remove_buffers_prep(struct io_kiocb *req,
4935 const struct io_uring_sqe *sqe)
4937 struct io_provide_buf *p = &req->pbuf;
4940 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4944 tmp = READ_ONCE(sqe->fd);
4945 if (!tmp || tmp > USHRT_MAX)
4948 memset(p, 0, sizeof(*p));
4950 p->bgid = READ_ONCE(sqe->buf_group);
4954 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4955 struct io_buffer_list *bl, unsigned nbufs)
4959 /* shouldn't happen */
4963 if (bl->buf_nr_pages) {
4966 i = bl->buf_ring->tail - bl->head;
4967 for (j = 0; j < bl->buf_nr_pages; j++)
4968 unpin_user_page(bl->buf_pages[j]);
4969 kvfree(bl->buf_pages);
4970 bl->buf_pages = NULL;
4971 bl->buf_nr_pages = 0;
4975 /* the head kbuf is the list itself */
4976 while (!list_empty(&bl->buf_list)) {
4977 struct io_buffer *nxt;
4979 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4980 list_del(&nxt->list);
4990 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4992 struct io_provide_buf *p = &req->pbuf;
4993 struct io_ring_ctx *ctx = req->ctx;
4994 struct io_buffer_list *bl;
4997 io_ring_submit_lock(ctx, issue_flags);
5000 bl = io_buffer_get_list(ctx, p->bgid);
5003 /* can't use provide/remove buffers command on mapped buffers */
5004 if (!bl->buf_nr_pages)
5005 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5010 /* complete before unlock, IOPOLL may need the lock */
5011 __io_req_complete(req, issue_flags, ret, 0);
5012 io_ring_submit_unlock(ctx, issue_flags);
5016 static int io_provide_buffers_prep(struct io_kiocb *req,
5017 const struct io_uring_sqe *sqe)
5019 unsigned long size, tmp_check;
5020 struct io_provide_buf *p = &req->pbuf;
5023 if (sqe->rw_flags || sqe->splice_fd_in)
5026 tmp = READ_ONCE(sqe->fd);
5027 if (!tmp || tmp > USHRT_MAX)
5030 p->addr = READ_ONCE(sqe->addr);
5031 p->len = READ_ONCE(sqe->len);
5033 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5036 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5039 size = (unsigned long)p->len * p->nbufs;
5040 if (!access_ok(u64_to_user_ptr(p->addr), size))
5043 p->bgid = READ_ONCE(sqe->buf_group);
5044 tmp = READ_ONCE(sqe->off);
5045 if (tmp > USHRT_MAX)
5051 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5053 struct io_buffer *buf;
5058 * Completions that don't happen inline (eg not under uring_lock) will
5059 * add to ->io_buffers_comp. If we don't have any free buffers, check
5060 * the completion list and splice those entries first.
5062 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5063 spin_lock(&ctx->completion_lock);
5064 if (!list_empty(&ctx->io_buffers_comp)) {
5065 list_splice_init(&ctx->io_buffers_comp,
5066 &ctx->io_buffers_cache);
5067 spin_unlock(&ctx->completion_lock);
5070 spin_unlock(&ctx->completion_lock);
5074 * No free buffers and no completion entries either. Allocate a new
5075 * page worth of buffer entries and add those to our freelist.
5077 page = alloc_page(GFP_KERNEL_ACCOUNT);
5081 list_add(&page->lru, &ctx->io_buffers_pages);
5083 buf = page_address(page);
5084 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5085 while (bufs_in_page) {
5086 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5094 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5095 struct io_buffer_list *bl)
5097 struct io_buffer *buf;
5098 u64 addr = pbuf->addr;
5099 int i, bid = pbuf->bid;
5101 for (i = 0; i < pbuf->nbufs; i++) {
5102 if (list_empty(&ctx->io_buffers_cache) &&
5103 io_refill_buffer_cache(ctx))
5105 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5107 list_move_tail(&buf->list, &bl->buf_list);
5109 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5111 buf->bgid = pbuf->bgid;
5117 return i ? 0 : -ENOMEM;
5120 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5124 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5129 for (i = 0; i < BGID_ARRAY; i++) {
5130 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5131 ctx->io_bl[i].bgid = i;
5137 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5139 struct io_provide_buf *p = &req->pbuf;
5140 struct io_ring_ctx *ctx = req->ctx;
5141 struct io_buffer_list *bl;
5144 io_ring_submit_lock(ctx, issue_flags);
5146 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5147 ret = io_init_bl_list(ctx);
5152 bl = io_buffer_get_list(ctx, p->bgid);
5153 if (unlikely(!bl)) {
5154 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
5159 ret = io_buffer_add_list(ctx, bl, p->bgid);
5165 /* can't add buffers via this command for a mapped buffer ring */
5166 if (bl->buf_nr_pages) {
5171 ret = io_add_buffers(ctx, p, bl);
5175 /* complete before unlock, IOPOLL may need the lock */
5176 __io_req_complete(req, issue_flags, ret, 0);
5177 io_ring_submit_unlock(ctx, issue_flags);
5181 static int io_epoll_ctl_prep(struct io_kiocb *req,
5182 const struct io_uring_sqe *sqe)
5184 #if defined(CONFIG_EPOLL)
5185 if (sqe->buf_index || sqe->splice_fd_in)
5188 req->epoll.epfd = READ_ONCE(sqe->fd);
5189 req->epoll.op = READ_ONCE(sqe->len);
5190 req->epoll.fd = READ_ONCE(sqe->off);
5192 if (ep_op_has_event(req->epoll.op)) {
5193 struct epoll_event __user *ev;
5195 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5196 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5206 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5208 #if defined(CONFIG_EPOLL)
5209 struct io_epoll *ie = &req->epoll;
5211 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5213 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5214 if (force_nonblock && ret == -EAGAIN)
5219 __io_req_complete(req, issue_flags, ret, 0);
5226 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5228 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5229 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5232 req->madvise.addr = READ_ONCE(sqe->addr);
5233 req->madvise.len = READ_ONCE(sqe->len);
5234 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5241 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5243 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5244 struct io_madvise *ma = &req->madvise;
5247 if (issue_flags & IO_URING_F_NONBLOCK)
5250 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5253 io_req_complete(req, ret);
5260 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5262 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5265 req->fadvise.offset = READ_ONCE(sqe->off);
5266 req->fadvise.len = READ_ONCE(sqe->len);
5267 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5271 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5273 struct io_fadvise *fa = &req->fadvise;
5276 if (issue_flags & IO_URING_F_NONBLOCK) {
5277 switch (fa->advice) {
5278 case POSIX_FADV_NORMAL:
5279 case POSIX_FADV_RANDOM:
5280 case POSIX_FADV_SEQUENTIAL:
5287 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5290 __io_req_complete(req, issue_flags, ret, 0);
5294 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5296 const char __user *path;
5298 if (sqe->buf_index || sqe->splice_fd_in)
5300 if (req->flags & REQ_F_FIXED_FILE)
5303 req->statx.dfd = READ_ONCE(sqe->fd);
5304 req->statx.mask = READ_ONCE(sqe->len);
5305 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5306 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5307 req->statx.flags = READ_ONCE(sqe->statx_flags);
5309 req->statx.filename = getname_flags(path,
5310 getname_statx_lookup_flags(req->statx.flags),
5313 if (IS_ERR(req->statx.filename)) {
5314 int ret = PTR_ERR(req->statx.filename);
5316 req->statx.filename = NULL;
5320 req->flags |= REQ_F_NEED_CLEANUP;
5324 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5326 struct io_statx *ctx = &req->statx;
5329 if (issue_flags & IO_URING_F_NONBLOCK)
5332 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5337 io_req_complete(req, ret);
5341 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5343 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5345 if (req->flags & REQ_F_FIXED_FILE)
5348 req->close.fd = READ_ONCE(sqe->fd);
5349 req->close.file_slot = READ_ONCE(sqe->file_index);
5350 if (req->close.file_slot && req->close.fd)
5356 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5358 struct files_struct *files = current->files;
5359 struct io_close *close = &req->close;
5360 struct fdtable *fdt;
5361 struct file *file = NULL;
5364 if (req->close.file_slot) {
5365 ret = io_close_fixed(req, issue_flags);
5369 spin_lock(&files->file_lock);
5370 fdt = files_fdtable(files);
5371 if (close->fd >= fdt->max_fds) {
5372 spin_unlock(&files->file_lock);
5375 file = fdt->fd[close->fd];
5376 if (!file || file->f_op == &io_uring_fops) {
5377 spin_unlock(&files->file_lock);
5382 /* if the file has a flush method, be safe and punt to async */
5383 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5384 spin_unlock(&files->file_lock);
5388 ret = __close_fd_get_file(close->fd, &file);
5389 spin_unlock(&files->file_lock);
5396 /* No ->flush() or already async, safely close from here */
5397 ret = filp_close(file, current->files);
5403 __io_req_complete(req, issue_flags, ret, 0);
5407 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5409 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5412 req->sync.off = READ_ONCE(sqe->off);
5413 req->sync.len = READ_ONCE(sqe->len);
5414 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5418 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5422 /* sync_file_range always requires a blocking context */
5423 if (issue_flags & IO_URING_F_NONBLOCK)
5426 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5430 io_req_complete(req, ret);
5434 #if defined(CONFIG_NET)
5435 static bool io_net_retry(struct socket *sock, int flags)
5437 if (!(flags & MSG_WAITALL))
5439 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5442 static int io_setup_async_msg(struct io_kiocb *req,
5443 struct io_async_msghdr *kmsg)
5445 struct io_async_msghdr *async_msg = req->async_data;
5449 if (io_alloc_async_data(req)) {
5450 kfree(kmsg->free_iov);
5453 async_msg = req->async_data;
5454 req->flags |= REQ_F_NEED_CLEANUP;
5455 memcpy(async_msg, kmsg, sizeof(*kmsg));
5456 async_msg->msg.msg_name = &async_msg->addr;
5457 /* if were using fast_iov, set it to the new one */
5458 if (!async_msg->free_iov)
5459 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5464 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5465 struct io_async_msghdr *iomsg)
5467 iomsg->msg.msg_name = &iomsg->addr;
5468 iomsg->free_iov = iomsg->fast_iov;
5469 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5470 req->sr_msg.msg_flags, &iomsg->free_iov);
5473 static int io_sendmsg_prep_async(struct io_kiocb *req)
5477 ret = io_sendmsg_copy_hdr(req, req->async_data);
5479 req->flags |= REQ_F_NEED_CLEANUP;
5483 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5485 struct io_sr_msg *sr = &req->sr_msg;
5487 if (unlikely(sqe->file_index))
5490 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5491 sr->len = READ_ONCE(sqe->len);
5492 sr->flags = READ_ONCE(sqe->addr2);
5493 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5495 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5496 if (sr->msg_flags & MSG_DONTWAIT)
5497 req->flags |= REQ_F_NOWAIT;
5499 #ifdef CONFIG_COMPAT
5500 if (req->ctx->compat)
5501 sr->msg_flags |= MSG_CMSG_COMPAT;
5507 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5509 struct io_async_msghdr iomsg, *kmsg;
5510 struct io_sr_msg *sr = &req->sr_msg;
5511 struct socket *sock;
5516 sock = sock_from_file(req->file);
5517 if (unlikely(!sock))
5520 if (req_has_async_data(req)) {
5521 kmsg = req->async_data;
5523 ret = io_sendmsg_copy_hdr(req, &iomsg);
5529 if (!(req->flags & REQ_F_POLLED) &&
5530 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5531 return io_setup_async_msg(req, kmsg);
5533 flags = sr->msg_flags;
5534 if (issue_flags & IO_URING_F_NONBLOCK)
5535 flags |= MSG_DONTWAIT;
5536 if (flags & MSG_WAITALL)
5537 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5539 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5541 if (ret < min_ret) {
5542 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5543 return io_setup_async_msg(req, kmsg);
5544 if (ret == -ERESTARTSYS)
5546 if (ret > 0 && io_net_retry(sock, flags)) {
5548 req->flags |= REQ_F_PARTIAL_IO;
5549 return io_setup_async_msg(req, kmsg);
5553 /* fast path, check for non-NULL to avoid function call */
5555 kfree(kmsg->free_iov);
5556 req->flags &= ~REQ_F_NEED_CLEANUP;
5559 else if (sr->done_io)
5561 __io_req_complete(req, issue_flags, ret, 0);
5565 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5567 struct io_sr_msg *sr = &req->sr_msg;
5570 struct socket *sock;
5575 if (!(req->flags & REQ_F_POLLED) &&
5576 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5579 sock = sock_from_file(req->file);
5580 if (unlikely(!sock))
5583 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5587 msg.msg_name = NULL;
5588 msg.msg_control = NULL;
5589 msg.msg_controllen = 0;
5590 msg.msg_namelen = 0;
5592 flags = sr->msg_flags;
5593 if (issue_flags & IO_URING_F_NONBLOCK)
5594 flags |= MSG_DONTWAIT;
5595 if (flags & MSG_WAITALL)
5596 min_ret = iov_iter_count(&msg.msg_iter);
5598 msg.msg_flags = flags;
5599 ret = sock_sendmsg(sock, &msg);
5600 if (ret < min_ret) {
5601 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5603 if (ret == -ERESTARTSYS)
5605 if (ret > 0 && io_net_retry(sock, flags)) {
5609 req->flags |= REQ_F_PARTIAL_IO;
5616 else if (sr->done_io)
5618 __io_req_complete(req, issue_flags, ret, 0);
5622 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5623 struct io_async_msghdr *iomsg)
5625 struct io_sr_msg *sr = &req->sr_msg;
5626 struct iovec __user *uiov;
5630 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5631 &iomsg->uaddr, &uiov, &iov_len);
5635 if (req->flags & REQ_F_BUFFER_SELECT) {
5638 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5640 sr->len = iomsg->fast_iov[0].iov_len;
5641 iomsg->free_iov = NULL;
5643 iomsg->free_iov = iomsg->fast_iov;
5644 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5645 &iomsg->free_iov, &iomsg->msg.msg_iter,
5654 #ifdef CONFIG_COMPAT
5655 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5656 struct io_async_msghdr *iomsg)
5658 struct io_sr_msg *sr = &req->sr_msg;
5659 struct compat_iovec __user *uiov;
5664 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5669 uiov = compat_ptr(ptr);
5670 if (req->flags & REQ_F_BUFFER_SELECT) {
5671 compat_ssize_t clen;
5675 if (!access_ok(uiov, sizeof(*uiov)))
5677 if (__get_user(clen, &uiov->iov_len))
5682 iomsg->free_iov = NULL;
5684 iomsg->free_iov = iomsg->fast_iov;
5685 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5686 UIO_FASTIOV, &iomsg->free_iov,
5687 &iomsg->msg.msg_iter, true);
5696 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5697 struct io_async_msghdr *iomsg)
5699 iomsg->msg.msg_name = &iomsg->addr;
5701 #ifdef CONFIG_COMPAT
5702 if (req->ctx->compat)
5703 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5706 return __io_recvmsg_copy_hdr(req, iomsg);
5709 static int io_recvmsg_prep_async(struct io_kiocb *req)
5713 ret = io_recvmsg_copy_hdr(req, req->async_data);
5715 req->flags |= REQ_F_NEED_CLEANUP;
5719 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5721 struct io_sr_msg *sr = &req->sr_msg;
5723 if (unlikely(sqe->file_index))
5726 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5727 sr->len = READ_ONCE(sqe->len);
5728 sr->flags = READ_ONCE(sqe->addr2);
5729 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5731 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5732 if (sr->msg_flags & MSG_DONTWAIT)
5733 req->flags |= REQ_F_NOWAIT;
5735 #ifdef CONFIG_COMPAT
5736 if (req->ctx->compat)
5737 sr->msg_flags |= MSG_CMSG_COMPAT;
5743 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5745 struct io_async_msghdr iomsg, *kmsg;
5746 struct io_sr_msg *sr = &req->sr_msg;
5747 struct socket *sock;
5749 int ret, min_ret = 0;
5750 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5752 sock = sock_from_file(req->file);
5753 if (unlikely(!sock))
5756 if (req_has_async_data(req)) {
5757 kmsg = req->async_data;
5759 ret = io_recvmsg_copy_hdr(req, &iomsg);
5765 if (!(req->flags & REQ_F_POLLED) &&
5766 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5767 return io_setup_async_msg(req, kmsg);
5769 if (io_do_buffer_select(req)) {
5772 buf = io_buffer_select(req, &sr->len, issue_flags);
5775 kmsg->fast_iov[0].iov_base = buf;
5776 kmsg->fast_iov[0].iov_len = sr->len;
5777 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
5781 flags = sr->msg_flags;
5783 flags |= MSG_DONTWAIT;
5784 if (flags & MSG_WAITALL)
5785 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5787 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
5788 if (ret < min_ret) {
5789 if (ret == -EAGAIN && force_nonblock)
5790 return io_setup_async_msg(req, kmsg);
5791 if (ret == -ERESTARTSYS)
5793 if (ret > 0 && io_net_retry(sock, flags)) {
5795 req->flags |= REQ_F_PARTIAL_IO;
5796 return io_setup_async_msg(req, kmsg);
5799 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5803 /* fast path, check for non-NULL to avoid function call */
5805 kfree(kmsg->free_iov);
5806 req->flags &= ~REQ_F_NEED_CLEANUP;
5809 else if (sr->done_io)
5811 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5815 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5817 struct io_sr_msg *sr = &req->sr_msg;
5819 struct socket *sock;
5822 int ret, min_ret = 0;
5823 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5825 if (!(req->flags & REQ_F_POLLED) &&
5826 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5829 sock = sock_from_file(req->file);
5830 if (unlikely(!sock))
5833 if (io_do_buffer_select(req)) {
5836 buf = io_buffer_select(req, &sr->len, issue_flags);
5842 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
5846 msg.msg_name = NULL;
5847 msg.msg_control = NULL;
5848 msg.msg_controllen = 0;
5849 msg.msg_namelen = 0;
5850 msg.msg_iocb = NULL;
5853 flags = sr->msg_flags;
5855 flags |= MSG_DONTWAIT;
5856 if (flags & MSG_WAITALL)
5857 min_ret = iov_iter_count(&msg.msg_iter);
5859 ret = sock_recvmsg(sock, &msg, flags);
5860 if (ret < min_ret) {
5861 if (ret == -EAGAIN && force_nonblock)
5863 if (ret == -ERESTARTSYS)
5865 if (ret > 0 && io_net_retry(sock, flags)) {
5869 req->flags |= REQ_F_PARTIAL_IO;
5873 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5880 else if (sr->done_io)
5882 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5886 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5888 struct io_accept *accept = &req->accept;
5891 if (sqe->len || sqe->buf_index)
5894 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5895 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5896 accept->flags = READ_ONCE(sqe->accept_flags);
5897 accept->nofile = rlimit(RLIMIT_NOFILE);
5898 flags = READ_ONCE(sqe->ioprio);
5899 if (flags & ~IORING_ACCEPT_MULTISHOT)
5902 accept->file_slot = READ_ONCE(sqe->file_index);
5903 if (accept->file_slot) {
5904 if (accept->flags & SOCK_CLOEXEC)
5906 if (flags & IORING_ACCEPT_MULTISHOT &&
5907 accept->file_slot != IORING_FILE_INDEX_ALLOC)
5910 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5912 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5913 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5914 if (flags & IORING_ACCEPT_MULTISHOT)
5915 req->flags |= REQ_F_APOLL_MULTISHOT;
5919 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5921 struct io_ring_ctx *ctx = req->ctx;
5922 struct io_accept *accept = &req->accept;
5923 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5924 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5925 bool fixed = !!accept->file_slot;
5931 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5932 if (unlikely(fd < 0))
5935 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5940 ret = PTR_ERR(file);
5941 if (ret == -EAGAIN && force_nonblock) {
5943 * if it's multishot and polled, we don't need to
5944 * return EAGAIN to arm the poll infra since it
5945 * has already been done
5947 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
5948 IO_APOLL_MULTI_POLLED)
5952 if (ret == -ERESTARTSYS)
5955 } else if (!fixed) {
5956 fd_install(fd, file);
5959 ret = io_fixed_fd_install(req, issue_flags, file,
5963 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
5964 __io_req_complete(req, issue_flags, ret, 0);
5970 spin_lock(&ctx->completion_lock);
5971 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
5973 io_commit_cqring(ctx);
5974 spin_unlock(&ctx->completion_lock);
5976 io_cqring_ev_posted(ctx);
5985 static int io_connect_prep_async(struct io_kiocb *req)
5987 struct io_async_connect *io = req->async_data;
5988 struct io_connect *conn = &req->connect;
5990 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5993 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5995 struct io_connect *conn = &req->connect;
5997 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6000 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6001 conn->addr_len = READ_ONCE(sqe->addr2);
6005 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6007 struct io_async_connect __io, *io;
6008 unsigned file_flags;
6010 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6012 if (req_has_async_data(req)) {
6013 io = req->async_data;
6015 ret = move_addr_to_kernel(req->connect.addr,
6016 req->connect.addr_len,
6023 file_flags = force_nonblock ? O_NONBLOCK : 0;
6025 ret = __sys_connect_file(req->file, &io->address,
6026 req->connect.addr_len, file_flags);
6027 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6028 if (req_has_async_data(req))
6030 if (io_alloc_async_data(req)) {
6034 memcpy(req->async_data, &__io, sizeof(__io));
6037 if (ret == -ERESTARTSYS)
6042 __io_req_complete(req, issue_flags, ret, 0);
6045 #else /* !CONFIG_NET */
6046 #define IO_NETOP_FN(op) \
6047 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6049 return -EOPNOTSUPP; \
6052 #define IO_NETOP_PREP(op) \
6054 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6056 return -EOPNOTSUPP; \
6059 #define IO_NETOP_PREP_ASYNC(op) \
6061 static int io_##op##_prep_async(struct io_kiocb *req) \
6063 return -EOPNOTSUPP; \
6066 IO_NETOP_PREP_ASYNC(sendmsg);
6067 IO_NETOP_PREP_ASYNC(recvmsg);
6068 IO_NETOP_PREP_ASYNC(connect);
6069 IO_NETOP_PREP(accept);
6072 #endif /* CONFIG_NET */
6074 struct io_poll_table {
6075 struct poll_table_struct pt;
6076 struct io_kiocb *req;
6081 #define IO_POLL_CANCEL_FLAG BIT(31)
6082 #define IO_POLL_REF_MASK GENMASK(30, 0)
6085 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6086 * bump it and acquire ownership. It's disallowed to modify requests while not
6087 * owning it, that prevents from races for enqueueing task_work's and b/w
6088 * arming poll and wakeups.
6090 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6092 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6095 static void io_poll_mark_cancelled(struct io_kiocb *req)
6097 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6100 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6102 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6103 if (req->opcode == IORING_OP_POLL_ADD)
6104 return req->async_data;
6105 return req->apoll->double_poll;
6108 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6110 if (req->opcode == IORING_OP_POLL_ADD)
6112 return &req->apoll->poll;
6115 static void io_poll_req_insert(struct io_kiocb *req)
6117 struct io_ring_ctx *ctx = req->ctx;
6118 struct hlist_head *list;
6120 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6121 hlist_add_head(&req->hash_node, list);
6124 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6125 wait_queue_func_t wake_func)
6128 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6129 /* mask in events that we always want/need */
6130 poll->events = events | IO_POLL_UNMASK;
6131 INIT_LIST_HEAD(&poll->wait.entry);
6132 init_waitqueue_func_entry(&poll->wait, wake_func);
6135 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6137 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6140 spin_lock_irq(&head->lock);
6141 list_del_init(&poll->wait.entry);
6143 spin_unlock_irq(&head->lock);
6147 static void io_poll_remove_entries(struct io_kiocb *req)
6150 * Nothing to do if neither of those flags are set. Avoid dipping
6151 * into the poll/apoll/double cachelines if we can.
6153 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6157 * While we hold the waitqueue lock and the waitqueue is nonempty,
6158 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6159 * lock in the first place can race with the waitqueue being freed.
6161 * We solve this as eventpoll does: by taking advantage of the fact that
6162 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6163 * we enter rcu_read_lock() and see that the pointer to the queue is
6164 * non-NULL, we can then lock it without the memory being freed out from
6167 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6168 * case the caller deletes the entry from the queue, leaving it empty.
6169 * In that case, only RCU prevents the queue memory from being freed.
6172 if (req->flags & REQ_F_SINGLE_POLL)
6173 io_poll_remove_entry(io_poll_get_single(req));
6174 if (req->flags & REQ_F_DOUBLE_POLL)
6175 io_poll_remove_entry(io_poll_get_double(req));
6179 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6181 * All poll tw should go through this. Checks for poll events, manages
6182 * references, does rewait, etc.
6184 * Returns a negative error on failure. >0 when no action require, which is
6185 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6186 * the request, then the mask is stored in req->cqe.res.
6188 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6190 struct io_ring_ctx *ctx = req->ctx;
6193 /* req->task == current here, checking PF_EXITING is safe */
6194 if (unlikely(req->task->flags & PF_EXITING))
6198 v = atomic_read(&req->poll_refs);
6200 /* tw handler should be the owner, and so have some references */
6201 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6203 if (v & IO_POLL_CANCEL_FLAG)
6206 if (!req->cqe.res) {
6207 struct poll_table_struct pt = { ._key = req->apoll_events };
6208 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
6210 if (unlikely(!io_assign_file(req, flags)))
6212 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6215 if ((unlikely(!req->cqe.res)))
6217 if (req->apoll_events & EPOLLONESHOT)
6220 /* multishot, just fill a CQE and proceed */
6221 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6222 __poll_t mask = mangle_poll(req->cqe.res &
6226 spin_lock(&ctx->completion_lock);
6227 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6228 mask, IORING_CQE_F_MORE);
6229 io_commit_cqring(ctx);
6230 spin_unlock(&ctx->completion_lock);
6232 io_cqring_ev_posted(ctx);
6238 io_tw_lock(req->ctx, locked);
6239 if (unlikely(req->task->flags & PF_EXITING))
6241 ret = io_issue_sqe(req,
6242 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6247 * Release all references, retry if someone tried to restart
6248 * task_work while we were executing it.
6250 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6255 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6257 struct io_ring_ctx *ctx = req->ctx;
6260 ret = io_poll_check_events(req, locked);
6265 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6271 io_poll_remove_entries(req);
6272 spin_lock(&ctx->completion_lock);
6273 hash_del(&req->hash_node);
6274 __io_req_complete_post(req, req->cqe.res, 0);
6275 io_commit_cqring(ctx);
6276 spin_unlock(&ctx->completion_lock);
6277 io_cqring_ev_posted(ctx);
6280 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6282 struct io_ring_ctx *ctx = req->ctx;
6285 ret = io_poll_check_events(req, locked);
6289 io_poll_remove_entries(req);
6290 spin_lock(&ctx->completion_lock);
6291 hash_del(&req->hash_node);
6292 spin_unlock(&ctx->completion_lock);
6295 io_req_task_submit(req, locked);
6297 io_req_complete_failed(req, ret);
6300 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
6302 req->cqe.res = mask;
6304 * This is useful for poll that is armed on behalf of another
6305 * request, and where the wakeup path could be on a different
6306 * CPU. We want to avoid pulling in req->apoll->events for that
6309 req->apoll_events = events;
6310 if (req->opcode == IORING_OP_POLL_ADD)
6311 req->io_task_work.func = io_poll_task_func;
6313 req->io_task_work.func = io_apoll_task_func;
6315 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6316 io_req_task_work_add(req, false);
6319 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6321 if (io_poll_get_ownership(req))
6322 __io_poll_execute(req, res, events);
6325 static void io_poll_cancel_req(struct io_kiocb *req)
6327 io_poll_mark_cancelled(req);
6328 /* kick tw, which should complete the request */
6329 io_poll_execute(req, 0, 0);
6332 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6333 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6334 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | POLLPRI)
6336 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6339 struct io_kiocb *req = wqe_to_req(wait);
6340 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6342 __poll_t mask = key_to_poll(key);
6344 if (unlikely(mask & POLLFREE)) {
6345 io_poll_mark_cancelled(req);
6346 /* we have to kick tw in case it's not already */
6347 io_poll_execute(req, 0, poll->events);
6350 * If the waitqueue is being freed early but someone is already
6351 * holds ownership over it, we have to tear down the request as
6352 * best we can. That means immediately removing the request from
6353 * its waitqueue and preventing all further accesses to the
6354 * waitqueue via the request.
6356 list_del_init(&poll->wait.entry);
6359 * Careful: this *must* be the last step, since as soon
6360 * as req->head is NULL'ed out, the request can be
6361 * completed and freed, since aio_poll_complete_work()
6362 * will no longer need to take the waitqueue lock.
6364 smp_store_release(&poll->head, NULL);
6368 /* for instances that support it check for an event match first */
6369 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
6372 if (io_poll_get_ownership(req)) {
6373 /* optional, saves extra locking for removal in tw handler */
6374 if (mask && poll->events & EPOLLONESHOT) {
6375 list_del_init(&poll->wait.entry);
6377 if (wqe_is_double(wait))
6378 req->flags &= ~REQ_F_DOUBLE_POLL;
6380 req->flags &= ~REQ_F_SINGLE_POLL;
6382 __io_poll_execute(req, mask, poll->events);
6387 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6388 struct wait_queue_head *head,
6389 struct io_poll_iocb **poll_ptr)
6391 struct io_kiocb *req = pt->req;
6392 unsigned long wqe_private = (unsigned long) req;
6395 * The file being polled uses multiple waitqueues for poll handling
6396 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6399 if (unlikely(pt->nr_entries)) {
6400 struct io_poll_iocb *first = poll;
6402 /* double add on the same waitqueue head, ignore */
6403 if (first->head == head)
6405 /* already have a 2nd entry, fail a third attempt */
6407 if ((*poll_ptr)->head == head)
6409 pt->error = -EINVAL;
6413 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6415 pt->error = -ENOMEM;
6418 /* mark as double wq entry */
6420 req->flags |= REQ_F_DOUBLE_POLL;
6421 io_init_poll_iocb(poll, first->events, first->wait.func);
6423 if (req->opcode == IORING_OP_POLL_ADD)
6424 req->flags |= REQ_F_ASYNC_DATA;
6427 req->flags |= REQ_F_SINGLE_POLL;
6430 poll->wait.private = (void *) wqe_private;
6432 if (poll->events & EPOLLEXCLUSIVE)
6433 add_wait_queue_exclusive(head, &poll->wait);
6435 add_wait_queue(head, &poll->wait);
6438 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6439 struct poll_table_struct *p)
6441 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6443 __io_queue_proc(&pt->req->poll, pt, head,
6444 (struct io_poll_iocb **) &pt->req->async_data);
6447 static int __io_arm_poll_handler(struct io_kiocb *req,
6448 struct io_poll_iocb *poll,
6449 struct io_poll_table *ipt, __poll_t mask)
6451 struct io_ring_ctx *ctx = req->ctx;
6454 INIT_HLIST_NODE(&req->hash_node);
6455 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6456 io_init_poll_iocb(poll, mask, io_poll_wake);
6457 poll->file = req->file;
6459 ipt->pt._key = mask;
6462 ipt->nr_entries = 0;
6465 * Take the ownership to delay any tw execution up until we're done
6466 * with poll arming. see io_poll_get_ownership().
6468 atomic_set(&req->poll_refs, 1);
6469 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6471 if (mask && (poll->events & EPOLLONESHOT)) {
6472 io_poll_remove_entries(req);
6473 /* no one else has access to the req, forget about the ref */
6476 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6477 io_poll_remove_entries(req);
6479 ipt->error = -EINVAL;
6483 spin_lock(&ctx->completion_lock);
6484 io_poll_req_insert(req);
6485 spin_unlock(&ctx->completion_lock);
6488 /* can't multishot if failed, just queue the event we've got */
6489 if (unlikely(ipt->error || !ipt->nr_entries))
6490 poll->events |= EPOLLONESHOT;
6491 __io_poll_execute(req, mask, poll->events);
6496 * Release ownership. If someone tried to queue a tw while it was
6497 * locked, kick it off for them.
6499 v = atomic_dec_return(&req->poll_refs);
6500 if (unlikely(v & IO_POLL_REF_MASK))
6501 __io_poll_execute(req, 0, poll->events);
6505 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6506 struct poll_table_struct *p)
6508 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6509 struct async_poll *apoll = pt->req->apoll;
6511 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6520 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6522 const struct io_op_def *def = &io_op_defs[req->opcode];
6523 struct io_ring_ctx *ctx = req->ctx;
6524 struct async_poll *apoll;
6525 struct io_poll_table ipt;
6526 __poll_t mask = POLLPRI | POLLERR;
6529 if (!def->pollin && !def->pollout)
6530 return IO_APOLL_ABORTED;
6531 if (!file_can_poll(req->file))
6532 return IO_APOLL_ABORTED;
6533 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
6534 return IO_APOLL_ABORTED;
6535 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
6536 mask |= EPOLLONESHOT;
6539 mask |= POLLIN | POLLRDNORM;
6541 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6542 if ((req->opcode == IORING_OP_RECVMSG) &&
6543 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6546 mask |= POLLOUT | POLLWRNORM;
6548 if (def->poll_exclusive)
6549 mask |= EPOLLEXCLUSIVE;
6550 if (req->flags & REQ_F_POLLED) {
6552 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6553 !list_empty(&ctx->apoll_cache)) {
6554 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6556 list_del_init(&apoll->poll.wait.entry);
6558 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6559 if (unlikely(!apoll))
6560 return IO_APOLL_ABORTED;
6562 apoll->double_poll = NULL;
6564 req->flags |= REQ_F_POLLED;
6565 ipt.pt._qproc = io_async_queue_proc;
6567 io_kbuf_recycle(req, issue_flags);
6569 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6570 if (ret || ipt.error)
6571 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6573 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
6574 mask, apoll->poll.events);
6579 * Returns true if we found and killed one or more poll requests
6581 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6582 struct task_struct *tsk, bool cancel_all)
6584 struct hlist_node *tmp;
6585 struct io_kiocb *req;
6589 spin_lock(&ctx->completion_lock);
6590 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6591 struct hlist_head *list;
6593 list = &ctx->cancel_hash[i];
6594 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6595 if (io_match_task_safe(req, tsk, cancel_all)) {
6596 hlist_del_init(&req->hash_node);
6597 io_poll_cancel_req(req);
6602 spin_unlock(&ctx->completion_lock);
6606 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
6607 struct io_cancel_data *cd)
6608 __must_hold(&ctx->completion_lock)
6610 struct hlist_head *list;
6611 struct io_kiocb *req;
6613 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
6614 hlist_for_each_entry(req, list, hash_node) {
6615 if (cd->data != req->cqe.user_data)
6617 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6619 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
6620 if (cd->seq == req->work.cancel_seq)
6622 req->work.cancel_seq = cd->seq;
6629 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
6630 struct io_cancel_data *cd)
6631 __must_hold(&ctx->completion_lock)
6633 struct io_kiocb *req;
6636 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6637 struct hlist_head *list;
6639 list = &ctx->cancel_hash[i];
6640 hlist_for_each_entry(req, list, hash_node) {
6641 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
6642 req->file != cd->file)
6644 if (cd->seq == req->work.cancel_seq)
6646 req->work.cancel_seq = cd->seq;
6653 static bool io_poll_disarm(struct io_kiocb *req)
6654 __must_hold(&ctx->completion_lock)
6656 if (!io_poll_get_ownership(req))
6658 io_poll_remove_entries(req);
6659 hash_del(&req->hash_node);
6663 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
6664 __must_hold(&ctx->completion_lock)
6666 struct io_kiocb *req;
6668 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
6669 req = io_poll_file_find(ctx, cd);
6671 req = io_poll_find(ctx, false, cd);
6674 io_poll_cancel_req(req);
6678 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6683 events = READ_ONCE(sqe->poll32_events);
6685 events = swahw32(events);
6687 if (!(flags & IORING_POLL_ADD_MULTI))
6688 events |= EPOLLONESHOT;
6689 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6692 static int io_poll_update_prep(struct io_kiocb *req,
6693 const struct io_uring_sqe *sqe)
6695 struct io_poll_update *upd = &req->poll_update;
6698 if (sqe->buf_index || sqe->splice_fd_in)
6700 flags = READ_ONCE(sqe->len);
6701 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6702 IORING_POLL_ADD_MULTI))
6704 /* meaningless without update */
6705 if (flags == IORING_POLL_ADD_MULTI)
6708 upd->old_user_data = READ_ONCE(sqe->addr);
6709 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6710 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6712 upd->new_user_data = READ_ONCE(sqe->off);
6713 if (!upd->update_user_data && upd->new_user_data)
6715 if (upd->update_events)
6716 upd->events = io_poll_parse_events(sqe, flags);
6717 else if (sqe->poll32_events)
6723 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6725 struct io_poll_iocb *poll = &req->poll;
6728 if (sqe->buf_index || sqe->off || sqe->addr)
6730 flags = READ_ONCE(sqe->len);
6731 if (flags & ~IORING_POLL_ADD_MULTI)
6733 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6736 io_req_set_refcount(req);
6737 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
6741 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6743 struct io_poll_iocb *poll = &req->poll;
6744 struct io_poll_table ipt;
6747 ipt.pt._qproc = io_poll_queue_proc;
6749 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6750 ret = ret ?: ipt.error;
6752 __io_req_complete(req, issue_flags, ret, 0);
6756 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6758 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
6759 struct io_ring_ctx *ctx = req->ctx;
6760 struct io_kiocb *preq;
6764 spin_lock(&ctx->completion_lock);
6765 preq = io_poll_find(ctx, true, &cd);
6766 if (!preq || !io_poll_disarm(preq)) {
6767 spin_unlock(&ctx->completion_lock);
6768 ret = preq ? -EALREADY : -ENOENT;
6771 spin_unlock(&ctx->completion_lock);
6773 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6774 /* only mask one event flags, keep behavior flags */
6775 if (req->poll_update.update_events) {
6776 preq->poll.events &= ~0xffff;
6777 preq->poll.events |= req->poll_update.events & 0xffff;
6778 preq->poll.events |= IO_POLL_UNMASK;
6780 if (req->poll_update.update_user_data)
6781 preq->cqe.user_data = req->poll_update.new_user_data;
6783 ret2 = io_poll_add(preq, issue_flags);
6784 /* successfully updated, don't complete poll request */
6790 preq->cqe.res = -ECANCELED;
6791 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6792 io_req_task_complete(preq, &locked);
6796 /* complete update request, we're done with it */
6797 __io_req_complete(req, issue_flags, ret, 0);
6801 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6803 struct io_timeout_data *data = container_of(timer,
6804 struct io_timeout_data, timer);
6805 struct io_kiocb *req = data->req;
6806 struct io_ring_ctx *ctx = req->ctx;
6807 unsigned long flags;
6809 spin_lock_irqsave(&ctx->timeout_lock, flags);
6810 list_del_init(&req->timeout.list);
6811 atomic_set(&req->ctx->cq_timeouts,
6812 atomic_read(&req->ctx->cq_timeouts) + 1);
6813 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6815 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6818 req->cqe.res = -ETIME;
6819 req->io_task_work.func = io_req_task_complete;
6820 io_req_task_work_add(req, false);
6821 return HRTIMER_NORESTART;
6824 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6825 struct io_cancel_data *cd)
6826 __must_hold(&ctx->timeout_lock)
6828 struct io_timeout_data *io;
6829 struct io_kiocb *req;
6832 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6833 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
6834 cd->data != req->cqe.user_data)
6836 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
6837 if (cd->seq == req->work.cancel_seq)
6839 req->work.cancel_seq = cd->seq;
6845 return ERR_PTR(-ENOENT);
6847 io = req->async_data;
6848 if (hrtimer_try_to_cancel(&io->timer) == -1)
6849 return ERR_PTR(-EALREADY);
6850 list_del_init(&req->timeout.list);
6854 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
6855 __must_hold(&ctx->completion_lock)
6857 struct io_kiocb *req;
6859 spin_lock_irq(&ctx->timeout_lock);
6860 req = io_timeout_extract(ctx, cd);
6861 spin_unlock_irq(&ctx->timeout_lock);
6864 return PTR_ERR(req);
6865 io_req_task_queue_fail(req, -ECANCELED);
6869 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6871 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6872 case IORING_TIMEOUT_BOOTTIME:
6873 return CLOCK_BOOTTIME;
6874 case IORING_TIMEOUT_REALTIME:
6875 return CLOCK_REALTIME;
6877 /* can't happen, vetted at prep time */
6881 return CLOCK_MONOTONIC;
6885 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6886 struct timespec64 *ts, enum hrtimer_mode mode)
6887 __must_hold(&ctx->timeout_lock)
6889 struct io_timeout_data *io;
6890 struct io_kiocb *req;
6893 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6894 found = user_data == req->cqe.user_data;
6901 io = req->async_data;
6902 if (hrtimer_try_to_cancel(&io->timer) == -1)
6904 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6905 io->timer.function = io_link_timeout_fn;
6906 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6910 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6911 struct timespec64 *ts, enum hrtimer_mode mode)
6912 __must_hold(&ctx->timeout_lock)
6914 struct io_cancel_data cd = { .data = user_data, };
6915 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
6916 struct io_timeout_data *data;
6919 return PTR_ERR(req);
6921 req->timeout.off = 0; /* noseq */
6922 data = req->async_data;
6923 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6924 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6925 data->timer.function = io_timeout_fn;
6926 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6930 static int io_timeout_remove_prep(struct io_kiocb *req,
6931 const struct io_uring_sqe *sqe)
6933 struct io_timeout_rem *tr = &req->timeout_rem;
6935 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6937 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
6940 tr->ltimeout = false;
6941 tr->addr = READ_ONCE(sqe->addr);
6942 tr->flags = READ_ONCE(sqe->timeout_flags);
6943 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6944 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6946 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6947 tr->ltimeout = true;
6948 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6950 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6952 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6954 } else if (tr->flags) {
6955 /* timeout removal doesn't support flags */
6962 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6964 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6969 * Remove or update an existing timeout command
6971 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6973 struct io_timeout_rem *tr = &req->timeout_rem;
6974 struct io_ring_ctx *ctx = req->ctx;
6977 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6978 struct io_cancel_data cd = { .data = tr->addr, };
6980 spin_lock(&ctx->completion_lock);
6981 ret = io_timeout_cancel(ctx, &cd);
6982 spin_unlock(&ctx->completion_lock);
6984 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6986 spin_lock_irq(&ctx->timeout_lock);
6988 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6990 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6991 spin_unlock_irq(&ctx->timeout_lock);
6996 io_req_complete_post(req, ret, 0);
7000 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
7001 bool is_timeout_link)
7003 struct io_timeout_data *data;
7005 u32 off = READ_ONCE(sqe->off);
7007 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7009 if (off && is_timeout_link)
7011 flags = READ_ONCE(sqe->timeout_flags);
7012 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7013 IORING_TIMEOUT_ETIME_SUCCESS))
7015 /* more than one clock specified is invalid, obviously */
7016 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7019 INIT_LIST_HEAD(&req->timeout.list);
7020 req->timeout.off = off;
7021 if (unlikely(off && !req->ctx->off_timeout_used))
7022 req->ctx->off_timeout_used = true;
7024 if (WARN_ON_ONCE(req_has_async_data(req)))
7026 if (io_alloc_async_data(req))
7029 data = req->async_data;
7031 data->flags = flags;
7033 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7036 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7039 INIT_LIST_HEAD(&req->timeout.list);
7040 data->mode = io_translate_timeout_mode(flags);
7041 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7043 if (is_timeout_link) {
7044 struct io_submit_link *link = &req->ctx->submit_state.link;
7048 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7050 req->timeout.head = link->last;
7051 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7056 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7058 struct io_ring_ctx *ctx = req->ctx;
7059 struct io_timeout_data *data = req->async_data;
7060 struct list_head *entry;
7061 u32 tail, off = req->timeout.off;
7063 spin_lock_irq(&ctx->timeout_lock);
7066 * sqe->off holds how many events that need to occur for this
7067 * timeout event to be satisfied. If it isn't set, then this is
7068 * a pure timeout request, sequence isn't used.
7070 if (io_is_timeout_noseq(req)) {
7071 entry = ctx->timeout_list.prev;
7075 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7076 req->timeout.target_seq = tail + off;
7078 /* Update the last seq here in case io_flush_timeouts() hasn't.
7079 * This is safe because ->completion_lock is held, and submissions
7080 * and completions are never mixed in the same ->completion_lock section.
7082 ctx->cq_last_tm_flush = tail;
7085 * Insertion sort, ensuring the first entry in the list is always
7086 * the one we need first.
7088 list_for_each_prev(entry, &ctx->timeout_list) {
7089 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7092 if (io_is_timeout_noseq(nxt))
7094 /* nxt.seq is behind @tail, otherwise would've been completed */
7095 if (off >= nxt->timeout.target_seq - tail)
7099 list_add(&req->timeout.list, entry);
7100 data->timer.function = io_timeout_fn;
7101 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7102 spin_unlock_irq(&ctx->timeout_lock);
7106 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7108 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7109 struct io_cancel_data *cd = data;
7111 if (req->ctx != cd->ctx)
7113 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7115 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7116 if (req->file != cd->file)
7119 if (req->cqe.user_data != cd->data)
7122 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7123 if (cd->seq == req->work.cancel_seq)
7125 req->work.cancel_seq = cd->seq;
7130 static int io_async_cancel_one(struct io_uring_task *tctx,
7131 struct io_cancel_data *cd)
7133 enum io_wq_cancel cancel_ret;
7137 if (!tctx || !tctx->io_wq)
7140 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7141 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7142 switch (cancel_ret) {
7143 case IO_WQ_CANCEL_OK:
7146 case IO_WQ_CANCEL_RUNNING:
7149 case IO_WQ_CANCEL_NOTFOUND:
7157 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7159 struct io_ring_ctx *ctx = req->ctx;
7162 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7164 ret = io_async_cancel_one(req->task->io_uring, cd);
7166 * Fall-through even for -EALREADY, as we may have poll armed
7167 * that need unarming.
7172 spin_lock(&ctx->completion_lock);
7173 ret = io_poll_cancel(ctx, cd);
7176 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7177 ret = io_timeout_cancel(ctx, cd);
7179 spin_unlock(&ctx->completion_lock);
7183 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7184 IORING_ASYNC_CANCEL_ANY)
7186 static int io_async_cancel_prep(struct io_kiocb *req,
7187 const struct io_uring_sqe *sqe)
7189 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7191 if (sqe->off || sqe->len || sqe->splice_fd_in)
7194 req->cancel.addr = READ_ONCE(sqe->addr);
7195 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7196 if (req->cancel.flags & ~CANCEL_FLAGS)
7198 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7199 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7201 req->cancel.fd = READ_ONCE(sqe->fd);
7207 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7208 unsigned int issue_flags)
7210 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7211 struct io_ring_ctx *ctx = cd->ctx;
7212 struct io_tctx_node *node;
7216 ret = io_try_cancel(req, cd);
7224 /* slow path, try all io-wq's */
7225 io_ring_submit_lock(ctx, issue_flags);
7227 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7228 struct io_uring_task *tctx = node->task->io_uring;
7230 ret = io_async_cancel_one(tctx, cd);
7231 if (ret != -ENOENT) {
7237 io_ring_submit_unlock(ctx, issue_flags);
7238 return all ? nr : ret;
7241 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7243 struct io_cancel_data cd = {
7245 .data = req->cancel.addr,
7246 .flags = req->cancel.flags,
7247 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7251 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7252 if (req->flags & REQ_F_FIXED_FILE)
7253 req->file = io_file_get_fixed(req, req->cancel.fd,
7256 req->file = io_file_get_normal(req, req->cancel.fd);
7261 cd.file = req->file;
7264 ret = __io_async_cancel(&cd, req, issue_flags);
7268 io_req_complete_post(req, ret, 0);
7272 static int io_rsrc_update_prep(struct io_kiocb *req,
7273 const struct io_uring_sqe *sqe)
7275 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7277 if (sqe->rw_flags || sqe->splice_fd_in)
7280 req->rsrc_update.offset = READ_ONCE(sqe->off);
7281 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7282 if (!req->rsrc_update.nr_args)
7284 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7288 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7290 struct io_ring_ctx *ctx = req->ctx;
7291 struct io_uring_rsrc_update2 up;
7294 up.offset = req->rsrc_update.offset;
7295 up.data = req->rsrc_update.arg;
7301 io_ring_submit_lock(ctx, issue_flags);
7302 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7303 &up, req->rsrc_update.nr_args);
7304 io_ring_submit_unlock(ctx, issue_flags);
7308 __io_req_complete(req, issue_flags, ret, 0);
7312 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7314 switch (req->opcode) {
7317 case IORING_OP_READV:
7318 case IORING_OP_READ_FIXED:
7319 case IORING_OP_READ:
7320 case IORING_OP_WRITEV:
7321 case IORING_OP_WRITE_FIXED:
7322 case IORING_OP_WRITE:
7323 return io_prep_rw(req, sqe);
7324 case IORING_OP_POLL_ADD:
7325 return io_poll_add_prep(req, sqe);
7326 case IORING_OP_POLL_REMOVE:
7327 return io_poll_update_prep(req, sqe);
7328 case IORING_OP_FSYNC:
7329 return io_fsync_prep(req, sqe);
7330 case IORING_OP_SYNC_FILE_RANGE:
7331 return io_sfr_prep(req, sqe);
7332 case IORING_OP_SENDMSG:
7333 case IORING_OP_SEND:
7334 return io_sendmsg_prep(req, sqe);
7335 case IORING_OP_RECVMSG:
7336 case IORING_OP_RECV:
7337 return io_recvmsg_prep(req, sqe);
7338 case IORING_OP_CONNECT:
7339 return io_connect_prep(req, sqe);
7340 case IORING_OP_TIMEOUT:
7341 return io_timeout_prep(req, sqe, false);
7342 case IORING_OP_TIMEOUT_REMOVE:
7343 return io_timeout_remove_prep(req, sqe);
7344 case IORING_OP_ASYNC_CANCEL:
7345 return io_async_cancel_prep(req, sqe);
7346 case IORING_OP_LINK_TIMEOUT:
7347 return io_timeout_prep(req, sqe, true);
7348 case IORING_OP_ACCEPT:
7349 return io_accept_prep(req, sqe);
7350 case IORING_OP_FALLOCATE:
7351 return io_fallocate_prep(req, sqe);
7352 case IORING_OP_OPENAT:
7353 return io_openat_prep(req, sqe);
7354 case IORING_OP_CLOSE:
7355 return io_close_prep(req, sqe);
7356 case IORING_OP_FILES_UPDATE:
7357 return io_rsrc_update_prep(req, sqe);
7358 case IORING_OP_STATX:
7359 return io_statx_prep(req, sqe);
7360 case IORING_OP_FADVISE:
7361 return io_fadvise_prep(req, sqe);
7362 case IORING_OP_MADVISE:
7363 return io_madvise_prep(req, sqe);
7364 case IORING_OP_OPENAT2:
7365 return io_openat2_prep(req, sqe);
7366 case IORING_OP_EPOLL_CTL:
7367 return io_epoll_ctl_prep(req, sqe);
7368 case IORING_OP_SPLICE:
7369 return io_splice_prep(req, sqe);
7370 case IORING_OP_PROVIDE_BUFFERS:
7371 return io_provide_buffers_prep(req, sqe);
7372 case IORING_OP_REMOVE_BUFFERS:
7373 return io_remove_buffers_prep(req, sqe);
7375 return io_tee_prep(req, sqe);
7376 case IORING_OP_SHUTDOWN:
7377 return io_shutdown_prep(req, sqe);
7378 case IORING_OP_RENAMEAT:
7379 return io_renameat_prep(req, sqe);
7380 case IORING_OP_UNLINKAT:
7381 return io_unlinkat_prep(req, sqe);
7382 case IORING_OP_MKDIRAT:
7383 return io_mkdirat_prep(req, sqe);
7384 case IORING_OP_SYMLINKAT:
7385 return io_symlinkat_prep(req, sqe);
7386 case IORING_OP_LINKAT:
7387 return io_linkat_prep(req, sqe);
7388 case IORING_OP_MSG_RING:
7389 return io_msg_ring_prep(req, sqe);
7392 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
7397 static int io_req_prep_async(struct io_kiocb *req)
7399 if (!io_op_defs[req->opcode].needs_async_setup)
7401 if (WARN_ON_ONCE(req_has_async_data(req)))
7403 if (io_alloc_async_data(req))
7406 switch (req->opcode) {
7407 case IORING_OP_READV:
7408 return io_rw_prep_async(req, READ);
7409 case IORING_OP_WRITEV:
7410 return io_rw_prep_async(req, WRITE);
7411 case IORING_OP_SENDMSG:
7412 return io_sendmsg_prep_async(req);
7413 case IORING_OP_RECVMSG:
7414 return io_recvmsg_prep_async(req);
7415 case IORING_OP_CONNECT:
7416 return io_connect_prep_async(req);
7418 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7423 static u32 io_get_sequence(struct io_kiocb *req)
7425 u32 seq = req->ctx->cached_sq_head;
7426 struct io_kiocb *cur;
7428 /* need original cached_sq_head, but it was increased for each req */
7429 io_for_each_link(cur, req)
7434 static __cold void io_drain_req(struct io_kiocb *req)
7436 struct io_ring_ctx *ctx = req->ctx;
7437 struct io_defer_entry *de;
7439 u32 seq = io_get_sequence(req);
7441 /* Still need defer if there is pending req in defer list. */
7442 spin_lock(&ctx->completion_lock);
7443 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7444 spin_unlock(&ctx->completion_lock);
7446 ctx->drain_active = false;
7447 io_req_task_queue(req);
7450 spin_unlock(&ctx->completion_lock);
7452 ret = io_req_prep_async(req);
7455 io_req_complete_failed(req, ret);
7458 io_prep_async_link(req);
7459 de = kmalloc(sizeof(*de), GFP_KERNEL);
7465 spin_lock(&ctx->completion_lock);
7466 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7467 spin_unlock(&ctx->completion_lock);
7472 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7475 list_add_tail(&de->list, &ctx->defer_list);
7476 spin_unlock(&ctx->completion_lock);
7479 static void io_clean_op(struct io_kiocb *req)
7481 if (req->flags & REQ_F_BUFFER_SELECTED) {
7482 spin_lock(&req->ctx->completion_lock);
7483 io_put_kbuf_comp(req);
7484 spin_unlock(&req->ctx->completion_lock);
7487 if (req->flags & REQ_F_NEED_CLEANUP) {
7488 switch (req->opcode) {
7489 case IORING_OP_READV:
7490 case IORING_OP_READ_FIXED:
7491 case IORING_OP_READ:
7492 case IORING_OP_WRITEV:
7493 case IORING_OP_WRITE_FIXED:
7494 case IORING_OP_WRITE: {
7495 struct io_async_rw *io = req->async_data;
7497 kfree(io->free_iovec);
7500 case IORING_OP_RECVMSG:
7501 case IORING_OP_SENDMSG: {
7502 struct io_async_msghdr *io = req->async_data;
7504 kfree(io->free_iov);
7507 case IORING_OP_OPENAT:
7508 case IORING_OP_OPENAT2:
7509 if (req->open.filename)
7510 putname(req->open.filename);
7512 case IORING_OP_RENAMEAT:
7513 putname(req->rename.oldpath);
7514 putname(req->rename.newpath);
7516 case IORING_OP_UNLINKAT:
7517 putname(req->unlink.filename);
7519 case IORING_OP_MKDIRAT:
7520 putname(req->mkdir.filename);
7522 case IORING_OP_SYMLINKAT:
7523 putname(req->symlink.oldpath);
7524 putname(req->symlink.newpath);
7526 case IORING_OP_LINKAT:
7527 putname(req->hardlink.oldpath);
7528 putname(req->hardlink.newpath);
7530 case IORING_OP_STATX:
7531 if (req->statx.filename)
7532 putname(req->statx.filename);
7536 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7537 kfree(req->apoll->double_poll);
7541 if (req->flags & REQ_F_CREDS)
7542 put_cred(req->creds);
7543 if (req->flags & REQ_F_ASYNC_DATA) {
7544 kfree(req->async_data);
7545 req->async_data = NULL;
7547 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7550 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7552 if (req->file || !io_op_defs[req->opcode].needs_file)
7555 if (req->flags & REQ_F_FIXED_FILE)
7556 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
7558 req->file = io_file_get_normal(req, req->cqe.fd);
7563 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7565 const struct cred *creds = NULL;
7568 if (unlikely(!io_assign_file(req, issue_flags)))
7571 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7572 creds = override_creds(req->creds);
7574 if (!io_op_defs[req->opcode].audit_skip)
7575 audit_uring_entry(req->opcode);
7577 switch (req->opcode) {
7579 ret = io_nop(req, issue_flags);
7581 case IORING_OP_READV:
7582 case IORING_OP_READ_FIXED:
7583 case IORING_OP_READ:
7584 ret = io_read(req, issue_flags);
7586 case IORING_OP_WRITEV:
7587 case IORING_OP_WRITE_FIXED:
7588 case IORING_OP_WRITE:
7589 ret = io_write(req, issue_flags);
7591 case IORING_OP_FSYNC:
7592 ret = io_fsync(req, issue_flags);
7594 case IORING_OP_POLL_ADD:
7595 ret = io_poll_add(req, issue_flags);
7597 case IORING_OP_POLL_REMOVE:
7598 ret = io_poll_update(req, issue_flags);
7600 case IORING_OP_SYNC_FILE_RANGE:
7601 ret = io_sync_file_range(req, issue_flags);
7603 case IORING_OP_SENDMSG:
7604 ret = io_sendmsg(req, issue_flags);
7606 case IORING_OP_SEND:
7607 ret = io_send(req, issue_flags);
7609 case IORING_OP_RECVMSG:
7610 ret = io_recvmsg(req, issue_flags);
7612 case IORING_OP_RECV:
7613 ret = io_recv(req, issue_flags);
7615 case IORING_OP_TIMEOUT:
7616 ret = io_timeout(req, issue_flags);
7618 case IORING_OP_TIMEOUT_REMOVE:
7619 ret = io_timeout_remove(req, issue_flags);
7621 case IORING_OP_ACCEPT:
7622 ret = io_accept(req, issue_flags);
7624 case IORING_OP_CONNECT:
7625 ret = io_connect(req, issue_flags);
7627 case IORING_OP_ASYNC_CANCEL:
7628 ret = io_async_cancel(req, issue_flags);
7630 case IORING_OP_FALLOCATE:
7631 ret = io_fallocate(req, issue_flags);
7633 case IORING_OP_OPENAT:
7634 ret = io_openat(req, issue_flags);
7636 case IORING_OP_CLOSE:
7637 ret = io_close(req, issue_flags);
7639 case IORING_OP_FILES_UPDATE:
7640 ret = io_files_update(req, issue_flags);
7642 case IORING_OP_STATX:
7643 ret = io_statx(req, issue_flags);
7645 case IORING_OP_FADVISE:
7646 ret = io_fadvise(req, issue_flags);
7648 case IORING_OP_MADVISE:
7649 ret = io_madvise(req, issue_flags);
7651 case IORING_OP_OPENAT2:
7652 ret = io_openat2(req, issue_flags);
7654 case IORING_OP_EPOLL_CTL:
7655 ret = io_epoll_ctl(req, issue_flags);
7657 case IORING_OP_SPLICE:
7658 ret = io_splice(req, issue_flags);
7660 case IORING_OP_PROVIDE_BUFFERS:
7661 ret = io_provide_buffers(req, issue_flags);
7663 case IORING_OP_REMOVE_BUFFERS:
7664 ret = io_remove_buffers(req, issue_flags);
7667 ret = io_tee(req, issue_flags);
7669 case IORING_OP_SHUTDOWN:
7670 ret = io_shutdown(req, issue_flags);
7672 case IORING_OP_RENAMEAT:
7673 ret = io_renameat(req, issue_flags);
7675 case IORING_OP_UNLINKAT:
7676 ret = io_unlinkat(req, issue_flags);
7678 case IORING_OP_MKDIRAT:
7679 ret = io_mkdirat(req, issue_flags);
7681 case IORING_OP_SYMLINKAT:
7682 ret = io_symlinkat(req, issue_flags);
7684 case IORING_OP_LINKAT:
7685 ret = io_linkat(req, issue_flags);
7687 case IORING_OP_MSG_RING:
7688 ret = io_msg_ring(req, issue_flags);
7695 if (!io_op_defs[req->opcode].audit_skip)
7696 audit_uring_exit(!ret, ret);
7699 revert_creds(creds);
7702 /* If the op doesn't have a file, we're not polling for it */
7703 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7704 io_iopoll_req_issued(req, issue_flags);
7709 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7711 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7713 req = io_put_req_find_next(req);
7714 return req ? &req->work : NULL;
7717 static void io_wq_submit_work(struct io_wq_work *work)
7719 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7720 const struct io_op_def *def = &io_op_defs[req->opcode];
7721 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7722 bool needs_poll = false;
7723 int ret = 0, err = -ECANCELED;
7725 /* one will be dropped by ->io_free_work() after returning to io-wq */
7726 if (!(req->flags & REQ_F_REFCOUNT))
7727 __io_req_set_refcount(req, 2);
7731 io_arm_ltimeout(req);
7733 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7734 if (work->flags & IO_WQ_WORK_CANCEL) {
7736 io_req_task_queue_fail(req, err);
7739 if (!io_assign_file(req, issue_flags)) {
7741 work->flags |= IO_WQ_WORK_CANCEL;
7745 if (req->flags & REQ_F_FORCE_ASYNC) {
7746 bool opcode_poll = def->pollin || def->pollout;
7748 if (opcode_poll && file_can_poll(req->file)) {
7750 issue_flags |= IO_URING_F_NONBLOCK;
7755 ret = io_issue_sqe(req, issue_flags);
7759 * We can get EAGAIN for iopolled IO even though we're
7760 * forcing a sync submission from here, since we can't
7761 * wait for request slots on the block side.
7764 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
7770 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7772 /* aborted or ready, in either case retry blocking */
7774 issue_flags &= ~IO_URING_F_NONBLOCK;
7777 /* avoid locking problems by failing it from a clean context */
7779 io_req_task_queue_fail(req, ret);
7782 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7785 return &table->files[i];
7788 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7791 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7793 return (struct file *) (slot->file_ptr & FFS_MASK);
7796 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7798 unsigned long file_ptr = (unsigned long) file;
7800 file_ptr |= io_file_get_flags(file);
7801 file_slot->file_ptr = file_ptr;
7804 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
7805 unsigned int issue_flags)
7807 struct io_ring_ctx *ctx = req->ctx;
7808 struct file *file = NULL;
7809 unsigned long file_ptr;
7811 io_ring_submit_lock(ctx, issue_flags);
7813 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7815 fd = array_index_nospec(fd, ctx->nr_user_files);
7816 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7817 file = (struct file *) (file_ptr & FFS_MASK);
7818 file_ptr &= ~FFS_MASK;
7819 /* mask in overlapping REQ_F and FFS bits */
7820 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7821 io_req_set_rsrc_node(req, ctx, 0);
7822 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
7824 io_ring_submit_unlock(ctx, issue_flags);
7829 * Drop the file for requeue operations. Only used of req->file is the
7830 * io_uring descriptor itself.
7832 static void io_drop_inflight_file(struct io_kiocb *req)
7834 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
7837 req->flags &= ~REQ_F_INFLIGHT;
7841 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
7843 struct file *file = fget(fd);
7845 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
7847 /* we don't allow fixed io_uring files */
7848 if (file && file->f_op == &io_uring_fops)
7849 req->flags |= REQ_F_INFLIGHT;
7853 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7855 struct io_kiocb *prev = req->timeout.prev;
7859 if (!(req->task->flags & PF_EXITING)) {
7860 struct io_cancel_data cd = {
7862 .data = prev->cqe.user_data,
7865 ret = io_try_cancel(req, &cd);
7867 io_req_complete_post(req, ret ?: -ETIME, 0);
7870 io_req_complete_post(req, -ETIME, 0);
7874 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7876 struct io_timeout_data *data = container_of(timer,
7877 struct io_timeout_data, timer);
7878 struct io_kiocb *prev, *req = data->req;
7879 struct io_ring_ctx *ctx = req->ctx;
7880 unsigned long flags;
7882 spin_lock_irqsave(&ctx->timeout_lock, flags);
7883 prev = req->timeout.head;
7884 req->timeout.head = NULL;
7887 * We don't expect the list to be empty, that will only happen if we
7888 * race with the completion of the linked work.
7891 io_remove_next_linked(prev);
7892 if (!req_ref_inc_not_zero(prev))
7895 list_del(&req->timeout.list);
7896 req->timeout.prev = prev;
7897 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7899 req->io_task_work.func = io_req_task_link_timeout;
7900 io_req_task_work_add(req, false);
7901 return HRTIMER_NORESTART;
7904 static void io_queue_linked_timeout(struct io_kiocb *req)
7906 struct io_ring_ctx *ctx = req->ctx;
7908 spin_lock_irq(&ctx->timeout_lock);
7910 * If the back reference is NULL, then our linked request finished
7911 * before we got a chance to setup the timer
7913 if (req->timeout.head) {
7914 struct io_timeout_data *data = req->async_data;
7916 data->timer.function = io_link_timeout_fn;
7917 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7919 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7921 spin_unlock_irq(&ctx->timeout_lock);
7922 /* drop submission reference */
7926 static void io_queue_async(struct io_kiocb *req, int ret)
7927 __must_hold(&req->ctx->uring_lock)
7929 struct io_kiocb *linked_timeout;
7931 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
7932 io_req_complete_failed(req, ret);
7936 linked_timeout = io_prep_linked_timeout(req);
7938 switch (io_arm_poll_handler(req, 0)) {
7939 case IO_APOLL_READY:
7940 io_req_task_queue(req);
7942 case IO_APOLL_ABORTED:
7944 * Queued up for async execution, worker will release
7945 * submit reference when the iocb is actually submitted.
7947 io_queue_iowq(req, NULL);
7954 io_queue_linked_timeout(linked_timeout);
7957 static inline void io_queue_sqe(struct io_kiocb *req)
7958 __must_hold(&req->ctx->uring_lock)
7962 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7964 if (req->flags & REQ_F_COMPLETE_INLINE) {
7965 io_req_add_compl_list(req);
7969 * We async punt it if the file wasn't marked NOWAIT, or if the file
7970 * doesn't support non-blocking read/write attempts
7973 io_arm_ltimeout(req);
7975 io_queue_async(req, ret);
7978 static void io_queue_sqe_fallback(struct io_kiocb *req)
7979 __must_hold(&req->ctx->uring_lock)
7981 if (unlikely(req->flags & REQ_F_FAIL)) {
7983 * We don't submit, fail them all, for that replace hardlinks
7984 * with normal links. Extra REQ_F_LINK is tolerated.
7986 req->flags &= ~REQ_F_HARDLINK;
7987 req->flags |= REQ_F_LINK;
7988 io_req_complete_failed(req, req->cqe.res);
7989 } else if (unlikely(req->ctx->drain_active)) {
7992 int ret = io_req_prep_async(req);
7995 io_req_complete_failed(req, ret);
7997 io_queue_iowq(req, NULL);
8002 * Check SQE restrictions (opcode and flags).
8004 * Returns 'true' if SQE is allowed, 'false' otherwise.
8006 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8007 struct io_kiocb *req,
8008 unsigned int sqe_flags)
8010 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8013 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8014 ctx->restrictions.sqe_flags_required)
8017 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8018 ctx->restrictions.sqe_flags_required))
8024 static void io_init_req_drain(struct io_kiocb *req)
8026 struct io_ring_ctx *ctx = req->ctx;
8027 struct io_kiocb *head = ctx->submit_state.link.head;
8029 ctx->drain_active = true;
8032 * If we need to drain a request in the middle of a link, drain
8033 * the head request and the next request/link after the current
8034 * link. Considering sequential execution of links,
8035 * REQ_F_IO_DRAIN will be maintained for every request of our
8038 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8039 ctx->drain_next = true;
8043 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8044 const struct io_uring_sqe *sqe)
8045 __must_hold(&ctx->uring_lock)
8047 unsigned int sqe_flags;
8051 /* req is partially pre-initialised, see io_preinit_req() */
8052 req->opcode = opcode = READ_ONCE(sqe->opcode);
8053 /* same numerical values with corresponding REQ_F_*, safe to copy */
8054 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8055 req->cqe.user_data = READ_ONCE(sqe->user_data);
8057 req->rsrc_node = NULL;
8058 req->task = current;
8060 if (unlikely(opcode >= IORING_OP_LAST)) {
8064 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8065 /* enforce forwards compatibility on users */
8066 if (sqe_flags & ~SQE_VALID_FLAGS)
8068 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8069 if (!io_op_defs[opcode].buffer_select)
8071 req->buf_index = READ_ONCE(sqe->buf_group);
8073 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8074 ctx->drain_disabled = true;
8075 if (sqe_flags & IOSQE_IO_DRAIN) {
8076 if (ctx->drain_disabled)
8078 io_init_req_drain(req);
8081 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8082 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8084 /* knock it to the slow queue path, will be drained there */
8085 if (ctx->drain_active)
8086 req->flags |= REQ_F_FORCE_ASYNC;
8087 /* if there is no link, we're at "next" request and need to drain */
8088 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8089 ctx->drain_next = false;
8090 ctx->drain_active = true;
8091 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8095 if (!io_op_defs[opcode].ioprio && sqe->ioprio)
8097 if (!io_op_defs[opcode].iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8100 if (io_op_defs[opcode].needs_file) {
8101 struct io_submit_state *state = &ctx->submit_state;
8103 req->cqe.fd = READ_ONCE(sqe->fd);
8106 * Plug now if we have more than 2 IO left after this, and the
8107 * target is potentially a read/write to block based storage.
8109 if (state->need_plug && io_op_defs[opcode].plug) {
8110 state->plug_started = true;
8111 state->need_plug = false;
8112 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8116 personality = READ_ONCE(sqe->personality);
8120 req->creds = xa_load(&ctx->personalities, personality);
8123 get_cred(req->creds);
8124 ret = security_uring_override_creds(req->creds);
8126 put_cred(req->creds);
8129 req->flags |= REQ_F_CREDS;
8132 return io_req_prep(req, sqe);
8135 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8136 struct io_kiocb *req, int ret)
8138 struct io_ring_ctx *ctx = req->ctx;
8139 struct io_submit_link *link = &ctx->submit_state.link;
8140 struct io_kiocb *head = link->head;
8142 trace_io_uring_req_failed(sqe, ctx, req, ret);
8145 * Avoid breaking links in the middle as it renders links with SQPOLL
8146 * unusable. Instead of failing eagerly, continue assembling the link if
8147 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8148 * should find the flag and handle the rest.
8150 req_fail_link_node(req, ret);
8151 if (head && !(head->flags & REQ_F_FAIL))
8152 req_fail_link_node(head, -ECANCELED);
8154 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8156 link->last->link = req;
8160 io_queue_sqe_fallback(req);
8165 link->last->link = req;
8172 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8173 const struct io_uring_sqe *sqe)
8174 __must_hold(&ctx->uring_lock)
8176 struct io_submit_link *link = &ctx->submit_state.link;
8179 ret = io_init_req(ctx, req, sqe);
8181 return io_submit_fail_init(sqe, req, ret);
8183 /* don't need @sqe from now on */
8184 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8186 ctx->flags & IORING_SETUP_SQPOLL);
8189 * If we already have a head request, queue this one for async
8190 * submittal once the head completes. If we don't have a head but
8191 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8192 * submitted sync once the chain is complete. If none of those
8193 * conditions are true (normal request), then just queue it.
8195 if (unlikely(link->head)) {
8196 ret = io_req_prep_async(req);
8198 return io_submit_fail_init(sqe, req, ret);
8200 trace_io_uring_link(ctx, req, link->head);
8201 link->last->link = req;
8204 if (req->flags & IO_REQ_LINK_FLAGS)
8206 /* last request of the link, flush it */
8209 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8212 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8213 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8214 if (req->flags & IO_REQ_LINK_FLAGS) {
8219 io_queue_sqe_fallback(req);
8229 * Batched submission is done, ensure local IO is flushed out.
8231 static void io_submit_state_end(struct io_ring_ctx *ctx)
8233 struct io_submit_state *state = &ctx->submit_state;
8235 if (unlikely(state->link.head))
8236 io_queue_sqe_fallback(state->link.head);
8237 /* flush only after queuing links as they can generate completions */
8238 io_submit_flush_completions(ctx);
8239 if (state->plug_started)
8240 blk_finish_plug(&state->plug);
8244 * Start submission side cache.
8246 static void io_submit_state_start(struct io_submit_state *state,
8247 unsigned int max_ios)
8249 state->plug_started = false;
8250 state->need_plug = max_ios > 2;
8251 state->submit_nr = max_ios;
8252 /* set only head, no need to init link_last in advance */
8253 state->link.head = NULL;
8256 static void io_commit_sqring(struct io_ring_ctx *ctx)
8258 struct io_rings *rings = ctx->rings;
8261 * Ensure any loads from the SQEs are done at this point,
8262 * since once we write the new head, the application could
8263 * write new data to them.
8265 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8269 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8270 * that is mapped by userspace. This means that care needs to be taken to
8271 * ensure that reads are stable, as we cannot rely on userspace always
8272 * being a good citizen. If members of the sqe are validated and then later
8273 * used, it's important that those reads are done through READ_ONCE() to
8274 * prevent a re-load down the line.
8276 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8278 unsigned head, mask = ctx->sq_entries - 1;
8279 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8282 * The cached sq head (or cq tail) serves two purposes:
8284 * 1) allows us to batch the cost of updating the user visible
8286 * 2) allows the kernel side to track the head on its own, even
8287 * though the application is the one updating it.
8289 head = READ_ONCE(ctx->sq_array[sq_idx]);
8290 if (likely(head < ctx->sq_entries))
8291 return &ctx->sq_sqes[head];
8293 /* drop invalid entries */
8295 WRITE_ONCE(ctx->rings->sq_dropped,
8296 READ_ONCE(ctx->rings->sq_dropped) + 1);
8300 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8301 __must_hold(&ctx->uring_lock)
8303 unsigned int entries = io_sqring_entries(ctx);
8307 if (unlikely(!entries))
8309 /* make sure SQ entry isn't read before tail */
8310 ret = left = min3(nr, ctx->sq_entries, entries);
8311 io_get_task_refs(left);
8312 io_submit_state_start(&ctx->submit_state, left);
8315 const struct io_uring_sqe *sqe;
8316 struct io_kiocb *req;
8318 if (unlikely(!io_alloc_req_refill(ctx)))
8320 req = io_alloc_req(ctx);
8321 sqe = io_get_sqe(ctx);
8322 if (unlikely(!sqe)) {
8323 io_req_add_to_cache(req, ctx);
8328 * Continue submitting even for sqe failure if the
8329 * ring was setup with IORING_SETUP_SUBMIT_ALL
8331 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8332 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8338 if (unlikely(left)) {
8340 /* try again if it submitted nothing and can't allocate a req */
8341 if (!ret && io_req_cache_empty(ctx))
8343 current->io_uring->cached_refs += left;
8346 io_submit_state_end(ctx);
8347 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8348 io_commit_sqring(ctx);
8352 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8354 return READ_ONCE(sqd->state);
8357 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8359 unsigned int to_submit;
8362 to_submit = io_sqring_entries(ctx);
8363 /* if we're handling multiple rings, cap submit size for fairness */
8364 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8365 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8367 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8368 const struct cred *creds = NULL;
8370 if (ctx->sq_creds != current_cred())
8371 creds = override_creds(ctx->sq_creds);
8373 mutex_lock(&ctx->uring_lock);
8374 if (!wq_list_empty(&ctx->iopoll_list))
8375 io_do_iopoll(ctx, true);
8378 * Don't submit if refs are dying, good for io_uring_register(),
8379 * but also it is relied upon by io_ring_exit_work()
8381 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8382 !(ctx->flags & IORING_SETUP_R_DISABLED))
8383 ret = io_submit_sqes(ctx, to_submit);
8384 mutex_unlock(&ctx->uring_lock);
8386 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8387 wake_up(&ctx->sqo_sq_wait);
8389 revert_creds(creds);
8395 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8397 struct io_ring_ctx *ctx;
8398 unsigned sq_thread_idle = 0;
8400 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8401 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8402 sqd->sq_thread_idle = sq_thread_idle;
8405 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8407 bool did_sig = false;
8408 struct ksignal ksig;
8410 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8411 signal_pending(current)) {
8412 mutex_unlock(&sqd->lock);
8413 if (signal_pending(current))
8414 did_sig = get_signal(&ksig);
8416 mutex_lock(&sqd->lock);
8418 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8421 static int io_sq_thread(void *data)
8423 struct io_sq_data *sqd = data;
8424 struct io_ring_ctx *ctx;
8425 unsigned long timeout = 0;
8426 char buf[TASK_COMM_LEN];
8429 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8430 set_task_comm(current, buf);
8432 if (sqd->sq_cpu != -1)
8433 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8435 set_cpus_allowed_ptr(current, cpu_online_mask);
8436 current->flags |= PF_NO_SETAFFINITY;
8438 audit_alloc_kernel(current);
8440 mutex_lock(&sqd->lock);
8442 bool cap_entries, sqt_spin = false;
8444 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8445 if (io_sqd_handle_event(sqd))
8447 timeout = jiffies + sqd->sq_thread_idle;
8450 cap_entries = !list_is_singular(&sqd->ctx_list);
8451 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8452 int ret = __io_sq_thread(ctx, cap_entries);
8454 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8457 if (io_run_task_work())
8460 if (sqt_spin || !time_after(jiffies, timeout)) {
8463 timeout = jiffies + sqd->sq_thread_idle;
8467 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8468 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8469 bool needs_sched = true;
8471 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8472 atomic_or(IORING_SQ_NEED_WAKEUP,
8473 &ctx->rings->sq_flags);
8474 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8475 !wq_list_empty(&ctx->iopoll_list)) {
8476 needs_sched = false;
8481 * Ensure the store of the wakeup flag is not
8482 * reordered with the load of the SQ tail
8484 smp_mb__after_atomic();
8486 if (io_sqring_entries(ctx)) {
8487 needs_sched = false;
8493 mutex_unlock(&sqd->lock);
8495 mutex_lock(&sqd->lock);
8497 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8498 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8499 &ctx->rings->sq_flags);
8502 finish_wait(&sqd->wait, &wait);
8503 timeout = jiffies + sqd->sq_thread_idle;
8506 io_uring_cancel_generic(true, sqd);
8508 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8509 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
8511 mutex_unlock(&sqd->lock);
8513 audit_free(current);
8515 complete(&sqd->exited);
8519 struct io_wait_queue {
8520 struct wait_queue_entry wq;
8521 struct io_ring_ctx *ctx;
8523 unsigned nr_timeouts;
8526 static inline bool io_should_wake(struct io_wait_queue *iowq)
8528 struct io_ring_ctx *ctx = iowq->ctx;
8529 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8532 * Wake up if we have enough events, or if a timeout occurred since we
8533 * started waiting. For timeouts, we always want to return to userspace,
8534 * regardless of event count.
8536 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8539 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8540 int wake_flags, void *key)
8542 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8546 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8547 * the task, and the next invocation will do it.
8549 if (io_should_wake(iowq) ||
8550 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
8551 return autoremove_wake_function(curr, mode, wake_flags, key);
8555 static int io_run_task_work_sig(void)
8557 if (io_run_task_work())
8559 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8560 return -ERESTARTSYS;
8561 if (task_sigpending(current))
8566 /* when returns >0, the caller should retry */
8567 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8568 struct io_wait_queue *iowq,
8572 unsigned long check_cq;
8574 /* make sure we run task_work before checking for signals */
8575 ret = io_run_task_work_sig();
8576 if (ret || io_should_wake(iowq))
8578 check_cq = READ_ONCE(ctx->check_cq);
8579 /* let the caller flush overflows, retry */
8580 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
8582 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
8584 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8590 * Wait until events become available, if we don't already have some. The
8591 * application must reap them itself, as they reside on the shared cq ring.
8593 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8594 const sigset_t __user *sig, size_t sigsz,
8595 struct __kernel_timespec __user *uts)
8597 struct io_wait_queue iowq;
8598 struct io_rings *rings = ctx->rings;
8599 ktime_t timeout = KTIME_MAX;
8603 io_cqring_overflow_flush(ctx);
8604 if (io_cqring_events(ctx) >= min_events)
8606 if (!io_run_task_work())
8611 #ifdef CONFIG_COMPAT
8612 if (in_compat_syscall())
8613 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8617 ret = set_user_sigmask(sig, sigsz);
8624 struct timespec64 ts;
8626 if (get_timespec64(&ts, uts))
8628 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8631 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8632 iowq.wq.private = current;
8633 INIT_LIST_HEAD(&iowq.wq.entry);
8635 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8636 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8638 trace_io_uring_cqring_wait(ctx, min_events);
8640 /* if we can't even flush overflow, don't wait for more */
8641 if (!io_cqring_overflow_flush(ctx)) {
8645 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8646 TASK_INTERRUPTIBLE);
8647 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8651 finish_wait(&ctx->cq_wait, &iowq.wq);
8652 restore_saved_sigmask_unless(ret == -EINTR);
8654 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8657 static void io_free_page_table(void **table, size_t size)
8659 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8661 for (i = 0; i < nr_tables; i++)
8666 static __cold void **io_alloc_page_table(size_t size)
8668 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8669 size_t init_size = size;
8672 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8676 for (i = 0; i < nr_tables; i++) {
8677 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8679 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8681 io_free_page_table(table, init_size);
8689 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8691 percpu_ref_exit(&ref_node->refs);
8695 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8697 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8698 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8699 unsigned long flags;
8700 bool first_add = false;
8701 unsigned long delay = HZ;
8703 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8706 /* if we are mid-quiesce then do not delay */
8707 if (node->rsrc_data->quiesce)
8710 while (!list_empty(&ctx->rsrc_ref_list)) {
8711 node = list_first_entry(&ctx->rsrc_ref_list,
8712 struct io_rsrc_node, node);
8713 /* recycle ref nodes in order */
8716 list_del(&node->node);
8717 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8719 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8722 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8725 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8727 struct io_rsrc_node *ref_node;
8729 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8733 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8738 INIT_LIST_HEAD(&ref_node->node);
8739 INIT_LIST_HEAD(&ref_node->rsrc_list);
8740 ref_node->done = false;
8744 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8745 struct io_rsrc_data *data_to_kill)
8746 __must_hold(&ctx->uring_lock)
8748 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8749 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8751 io_rsrc_refs_drop(ctx);
8754 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8756 rsrc_node->rsrc_data = data_to_kill;
8757 spin_lock_irq(&ctx->rsrc_ref_lock);
8758 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8759 spin_unlock_irq(&ctx->rsrc_ref_lock);
8761 atomic_inc(&data_to_kill->refs);
8762 percpu_ref_kill(&rsrc_node->refs);
8763 ctx->rsrc_node = NULL;
8766 if (!ctx->rsrc_node) {
8767 ctx->rsrc_node = ctx->rsrc_backup_node;
8768 ctx->rsrc_backup_node = NULL;
8772 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8774 if (ctx->rsrc_backup_node)
8776 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8777 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8780 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8781 struct io_ring_ctx *ctx)
8785 /* As we may drop ->uring_lock, other task may have started quiesce */
8789 data->quiesce = true;
8791 ret = io_rsrc_node_switch_start(ctx);
8794 io_rsrc_node_switch(ctx, data);
8796 /* kill initial ref, already quiesced if zero */
8797 if (atomic_dec_and_test(&data->refs))
8799 mutex_unlock(&ctx->uring_lock);
8800 flush_delayed_work(&ctx->rsrc_put_work);
8801 ret = wait_for_completion_interruptible(&data->done);
8803 mutex_lock(&ctx->uring_lock);
8804 if (atomic_read(&data->refs) > 0) {
8806 * it has been revived by another thread while
8809 mutex_unlock(&ctx->uring_lock);
8815 atomic_inc(&data->refs);
8816 /* wait for all works potentially completing data->done */
8817 flush_delayed_work(&ctx->rsrc_put_work);
8818 reinit_completion(&data->done);
8820 ret = io_run_task_work_sig();
8821 mutex_lock(&ctx->uring_lock);
8823 data->quiesce = false;
8828 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8830 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8831 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8833 return &data->tags[table_idx][off];
8836 static void io_rsrc_data_free(struct io_rsrc_data *data)
8838 size_t size = data->nr * sizeof(data->tags[0][0]);
8841 io_free_page_table((void **)data->tags, size);
8845 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8846 u64 __user *utags, unsigned nr,
8847 struct io_rsrc_data **pdata)
8849 struct io_rsrc_data *data;
8853 data = kzalloc(sizeof(*data), GFP_KERNEL);
8856 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8864 data->do_put = do_put;
8867 for (i = 0; i < nr; i++) {
8868 u64 *tag_slot = io_get_tag_slot(data, i);
8870 if (copy_from_user(tag_slot, &utags[i],
8876 atomic_set(&data->refs, 1);
8877 init_completion(&data->done);
8881 io_rsrc_data_free(data);
8885 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8887 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8888 GFP_KERNEL_ACCOUNT);
8889 if (unlikely(!table->files))
8892 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
8893 if (unlikely(!table->bitmap)) {
8894 kvfree(table->files);
8901 static void io_free_file_tables(struct io_file_table *table)
8903 kvfree(table->files);
8904 bitmap_free(table->bitmap);
8905 table->files = NULL;
8906 table->bitmap = NULL;
8909 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
8911 WARN_ON_ONCE(test_bit(bit, table->bitmap));
8912 __set_bit(bit, table->bitmap);
8913 if (bit == table->alloc_hint)
8914 table->alloc_hint++;
8917 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
8919 __clear_bit(bit, table->bitmap);
8920 table->alloc_hint = bit;
8923 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8925 #if !defined(IO_URING_SCM_ALL)
8928 for (i = 0; i < ctx->nr_user_files; i++) {
8929 struct file *file = io_file_from_index(ctx, i);
8933 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
8935 io_file_bitmap_clear(&ctx->file_table, i);
8940 #if defined(CONFIG_UNIX)
8941 if (ctx->ring_sock) {
8942 struct sock *sock = ctx->ring_sock->sk;
8943 struct sk_buff *skb;
8945 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8949 io_free_file_tables(&ctx->file_table);
8950 io_rsrc_data_free(ctx->file_data);
8951 ctx->file_data = NULL;
8952 ctx->nr_user_files = 0;
8955 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8959 if (!ctx->file_data)
8961 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8963 __io_sqe_files_unregister(ctx);
8967 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8968 __releases(&sqd->lock)
8970 WARN_ON_ONCE(sqd->thread == current);
8973 * Do the dance but not conditional clear_bit() because it'd race with
8974 * other threads incrementing park_pending and setting the bit.
8976 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8977 if (atomic_dec_return(&sqd->park_pending))
8978 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8979 mutex_unlock(&sqd->lock);
8982 static void io_sq_thread_park(struct io_sq_data *sqd)
8983 __acquires(&sqd->lock)
8985 WARN_ON_ONCE(sqd->thread == current);
8987 atomic_inc(&sqd->park_pending);
8988 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8989 mutex_lock(&sqd->lock);
8991 wake_up_process(sqd->thread);
8994 static void io_sq_thread_stop(struct io_sq_data *sqd)
8996 WARN_ON_ONCE(sqd->thread == current);
8997 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8999 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9000 mutex_lock(&sqd->lock);
9002 wake_up_process(sqd->thread);
9003 mutex_unlock(&sqd->lock);
9004 wait_for_completion(&sqd->exited);
9007 static void io_put_sq_data(struct io_sq_data *sqd)
9009 if (refcount_dec_and_test(&sqd->refs)) {
9010 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9012 io_sq_thread_stop(sqd);
9017 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9019 struct io_sq_data *sqd = ctx->sq_data;
9022 io_sq_thread_park(sqd);
9023 list_del_init(&ctx->sqd_list);
9024 io_sqd_update_thread_idle(sqd);
9025 io_sq_thread_unpark(sqd);
9027 io_put_sq_data(sqd);
9028 ctx->sq_data = NULL;
9032 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9034 struct io_ring_ctx *ctx_attach;
9035 struct io_sq_data *sqd;
9038 f = fdget(p->wq_fd);
9040 return ERR_PTR(-ENXIO);
9041 if (f.file->f_op != &io_uring_fops) {
9043 return ERR_PTR(-EINVAL);
9046 ctx_attach = f.file->private_data;
9047 sqd = ctx_attach->sq_data;
9050 return ERR_PTR(-EINVAL);
9052 if (sqd->task_tgid != current->tgid) {
9054 return ERR_PTR(-EPERM);
9057 refcount_inc(&sqd->refs);
9062 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9065 struct io_sq_data *sqd;
9068 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9069 sqd = io_attach_sq_data(p);
9074 /* fall through for EPERM case, setup new sqd/task */
9075 if (PTR_ERR(sqd) != -EPERM)
9079 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9081 return ERR_PTR(-ENOMEM);
9083 atomic_set(&sqd->park_pending, 0);
9084 refcount_set(&sqd->refs, 1);
9085 INIT_LIST_HEAD(&sqd->ctx_list);
9086 mutex_init(&sqd->lock);
9087 init_waitqueue_head(&sqd->wait);
9088 init_completion(&sqd->exited);
9093 * Ensure the UNIX gc is aware of our file set, so we are certain that
9094 * the io_uring can be safely unregistered on process exit, even if we have
9095 * loops in the file referencing. We account only files that can hold other
9096 * files because otherwise they can't form a loop and so are not interesting
9099 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9101 #if defined(CONFIG_UNIX)
9102 struct sock *sk = ctx->ring_sock->sk;
9103 struct sk_buff_head *head = &sk->sk_receive_queue;
9104 struct scm_fp_list *fpl;
9105 struct sk_buff *skb;
9107 if (likely(!io_file_need_scm(file)))
9111 * See if we can merge this file into an existing skb SCM_RIGHTS
9112 * file set. If there's no room, fall back to allocating a new skb
9113 * and filling it in.
9115 spin_lock_irq(&head->lock);
9116 skb = skb_peek(head);
9117 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9118 __skb_unlink(skb, head);
9121 spin_unlock_irq(&head->lock);
9124 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9128 skb = alloc_skb(0, GFP_KERNEL);
9134 fpl->user = get_uid(current_user());
9135 fpl->max = SCM_MAX_FD;
9138 UNIXCB(skb).fp = fpl;
9140 skb->destructor = unix_destruct_scm;
9141 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9144 fpl = UNIXCB(skb).fp;
9145 fpl->fp[fpl->count++] = get_file(file);
9146 unix_inflight(fpl->user, file);
9147 skb_queue_head(head, skb);
9153 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9155 struct file *file = prsrc->file;
9156 #if defined(CONFIG_UNIX)
9157 struct sock *sock = ctx->ring_sock->sk;
9158 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9159 struct sk_buff *skb;
9162 if (!io_file_need_scm(file)) {
9167 __skb_queue_head_init(&list);
9170 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9171 * remove this entry and rearrange the file array.
9173 skb = skb_dequeue(head);
9175 struct scm_fp_list *fp;
9177 fp = UNIXCB(skb).fp;
9178 for (i = 0; i < fp->count; i++) {
9181 if (fp->fp[i] != file)
9184 unix_notinflight(fp->user, fp->fp[i]);
9185 left = fp->count - 1 - i;
9187 memmove(&fp->fp[i], &fp->fp[i + 1],
9188 left * sizeof(struct file *));
9195 __skb_queue_tail(&list, skb);
9205 __skb_queue_tail(&list, skb);
9207 skb = skb_dequeue(head);
9210 if (skb_peek(&list)) {
9211 spin_lock_irq(&head->lock);
9212 while ((skb = __skb_dequeue(&list)) != NULL)
9213 __skb_queue_tail(head, skb);
9214 spin_unlock_irq(&head->lock);
9221 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9223 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9224 struct io_ring_ctx *ctx = rsrc_data->ctx;
9225 struct io_rsrc_put *prsrc, *tmp;
9227 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9228 list_del(&prsrc->list);
9231 if (ctx->flags & IORING_SETUP_IOPOLL)
9232 mutex_lock(&ctx->uring_lock);
9234 spin_lock(&ctx->completion_lock);
9235 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9236 io_commit_cqring(ctx);
9237 spin_unlock(&ctx->completion_lock);
9238 io_cqring_ev_posted(ctx);
9240 if (ctx->flags & IORING_SETUP_IOPOLL)
9241 mutex_unlock(&ctx->uring_lock);
9244 rsrc_data->do_put(ctx, prsrc);
9248 io_rsrc_node_destroy(ref_node);
9249 if (atomic_dec_and_test(&rsrc_data->refs))
9250 complete(&rsrc_data->done);
9253 static void io_rsrc_put_work(struct work_struct *work)
9255 struct io_ring_ctx *ctx;
9256 struct llist_node *node;
9258 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9259 node = llist_del_all(&ctx->rsrc_put_llist);
9262 struct io_rsrc_node *ref_node;
9263 struct llist_node *next = node->next;
9265 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9266 __io_rsrc_put_work(ref_node);
9271 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9272 unsigned nr_args, u64 __user *tags)
9274 __s32 __user *fds = (__s32 __user *) arg;
9283 if (nr_args > IORING_MAX_FIXED_FILES)
9285 if (nr_args > rlimit(RLIMIT_NOFILE))
9287 ret = io_rsrc_node_switch_start(ctx);
9290 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9295 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9296 io_rsrc_data_free(ctx->file_data);
9297 ctx->file_data = NULL;
9301 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9302 struct io_fixed_file *file_slot;
9304 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
9308 /* allow sparse sets */
9309 if (!fds || fd == -1) {
9311 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9318 if (unlikely(!file))
9322 * Don't allow io_uring instances to be registered. If UNIX
9323 * isn't enabled, then this causes a reference cycle and this
9324 * instance can never get freed. If UNIX is enabled we'll
9325 * handle it just fine, but there's still no point in allowing
9326 * a ring fd as it doesn't support regular read/write anyway.
9328 if (file->f_op == &io_uring_fops) {
9332 ret = io_scm_file_account(ctx, file);
9337 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9338 io_fixed_file_set(file_slot, file);
9339 io_file_bitmap_set(&ctx->file_table, i);
9342 io_rsrc_node_switch(ctx, NULL);
9345 __io_sqe_files_unregister(ctx);
9349 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9350 struct io_rsrc_node *node, void *rsrc)
9352 u64 *tag_slot = io_get_tag_slot(data, idx);
9353 struct io_rsrc_put *prsrc;
9355 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9359 prsrc->tag = *tag_slot;
9362 list_add(&prsrc->list, &node->rsrc_list);
9366 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9367 unsigned int issue_flags, u32 slot_index)
9369 struct io_ring_ctx *ctx = req->ctx;
9370 bool needs_switch = false;
9371 struct io_fixed_file *file_slot;
9374 io_ring_submit_lock(ctx, issue_flags);
9375 if (file->f_op == &io_uring_fops)
9378 if (!ctx->file_data)
9381 if (slot_index >= ctx->nr_user_files)
9384 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9385 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9387 if (file_slot->file_ptr) {
9388 struct file *old_file;
9390 ret = io_rsrc_node_switch_start(ctx);
9394 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9395 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9396 ctx->rsrc_node, old_file);
9399 file_slot->file_ptr = 0;
9400 io_file_bitmap_clear(&ctx->file_table, slot_index);
9401 needs_switch = true;
9404 ret = io_scm_file_account(ctx, file);
9406 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9407 io_fixed_file_set(file_slot, file);
9408 io_file_bitmap_set(&ctx->file_table, slot_index);
9412 io_rsrc_node_switch(ctx, ctx->file_data);
9413 io_ring_submit_unlock(ctx, issue_flags);
9419 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9421 unsigned int offset = req->close.file_slot - 1;
9422 struct io_ring_ctx *ctx = req->ctx;
9423 struct io_fixed_file *file_slot;
9427 io_ring_submit_lock(ctx, issue_flags);
9429 if (unlikely(!ctx->file_data))
9432 if (offset >= ctx->nr_user_files)
9434 ret = io_rsrc_node_switch_start(ctx);
9438 offset = array_index_nospec(offset, ctx->nr_user_files);
9439 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9441 if (!file_slot->file_ptr)
9444 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9445 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9449 file_slot->file_ptr = 0;
9450 io_file_bitmap_clear(&ctx->file_table, offset);
9451 io_rsrc_node_switch(ctx, ctx->file_data);
9454 io_ring_submit_unlock(ctx, issue_flags);
9458 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9459 struct io_uring_rsrc_update2 *up,
9462 u64 __user *tags = u64_to_user_ptr(up->tags);
9463 __s32 __user *fds = u64_to_user_ptr(up->data);
9464 struct io_rsrc_data *data = ctx->file_data;
9465 struct io_fixed_file *file_slot;
9469 bool needs_switch = false;
9471 if (!ctx->file_data)
9473 if (up->offset + nr_args > ctx->nr_user_files)
9476 for (done = 0; done < nr_args; done++) {
9479 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9480 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9484 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9488 if (fd == IORING_REGISTER_FILES_SKIP)
9491 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9492 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9494 if (file_slot->file_ptr) {
9495 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9496 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9499 file_slot->file_ptr = 0;
9500 io_file_bitmap_clear(&ctx->file_table, i);
9501 needs_switch = true;
9510 * Don't allow io_uring instances to be registered. If
9511 * UNIX isn't enabled, then this causes a reference
9512 * cycle and this instance can never get freed. If UNIX
9513 * is enabled we'll handle it just fine, but there's
9514 * still no point in allowing a ring fd as it doesn't
9515 * support regular read/write anyway.
9517 if (file->f_op == &io_uring_fops) {
9522 err = io_scm_file_account(ctx, file);
9527 *io_get_tag_slot(data, i) = tag;
9528 io_fixed_file_set(file_slot, file);
9529 io_file_bitmap_set(&ctx->file_table, i);
9534 io_rsrc_node_switch(ctx, data);
9535 return done ? done : err;
9538 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9539 struct task_struct *task)
9541 struct io_wq_hash *hash;
9542 struct io_wq_data data;
9543 unsigned int concurrency;
9545 mutex_lock(&ctx->uring_lock);
9546 hash = ctx->hash_map;
9548 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9550 mutex_unlock(&ctx->uring_lock);
9551 return ERR_PTR(-ENOMEM);
9553 refcount_set(&hash->refs, 1);
9554 init_waitqueue_head(&hash->wait);
9555 ctx->hash_map = hash;
9557 mutex_unlock(&ctx->uring_lock);
9561 data.free_work = io_wq_free_work;
9562 data.do_work = io_wq_submit_work;
9564 /* Do QD, or 4 * CPUS, whatever is smallest */
9565 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9567 return io_wq_create(concurrency, &data);
9570 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9571 struct io_ring_ctx *ctx)
9573 struct io_uring_task *tctx;
9576 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9577 if (unlikely(!tctx))
9580 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9581 sizeof(struct file *), GFP_KERNEL);
9582 if (unlikely(!tctx->registered_rings)) {
9587 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9588 if (unlikely(ret)) {
9589 kfree(tctx->registered_rings);
9594 tctx->io_wq = io_init_wq_offload(ctx, task);
9595 if (IS_ERR(tctx->io_wq)) {
9596 ret = PTR_ERR(tctx->io_wq);
9597 percpu_counter_destroy(&tctx->inflight);
9598 kfree(tctx->registered_rings);
9604 init_waitqueue_head(&tctx->wait);
9605 atomic_set(&tctx->in_idle, 0);
9606 task->io_uring = tctx;
9607 spin_lock_init(&tctx->task_lock);
9608 INIT_WQ_LIST(&tctx->task_list);
9609 INIT_WQ_LIST(&tctx->prior_task_list);
9610 init_task_work(&tctx->task_work, tctx_task_work);
9614 void __io_uring_free(struct task_struct *tsk)
9616 struct io_uring_task *tctx = tsk->io_uring;
9618 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9619 WARN_ON_ONCE(tctx->io_wq);
9620 WARN_ON_ONCE(tctx->cached_refs);
9622 kfree(tctx->registered_rings);
9623 percpu_counter_destroy(&tctx->inflight);
9625 tsk->io_uring = NULL;
9628 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9629 struct io_uring_params *p)
9633 /* Retain compatibility with failing for an invalid attach attempt */
9634 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9635 IORING_SETUP_ATTACH_WQ) {
9638 f = fdget(p->wq_fd);
9641 if (f.file->f_op != &io_uring_fops) {
9647 if (ctx->flags & IORING_SETUP_SQPOLL) {
9648 struct task_struct *tsk;
9649 struct io_sq_data *sqd;
9652 ret = security_uring_sqpoll();
9656 sqd = io_get_sq_data(p, &attached);
9662 ctx->sq_creds = get_current_cred();
9664 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9665 if (!ctx->sq_thread_idle)
9666 ctx->sq_thread_idle = HZ;
9668 io_sq_thread_park(sqd);
9669 list_add(&ctx->sqd_list, &sqd->ctx_list);
9670 io_sqd_update_thread_idle(sqd);
9671 /* don't attach to a dying SQPOLL thread, would be racy */
9672 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9673 io_sq_thread_unpark(sqd);
9680 if (p->flags & IORING_SETUP_SQ_AFF) {
9681 int cpu = p->sq_thread_cpu;
9684 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9691 sqd->task_pid = current->pid;
9692 sqd->task_tgid = current->tgid;
9693 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9700 ret = io_uring_alloc_task_context(tsk, ctx);
9701 wake_up_new_task(tsk);
9704 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9705 /* Can't have SQ_AFF without SQPOLL */
9712 complete(&ctx->sq_data->exited);
9714 io_sq_thread_finish(ctx);
9718 static inline void __io_unaccount_mem(struct user_struct *user,
9719 unsigned long nr_pages)
9721 atomic_long_sub(nr_pages, &user->locked_vm);
9724 static inline int __io_account_mem(struct user_struct *user,
9725 unsigned long nr_pages)
9727 unsigned long page_limit, cur_pages, new_pages;
9729 /* Don't allow more pages than we can safely lock */
9730 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9733 cur_pages = atomic_long_read(&user->locked_vm);
9734 new_pages = cur_pages + nr_pages;
9735 if (new_pages > page_limit)
9737 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9738 new_pages) != cur_pages);
9743 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9746 __io_unaccount_mem(ctx->user, nr_pages);
9748 if (ctx->mm_account)
9749 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9752 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9757 ret = __io_account_mem(ctx->user, nr_pages);
9762 if (ctx->mm_account)
9763 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9768 static void io_mem_free(void *ptr)
9775 page = virt_to_head_page(ptr);
9776 if (put_page_testzero(page))
9777 free_compound_page(page);
9780 static void *io_mem_alloc(size_t size)
9782 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9784 return (void *) __get_free_pages(gfp, get_order(size));
9787 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9790 struct io_rings *rings;
9791 size_t off, sq_array_size;
9793 off = struct_size(rings, cqes, cq_entries);
9794 if (off == SIZE_MAX)
9798 off = ALIGN(off, SMP_CACHE_BYTES);
9806 sq_array_size = array_size(sizeof(u32), sq_entries);
9807 if (sq_array_size == SIZE_MAX)
9810 if (check_add_overflow(off, sq_array_size, &off))
9816 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9818 struct io_mapped_ubuf *imu = *slot;
9821 if (imu != ctx->dummy_ubuf) {
9822 for (i = 0; i < imu->nr_bvecs; i++)
9823 unpin_user_page(imu->bvec[i].bv_page);
9824 if (imu->acct_pages)
9825 io_unaccount_mem(ctx, imu->acct_pages);
9831 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9833 io_buffer_unmap(ctx, &prsrc->buf);
9837 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9841 for (i = 0; i < ctx->nr_user_bufs; i++)
9842 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9843 kfree(ctx->user_bufs);
9844 io_rsrc_data_free(ctx->buf_data);
9845 ctx->user_bufs = NULL;
9846 ctx->buf_data = NULL;
9847 ctx->nr_user_bufs = 0;
9850 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9857 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9859 __io_sqe_buffers_unregister(ctx);
9863 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9864 void __user *arg, unsigned index)
9866 struct iovec __user *src;
9868 #ifdef CONFIG_COMPAT
9870 struct compat_iovec __user *ciovs;
9871 struct compat_iovec ciov;
9873 ciovs = (struct compat_iovec __user *) arg;
9874 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9877 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9878 dst->iov_len = ciov.iov_len;
9882 src = (struct iovec __user *) arg;
9883 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9889 * Not super efficient, but this is just a registration time. And we do cache
9890 * the last compound head, so generally we'll only do a full search if we don't
9893 * We check if the given compound head page has already been accounted, to
9894 * avoid double accounting it. This allows us to account the full size of the
9895 * page, not just the constituent pages of a huge page.
9897 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9898 int nr_pages, struct page *hpage)
9902 /* check current page array */
9903 for (i = 0; i < nr_pages; i++) {
9904 if (!PageCompound(pages[i]))
9906 if (compound_head(pages[i]) == hpage)
9910 /* check previously registered pages */
9911 for (i = 0; i < ctx->nr_user_bufs; i++) {
9912 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9914 for (j = 0; j < imu->nr_bvecs; j++) {
9915 if (!PageCompound(imu->bvec[j].bv_page))
9917 if (compound_head(imu->bvec[j].bv_page) == hpage)
9925 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9926 int nr_pages, struct io_mapped_ubuf *imu,
9927 struct page **last_hpage)
9931 imu->acct_pages = 0;
9932 for (i = 0; i < nr_pages; i++) {
9933 if (!PageCompound(pages[i])) {
9938 hpage = compound_head(pages[i]);
9939 if (hpage == *last_hpage)
9941 *last_hpage = hpage;
9942 if (headpage_already_acct(ctx, pages, i, hpage))
9944 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9948 if (!imu->acct_pages)
9951 ret = io_account_mem(ctx, imu->acct_pages);
9953 imu->acct_pages = 0;
9957 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
9960 unsigned long start, end, nr_pages;
9961 struct vm_area_struct **vmas = NULL;
9962 struct page **pages = NULL;
9963 int i, pret, ret = -ENOMEM;
9965 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9966 start = ubuf >> PAGE_SHIFT;
9967 nr_pages = end - start;
9969 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9973 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9979 mmap_read_lock(current->mm);
9980 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9982 if (pret == nr_pages) {
9983 /* don't support file backed memory */
9984 for (i = 0; i < nr_pages; i++) {
9985 struct vm_area_struct *vma = vmas[i];
9987 if (vma_is_shmem(vma))
9990 !is_file_hugepages(vma->vm_file)) {
9997 ret = pret < 0 ? pret : -EFAULT;
9999 mmap_read_unlock(current->mm);
10002 * if we did partial map, or found file backed vmas,
10003 * release any pages we did get
10006 unpin_user_pages(pages, pret);
10014 pages = ERR_PTR(ret);
10019 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10020 struct io_mapped_ubuf **pimu,
10021 struct page **last_hpage)
10023 struct io_mapped_ubuf *imu = NULL;
10024 struct page **pages = NULL;
10027 int ret, nr_pages, i;
10029 if (!iov->iov_base) {
10030 *pimu = ctx->dummy_ubuf;
10037 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10039 if (IS_ERR(pages)) {
10040 ret = PTR_ERR(pages);
10045 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10049 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10051 unpin_user_pages(pages, nr_pages);
10055 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10056 size = iov->iov_len;
10057 for (i = 0; i < nr_pages; i++) {
10060 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10061 imu->bvec[i].bv_page = pages[i];
10062 imu->bvec[i].bv_len = vec_len;
10063 imu->bvec[i].bv_offset = off;
10067 /* store original address for later verification */
10068 imu->ubuf = (unsigned long) iov->iov_base;
10069 imu->ubuf_end = imu->ubuf + iov->iov_len;
10070 imu->nr_bvecs = nr_pages;
10080 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10082 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10083 return ctx->user_bufs ? 0 : -ENOMEM;
10086 static int io_buffer_validate(struct iovec *iov)
10088 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10091 * Don't impose further limits on the size and buffer
10092 * constraints here, we'll -EINVAL later when IO is
10093 * submitted if they are wrong.
10095 if (!iov->iov_base)
10096 return iov->iov_len ? -EFAULT : 0;
10100 /* arbitrary limit, but we need something */
10101 if (iov->iov_len > SZ_1G)
10104 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10110 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10111 unsigned int nr_args, u64 __user *tags)
10113 struct page *last_hpage = NULL;
10114 struct io_rsrc_data *data;
10118 if (ctx->user_bufs)
10120 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10122 ret = io_rsrc_node_switch_start(ctx);
10125 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10128 ret = io_buffers_map_alloc(ctx, nr_args);
10130 io_rsrc_data_free(data);
10134 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10135 ret = io_copy_iov(ctx, &iov, arg, i);
10138 ret = io_buffer_validate(&iov);
10141 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10146 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10152 WARN_ON_ONCE(ctx->buf_data);
10154 ctx->buf_data = data;
10156 __io_sqe_buffers_unregister(ctx);
10158 io_rsrc_node_switch(ctx, NULL);
10162 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10163 struct io_uring_rsrc_update2 *up,
10164 unsigned int nr_args)
10166 u64 __user *tags = u64_to_user_ptr(up->tags);
10167 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10168 struct page *last_hpage = NULL;
10169 bool needs_switch = false;
10173 if (!ctx->buf_data)
10175 if (up->offset + nr_args > ctx->nr_user_bufs)
10178 for (done = 0; done < nr_args; done++) {
10179 struct io_mapped_ubuf *imu;
10180 int offset = up->offset + done;
10183 err = io_copy_iov(ctx, &iov, iovs, done);
10186 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10190 err = io_buffer_validate(&iov);
10193 if (!iov.iov_base && tag) {
10197 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10201 i = array_index_nospec(offset, ctx->nr_user_bufs);
10202 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10203 err = io_queue_rsrc_removal(ctx->buf_data, i,
10204 ctx->rsrc_node, ctx->user_bufs[i]);
10205 if (unlikely(err)) {
10206 io_buffer_unmap(ctx, &imu);
10209 ctx->user_bufs[i] = NULL;
10210 needs_switch = true;
10213 ctx->user_bufs[i] = imu;
10214 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10218 io_rsrc_node_switch(ctx, ctx->buf_data);
10219 return done ? done : err;
10222 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10223 unsigned int eventfd_async)
10225 struct io_ev_fd *ev_fd;
10226 __s32 __user *fds = arg;
10229 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10230 lockdep_is_held(&ctx->uring_lock));
10234 if (copy_from_user(&fd, fds, sizeof(*fds)))
10237 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10241 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10242 if (IS_ERR(ev_fd->cq_ev_fd)) {
10243 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10247 ev_fd->eventfd_async = eventfd_async;
10248 ctx->has_evfd = true;
10249 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10253 static void io_eventfd_put(struct rcu_head *rcu)
10255 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10257 eventfd_ctx_put(ev_fd->cq_ev_fd);
10261 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10263 struct io_ev_fd *ev_fd;
10265 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10266 lockdep_is_held(&ctx->uring_lock));
10268 ctx->has_evfd = false;
10269 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10270 call_rcu(&ev_fd->rcu, io_eventfd_put);
10277 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10279 struct io_buffer_list *bl;
10280 unsigned long index;
10283 for (i = 0; i < BGID_ARRAY; i++) {
10286 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10289 xa_for_each(&ctx->io_bl_xa, index, bl) {
10290 xa_erase(&ctx->io_bl_xa, bl->bgid);
10291 __io_remove_buffers(ctx, bl, -1U);
10294 while (!list_empty(&ctx->io_buffers_pages)) {
10297 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10298 list_del_init(&page->lru);
10303 static void io_req_caches_free(struct io_ring_ctx *ctx)
10305 struct io_submit_state *state = &ctx->submit_state;
10308 mutex_lock(&ctx->uring_lock);
10309 io_flush_cached_locked_reqs(ctx, state);
10311 while (!io_req_cache_empty(ctx)) {
10312 struct io_wq_work_node *node;
10313 struct io_kiocb *req;
10315 node = wq_stack_extract(&state->free_list);
10316 req = container_of(node, struct io_kiocb, comp_list);
10317 kmem_cache_free(req_cachep, req);
10321 percpu_ref_put_many(&ctx->refs, nr);
10322 mutex_unlock(&ctx->uring_lock);
10325 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10327 if (data && !atomic_dec_and_test(&data->refs))
10328 wait_for_completion(&data->done);
10331 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10333 struct async_poll *apoll;
10335 while (!list_empty(&ctx->apoll_cache)) {
10336 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10338 list_del(&apoll->poll.wait.entry);
10343 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10345 io_sq_thread_finish(ctx);
10347 if (ctx->mm_account) {
10348 mmdrop(ctx->mm_account);
10349 ctx->mm_account = NULL;
10352 io_rsrc_refs_drop(ctx);
10353 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10354 io_wait_rsrc_data(ctx->buf_data);
10355 io_wait_rsrc_data(ctx->file_data);
10357 mutex_lock(&ctx->uring_lock);
10359 __io_sqe_buffers_unregister(ctx);
10360 if (ctx->file_data)
10361 __io_sqe_files_unregister(ctx);
10363 __io_cqring_overflow_flush(ctx, true);
10364 io_eventfd_unregister(ctx);
10365 io_flush_apoll_cache(ctx);
10366 mutex_unlock(&ctx->uring_lock);
10367 io_destroy_buffers(ctx);
10369 put_cred(ctx->sq_creds);
10371 /* there are no registered resources left, nobody uses it */
10372 if (ctx->rsrc_node)
10373 io_rsrc_node_destroy(ctx->rsrc_node);
10374 if (ctx->rsrc_backup_node)
10375 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10376 flush_delayed_work(&ctx->rsrc_put_work);
10377 flush_delayed_work(&ctx->fallback_work);
10379 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10380 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10382 #if defined(CONFIG_UNIX)
10383 if (ctx->ring_sock) {
10384 ctx->ring_sock->file = NULL; /* so that iput() is called */
10385 sock_release(ctx->ring_sock);
10388 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10390 io_mem_free(ctx->rings);
10391 io_mem_free(ctx->sq_sqes);
10393 percpu_ref_exit(&ctx->refs);
10394 free_uid(ctx->user);
10395 io_req_caches_free(ctx);
10397 io_wq_put_hash(ctx->hash_map);
10398 kfree(ctx->cancel_hash);
10399 kfree(ctx->dummy_ubuf);
10401 xa_destroy(&ctx->io_bl_xa);
10405 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10407 struct io_ring_ctx *ctx = file->private_data;
10410 poll_wait(file, &ctx->cq_wait, wait);
10412 * synchronizes with barrier from wq_has_sleeper call in
10416 if (!io_sqring_full(ctx))
10417 mask |= EPOLLOUT | EPOLLWRNORM;
10420 * Don't flush cqring overflow list here, just do a simple check.
10421 * Otherwise there could possible be ABBA deadlock:
10424 * lock(&ctx->uring_lock);
10426 * lock(&ctx->uring_lock);
10429 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10430 * pushs them to do the flush.
10432 if (io_cqring_events(ctx) ||
10433 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10434 mask |= EPOLLIN | EPOLLRDNORM;
10439 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10441 const struct cred *creds;
10443 creds = xa_erase(&ctx->personalities, id);
10452 struct io_tctx_exit {
10453 struct callback_head task_work;
10454 struct completion completion;
10455 struct io_ring_ctx *ctx;
10458 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10460 struct io_uring_task *tctx = current->io_uring;
10461 struct io_tctx_exit *work;
10463 work = container_of(cb, struct io_tctx_exit, task_work);
10465 * When @in_idle, we're in cancellation and it's racy to remove the
10466 * node. It'll be removed by the end of cancellation, just ignore it.
10468 if (!atomic_read(&tctx->in_idle))
10469 io_uring_del_tctx_node((unsigned long)work->ctx);
10470 complete(&work->completion);
10473 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10475 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10477 return req->ctx == data;
10480 static __cold void io_ring_exit_work(struct work_struct *work)
10482 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10483 unsigned long timeout = jiffies + HZ * 60 * 5;
10484 unsigned long interval = HZ / 20;
10485 struct io_tctx_exit exit;
10486 struct io_tctx_node *node;
10490 * If we're doing polled IO and end up having requests being
10491 * submitted async (out-of-line), then completions can come in while
10492 * we're waiting for refs to drop. We need to reap these manually,
10493 * as nobody else will be looking for them.
10496 io_uring_try_cancel_requests(ctx, NULL, true);
10497 if (ctx->sq_data) {
10498 struct io_sq_data *sqd = ctx->sq_data;
10499 struct task_struct *tsk;
10501 io_sq_thread_park(sqd);
10503 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10504 io_wq_cancel_cb(tsk->io_uring->io_wq,
10505 io_cancel_ctx_cb, ctx, true);
10506 io_sq_thread_unpark(sqd);
10509 io_req_caches_free(ctx);
10511 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10512 /* there is little hope left, don't run it too often */
10513 interval = HZ * 60;
10515 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10517 init_completion(&exit.completion);
10518 init_task_work(&exit.task_work, io_tctx_exit_cb);
10521 * Some may use context even when all refs and requests have been put,
10522 * and they are free to do so while still holding uring_lock or
10523 * completion_lock, see io_req_task_submit(). Apart from other work,
10524 * this lock/unlock section also waits them to finish.
10526 mutex_lock(&ctx->uring_lock);
10527 while (!list_empty(&ctx->tctx_list)) {
10528 WARN_ON_ONCE(time_after(jiffies, timeout));
10530 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10532 /* don't spin on a single task if cancellation failed */
10533 list_rotate_left(&ctx->tctx_list);
10534 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10535 if (WARN_ON_ONCE(ret))
10538 mutex_unlock(&ctx->uring_lock);
10539 wait_for_completion(&exit.completion);
10540 mutex_lock(&ctx->uring_lock);
10542 mutex_unlock(&ctx->uring_lock);
10543 spin_lock(&ctx->completion_lock);
10544 spin_unlock(&ctx->completion_lock);
10546 io_ring_ctx_free(ctx);
10549 /* Returns true if we found and killed one or more timeouts */
10550 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10551 struct task_struct *tsk, bool cancel_all)
10553 struct io_kiocb *req, *tmp;
10556 spin_lock(&ctx->completion_lock);
10557 spin_lock_irq(&ctx->timeout_lock);
10558 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10559 if (io_match_task(req, tsk, cancel_all)) {
10560 io_kill_timeout(req, -ECANCELED);
10564 spin_unlock_irq(&ctx->timeout_lock);
10565 io_commit_cqring(ctx);
10566 spin_unlock(&ctx->completion_lock);
10568 io_cqring_ev_posted(ctx);
10569 return canceled != 0;
10572 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10574 unsigned long index;
10575 struct creds *creds;
10577 mutex_lock(&ctx->uring_lock);
10578 percpu_ref_kill(&ctx->refs);
10580 __io_cqring_overflow_flush(ctx, true);
10581 xa_for_each(&ctx->personalities, index, creds)
10582 io_unregister_personality(ctx, index);
10583 mutex_unlock(&ctx->uring_lock);
10585 /* failed during ring init, it couldn't have issued any requests */
10587 io_kill_timeouts(ctx, NULL, true);
10588 io_poll_remove_all(ctx, NULL, true);
10589 /* if we failed setting up the ctx, we might not have any rings */
10590 io_iopoll_try_reap_events(ctx);
10593 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10595 * Use system_unbound_wq to avoid spawning tons of event kworkers
10596 * if we're exiting a ton of rings at the same time. It just adds
10597 * noise and overhead, there's no discernable change in runtime
10598 * over using system_wq.
10600 queue_work(system_unbound_wq, &ctx->exit_work);
10603 static int io_uring_release(struct inode *inode, struct file *file)
10605 struct io_ring_ctx *ctx = file->private_data;
10607 file->private_data = NULL;
10608 io_ring_ctx_wait_and_kill(ctx);
10612 struct io_task_cancel {
10613 struct task_struct *task;
10617 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10619 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10620 struct io_task_cancel *cancel = data;
10622 return io_match_task_safe(req, cancel->task, cancel->all);
10625 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10626 struct task_struct *task,
10629 struct io_defer_entry *de;
10632 spin_lock(&ctx->completion_lock);
10633 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10634 if (io_match_task_safe(de->req, task, cancel_all)) {
10635 list_cut_position(&list, &ctx->defer_list, &de->list);
10639 spin_unlock(&ctx->completion_lock);
10640 if (list_empty(&list))
10643 while (!list_empty(&list)) {
10644 de = list_first_entry(&list, struct io_defer_entry, list);
10645 list_del_init(&de->list);
10646 io_req_complete_failed(de->req, -ECANCELED);
10652 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10654 struct io_tctx_node *node;
10655 enum io_wq_cancel cret;
10658 mutex_lock(&ctx->uring_lock);
10659 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10660 struct io_uring_task *tctx = node->task->io_uring;
10663 * io_wq will stay alive while we hold uring_lock, because it's
10664 * killed after ctx nodes, which requires to take the lock.
10666 if (!tctx || !tctx->io_wq)
10668 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10669 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10671 mutex_unlock(&ctx->uring_lock);
10676 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10677 struct task_struct *task,
10680 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10681 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10683 /* failed during ring init, it couldn't have issued any requests */
10688 enum io_wq_cancel cret;
10692 ret |= io_uring_try_cancel_iowq(ctx);
10693 } else if (tctx && tctx->io_wq) {
10695 * Cancels requests of all rings, not only @ctx, but
10696 * it's fine as the task is in exit/exec.
10698 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10700 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10703 /* SQPOLL thread does its own polling */
10704 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10705 (ctx->sq_data && ctx->sq_data->thread == current)) {
10706 while (!wq_list_empty(&ctx->iopoll_list)) {
10707 io_iopoll_try_reap_events(ctx);
10712 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10713 ret |= io_poll_remove_all(ctx, task, cancel_all);
10714 ret |= io_kill_timeouts(ctx, task, cancel_all);
10716 ret |= io_run_task_work();
10723 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10725 struct io_uring_task *tctx = current->io_uring;
10726 struct io_tctx_node *node;
10729 if (unlikely(!tctx)) {
10730 ret = io_uring_alloc_task_context(current, ctx);
10734 tctx = current->io_uring;
10735 if (ctx->iowq_limits_set) {
10736 unsigned int limits[2] = { ctx->iowq_limits[0],
10737 ctx->iowq_limits[1], };
10739 ret = io_wq_max_workers(tctx->io_wq, limits);
10744 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10745 node = kmalloc(sizeof(*node), GFP_KERNEL);
10749 node->task = current;
10751 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10752 node, GFP_KERNEL));
10758 mutex_lock(&ctx->uring_lock);
10759 list_add(&node->ctx_node, &ctx->tctx_list);
10760 mutex_unlock(&ctx->uring_lock);
10767 * Note that this task has used io_uring. We use it for cancelation purposes.
10769 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10771 struct io_uring_task *tctx = current->io_uring;
10773 if (likely(tctx && tctx->last == ctx))
10775 return __io_uring_add_tctx_node(ctx);
10779 * Remove this io_uring_file -> task mapping.
10781 static __cold void io_uring_del_tctx_node(unsigned long index)
10783 struct io_uring_task *tctx = current->io_uring;
10784 struct io_tctx_node *node;
10788 node = xa_erase(&tctx->xa, index);
10792 WARN_ON_ONCE(current != node->task);
10793 WARN_ON_ONCE(list_empty(&node->ctx_node));
10795 mutex_lock(&node->ctx->uring_lock);
10796 list_del(&node->ctx_node);
10797 mutex_unlock(&node->ctx->uring_lock);
10799 if (tctx->last == node->ctx)
10804 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10806 struct io_wq *wq = tctx->io_wq;
10807 struct io_tctx_node *node;
10808 unsigned long index;
10810 xa_for_each(&tctx->xa, index, node) {
10811 io_uring_del_tctx_node(index);
10816 * Must be after io_uring_del_tctx_node() (removes nodes under
10817 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10819 io_wq_put_and_exit(wq);
10820 tctx->io_wq = NULL;
10824 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10828 return percpu_counter_sum(&tctx->inflight);
10832 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10833 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10835 static __cold void io_uring_cancel_generic(bool cancel_all,
10836 struct io_sq_data *sqd)
10838 struct io_uring_task *tctx = current->io_uring;
10839 struct io_ring_ctx *ctx;
10843 WARN_ON_ONCE(sqd && sqd->thread != current);
10845 if (!current->io_uring)
10848 io_wq_exit_start(tctx->io_wq);
10850 atomic_inc(&tctx->in_idle);
10852 io_uring_drop_tctx_refs(current);
10853 /* read completions before cancelations */
10854 inflight = tctx_inflight(tctx, !cancel_all);
10859 struct io_tctx_node *node;
10860 unsigned long index;
10862 xa_for_each(&tctx->xa, index, node) {
10863 /* sqpoll task will cancel all its requests */
10864 if (node->ctx->sq_data)
10866 io_uring_try_cancel_requests(node->ctx, current,
10870 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10871 io_uring_try_cancel_requests(ctx, current,
10875 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10876 io_run_task_work();
10877 io_uring_drop_tctx_refs(current);
10880 * If we've seen completions, retry without waiting. This
10881 * avoids a race where a completion comes in before we did
10882 * prepare_to_wait().
10884 if (inflight == tctx_inflight(tctx, !cancel_all))
10886 finish_wait(&tctx->wait, &wait);
10889 io_uring_clean_tctx(tctx);
10892 * We shouldn't run task_works after cancel, so just leave
10893 * ->in_idle set for normal exit.
10895 atomic_dec(&tctx->in_idle);
10896 /* for exec all current's requests should be gone, kill tctx */
10897 __io_uring_free(current);
10901 void __io_uring_cancel(bool cancel_all)
10903 io_uring_cancel_generic(cancel_all, NULL);
10906 void io_uring_unreg_ringfd(void)
10908 struct io_uring_task *tctx = current->io_uring;
10911 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10912 if (tctx->registered_rings[i]) {
10913 fput(tctx->registered_rings[i]);
10914 tctx->registered_rings[i] = NULL;
10919 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10920 int start, int end)
10925 for (offset = start; offset < end; offset++) {
10926 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10927 if (tctx->registered_rings[offset])
10933 } else if (file->f_op != &io_uring_fops) {
10935 return -EOPNOTSUPP;
10937 tctx->registered_rings[offset] = file;
10945 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10946 * invocation. User passes in an array of struct io_uring_rsrc_update
10947 * with ->data set to the ring_fd, and ->offset given for the desired
10948 * index. If no index is desired, application may set ->offset == -1U
10949 * and we'll find an available index. Returns number of entries
10950 * successfully processed, or < 0 on error if none were processed.
10952 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10955 struct io_uring_rsrc_update __user *arg = __arg;
10956 struct io_uring_rsrc_update reg;
10957 struct io_uring_task *tctx;
10960 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10963 mutex_unlock(&ctx->uring_lock);
10964 ret = io_uring_add_tctx_node(ctx);
10965 mutex_lock(&ctx->uring_lock);
10969 tctx = current->io_uring;
10970 for (i = 0; i < nr_args; i++) {
10973 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10983 if (reg.offset == -1U) {
10985 end = IO_RINGFD_REG_MAX;
10987 if (reg.offset >= IO_RINGFD_REG_MAX) {
10991 start = reg.offset;
10995 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11000 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11001 fput(tctx->registered_rings[reg.offset]);
11002 tctx->registered_rings[reg.offset] = NULL;
11008 return i ? i : ret;
11011 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11014 struct io_uring_rsrc_update __user *arg = __arg;
11015 struct io_uring_task *tctx = current->io_uring;
11016 struct io_uring_rsrc_update reg;
11019 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11024 for (i = 0; i < nr_args; i++) {
11025 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11029 if (reg.resv || reg.offset >= IO_RINGFD_REG_MAX) {
11034 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11035 if (tctx->registered_rings[reg.offset]) {
11036 fput(tctx->registered_rings[reg.offset]);
11037 tctx->registered_rings[reg.offset] = NULL;
11041 return i ? i : ret;
11044 static void *io_uring_validate_mmap_request(struct file *file,
11045 loff_t pgoff, size_t sz)
11047 struct io_ring_ctx *ctx = file->private_data;
11048 loff_t offset = pgoff << PAGE_SHIFT;
11053 case IORING_OFF_SQ_RING:
11054 case IORING_OFF_CQ_RING:
11057 case IORING_OFF_SQES:
11058 ptr = ctx->sq_sqes;
11061 return ERR_PTR(-EINVAL);
11064 page = virt_to_head_page(ptr);
11065 if (sz > page_size(page))
11066 return ERR_PTR(-EINVAL);
11073 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11075 size_t sz = vma->vm_end - vma->vm_start;
11079 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11081 return PTR_ERR(ptr);
11083 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11084 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11087 #else /* !CONFIG_MMU */
11089 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11091 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11094 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11096 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11099 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11100 unsigned long addr, unsigned long len,
11101 unsigned long pgoff, unsigned long flags)
11105 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11107 return PTR_ERR(ptr);
11109 return (unsigned long) ptr;
11112 #endif /* !CONFIG_MMU */
11114 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11119 if (!io_sqring_full(ctx))
11121 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11123 if (!io_sqring_full(ctx))
11126 } while (!signal_pending(current));
11128 finish_wait(&ctx->sqo_sq_wait, &wait);
11132 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11134 if (flags & IORING_ENTER_EXT_ARG) {
11135 struct io_uring_getevents_arg arg;
11137 if (argsz != sizeof(arg))
11139 if (copy_from_user(&arg, argp, sizeof(arg)))
11145 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11146 struct __kernel_timespec __user **ts,
11147 const sigset_t __user **sig)
11149 struct io_uring_getevents_arg arg;
11152 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11153 * is just a pointer to the sigset_t.
11155 if (!(flags & IORING_ENTER_EXT_ARG)) {
11156 *sig = (const sigset_t __user *) argp;
11162 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11163 * timespec and sigset_t pointers if good.
11165 if (*argsz != sizeof(arg))
11167 if (copy_from_user(&arg, argp, sizeof(arg)))
11171 *sig = u64_to_user_ptr(arg.sigmask);
11172 *argsz = arg.sigmask_sz;
11173 *ts = u64_to_user_ptr(arg.ts);
11177 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11178 u32, min_complete, u32, flags, const void __user *, argp,
11181 struct io_ring_ctx *ctx;
11185 io_run_task_work();
11187 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11188 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11189 IORING_ENTER_REGISTERED_RING)))
11193 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11194 * need only dereference our task private array to find it.
11196 if (flags & IORING_ENTER_REGISTERED_RING) {
11197 struct io_uring_task *tctx = current->io_uring;
11199 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11201 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11202 f.file = tctx->registered_rings[fd];
11203 if (unlikely(!f.file))
11207 if (unlikely(!f.file))
11212 if (unlikely(f.file->f_op != &io_uring_fops))
11216 ctx = f.file->private_data;
11217 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11221 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11225 * For SQ polling, the thread will do all submissions and completions.
11226 * Just return the requested submit count, and wake the thread if
11227 * we were asked to.
11230 if (ctx->flags & IORING_SETUP_SQPOLL) {
11231 io_cqring_overflow_flush(ctx);
11233 if (unlikely(ctx->sq_data->thread == NULL)) {
11237 if (flags & IORING_ENTER_SQ_WAKEUP)
11238 wake_up(&ctx->sq_data->wait);
11239 if (flags & IORING_ENTER_SQ_WAIT) {
11240 ret = io_sqpoll_wait_sq(ctx);
11245 } else if (to_submit) {
11246 ret = io_uring_add_tctx_node(ctx);
11250 mutex_lock(&ctx->uring_lock);
11251 ret = io_submit_sqes(ctx, to_submit);
11252 if (ret != to_submit) {
11253 mutex_unlock(&ctx->uring_lock);
11256 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11257 goto iopoll_locked;
11258 mutex_unlock(&ctx->uring_lock);
11260 if (flags & IORING_ENTER_GETEVENTS) {
11262 if (ctx->syscall_iopoll) {
11264 * We disallow the app entering submit/complete with
11265 * polling, but we still need to lock the ring to
11266 * prevent racing with polled issue that got punted to
11269 mutex_lock(&ctx->uring_lock);
11271 ret2 = io_validate_ext_arg(flags, argp, argsz);
11272 if (likely(!ret2)) {
11273 min_complete = min(min_complete,
11275 ret2 = io_iopoll_check(ctx, min_complete);
11277 mutex_unlock(&ctx->uring_lock);
11279 const sigset_t __user *sig;
11280 struct __kernel_timespec __user *ts;
11282 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11283 if (likely(!ret2)) {
11284 min_complete = min(min_complete,
11286 ret2 = io_cqring_wait(ctx, min_complete, sig,
11295 * EBADR indicates that one or more CQE were dropped.
11296 * Once the user has been informed we can clear the bit
11297 * as they are obviously ok with those drops.
11299 if (unlikely(ret2 == -EBADR))
11300 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11306 percpu_ref_put(&ctx->refs);
11308 if (!(flags & IORING_ENTER_REGISTERED_RING))
11313 #ifdef CONFIG_PROC_FS
11314 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11315 const struct cred *cred)
11317 struct user_namespace *uns = seq_user_ns(m);
11318 struct group_info *gi;
11323 seq_printf(m, "%5d\n", id);
11324 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11325 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11326 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11327 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11328 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11329 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11330 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11331 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11332 seq_puts(m, "\n\tGroups:\t");
11333 gi = cred->group_info;
11334 for (g = 0; g < gi->ngroups; g++) {
11335 seq_put_decimal_ull(m, g ? " " : "",
11336 from_kgid_munged(uns, gi->gid[g]));
11338 seq_puts(m, "\n\tCapEff:\t");
11339 cap = cred->cap_effective;
11340 CAP_FOR_EACH_U32(__capi)
11341 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11346 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11347 struct seq_file *m)
11349 struct io_sq_data *sq = NULL;
11350 struct io_overflow_cqe *ocqe;
11351 struct io_rings *r = ctx->rings;
11352 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11353 unsigned int sq_head = READ_ONCE(r->sq.head);
11354 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11355 unsigned int cq_head = READ_ONCE(r->cq.head);
11356 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11357 unsigned int sq_entries, cq_entries;
11362 * we may get imprecise sqe and cqe info if uring is actively running
11363 * since we get cached_sq_head and cached_cq_tail without uring_lock
11364 * and sq_tail and cq_head are changed by userspace. But it's ok since
11365 * we usually use these info when it is stuck.
11367 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11368 seq_printf(m, "SqHead:\t%u\n", sq_head);
11369 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11370 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11371 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11372 seq_printf(m, "CqHead:\t%u\n", cq_head);
11373 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11374 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11375 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11376 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11377 for (i = 0; i < sq_entries; i++) {
11378 unsigned int entry = i + sq_head;
11379 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11380 struct io_uring_sqe *sqe;
11382 if (sq_idx > sq_mask)
11384 sqe = &ctx->sq_sqes[sq_idx];
11385 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11386 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11389 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11390 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11391 for (i = 0; i < cq_entries; i++) {
11392 unsigned int entry = i + cq_head;
11393 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
11395 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11396 entry & cq_mask, cqe->user_data, cqe->res,
11401 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11402 * since fdinfo case grabs it in the opposite direction of normal use
11403 * cases. If we fail to get the lock, we just don't iterate any
11404 * structures that could be going away outside the io_uring mutex.
11406 has_lock = mutex_trylock(&ctx->uring_lock);
11408 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11414 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11415 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11416 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11417 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11418 struct file *f = io_file_from_index(ctx, i);
11421 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11423 seq_printf(m, "%5u: <none>\n", i);
11425 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11426 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11427 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11428 unsigned int len = buf->ubuf_end - buf->ubuf;
11430 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11432 if (has_lock && !xa_empty(&ctx->personalities)) {
11433 unsigned long index;
11434 const struct cred *cred;
11436 seq_printf(m, "Personalities:\n");
11437 xa_for_each(&ctx->personalities, index, cred)
11438 io_uring_show_cred(m, index, cred);
11441 mutex_unlock(&ctx->uring_lock);
11443 seq_puts(m, "PollList:\n");
11444 spin_lock(&ctx->completion_lock);
11445 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11446 struct hlist_head *list = &ctx->cancel_hash[i];
11447 struct io_kiocb *req;
11449 hlist_for_each_entry(req, list, hash_node)
11450 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11451 task_work_pending(req->task));
11454 seq_puts(m, "CqOverflowList:\n");
11455 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11456 struct io_uring_cqe *cqe = &ocqe->cqe;
11458 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11459 cqe->user_data, cqe->res, cqe->flags);
11463 spin_unlock(&ctx->completion_lock);
11466 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11468 struct io_ring_ctx *ctx = f->private_data;
11470 if (percpu_ref_tryget(&ctx->refs)) {
11471 __io_uring_show_fdinfo(ctx, m);
11472 percpu_ref_put(&ctx->refs);
11477 static const struct file_operations io_uring_fops = {
11478 .release = io_uring_release,
11479 .mmap = io_uring_mmap,
11481 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11482 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11484 .poll = io_uring_poll,
11485 #ifdef CONFIG_PROC_FS
11486 .show_fdinfo = io_uring_show_fdinfo,
11490 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11491 struct io_uring_params *p)
11493 struct io_rings *rings;
11494 size_t size, sq_array_offset;
11496 /* make sure these are sane, as we already accounted them */
11497 ctx->sq_entries = p->sq_entries;
11498 ctx->cq_entries = p->cq_entries;
11500 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11501 if (size == SIZE_MAX)
11504 rings = io_mem_alloc(size);
11508 ctx->rings = rings;
11509 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11510 rings->sq_ring_mask = p->sq_entries - 1;
11511 rings->cq_ring_mask = p->cq_entries - 1;
11512 rings->sq_ring_entries = p->sq_entries;
11513 rings->cq_ring_entries = p->cq_entries;
11515 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11516 if (size == SIZE_MAX) {
11517 io_mem_free(ctx->rings);
11522 ctx->sq_sqes = io_mem_alloc(size);
11523 if (!ctx->sq_sqes) {
11524 io_mem_free(ctx->rings);
11532 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11536 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11540 ret = io_uring_add_tctx_node(ctx);
11545 fd_install(fd, file);
11550 * Allocate an anonymous fd, this is what constitutes the application
11551 * visible backing of an io_uring instance. The application mmaps this
11552 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11553 * we have to tie this fd to a socket for file garbage collection purposes.
11555 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11558 #if defined(CONFIG_UNIX)
11561 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11564 return ERR_PTR(ret);
11567 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11568 O_RDWR | O_CLOEXEC, NULL);
11569 #if defined(CONFIG_UNIX)
11570 if (IS_ERR(file)) {
11571 sock_release(ctx->ring_sock);
11572 ctx->ring_sock = NULL;
11574 ctx->ring_sock->file = file;
11580 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11581 struct io_uring_params __user *params)
11583 struct io_ring_ctx *ctx;
11589 if (entries > IORING_MAX_ENTRIES) {
11590 if (!(p->flags & IORING_SETUP_CLAMP))
11592 entries = IORING_MAX_ENTRIES;
11596 * Use twice as many entries for the CQ ring. It's possible for the
11597 * application to drive a higher depth than the size of the SQ ring,
11598 * since the sqes are only used at submission time. This allows for
11599 * some flexibility in overcommitting a bit. If the application has
11600 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11601 * of CQ ring entries manually.
11603 p->sq_entries = roundup_pow_of_two(entries);
11604 if (p->flags & IORING_SETUP_CQSIZE) {
11606 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11607 * to a power-of-two, if it isn't already. We do NOT impose
11608 * any cq vs sq ring sizing.
11610 if (!p->cq_entries)
11612 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11613 if (!(p->flags & IORING_SETUP_CLAMP))
11615 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11617 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11618 if (p->cq_entries < p->sq_entries)
11621 p->cq_entries = 2 * p->sq_entries;
11624 ctx = io_ring_ctx_alloc(p);
11629 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
11630 * space applications don't need to do io completion events
11631 * polling again, they can rely on io_sq_thread to do polling
11632 * work, which can reduce cpu usage and uring_lock contention.
11634 if (ctx->flags & IORING_SETUP_IOPOLL &&
11635 !(ctx->flags & IORING_SETUP_SQPOLL))
11636 ctx->syscall_iopoll = 1;
11638 ctx->compat = in_compat_syscall();
11639 if (!capable(CAP_IPC_LOCK))
11640 ctx->user = get_uid(current_user());
11643 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
11644 * COOP_TASKRUN is set, then IPIs are never needed by the app.
11647 if (ctx->flags & IORING_SETUP_SQPOLL) {
11648 /* IPI related flags don't make sense with SQPOLL */
11649 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
11650 IORING_SETUP_TASKRUN_FLAG))
11652 ctx->notify_method = TWA_SIGNAL_NO_IPI;
11653 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
11654 ctx->notify_method = TWA_SIGNAL_NO_IPI;
11656 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
11658 ctx->notify_method = TWA_SIGNAL;
11662 * This is just grabbed for accounting purposes. When a process exits,
11663 * the mm is exited and dropped before the files, hence we need to hang
11664 * on to this mm purely for the purposes of being able to unaccount
11665 * memory (locked/pinned vm). It's not used for anything else.
11667 mmgrab(current->mm);
11668 ctx->mm_account = current->mm;
11670 ret = io_allocate_scq_urings(ctx, p);
11674 ret = io_sq_offload_create(ctx, p);
11677 /* always set a rsrc node */
11678 ret = io_rsrc_node_switch_start(ctx);
11681 io_rsrc_node_switch(ctx, NULL);
11683 memset(&p->sq_off, 0, sizeof(p->sq_off));
11684 p->sq_off.head = offsetof(struct io_rings, sq.head);
11685 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11686 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11687 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11688 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11689 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11690 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11692 memset(&p->cq_off, 0, sizeof(p->cq_off));
11693 p->cq_off.head = offsetof(struct io_rings, cq.head);
11694 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11695 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11696 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11697 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11698 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11699 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11701 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11702 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11703 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11704 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11705 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11706 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
11707 IORING_FEAT_LINKED_FILE;
11709 if (copy_to_user(params, p, sizeof(*p))) {
11714 file = io_uring_get_file(ctx);
11715 if (IS_ERR(file)) {
11716 ret = PTR_ERR(file);
11721 * Install ring fd as the very last thing, so we don't risk someone
11722 * having closed it before we finish setup
11724 ret = io_uring_install_fd(ctx, file);
11726 /* fput will clean it up */
11731 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11734 io_ring_ctx_wait_and_kill(ctx);
11739 * Sets up an aio uring context, and returns the fd. Applications asks for a
11740 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11741 * params structure passed in.
11743 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11745 struct io_uring_params p;
11748 if (copy_from_user(&p, params, sizeof(p)))
11750 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11755 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11756 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11757 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11758 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
11759 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG))
11762 return io_uring_create(entries, &p, params);
11765 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11766 struct io_uring_params __user *, params)
11768 return io_uring_setup(entries, params);
11771 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11774 struct io_uring_probe *p;
11778 size = struct_size(p, ops, nr_args);
11779 if (size == SIZE_MAX)
11781 p = kzalloc(size, GFP_KERNEL);
11786 if (copy_from_user(p, arg, size))
11789 if (memchr_inv(p, 0, size))
11792 p->last_op = IORING_OP_LAST - 1;
11793 if (nr_args > IORING_OP_LAST)
11794 nr_args = IORING_OP_LAST;
11796 for (i = 0; i < nr_args; i++) {
11798 if (!io_op_defs[i].not_supported)
11799 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11804 if (copy_to_user(arg, p, size))
11811 static int io_register_personality(struct io_ring_ctx *ctx)
11813 const struct cred *creds;
11817 creds = get_current_cred();
11819 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11820 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11828 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11829 void __user *arg, unsigned int nr_args)
11831 struct io_uring_restriction *res;
11835 /* Restrictions allowed only if rings started disabled */
11836 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11839 /* We allow only a single restrictions registration */
11840 if (ctx->restrictions.registered)
11843 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11846 size = array_size(nr_args, sizeof(*res));
11847 if (size == SIZE_MAX)
11850 res = memdup_user(arg, size);
11852 return PTR_ERR(res);
11856 for (i = 0; i < nr_args; i++) {
11857 switch (res[i].opcode) {
11858 case IORING_RESTRICTION_REGISTER_OP:
11859 if (res[i].register_op >= IORING_REGISTER_LAST) {
11864 __set_bit(res[i].register_op,
11865 ctx->restrictions.register_op);
11867 case IORING_RESTRICTION_SQE_OP:
11868 if (res[i].sqe_op >= IORING_OP_LAST) {
11873 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11875 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11876 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11878 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11879 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11888 /* Reset all restrictions if an error happened */
11890 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11892 ctx->restrictions.registered = true;
11898 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11900 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11903 if (ctx->restrictions.registered)
11904 ctx->restricted = 1;
11906 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11907 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11908 wake_up(&ctx->sq_data->wait);
11912 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11913 struct io_uring_rsrc_update2 *up,
11919 if (check_add_overflow(up->offset, nr_args, &tmp))
11921 err = io_rsrc_node_switch_start(ctx);
11926 case IORING_RSRC_FILE:
11927 return __io_sqe_files_update(ctx, up, nr_args);
11928 case IORING_RSRC_BUFFER:
11929 return __io_sqe_buffers_update(ctx, up, nr_args);
11934 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11937 struct io_uring_rsrc_update2 up;
11941 memset(&up, 0, sizeof(up));
11942 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11944 if (up.resv || up.resv2)
11946 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11949 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11950 unsigned size, unsigned type)
11952 struct io_uring_rsrc_update2 up;
11954 if (size != sizeof(up))
11956 if (copy_from_user(&up, arg, sizeof(up)))
11958 if (!up.nr || up.resv || up.resv2)
11960 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11963 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11964 unsigned int size, unsigned int type)
11966 struct io_uring_rsrc_register rr;
11968 /* keep it extendible */
11969 if (size != sizeof(rr))
11972 memset(&rr, 0, sizeof(rr));
11973 if (copy_from_user(&rr, arg, size))
11975 if (!rr.nr || rr.resv2)
11977 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
11981 case IORING_RSRC_FILE:
11982 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
11984 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11985 rr.nr, u64_to_user_ptr(rr.tags));
11986 case IORING_RSRC_BUFFER:
11987 if (rr.flags & IORING_RSRC_REGISTER_SPARSE)
11989 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11990 rr.nr, u64_to_user_ptr(rr.tags));
11995 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11996 void __user *arg, unsigned len)
11998 struct io_uring_task *tctx = current->io_uring;
11999 cpumask_var_t new_mask;
12002 if (!tctx || !tctx->io_wq)
12005 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12008 cpumask_clear(new_mask);
12009 if (len > cpumask_size())
12010 len = cpumask_size();
12012 if (in_compat_syscall()) {
12013 ret = compat_get_bitmap(cpumask_bits(new_mask),
12014 (const compat_ulong_t __user *)arg,
12015 len * 8 /* CHAR_BIT */);
12017 ret = copy_from_user(new_mask, arg, len);
12021 free_cpumask_var(new_mask);
12025 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12026 free_cpumask_var(new_mask);
12030 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12032 struct io_uring_task *tctx = current->io_uring;
12034 if (!tctx || !tctx->io_wq)
12037 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12040 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12042 __must_hold(&ctx->uring_lock)
12044 struct io_tctx_node *node;
12045 struct io_uring_task *tctx = NULL;
12046 struct io_sq_data *sqd = NULL;
12047 __u32 new_count[2];
12050 if (copy_from_user(new_count, arg, sizeof(new_count)))
12052 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12053 if (new_count[i] > INT_MAX)
12056 if (ctx->flags & IORING_SETUP_SQPOLL) {
12057 sqd = ctx->sq_data;
12060 * Observe the correct sqd->lock -> ctx->uring_lock
12061 * ordering. Fine to drop uring_lock here, we hold
12062 * a ref to the ctx.
12064 refcount_inc(&sqd->refs);
12065 mutex_unlock(&ctx->uring_lock);
12066 mutex_lock(&sqd->lock);
12067 mutex_lock(&ctx->uring_lock);
12069 tctx = sqd->thread->io_uring;
12072 tctx = current->io_uring;
12075 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12077 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12079 ctx->iowq_limits[i] = new_count[i];
12080 ctx->iowq_limits_set = true;
12082 if (tctx && tctx->io_wq) {
12083 ret = io_wq_max_workers(tctx->io_wq, new_count);
12087 memset(new_count, 0, sizeof(new_count));
12091 mutex_unlock(&sqd->lock);
12092 io_put_sq_data(sqd);
12095 if (copy_to_user(arg, new_count, sizeof(new_count)))
12098 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12102 /* now propagate the restriction to all registered users */
12103 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12104 struct io_uring_task *tctx = node->task->io_uring;
12106 if (WARN_ON_ONCE(!tctx->io_wq))
12109 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12110 new_count[i] = ctx->iowq_limits[i];
12111 /* ignore errors, it always returns zero anyway */
12112 (void)io_wq_max_workers(tctx->io_wq, new_count);
12117 mutex_unlock(&sqd->lock);
12118 io_put_sq_data(sqd);
12123 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12125 struct io_uring_buf_ring *br;
12126 struct io_uring_buf_reg reg;
12127 struct io_buffer_list *bl;
12128 struct page **pages;
12131 if (copy_from_user(®, arg, sizeof(reg)))
12134 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12136 if (!reg.ring_addr)
12138 if (reg.ring_addr & ~PAGE_MASK)
12140 if (!is_power_of_2(reg.ring_entries))
12143 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12144 int ret = io_init_bl_list(ctx);
12149 bl = io_buffer_get_list(ctx, reg.bgid);
12150 if (bl && bl->buf_nr_pages)
12153 bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12158 pages = io_pin_pages(reg.ring_addr,
12159 struct_size(br, bufs, reg.ring_entries),
12161 if (IS_ERR(pages)) {
12163 return PTR_ERR(pages);
12166 br = page_address(pages[0]);
12167 bl->buf_pages = pages;
12168 bl->buf_nr_pages = nr_pages;
12169 bl->nr_entries = reg.ring_entries;
12171 bl->mask = reg.ring_entries - 1;
12172 io_buffer_add_list(ctx, bl, reg.bgid);
12176 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12178 struct io_uring_buf_reg reg;
12179 struct io_buffer_list *bl;
12181 if (copy_from_user(®, arg, sizeof(reg)))
12183 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12186 bl = io_buffer_get_list(ctx, reg.bgid);
12189 if (!bl->buf_nr_pages)
12192 __io_remove_buffers(ctx, bl, -1U);
12193 if (bl->bgid >= BGID_ARRAY) {
12194 xa_erase(&ctx->io_bl_xa, bl->bgid);
12200 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12201 void __user *arg, unsigned nr_args)
12202 __releases(ctx->uring_lock)
12203 __acquires(ctx->uring_lock)
12208 * We're inside the ring mutex, if the ref is already dying, then
12209 * someone else killed the ctx or is already going through
12210 * io_uring_register().
12212 if (percpu_ref_is_dying(&ctx->refs))
12215 if (ctx->restricted) {
12216 if (opcode >= IORING_REGISTER_LAST)
12218 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12219 if (!test_bit(opcode, ctx->restrictions.register_op))
12224 case IORING_REGISTER_BUFFERS:
12225 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12227 case IORING_UNREGISTER_BUFFERS:
12229 if (arg || nr_args)
12231 ret = io_sqe_buffers_unregister(ctx);
12233 case IORING_REGISTER_FILES:
12237 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12239 case IORING_UNREGISTER_FILES:
12241 if (arg || nr_args)
12243 ret = io_sqe_files_unregister(ctx);
12245 case IORING_REGISTER_FILES_UPDATE:
12246 ret = io_register_files_update(ctx, arg, nr_args);
12248 case IORING_REGISTER_EVENTFD:
12252 ret = io_eventfd_register(ctx, arg, 0);
12254 case IORING_REGISTER_EVENTFD_ASYNC:
12258 ret = io_eventfd_register(ctx, arg, 1);
12260 case IORING_UNREGISTER_EVENTFD:
12262 if (arg || nr_args)
12264 ret = io_eventfd_unregister(ctx);
12266 case IORING_REGISTER_PROBE:
12268 if (!arg || nr_args > 256)
12270 ret = io_probe(ctx, arg, nr_args);
12272 case IORING_REGISTER_PERSONALITY:
12274 if (arg || nr_args)
12276 ret = io_register_personality(ctx);
12278 case IORING_UNREGISTER_PERSONALITY:
12282 ret = io_unregister_personality(ctx, nr_args);
12284 case IORING_REGISTER_ENABLE_RINGS:
12286 if (arg || nr_args)
12288 ret = io_register_enable_rings(ctx);
12290 case IORING_REGISTER_RESTRICTIONS:
12291 ret = io_register_restrictions(ctx, arg, nr_args);
12293 case IORING_REGISTER_FILES2:
12294 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12296 case IORING_REGISTER_FILES_UPDATE2:
12297 ret = io_register_rsrc_update(ctx, arg, nr_args,
12300 case IORING_REGISTER_BUFFERS2:
12301 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12303 case IORING_REGISTER_BUFFERS_UPDATE:
12304 ret = io_register_rsrc_update(ctx, arg, nr_args,
12305 IORING_RSRC_BUFFER);
12307 case IORING_REGISTER_IOWQ_AFF:
12309 if (!arg || !nr_args)
12311 ret = io_register_iowq_aff(ctx, arg, nr_args);
12313 case IORING_UNREGISTER_IOWQ_AFF:
12315 if (arg || nr_args)
12317 ret = io_unregister_iowq_aff(ctx);
12319 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12321 if (!arg || nr_args != 2)
12323 ret = io_register_iowq_max_workers(ctx, arg);
12325 case IORING_REGISTER_RING_FDS:
12326 ret = io_ringfd_register(ctx, arg, nr_args);
12328 case IORING_UNREGISTER_RING_FDS:
12329 ret = io_ringfd_unregister(ctx, arg, nr_args);
12331 case IORING_REGISTER_PBUF_RING:
12333 if (!arg || nr_args != 1)
12335 ret = io_register_pbuf_ring(ctx, arg);
12337 case IORING_UNREGISTER_PBUF_RING:
12339 if (!arg || nr_args != 1)
12341 ret = io_unregister_pbuf_ring(ctx, arg);
12351 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12352 void __user *, arg, unsigned int, nr_args)
12354 struct io_ring_ctx *ctx;
12363 if (f.file->f_op != &io_uring_fops)
12366 ctx = f.file->private_data;
12368 io_run_task_work();
12370 mutex_lock(&ctx->uring_lock);
12371 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12372 mutex_unlock(&ctx->uring_lock);
12373 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12379 static int __init io_uring_init(void)
12381 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
12382 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
12383 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
12386 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
12387 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
12388 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
12389 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
12390 BUILD_BUG_SQE_ELEM(1, __u8, flags);
12391 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
12392 BUILD_BUG_SQE_ELEM(4, __s32, fd);
12393 BUILD_BUG_SQE_ELEM(8, __u64, off);
12394 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
12395 BUILD_BUG_SQE_ELEM(16, __u64, addr);
12396 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
12397 BUILD_BUG_SQE_ELEM(24, __u32, len);
12398 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
12399 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
12400 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
12401 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
12402 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
12403 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
12404 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
12405 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
12406 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
12407 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
12408 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
12409 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
12410 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
12411 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
12412 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
12413 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
12414 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
12415 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
12416 BUILD_BUG_SQE_ELEM(42, __u16, personality);
12417 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
12418 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
12420 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
12421 sizeof(struct io_uring_rsrc_update));
12422 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
12423 sizeof(struct io_uring_rsrc_update2));
12425 /* ->buf_index is u16 */
12426 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
12427 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
12428 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
12429 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
12430 offsetof(struct io_uring_buf_ring, tail));
12432 /* should fit into one byte */
12433 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
12434 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
12435 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
12437 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
12438 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
12440 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
12442 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
12446 __initcall(io_uring_init);