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/tracehook.h>
82 #include <linux/audit.h>
83 #include <linux/security.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
98 #define IORING_MAX_FIXED_FILES (1U << 15)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
102 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
103 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
104 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
106 #define IORING_MAX_REG_BUFFERS (1U << 14)
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
118 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
121 u32 head ____cacheline_aligned_in_smp;
122 u32 tail ____cacheline_aligned_in_smp;
126 * This data is shared with the application through the mmap at offsets
127 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
129 * The offsets to the member fields are published through struct
130 * io_sqring_offsets when calling io_uring_setup.
134 * Head and tail offsets into the ring; the offsets need to be
135 * masked to get valid indices.
137 * The kernel controls head of the sq ring and the tail of the cq ring,
138 * and the application controls tail of the sq ring and the head of the
141 struct io_uring sq, cq;
143 * Bitmasks to apply to head and tail offsets (constant, equals
146 u32 sq_ring_mask, cq_ring_mask;
147 /* Ring sizes (constant, power of 2) */
148 u32 sq_ring_entries, cq_ring_entries;
150 * Number of invalid entries dropped by the kernel due to
151 * invalid index stored in array
153 * Written by the kernel, shouldn't be modified by the
154 * application (i.e. get number of "new events" by comparing to
157 * After a new SQ head value was read by the application this
158 * counter includes all submissions that were dropped reaching
159 * the new SQ head (and possibly more).
165 * Written by the kernel, shouldn't be modified by the
168 * The application needs a full memory barrier before checking
169 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
175 * Written by the application, shouldn't be modified by the
180 * Number of completion events lost because the queue was full;
181 * this should be avoided by the application by making sure
182 * there are not more requests pending than there is space in
183 * the completion queue.
185 * Written by the kernel, shouldn't be modified by the
186 * application (i.e. get number of "new events" by comparing to
189 * As completion events come in out of order this counter is not
190 * ordered with any other data.
194 * Ring buffer of completion events.
196 * The kernel writes completion events fresh every time they are
197 * produced, so the application is allowed to modify pending
200 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
203 enum io_uring_cmd_flags {
204 IO_URING_F_COMPLETE_DEFER = 1,
205 IO_URING_F_UNLOCKED = 2,
206 /* int's last bit, sign checks are usually faster than a bit test */
207 IO_URING_F_NONBLOCK = INT_MIN,
210 struct io_mapped_ubuf {
213 unsigned int nr_bvecs;
214 unsigned long acct_pages;
215 struct bio_vec bvec[];
220 struct io_overflow_cqe {
221 struct io_uring_cqe cqe;
222 struct list_head list;
225 struct io_fixed_file {
226 /* file * with additional FFS_* flags */
227 unsigned long file_ptr;
231 struct list_head list;
236 struct io_mapped_ubuf *buf;
240 struct io_file_table {
241 struct io_fixed_file *files;
244 struct io_rsrc_node {
245 struct percpu_ref refs;
246 struct list_head node;
247 struct list_head rsrc_list;
248 struct io_rsrc_data *rsrc_data;
249 struct llist_node llist;
253 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
255 struct io_rsrc_data {
256 struct io_ring_ctx *ctx;
262 struct completion done;
267 struct list_head list;
273 struct io_restriction {
274 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
275 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
276 u8 sqe_flags_allowed;
277 u8 sqe_flags_required;
282 IO_SQ_THREAD_SHOULD_STOP = 0,
283 IO_SQ_THREAD_SHOULD_PARK,
288 atomic_t park_pending;
291 /* ctx's that are using this sqd */
292 struct list_head ctx_list;
294 struct task_struct *thread;
295 struct wait_queue_head wait;
297 unsigned sq_thread_idle;
303 struct completion exited;
306 #define IO_COMPL_BATCH 32
307 #define IO_REQ_CACHE_SIZE 32
308 #define IO_REQ_ALLOC_BATCH 8
310 struct io_submit_link {
311 struct io_kiocb *head;
312 struct io_kiocb *last;
315 struct io_submit_state {
316 /* inline/task_work completion list, under ->uring_lock */
317 struct io_wq_work_node free_list;
318 /* batch completion logic */
319 struct io_wq_work_list compl_reqs;
320 struct io_submit_link link;
325 unsigned short submit_nr;
326 struct blk_plug plug;
330 /* const or read-mostly hot data */
332 struct percpu_ref refs;
334 struct io_rings *rings;
336 unsigned int compat: 1;
337 unsigned int drain_next: 1;
338 unsigned int eventfd_async: 1;
339 unsigned int restricted: 1;
340 unsigned int off_timeout_used: 1;
341 unsigned int drain_active: 1;
342 unsigned int drain_disabled: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 int rsrc_cached_refs;
372 struct io_file_table file_table;
373 unsigned nr_user_files;
374 unsigned nr_user_bufs;
375 struct io_mapped_ubuf **user_bufs;
377 struct io_submit_state submit_state;
378 struct list_head timeout_list;
379 struct list_head ltimeout_list;
380 struct list_head cq_overflow_list;
381 struct xarray io_buffers;
382 struct xarray personalities;
384 unsigned sq_thread_idle;
385 } ____cacheline_aligned_in_smp;
387 /* IRQ completion list, under ->completion_lock */
388 struct io_wq_work_list locked_free_list;
389 unsigned int locked_free_nr;
391 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
392 struct io_sq_data *sq_data; /* if using sq thread polling */
394 struct wait_queue_head sqo_sq_wait;
395 struct list_head sqd_list;
397 unsigned long check_cq_overflow;
400 unsigned cached_cq_tail;
402 struct eventfd_ctx *cq_ev_fd;
403 struct wait_queue_head cq_wait;
405 atomic_t cq_timeouts;
406 unsigned cq_last_tm_flush;
407 } ____cacheline_aligned_in_smp;
410 spinlock_t completion_lock;
412 spinlock_t timeout_lock;
415 * ->iopoll_list is protected by the ctx->uring_lock for
416 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417 * For SQPOLL, only the single threaded io_sq_thread() will
418 * manipulate the list, hence no extra locking is needed there.
420 struct io_wq_work_list iopoll_list;
421 struct hlist_head *cancel_hash;
422 unsigned cancel_hash_bits;
423 bool poll_multi_queue;
424 } ____cacheline_aligned_in_smp;
426 struct io_restriction restrictions;
428 /* slow path rsrc auxilary data, used by update/register */
430 struct io_rsrc_node *rsrc_backup_node;
431 struct io_mapped_ubuf *dummy_ubuf;
432 struct io_rsrc_data *file_data;
433 struct io_rsrc_data *buf_data;
435 struct delayed_work rsrc_put_work;
436 struct llist_head rsrc_put_llist;
437 struct list_head rsrc_ref_list;
438 spinlock_t rsrc_ref_lock;
441 /* Keep this last, we don't need it for the fast path */
443 #if defined(CONFIG_UNIX)
444 struct socket *ring_sock;
446 /* hashed buffered write serialization */
447 struct io_wq_hash *hash_map;
449 /* Only used for accounting purposes */
450 struct user_struct *user;
451 struct mm_struct *mm_account;
453 /* ctx exit and cancelation */
454 struct llist_head fallback_llist;
455 struct delayed_work fallback_work;
456 struct work_struct exit_work;
457 struct list_head tctx_list;
458 struct completion ref_comp;
460 bool iowq_limits_set;
464 struct io_uring_task {
465 /* submission side */
468 struct wait_queue_head wait;
469 const struct io_ring_ctx *last;
471 struct percpu_counter inflight;
472 atomic_t inflight_tracked;
475 spinlock_t task_lock;
476 struct io_wq_work_list task_list;
477 struct io_wq_work_list prior_task_list;
478 struct callback_head task_work;
483 * First field must be the file pointer in all the
484 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
486 struct io_poll_iocb {
488 struct wait_queue_head *head;
490 struct wait_queue_entry wait;
493 struct io_poll_update {
499 bool update_user_data;
508 struct io_timeout_data {
509 struct io_kiocb *req;
510 struct hrtimer timer;
511 struct timespec64 ts;
512 enum hrtimer_mode mode;
518 struct sockaddr __user *addr;
519 int __user *addr_len;
522 unsigned long nofile;
542 struct list_head list;
543 /* head of the link, used by linked timeouts only */
544 struct io_kiocb *head;
545 /* for linked completions */
546 struct io_kiocb *prev;
549 struct io_timeout_rem {
554 struct timespec64 ts;
560 /* NOTE: kiocb has the file as the first member, so don't do it here */
568 struct sockaddr __user *addr;
575 struct compat_msghdr __user *umsg_compat;
576 struct user_msghdr __user *umsg;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
624 struct file *file_in;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
674 struct filename *filename;
680 struct filename *oldpath;
681 struct filename *newpath;
688 struct filename *oldpath;
689 struct filename *newpath;
693 struct io_async_connect {
694 struct sockaddr_storage address;
697 struct io_async_msghdr {
698 struct iovec fast_iov[UIO_FASTIOV];
699 /* points to an allocated iov, if NULL we use fast_iov instead */
700 struct iovec *free_iov;
701 struct sockaddr __user *uaddr;
703 struct sockaddr_storage addr;
707 struct iov_iter iter;
708 struct iov_iter_state iter_state;
709 struct iovec fast_iov[UIO_FASTIOV];
713 struct io_rw_state s;
714 const struct iovec *free_iovec;
716 struct wait_page_queue wpq;
720 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
721 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
722 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
723 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
724 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
725 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
726 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
728 /* first byte is taken by user flags, shift it to not overlap */
733 REQ_F_LINK_TIMEOUT_BIT,
734 REQ_F_NEED_CLEANUP_BIT,
736 REQ_F_BUFFER_SELECTED_BIT,
737 REQ_F_COMPLETE_INLINE_BIT,
741 REQ_F_ARM_LTIMEOUT_BIT,
742 REQ_F_ASYNC_DATA_BIT,
743 REQ_F_SKIP_LINK_CQES_BIT,
744 /* keep async read/write and isreg together and in order */
745 REQ_F_SUPPORT_NOWAIT_BIT,
748 /* not a real bit, just to check we're not overflowing the space */
754 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
755 /* drain existing IO first */
756 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
758 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
759 /* doesn't sever on completion < 0 */
760 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
762 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
763 /* IOSQE_BUFFER_SELECT */
764 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
765 /* IOSQE_CQE_SKIP_SUCCESS */
766 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
768 /* fail rest of links */
769 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
770 /* on inflight list, should be cancelled and waited on exit reliably */
771 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
772 /* read/write uses file position */
773 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
774 /* must not punt to workers */
775 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
776 /* has or had linked timeout */
777 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
779 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
780 /* already went through poll handler */
781 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
782 /* buffer already selected */
783 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
784 /* completion is deferred through io_comp_state */
785 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
786 /* caller should reissue async */
787 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
788 /* supports async reads/writes */
789 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
791 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
792 /* has creds assigned */
793 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
794 /* skip refcounting if not set */
795 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
796 /* there is a linked timeout that has to be armed */
797 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
798 /* ->async_data allocated */
799 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
800 /* don't post CQEs while failing linked requests */
801 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
805 struct io_poll_iocb poll;
806 struct io_poll_iocb *double_poll;
809 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
811 struct io_task_work {
813 struct io_wq_work_node node;
814 struct llist_node fallback_node;
816 io_req_tw_func_t func;
820 IORING_RSRC_FILE = 0,
821 IORING_RSRC_BUFFER = 1,
825 * NOTE! Each of the iocb union members has the file pointer
826 * as the first entry in their struct definition. So you can
827 * access the file pointer through any of the sub-structs,
828 * or directly as just 'ki_filp' in this struct.
834 struct io_poll_iocb poll;
835 struct io_poll_update poll_update;
836 struct io_accept accept;
838 struct io_cancel cancel;
839 struct io_timeout timeout;
840 struct io_timeout_rem timeout_rem;
841 struct io_connect connect;
842 struct io_sr_msg sr_msg;
844 struct io_close close;
845 struct io_rsrc_update rsrc_update;
846 struct io_fadvise fadvise;
847 struct io_madvise madvise;
848 struct io_epoll epoll;
849 struct io_splice splice;
850 struct io_provide_buf pbuf;
851 struct io_statx statx;
852 struct io_shutdown shutdown;
853 struct io_rename rename;
854 struct io_unlink unlink;
855 struct io_mkdir mkdir;
856 struct io_symlink symlink;
857 struct io_hardlink hardlink;
861 /* polled IO has completed */
870 struct io_ring_ctx *ctx;
871 struct task_struct *task;
873 struct percpu_ref *fixed_rsrc_refs;
874 /* store used ubuf, so we can prevent reloading */
875 struct io_mapped_ubuf *imu;
877 /* used by request caches, completion batching and iopoll */
878 struct io_wq_work_node comp_list;
880 struct io_kiocb *link;
881 struct io_task_work io_task_work;
882 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
883 struct hlist_node hash_node;
884 /* internal polling, see IORING_FEAT_FAST_POLL */
885 struct async_poll *apoll;
886 /* opcode allocated if it needs to store data for async defer */
888 struct io_wq_work work;
889 /* custom credentials, valid IFF REQ_F_CREDS is set */
890 const struct cred *creds;
891 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
892 struct io_buffer *kbuf;
896 struct io_tctx_node {
897 struct list_head ctx_node;
898 struct task_struct *task;
899 struct io_ring_ctx *ctx;
902 struct io_defer_entry {
903 struct list_head list;
904 struct io_kiocb *req;
909 /* needs req->file assigned */
910 unsigned needs_file : 1;
911 /* should block plug */
913 /* hash wq insertion if file is a regular file */
914 unsigned hash_reg_file : 1;
915 /* unbound wq insertion if file is a non-regular file */
916 unsigned unbound_nonreg_file : 1;
917 /* set if opcode supports polled "wait" */
919 unsigned pollout : 1;
920 /* op supports buffer selection */
921 unsigned buffer_select : 1;
922 /* do prep async if is going to be punted */
923 unsigned needs_async_setup : 1;
924 /* opcode is not supported by this kernel */
925 unsigned not_supported : 1;
927 unsigned audit_skip : 1;
928 /* size of async data needed, if any */
929 unsigned short async_size;
932 static const struct io_op_def io_op_defs[] = {
933 [IORING_OP_NOP] = {},
934 [IORING_OP_READV] = {
936 .unbound_nonreg_file = 1,
939 .needs_async_setup = 1,
942 .async_size = sizeof(struct io_async_rw),
944 [IORING_OP_WRITEV] = {
947 .unbound_nonreg_file = 1,
949 .needs_async_setup = 1,
952 .async_size = sizeof(struct io_async_rw),
954 [IORING_OP_FSYNC] = {
958 [IORING_OP_READ_FIXED] = {
960 .unbound_nonreg_file = 1,
964 .async_size = sizeof(struct io_async_rw),
966 [IORING_OP_WRITE_FIXED] = {
969 .unbound_nonreg_file = 1,
973 .async_size = sizeof(struct io_async_rw),
975 [IORING_OP_POLL_ADD] = {
977 .unbound_nonreg_file = 1,
980 [IORING_OP_POLL_REMOVE] = {
983 [IORING_OP_SYNC_FILE_RANGE] = {
987 [IORING_OP_SENDMSG] = {
989 .unbound_nonreg_file = 1,
991 .needs_async_setup = 1,
992 .async_size = sizeof(struct io_async_msghdr),
994 [IORING_OP_RECVMSG] = {
996 .unbound_nonreg_file = 1,
999 .needs_async_setup = 1,
1000 .async_size = sizeof(struct io_async_msghdr),
1002 [IORING_OP_TIMEOUT] = {
1004 .async_size = sizeof(struct io_timeout_data),
1006 [IORING_OP_TIMEOUT_REMOVE] = {
1007 /* used by timeout updates' prep() */
1010 [IORING_OP_ACCEPT] = {
1012 .unbound_nonreg_file = 1,
1015 [IORING_OP_ASYNC_CANCEL] = {
1018 [IORING_OP_LINK_TIMEOUT] = {
1020 .async_size = sizeof(struct io_timeout_data),
1022 [IORING_OP_CONNECT] = {
1024 .unbound_nonreg_file = 1,
1026 .needs_async_setup = 1,
1027 .async_size = sizeof(struct io_async_connect),
1029 [IORING_OP_FALLOCATE] = {
1032 [IORING_OP_OPENAT] = {},
1033 [IORING_OP_CLOSE] = {},
1034 [IORING_OP_FILES_UPDATE] = {
1037 [IORING_OP_STATX] = {
1040 [IORING_OP_READ] = {
1042 .unbound_nonreg_file = 1,
1047 .async_size = sizeof(struct io_async_rw),
1049 [IORING_OP_WRITE] = {
1052 .unbound_nonreg_file = 1,
1056 .async_size = sizeof(struct io_async_rw),
1058 [IORING_OP_FADVISE] = {
1062 [IORING_OP_MADVISE] = {},
1063 [IORING_OP_SEND] = {
1065 .unbound_nonreg_file = 1,
1069 [IORING_OP_RECV] = {
1071 .unbound_nonreg_file = 1,
1076 [IORING_OP_OPENAT2] = {
1078 [IORING_OP_EPOLL_CTL] = {
1079 .unbound_nonreg_file = 1,
1082 [IORING_OP_SPLICE] = {
1085 .unbound_nonreg_file = 1,
1088 [IORING_OP_PROVIDE_BUFFERS] = {
1091 [IORING_OP_REMOVE_BUFFERS] = {
1097 .unbound_nonreg_file = 1,
1100 [IORING_OP_SHUTDOWN] = {
1103 [IORING_OP_RENAMEAT] = {},
1104 [IORING_OP_UNLINKAT] = {},
1105 [IORING_OP_MKDIRAT] = {},
1106 [IORING_OP_SYMLINKAT] = {},
1107 [IORING_OP_LINKAT] = {},
1110 /* requests with any of those set should undergo io_disarm_next() */
1111 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1113 static bool io_disarm_next(struct io_kiocb *req);
1114 static void io_uring_del_tctx_node(unsigned long index);
1115 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1116 struct task_struct *task,
1118 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1120 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1122 static void io_put_req(struct io_kiocb *req);
1123 static void io_put_req_deferred(struct io_kiocb *req);
1124 static void io_dismantle_req(struct io_kiocb *req);
1125 static void io_queue_linked_timeout(struct io_kiocb *req);
1126 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1127 struct io_uring_rsrc_update2 *up,
1129 static void io_clean_op(struct io_kiocb *req);
1130 static struct file *io_file_get(struct io_ring_ctx *ctx,
1131 struct io_kiocb *req, int fd, bool fixed);
1132 static void __io_queue_sqe(struct io_kiocb *req);
1133 static void io_rsrc_put_work(struct work_struct *work);
1135 static void io_req_task_queue(struct io_kiocb *req);
1136 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1137 static int io_req_prep_async(struct io_kiocb *req);
1139 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1140 unsigned int issue_flags, u32 slot_index);
1141 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1143 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1145 static struct kmem_cache *req_cachep;
1147 static const struct file_operations io_uring_fops;
1149 struct sock *io_uring_get_socket(struct file *file)
1151 #if defined(CONFIG_UNIX)
1152 if (file->f_op == &io_uring_fops) {
1153 struct io_ring_ctx *ctx = file->private_data;
1155 return ctx->ring_sock->sk;
1160 EXPORT_SYMBOL(io_uring_get_socket);
1162 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1165 mutex_lock(&ctx->uring_lock);
1170 #define io_for_each_link(pos, head) \
1171 for (pos = (head); pos; pos = pos->link)
1174 * Shamelessly stolen from the mm implementation of page reference checking,
1175 * see commit f958d7b528b1 for details.
1177 #define req_ref_zero_or_close_to_overflow(req) \
1178 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1180 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1182 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1183 return atomic_inc_not_zero(&req->refs);
1186 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1188 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1191 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1192 return atomic_dec_and_test(&req->refs);
1195 static inline void req_ref_get(struct io_kiocb *req)
1197 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1198 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1199 atomic_inc(&req->refs);
1202 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1204 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1205 __io_submit_flush_completions(ctx);
1208 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1210 if (!(req->flags & REQ_F_REFCOUNT)) {
1211 req->flags |= REQ_F_REFCOUNT;
1212 atomic_set(&req->refs, nr);
1216 static inline void io_req_set_refcount(struct io_kiocb *req)
1218 __io_req_set_refcount(req, 1);
1221 #define IO_RSRC_REF_BATCH 100
1223 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1224 struct io_ring_ctx *ctx)
1225 __must_hold(&ctx->uring_lock)
1227 struct percpu_ref *ref = req->fixed_rsrc_refs;
1230 if (ref == &ctx->rsrc_node->refs)
1231 ctx->rsrc_cached_refs++;
1233 percpu_ref_put(ref);
1237 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1239 if (req->fixed_rsrc_refs)
1240 percpu_ref_put(req->fixed_rsrc_refs);
1243 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1244 __must_hold(&ctx->uring_lock)
1246 if (ctx->rsrc_cached_refs) {
1247 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1248 ctx->rsrc_cached_refs = 0;
1252 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1253 __must_hold(&ctx->uring_lock)
1255 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1256 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1259 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1260 struct io_ring_ctx *ctx)
1262 if (!req->fixed_rsrc_refs) {
1263 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1264 ctx->rsrc_cached_refs--;
1265 if (unlikely(ctx->rsrc_cached_refs < 0))
1266 io_rsrc_refs_refill(ctx);
1270 static unsigned int __io_put_kbuf(struct io_kiocb *req)
1272 struct io_buffer *kbuf = req->kbuf;
1273 unsigned int cflags;
1275 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1276 cflags |= IORING_CQE_F_BUFFER;
1277 req->flags &= ~REQ_F_BUFFER_SELECTED;
1283 static inline unsigned int io_put_kbuf(struct io_kiocb *req)
1285 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1287 return __io_put_kbuf(req);
1290 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1292 bool got = percpu_ref_tryget(ref);
1294 /* already at zero, wait for ->release() */
1296 wait_for_completion(compl);
1297 percpu_ref_resurrect(ref);
1299 percpu_ref_put(ref);
1302 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1304 __must_hold(&req->ctx->timeout_lock)
1306 struct io_kiocb *req;
1308 if (task && head->task != task)
1313 io_for_each_link(req, head) {
1314 if (req->flags & REQ_F_INFLIGHT)
1320 static bool io_match_linked(struct io_kiocb *head)
1322 struct io_kiocb *req;
1324 io_for_each_link(req, head) {
1325 if (req->flags & REQ_F_INFLIGHT)
1332 * As io_match_task() but protected against racing with linked timeouts.
1333 * User must not hold timeout_lock.
1335 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1340 if (task && head->task != task)
1345 if (head->flags & REQ_F_LINK_TIMEOUT) {
1346 struct io_ring_ctx *ctx = head->ctx;
1348 /* protect against races with linked timeouts */
1349 spin_lock_irq(&ctx->timeout_lock);
1350 matched = io_match_linked(head);
1351 spin_unlock_irq(&ctx->timeout_lock);
1353 matched = io_match_linked(head);
1358 static inline bool req_has_async_data(struct io_kiocb *req)
1360 return req->flags & REQ_F_ASYNC_DATA;
1363 static inline void req_set_fail(struct io_kiocb *req)
1365 req->flags |= REQ_F_FAIL;
1366 if (req->flags & REQ_F_CQE_SKIP) {
1367 req->flags &= ~REQ_F_CQE_SKIP;
1368 req->flags |= REQ_F_SKIP_LINK_CQES;
1372 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1378 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1380 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1382 complete(&ctx->ref_comp);
1385 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1387 return !req->timeout.off;
1390 static __cold void io_fallback_req_func(struct work_struct *work)
1392 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1393 fallback_work.work);
1394 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1395 struct io_kiocb *req, *tmp;
1396 bool locked = false;
1398 percpu_ref_get(&ctx->refs);
1399 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1400 req->io_task_work.func(req, &locked);
1403 io_submit_flush_completions(ctx);
1404 mutex_unlock(&ctx->uring_lock);
1406 percpu_ref_put(&ctx->refs);
1409 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1411 struct io_ring_ctx *ctx;
1414 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1419 * Use 5 bits less than the max cq entries, that should give us around
1420 * 32 entries per hash list if totally full and uniformly spread.
1422 hash_bits = ilog2(p->cq_entries);
1426 ctx->cancel_hash_bits = hash_bits;
1427 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1429 if (!ctx->cancel_hash)
1431 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1433 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1434 if (!ctx->dummy_ubuf)
1436 /* set invalid range, so io_import_fixed() fails meeting it */
1437 ctx->dummy_ubuf->ubuf = -1UL;
1439 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1440 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1443 ctx->flags = p->flags;
1444 init_waitqueue_head(&ctx->sqo_sq_wait);
1445 INIT_LIST_HEAD(&ctx->sqd_list);
1446 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1447 init_completion(&ctx->ref_comp);
1448 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1449 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1450 mutex_init(&ctx->uring_lock);
1451 init_waitqueue_head(&ctx->cq_wait);
1452 spin_lock_init(&ctx->completion_lock);
1453 spin_lock_init(&ctx->timeout_lock);
1454 INIT_WQ_LIST(&ctx->iopoll_list);
1455 INIT_LIST_HEAD(&ctx->defer_list);
1456 INIT_LIST_HEAD(&ctx->timeout_list);
1457 INIT_LIST_HEAD(&ctx->ltimeout_list);
1458 spin_lock_init(&ctx->rsrc_ref_lock);
1459 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1460 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1461 init_llist_head(&ctx->rsrc_put_llist);
1462 INIT_LIST_HEAD(&ctx->tctx_list);
1463 ctx->submit_state.free_list.next = NULL;
1464 INIT_WQ_LIST(&ctx->locked_free_list);
1465 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1466 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1469 kfree(ctx->dummy_ubuf);
1470 kfree(ctx->cancel_hash);
1475 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1477 struct io_rings *r = ctx->rings;
1479 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1483 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1485 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1486 struct io_ring_ctx *ctx = req->ctx;
1488 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1494 #define FFS_NOWAIT 0x1UL
1495 #define FFS_ISREG 0x2UL
1496 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1498 static inline bool io_req_ffs_set(struct io_kiocb *req)
1500 return req->flags & REQ_F_FIXED_FILE;
1503 static inline void io_req_track_inflight(struct io_kiocb *req)
1505 if (!(req->flags & REQ_F_INFLIGHT)) {
1506 req->flags |= REQ_F_INFLIGHT;
1507 atomic_inc(¤t->io_uring->inflight_tracked);
1511 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1513 if (WARN_ON_ONCE(!req->link))
1516 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1517 req->flags |= REQ_F_LINK_TIMEOUT;
1519 /* linked timeouts should have two refs once prep'ed */
1520 io_req_set_refcount(req);
1521 __io_req_set_refcount(req->link, 2);
1525 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1527 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1529 return __io_prep_linked_timeout(req);
1532 static void io_prep_async_work(struct io_kiocb *req)
1534 const struct io_op_def *def = &io_op_defs[req->opcode];
1535 struct io_ring_ctx *ctx = req->ctx;
1537 if (!(req->flags & REQ_F_CREDS)) {
1538 req->flags |= REQ_F_CREDS;
1539 req->creds = get_current_cred();
1542 req->work.list.next = NULL;
1543 req->work.flags = 0;
1544 if (req->flags & REQ_F_FORCE_ASYNC)
1545 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1547 if (req->flags & REQ_F_ISREG) {
1548 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1549 io_wq_hash_work(&req->work, file_inode(req->file));
1550 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1551 if (def->unbound_nonreg_file)
1552 req->work.flags |= IO_WQ_WORK_UNBOUND;
1555 switch (req->opcode) {
1556 case IORING_OP_SPLICE:
1558 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1559 req->work.flags |= IO_WQ_WORK_UNBOUND;
1564 static void io_prep_async_link(struct io_kiocb *req)
1566 struct io_kiocb *cur;
1568 if (req->flags & REQ_F_LINK_TIMEOUT) {
1569 struct io_ring_ctx *ctx = req->ctx;
1571 spin_lock_irq(&ctx->timeout_lock);
1572 io_for_each_link(cur, req)
1573 io_prep_async_work(cur);
1574 spin_unlock_irq(&ctx->timeout_lock);
1576 io_for_each_link(cur, req)
1577 io_prep_async_work(cur);
1581 static inline void io_req_add_compl_list(struct io_kiocb *req)
1583 struct io_ring_ctx *ctx = req->ctx;
1584 struct io_submit_state *state = &ctx->submit_state;
1586 if (!(req->flags & REQ_F_CQE_SKIP))
1587 ctx->submit_state.flush_cqes = true;
1588 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1591 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1593 struct io_ring_ctx *ctx = req->ctx;
1594 struct io_kiocb *link = io_prep_linked_timeout(req);
1595 struct io_uring_task *tctx = req->task->io_uring;
1598 BUG_ON(!tctx->io_wq);
1600 /* init ->work of the whole link before punting */
1601 io_prep_async_link(req);
1604 * Not expected to happen, but if we do have a bug where this _can_
1605 * happen, catch it here and ensure the request is marked as
1606 * canceled. That will make io-wq go through the usual work cancel
1607 * procedure rather than attempt to run this request (or create a new
1610 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1611 req->work.flags |= IO_WQ_WORK_CANCEL;
1613 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1614 &req->work, req->flags);
1615 io_wq_enqueue(tctx->io_wq, &req->work);
1617 io_queue_linked_timeout(link);
1620 static void io_kill_timeout(struct io_kiocb *req, int status)
1621 __must_hold(&req->ctx->completion_lock)
1622 __must_hold(&req->ctx->timeout_lock)
1624 struct io_timeout_data *io = req->async_data;
1626 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1629 atomic_set(&req->ctx->cq_timeouts,
1630 atomic_read(&req->ctx->cq_timeouts) + 1);
1631 list_del_init(&req->timeout.list);
1632 io_fill_cqe_req(req, status, 0);
1633 io_put_req_deferred(req);
1637 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1639 while (!list_empty(&ctx->defer_list)) {
1640 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1641 struct io_defer_entry, list);
1643 if (req_need_defer(de->req, de->seq))
1645 list_del_init(&de->list);
1646 io_req_task_queue(de->req);
1651 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1652 __must_hold(&ctx->completion_lock)
1654 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1656 spin_lock_irq(&ctx->timeout_lock);
1657 while (!list_empty(&ctx->timeout_list)) {
1658 u32 events_needed, events_got;
1659 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1660 struct io_kiocb, timeout.list);
1662 if (io_is_timeout_noseq(req))
1666 * Since seq can easily wrap around over time, subtract
1667 * the last seq at which timeouts were flushed before comparing.
1668 * Assuming not more than 2^31-1 events have happened since,
1669 * these subtractions won't have wrapped, so we can check if
1670 * target is in [last_seq, current_seq] by comparing the two.
1672 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1673 events_got = seq - ctx->cq_last_tm_flush;
1674 if (events_got < events_needed)
1677 list_del_init(&req->timeout.list);
1678 io_kill_timeout(req, 0);
1680 ctx->cq_last_tm_flush = seq;
1681 spin_unlock_irq(&ctx->timeout_lock);
1684 static __cold void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1686 if (ctx->off_timeout_used)
1687 io_flush_timeouts(ctx);
1688 if (ctx->drain_active)
1689 io_queue_deferred(ctx);
1692 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1694 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1695 __io_commit_cqring_flush(ctx);
1696 /* order cqe stores with ring update */
1697 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1700 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1702 struct io_rings *r = ctx->rings;
1704 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1707 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1709 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1712 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1714 struct io_rings *rings = ctx->rings;
1715 unsigned tail, mask = ctx->cq_entries - 1;
1718 * writes to the cq entry need to come after reading head; the
1719 * control dependency is enough as we're using WRITE_ONCE to
1722 if (__io_cqring_events(ctx) == ctx->cq_entries)
1725 tail = ctx->cached_cq_tail++;
1726 return &rings->cqes[tail & mask];
1729 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1731 if (likely(!ctx->cq_ev_fd))
1733 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1735 return !ctx->eventfd_async || io_wq_current_is_worker();
1739 * This should only get called when at least one event has been posted.
1740 * Some applications rely on the eventfd notification count only changing
1741 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1742 * 1:1 relationship between how many times this function is called (and
1743 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1745 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1748 * wake_up_all() may seem excessive, but io_wake_function() and
1749 * io_should_wake() handle the termination of the loop and only
1750 * wake as many waiters as we need to.
1752 if (wq_has_sleeper(&ctx->cq_wait))
1753 wake_up_all(&ctx->cq_wait);
1754 if (io_should_trigger_evfd(ctx))
1755 eventfd_signal(ctx->cq_ev_fd, 1);
1758 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1760 /* see waitqueue_active() comment */
1763 if (ctx->flags & IORING_SETUP_SQPOLL) {
1764 if (waitqueue_active(&ctx->cq_wait))
1765 wake_up_all(&ctx->cq_wait);
1767 if (io_should_trigger_evfd(ctx))
1768 eventfd_signal(ctx->cq_ev_fd, 1);
1771 /* Returns true if there are no backlogged entries after the flush */
1772 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1774 bool all_flushed, posted;
1776 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1780 spin_lock(&ctx->completion_lock);
1781 while (!list_empty(&ctx->cq_overflow_list)) {
1782 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1783 struct io_overflow_cqe *ocqe;
1787 ocqe = list_first_entry(&ctx->cq_overflow_list,
1788 struct io_overflow_cqe, list);
1790 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1792 io_account_cq_overflow(ctx);
1795 list_del(&ocqe->list);
1799 all_flushed = list_empty(&ctx->cq_overflow_list);
1801 clear_bit(0, &ctx->check_cq_overflow);
1802 WRITE_ONCE(ctx->rings->sq_flags,
1803 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1807 io_commit_cqring(ctx);
1808 spin_unlock(&ctx->completion_lock);
1810 io_cqring_ev_posted(ctx);
1814 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1818 if (test_bit(0, &ctx->check_cq_overflow)) {
1819 /* iopoll syncs against uring_lock, not completion_lock */
1820 if (ctx->flags & IORING_SETUP_IOPOLL)
1821 mutex_lock(&ctx->uring_lock);
1822 ret = __io_cqring_overflow_flush(ctx, false);
1823 if (ctx->flags & IORING_SETUP_IOPOLL)
1824 mutex_unlock(&ctx->uring_lock);
1830 /* must to be called somewhat shortly after putting a request */
1831 static inline void io_put_task(struct task_struct *task, int nr)
1833 struct io_uring_task *tctx = task->io_uring;
1835 if (likely(task == current)) {
1836 tctx->cached_refs += nr;
1838 percpu_counter_sub(&tctx->inflight, nr);
1839 if (unlikely(atomic_read(&tctx->in_idle)))
1840 wake_up(&tctx->wait);
1841 put_task_struct_many(task, nr);
1845 static void io_task_refs_refill(struct io_uring_task *tctx)
1847 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1849 percpu_counter_add(&tctx->inflight, refill);
1850 refcount_add(refill, ¤t->usage);
1851 tctx->cached_refs += refill;
1854 static inline void io_get_task_refs(int nr)
1856 struct io_uring_task *tctx = current->io_uring;
1858 tctx->cached_refs -= nr;
1859 if (unlikely(tctx->cached_refs < 0))
1860 io_task_refs_refill(tctx);
1863 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1865 struct io_uring_task *tctx = task->io_uring;
1866 unsigned int refs = tctx->cached_refs;
1869 tctx->cached_refs = 0;
1870 percpu_counter_sub(&tctx->inflight, refs);
1871 put_task_struct_many(task, refs);
1875 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1876 s32 res, u32 cflags)
1878 struct io_overflow_cqe *ocqe;
1880 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1883 * If we're in ring overflow flush mode, or in task cancel mode,
1884 * or cannot allocate an overflow entry, then we need to drop it
1887 io_account_cq_overflow(ctx);
1890 if (list_empty(&ctx->cq_overflow_list)) {
1891 set_bit(0, &ctx->check_cq_overflow);
1892 WRITE_ONCE(ctx->rings->sq_flags,
1893 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1896 ocqe->cqe.user_data = user_data;
1897 ocqe->cqe.res = res;
1898 ocqe->cqe.flags = cflags;
1899 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1903 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
1904 s32 res, u32 cflags)
1906 struct io_uring_cqe *cqe;
1908 trace_io_uring_complete(ctx, user_data, res, cflags);
1911 * If we can't get a cq entry, userspace overflowed the
1912 * submission (by quite a lot). Increment the overflow count in
1915 cqe = io_get_cqe(ctx);
1917 WRITE_ONCE(cqe->user_data, user_data);
1918 WRITE_ONCE(cqe->res, res);
1919 WRITE_ONCE(cqe->flags, cflags);
1922 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1925 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
1927 if (!(req->flags & REQ_F_CQE_SKIP))
1928 __io_fill_cqe(req->ctx, req->user_data, res, cflags);
1931 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1932 s32 res, u32 cflags)
1935 return __io_fill_cqe(ctx, user_data, res, cflags);
1938 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
1941 struct io_ring_ctx *ctx = req->ctx;
1943 if (!(req->flags & REQ_F_CQE_SKIP))
1944 __io_fill_cqe(ctx, req->user_data, res, cflags);
1946 * If we're the last reference to this request, add to our locked
1949 if (req_ref_put_and_test(req)) {
1950 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1951 if (req->flags & IO_DISARM_MASK)
1952 io_disarm_next(req);
1954 io_req_task_queue(req->link);
1958 io_req_put_rsrc(req, ctx);
1959 io_dismantle_req(req);
1960 io_put_task(req->task, 1);
1961 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1962 ctx->locked_free_nr++;
1966 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1969 struct io_ring_ctx *ctx = req->ctx;
1971 spin_lock(&ctx->completion_lock);
1972 __io_req_complete_post(req, res, cflags);
1973 io_commit_cqring(ctx);
1974 spin_unlock(&ctx->completion_lock);
1975 io_cqring_ev_posted(ctx);
1978 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1982 req->cflags = cflags;
1983 req->flags |= REQ_F_COMPLETE_INLINE;
1986 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1987 s32 res, u32 cflags)
1989 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1990 io_req_complete_state(req, res, cflags);
1992 io_req_complete_post(req, res, cflags);
1995 static inline void io_req_complete(struct io_kiocb *req, s32 res)
1997 __io_req_complete(req, 0, res, 0);
2000 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2003 io_req_complete_post(req, res, 0);
2006 static void io_req_complete_fail_submit(struct io_kiocb *req)
2009 * We don't submit, fail them all, for that replace hardlinks with
2010 * normal links. Extra REQ_F_LINK is tolerated.
2012 req->flags &= ~REQ_F_HARDLINK;
2013 req->flags |= REQ_F_LINK;
2014 io_req_complete_failed(req, req->result);
2018 * Don't initialise the fields below on every allocation, but do that in
2019 * advance and keep them valid across allocations.
2021 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2025 req->async_data = NULL;
2026 /* not necessary, but safer to zero */
2030 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2031 struct io_submit_state *state)
2033 spin_lock(&ctx->completion_lock);
2034 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2035 ctx->locked_free_nr = 0;
2036 spin_unlock(&ctx->completion_lock);
2039 /* Returns true IFF there are requests in the cache */
2040 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2042 struct io_submit_state *state = &ctx->submit_state;
2045 * If we have more than a batch's worth of requests in our IRQ side
2046 * locked cache, grab the lock and move them over to our submission
2049 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2050 io_flush_cached_locked_reqs(ctx, state);
2051 return !!state->free_list.next;
2055 * A request might get retired back into the request caches even before opcode
2056 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2057 * Because of that, io_alloc_req() should be called only under ->uring_lock
2058 * and with extra caution to not get a request that is still worked on.
2060 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2061 __must_hold(&ctx->uring_lock)
2063 struct io_submit_state *state = &ctx->submit_state;
2064 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2065 void *reqs[IO_REQ_ALLOC_BATCH];
2066 struct io_kiocb *req;
2069 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2072 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2075 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2076 * retry single alloc to be on the safe side.
2078 if (unlikely(ret <= 0)) {
2079 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2085 percpu_ref_get_many(&ctx->refs, ret);
2086 for (i = 0; i < ret; i++) {
2089 io_preinit_req(req, ctx);
2090 wq_stack_add_head(&req->comp_list, &state->free_list);
2095 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2097 if (unlikely(!ctx->submit_state.free_list.next))
2098 return __io_alloc_req_refill(ctx);
2102 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2104 struct io_wq_work_node *node;
2106 node = wq_stack_extract(&ctx->submit_state.free_list);
2107 return container_of(node, struct io_kiocb, comp_list);
2110 static inline void io_put_file(struct file *file)
2116 static inline void io_dismantle_req(struct io_kiocb *req)
2118 unsigned int flags = req->flags;
2120 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2122 if (!(flags & REQ_F_FIXED_FILE))
2123 io_put_file(req->file);
2126 static __cold void __io_free_req(struct io_kiocb *req)
2128 struct io_ring_ctx *ctx = req->ctx;
2130 io_req_put_rsrc(req, ctx);
2131 io_dismantle_req(req);
2132 io_put_task(req->task, 1);
2134 spin_lock(&ctx->completion_lock);
2135 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2136 ctx->locked_free_nr++;
2137 spin_unlock(&ctx->completion_lock);
2140 static inline void io_remove_next_linked(struct io_kiocb *req)
2142 struct io_kiocb *nxt = req->link;
2144 req->link = nxt->link;
2148 static bool io_kill_linked_timeout(struct io_kiocb *req)
2149 __must_hold(&req->ctx->completion_lock)
2150 __must_hold(&req->ctx->timeout_lock)
2152 struct io_kiocb *link = req->link;
2154 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2155 struct io_timeout_data *io = link->async_data;
2157 io_remove_next_linked(req);
2158 link->timeout.head = NULL;
2159 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2160 list_del(&link->timeout.list);
2161 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2162 io_fill_cqe_req(link, -ECANCELED, 0);
2163 io_put_req_deferred(link);
2170 static void io_fail_links(struct io_kiocb *req)
2171 __must_hold(&req->ctx->completion_lock)
2173 struct io_kiocb *nxt, *link = req->link;
2174 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2178 long res = -ECANCELED;
2180 if (link->flags & REQ_F_FAIL)
2186 trace_io_uring_fail_link(req, link);
2188 link->flags &= ~REQ_F_CQE_SKIP;
2189 io_fill_cqe_req(link, res, 0);
2191 io_put_req_deferred(link);
2196 static bool io_disarm_next(struct io_kiocb *req)
2197 __must_hold(&req->ctx->completion_lock)
2199 bool posted = false;
2201 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2202 struct io_kiocb *link = req->link;
2204 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2205 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2206 io_remove_next_linked(req);
2207 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2208 io_fill_cqe_req(link, -ECANCELED, 0);
2209 io_put_req_deferred(link);
2212 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2213 struct io_ring_ctx *ctx = req->ctx;
2215 spin_lock_irq(&ctx->timeout_lock);
2216 posted = io_kill_linked_timeout(req);
2217 spin_unlock_irq(&ctx->timeout_lock);
2219 if (unlikely((req->flags & REQ_F_FAIL) &&
2220 !(req->flags & REQ_F_HARDLINK))) {
2221 posted |= (req->link != NULL);
2227 static void __io_req_find_next_prep(struct io_kiocb *req)
2229 struct io_ring_ctx *ctx = req->ctx;
2232 spin_lock(&ctx->completion_lock);
2233 posted = io_disarm_next(req);
2235 io_commit_cqring(ctx);
2236 spin_unlock(&ctx->completion_lock);
2238 io_cqring_ev_posted(ctx);
2241 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2243 struct io_kiocb *nxt;
2245 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2248 * If LINK is set, we have dependent requests in this chain. If we
2249 * didn't fail this request, queue the first one up, moving any other
2250 * dependencies to the next request. In case of failure, fail the rest
2253 if (unlikely(req->flags & IO_DISARM_MASK))
2254 __io_req_find_next_prep(req);
2260 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2265 io_submit_flush_completions(ctx);
2266 mutex_unlock(&ctx->uring_lock);
2269 percpu_ref_put(&ctx->refs);
2272 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2274 io_commit_cqring(ctx);
2275 spin_unlock(&ctx->completion_lock);
2276 io_cqring_ev_posted(ctx);
2279 static void handle_prev_tw_list(struct io_wq_work_node *node,
2280 struct io_ring_ctx **ctx, bool *uring_locked)
2282 if (*ctx && !*uring_locked)
2283 spin_lock(&(*ctx)->completion_lock);
2286 struct io_wq_work_node *next = node->next;
2287 struct io_kiocb *req = container_of(node, struct io_kiocb,
2290 if (req->ctx != *ctx) {
2291 if (unlikely(!*uring_locked && *ctx))
2292 ctx_commit_and_unlock(*ctx);
2294 ctx_flush_and_put(*ctx, uring_locked);
2296 /* if not contended, grab and improve batching */
2297 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2298 percpu_ref_get(&(*ctx)->refs);
2299 if (unlikely(!*uring_locked))
2300 spin_lock(&(*ctx)->completion_lock);
2302 if (likely(*uring_locked))
2303 req->io_task_work.func(req, uring_locked);
2305 __io_req_complete_post(req, req->result, io_put_kbuf(req));
2309 if (unlikely(!*uring_locked))
2310 ctx_commit_and_unlock(*ctx);
2313 static void handle_tw_list(struct io_wq_work_node *node,
2314 struct io_ring_ctx **ctx, bool *locked)
2317 struct io_wq_work_node *next = node->next;
2318 struct io_kiocb *req = container_of(node, struct io_kiocb,
2321 if (req->ctx != *ctx) {
2322 ctx_flush_and_put(*ctx, locked);
2324 /* if not contended, grab and improve batching */
2325 *locked = mutex_trylock(&(*ctx)->uring_lock);
2326 percpu_ref_get(&(*ctx)->refs);
2328 req->io_task_work.func(req, locked);
2333 static void tctx_task_work(struct callback_head *cb)
2335 bool uring_locked = false;
2336 struct io_ring_ctx *ctx = NULL;
2337 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2341 struct io_wq_work_node *node1, *node2;
2343 if (!tctx->task_list.first &&
2344 !tctx->prior_task_list.first && uring_locked)
2345 io_submit_flush_completions(ctx);
2347 spin_lock_irq(&tctx->task_lock);
2348 node1 = tctx->prior_task_list.first;
2349 node2 = tctx->task_list.first;
2350 INIT_WQ_LIST(&tctx->task_list);
2351 INIT_WQ_LIST(&tctx->prior_task_list);
2352 if (!node2 && !node1)
2353 tctx->task_running = false;
2354 spin_unlock_irq(&tctx->task_lock);
2355 if (!node2 && !node1)
2359 handle_prev_tw_list(node1, &ctx, &uring_locked);
2362 handle_tw_list(node2, &ctx, &uring_locked);
2366 ctx_flush_and_put(ctx, &uring_locked);
2368 /* relaxed read is enough as only the task itself sets ->in_idle */
2369 if (unlikely(atomic_read(&tctx->in_idle)))
2370 io_uring_drop_tctx_refs(current);
2373 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2375 struct task_struct *tsk = req->task;
2376 struct io_uring_task *tctx = tsk->io_uring;
2377 enum task_work_notify_mode notify;
2378 struct io_wq_work_node *node;
2379 unsigned long flags;
2382 WARN_ON_ONCE(!tctx);
2384 spin_lock_irqsave(&tctx->task_lock, flags);
2386 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2388 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2389 running = tctx->task_running;
2391 tctx->task_running = true;
2392 spin_unlock_irqrestore(&tctx->task_lock, flags);
2394 /* task_work already pending, we're done */
2399 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2400 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2401 * processing task_work. There's no reliable way to tell if TWA_RESUME
2404 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2405 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2406 if (notify == TWA_NONE)
2407 wake_up_process(tsk);
2411 spin_lock_irqsave(&tctx->task_lock, flags);
2412 tctx->task_running = false;
2413 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2414 spin_unlock_irqrestore(&tctx->task_lock, flags);
2417 req = container_of(node, struct io_kiocb, io_task_work.node);
2419 if (llist_add(&req->io_task_work.fallback_node,
2420 &req->ctx->fallback_llist))
2421 schedule_delayed_work(&req->ctx->fallback_work, 1);
2425 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2427 struct io_ring_ctx *ctx = req->ctx;
2429 /* not needed for normal modes, but SQPOLL depends on it */
2430 io_tw_lock(ctx, locked);
2431 io_req_complete_failed(req, req->result);
2434 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2436 struct io_ring_ctx *ctx = req->ctx;
2438 io_tw_lock(ctx, locked);
2439 /* req->task == current here, checking PF_EXITING is safe */
2440 if (likely(!(req->task->flags & PF_EXITING)))
2441 __io_queue_sqe(req);
2443 io_req_complete_failed(req, -EFAULT);
2446 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2449 req->io_task_work.func = io_req_task_cancel;
2450 io_req_task_work_add(req, false);
2453 static void io_req_task_queue(struct io_kiocb *req)
2455 req->io_task_work.func = io_req_task_submit;
2456 io_req_task_work_add(req, false);
2459 static void io_req_task_queue_reissue(struct io_kiocb *req)
2461 req->io_task_work.func = io_queue_async_work;
2462 io_req_task_work_add(req, false);
2465 static inline void io_queue_next(struct io_kiocb *req)
2467 struct io_kiocb *nxt = io_req_find_next(req);
2470 io_req_task_queue(nxt);
2473 static void io_free_req(struct io_kiocb *req)
2479 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2484 static void io_free_batch_list(struct io_ring_ctx *ctx,
2485 struct io_wq_work_node *node)
2486 __must_hold(&ctx->uring_lock)
2488 struct task_struct *task = NULL;
2492 struct io_kiocb *req = container_of(node, struct io_kiocb,
2495 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2496 node = req->comp_list.next;
2497 if (!req_ref_put_and_test(req))
2501 io_req_put_rsrc_locked(req, ctx);
2503 io_dismantle_req(req);
2505 if (req->task != task) {
2507 io_put_task(task, task_refs);
2512 node = req->comp_list.next;
2513 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2517 io_put_task(task, task_refs);
2520 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2521 __must_hold(&ctx->uring_lock)
2523 struct io_wq_work_node *node, *prev;
2524 struct io_submit_state *state = &ctx->submit_state;
2526 if (state->flush_cqes) {
2527 spin_lock(&ctx->completion_lock);
2528 wq_list_for_each(node, prev, &state->compl_reqs) {
2529 struct io_kiocb *req = container_of(node, struct io_kiocb,
2532 if (!(req->flags & REQ_F_CQE_SKIP))
2533 __io_fill_cqe(ctx, req->user_data, req->result,
2537 io_commit_cqring(ctx);
2538 spin_unlock(&ctx->completion_lock);
2539 io_cqring_ev_posted(ctx);
2540 state->flush_cqes = false;
2543 io_free_batch_list(ctx, state->compl_reqs.first);
2544 INIT_WQ_LIST(&state->compl_reqs);
2548 * Drop reference to request, return next in chain (if there is one) if this
2549 * was the last reference to this request.
2551 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2553 struct io_kiocb *nxt = NULL;
2555 if (req_ref_put_and_test(req)) {
2556 nxt = io_req_find_next(req);
2562 static inline void io_put_req(struct io_kiocb *req)
2564 if (req_ref_put_and_test(req))
2568 static inline void io_put_req_deferred(struct io_kiocb *req)
2570 if (req_ref_put_and_test(req)) {
2571 req->io_task_work.func = io_free_req_work;
2572 io_req_task_work_add(req, false);
2576 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2578 /* See comment at the top of this file */
2580 return __io_cqring_events(ctx);
2583 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2585 struct io_rings *rings = ctx->rings;
2587 /* make sure SQ entry isn't read before tail */
2588 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2591 static inline bool io_run_task_work(void)
2593 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2594 __set_current_state(TASK_RUNNING);
2595 tracehook_notify_signal();
2602 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2604 struct io_wq_work_node *pos, *start, *prev;
2605 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2606 DEFINE_IO_COMP_BATCH(iob);
2610 * Only spin for completions if we don't have multiple devices hanging
2611 * off our complete list.
2613 if (ctx->poll_multi_queue || force_nonspin)
2614 poll_flags |= BLK_POLL_ONESHOT;
2616 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2617 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2618 struct kiocb *kiocb = &req->rw.kiocb;
2622 * Move completed and retryable entries to our local lists.
2623 * If we find a request that requires polling, break out
2624 * and complete those lists first, if we have entries there.
2626 if (READ_ONCE(req->iopoll_completed))
2629 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2630 if (unlikely(ret < 0))
2633 poll_flags |= BLK_POLL_ONESHOT;
2635 /* iopoll may have completed current req */
2636 if (!rq_list_empty(iob.req_list) ||
2637 READ_ONCE(req->iopoll_completed))
2641 if (!rq_list_empty(iob.req_list))
2647 wq_list_for_each_resume(pos, prev) {
2648 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2650 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2651 if (!smp_load_acquire(&req->iopoll_completed))
2653 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2656 __io_fill_cqe(ctx, req->user_data, req->result, io_put_kbuf(req));
2660 if (unlikely(!nr_events))
2663 io_commit_cqring(ctx);
2664 io_cqring_ev_posted_iopoll(ctx);
2665 pos = start ? start->next : ctx->iopoll_list.first;
2666 wq_list_cut(&ctx->iopoll_list, prev, start);
2667 io_free_batch_list(ctx, pos);
2672 * We can't just wait for polled events to come to us, we have to actively
2673 * find and complete them.
2675 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2677 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2680 mutex_lock(&ctx->uring_lock);
2681 while (!wq_list_empty(&ctx->iopoll_list)) {
2682 /* let it sleep and repeat later if can't complete a request */
2683 if (io_do_iopoll(ctx, true) == 0)
2686 * Ensure we allow local-to-the-cpu processing to take place,
2687 * in this case we need to ensure that we reap all events.
2688 * Also let task_work, etc. to progress by releasing the mutex
2690 if (need_resched()) {
2691 mutex_unlock(&ctx->uring_lock);
2693 mutex_lock(&ctx->uring_lock);
2696 mutex_unlock(&ctx->uring_lock);
2699 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2701 unsigned int nr_events = 0;
2705 * We disallow the app entering submit/complete with polling, but we
2706 * still need to lock the ring to prevent racing with polled issue
2707 * that got punted to a workqueue.
2709 mutex_lock(&ctx->uring_lock);
2711 * Don't enter poll loop if we already have events pending.
2712 * If we do, we can potentially be spinning for commands that
2713 * already triggered a CQE (eg in error).
2715 if (test_bit(0, &ctx->check_cq_overflow))
2716 __io_cqring_overflow_flush(ctx, false);
2717 if (io_cqring_events(ctx))
2721 * If a submit got punted to a workqueue, we can have the
2722 * application entering polling for a command before it gets
2723 * issued. That app will hold the uring_lock for the duration
2724 * of the poll right here, so we need to take a breather every
2725 * now and then to ensure that the issue has a chance to add
2726 * the poll to the issued list. Otherwise we can spin here
2727 * forever, while the workqueue is stuck trying to acquire the
2730 if (wq_list_empty(&ctx->iopoll_list)) {
2731 u32 tail = ctx->cached_cq_tail;
2733 mutex_unlock(&ctx->uring_lock);
2735 mutex_lock(&ctx->uring_lock);
2737 /* some requests don't go through iopoll_list */
2738 if (tail != ctx->cached_cq_tail ||
2739 wq_list_empty(&ctx->iopoll_list))
2742 ret = io_do_iopoll(ctx, !min);
2747 } while (nr_events < min && !need_resched());
2749 mutex_unlock(&ctx->uring_lock);
2753 static void kiocb_end_write(struct io_kiocb *req)
2756 * Tell lockdep we inherited freeze protection from submission
2759 if (req->flags & REQ_F_ISREG) {
2760 struct super_block *sb = file_inode(req->file)->i_sb;
2762 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2768 static bool io_resubmit_prep(struct io_kiocb *req)
2770 struct io_async_rw *rw = req->async_data;
2772 if (!req_has_async_data(req))
2773 return !io_req_prep_async(req);
2774 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2778 static bool io_rw_should_reissue(struct io_kiocb *req)
2780 umode_t mode = file_inode(req->file)->i_mode;
2781 struct io_ring_ctx *ctx = req->ctx;
2783 if (!S_ISBLK(mode) && !S_ISREG(mode))
2785 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2786 !(ctx->flags & IORING_SETUP_IOPOLL)))
2789 * If ref is dying, we might be running poll reap from the exit work.
2790 * Don't attempt to reissue from that path, just let it fail with
2793 if (percpu_ref_is_dying(&ctx->refs))
2796 * Play it safe and assume not safe to re-import and reissue if we're
2797 * not in the original thread group (or in task context).
2799 if (!same_thread_group(req->task, current) || !in_task())
2804 static bool io_resubmit_prep(struct io_kiocb *req)
2808 static bool io_rw_should_reissue(struct io_kiocb *req)
2814 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2816 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2817 kiocb_end_write(req);
2818 if (unlikely(res != req->result)) {
2819 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2820 io_rw_should_reissue(req)) {
2821 req->flags |= REQ_F_REISSUE;
2830 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2832 unsigned int cflags = io_put_kbuf(req);
2833 int res = req->result;
2836 io_req_complete_state(req, res, cflags);
2837 io_req_add_compl_list(req);
2839 io_req_complete_post(req, res, cflags);
2843 static void __io_complete_rw(struct io_kiocb *req, long res,
2844 unsigned int issue_flags)
2846 if (__io_complete_rw_common(req, res))
2848 __io_req_complete(req, issue_flags, req->result, io_put_kbuf(req));
2851 static void io_complete_rw(struct kiocb *kiocb, long res)
2853 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2855 if (__io_complete_rw_common(req, res))
2858 req->io_task_work.func = io_req_task_complete;
2859 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
2862 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
2864 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2866 if (kiocb->ki_flags & IOCB_WRITE)
2867 kiocb_end_write(req);
2868 if (unlikely(res != req->result)) {
2869 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2870 req->flags |= REQ_F_REISSUE;
2876 /* order with io_iopoll_complete() checking ->iopoll_completed */
2877 smp_store_release(&req->iopoll_completed, 1);
2881 * After the iocb has been issued, it's safe to be found on the poll list.
2882 * Adding the kiocb to the list AFTER submission ensures that we don't
2883 * find it from a io_do_iopoll() thread before the issuer is done
2884 * accessing the kiocb cookie.
2886 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2888 struct io_ring_ctx *ctx = req->ctx;
2889 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2891 /* workqueue context doesn't hold uring_lock, grab it now */
2892 if (unlikely(needs_lock))
2893 mutex_lock(&ctx->uring_lock);
2896 * Track whether we have multiple files in our lists. This will impact
2897 * how we do polling eventually, not spinning if we're on potentially
2898 * different devices.
2900 if (wq_list_empty(&ctx->iopoll_list)) {
2901 ctx->poll_multi_queue = false;
2902 } else if (!ctx->poll_multi_queue) {
2903 struct io_kiocb *list_req;
2905 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2907 if (list_req->file != req->file)
2908 ctx->poll_multi_queue = true;
2912 * For fast devices, IO may have already completed. If it has, add
2913 * it to the front so we find it first.
2915 if (READ_ONCE(req->iopoll_completed))
2916 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2918 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2920 if (unlikely(needs_lock)) {
2922 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2923 * in sq thread task context or in io worker task context. If
2924 * current task context is sq thread, we don't need to check
2925 * whether should wake up sq thread.
2927 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2928 wq_has_sleeper(&ctx->sq_data->wait))
2929 wake_up(&ctx->sq_data->wait);
2931 mutex_unlock(&ctx->uring_lock);
2935 static bool io_bdev_nowait(struct block_device *bdev)
2937 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2941 * If we tracked the file through the SCM inflight mechanism, we could support
2942 * any file. For now, just ensure that anything potentially problematic is done
2945 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2947 if (S_ISBLK(mode)) {
2948 if (IS_ENABLED(CONFIG_BLOCK) &&
2949 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2955 if (S_ISREG(mode)) {
2956 if (IS_ENABLED(CONFIG_BLOCK) &&
2957 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2958 file->f_op != &io_uring_fops)
2963 /* any ->read/write should understand O_NONBLOCK */
2964 if (file->f_flags & O_NONBLOCK)
2966 return file->f_mode & FMODE_NOWAIT;
2970 * If we tracked the file through the SCM inflight mechanism, we could support
2971 * any file. For now, just ensure that anything potentially problematic is done
2974 static unsigned int io_file_get_flags(struct file *file)
2976 umode_t mode = file_inode(file)->i_mode;
2977 unsigned int res = 0;
2981 if (__io_file_supports_nowait(file, mode))
2986 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2988 return req->flags & REQ_F_SUPPORT_NOWAIT;
2991 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2993 struct io_ring_ctx *ctx = req->ctx;
2994 struct kiocb *kiocb = &req->rw.kiocb;
2995 struct file *file = req->file;
2999 if (!io_req_ffs_set(req))
3000 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3002 kiocb->ki_pos = READ_ONCE(sqe->off);
3003 if (kiocb->ki_pos == -1) {
3004 if (!(file->f_mode & FMODE_STREAM)) {
3005 req->flags |= REQ_F_CUR_POS;
3006 kiocb->ki_pos = file->f_pos;
3011 kiocb->ki_flags = iocb_flags(file);
3012 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3017 * If the file is marked O_NONBLOCK, still allow retry for it if it
3018 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3019 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3021 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3022 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3023 req->flags |= REQ_F_NOWAIT;
3025 if (ctx->flags & IORING_SETUP_IOPOLL) {
3026 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3029 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3030 kiocb->ki_complete = io_complete_rw_iopoll;
3031 req->iopoll_completed = 0;
3033 if (kiocb->ki_flags & IOCB_HIPRI)
3035 kiocb->ki_complete = io_complete_rw;
3038 ioprio = READ_ONCE(sqe->ioprio);
3040 ret = ioprio_check_cap(ioprio);
3044 kiocb->ki_ioprio = ioprio;
3046 kiocb->ki_ioprio = get_current_ioprio();
3050 req->rw.addr = READ_ONCE(sqe->addr);
3051 req->rw.len = READ_ONCE(sqe->len);
3052 req->buf_index = READ_ONCE(sqe->buf_index);
3056 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3062 case -ERESTARTNOINTR:
3063 case -ERESTARTNOHAND:
3064 case -ERESTART_RESTARTBLOCK:
3066 * We can't just restart the syscall, since previously
3067 * submitted sqes may already be in progress. Just fail this
3073 kiocb->ki_complete(kiocb, ret);
3077 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3078 unsigned int issue_flags)
3080 struct io_async_rw *io = req->async_data;
3082 /* add previously done IO, if any */
3083 if (req_has_async_data(req) && io->bytes_done > 0) {
3085 ret = io->bytes_done;
3087 ret += io->bytes_done;
3090 if (req->flags & REQ_F_CUR_POS)
3091 req->file->f_pos = req->rw.kiocb.ki_pos;
3092 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3093 __io_complete_rw(req, ret, issue_flags);
3095 io_rw_done(&req->rw.kiocb, ret);
3097 if (req->flags & REQ_F_REISSUE) {
3098 req->flags &= ~REQ_F_REISSUE;
3099 if (io_resubmit_prep(req)) {
3100 io_req_task_queue_reissue(req);
3104 req->io_task_work.func = io_req_task_complete;
3105 io_req_task_work_add(req, false);
3110 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3111 struct io_mapped_ubuf *imu)
3113 size_t len = req->rw.len;
3114 u64 buf_end, buf_addr = req->rw.addr;
3117 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3119 /* not inside the mapped region */
3120 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3124 * May not be a start of buffer, set size appropriately
3125 * and advance us to the beginning.
3127 offset = buf_addr - imu->ubuf;
3128 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3132 * Don't use iov_iter_advance() here, as it's really slow for
3133 * using the latter parts of a big fixed buffer - it iterates
3134 * over each segment manually. We can cheat a bit here, because
3137 * 1) it's a BVEC iter, we set it up
3138 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3139 * first and last bvec
3141 * So just find our index, and adjust the iterator afterwards.
3142 * If the offset is within the first bvec (or the whole first
3143 * bvec, just use iov_iter_advance(). This makes it easier
3144 * since we can just skip the first segment, which may not
3145 * be PAGE_SIZE aligned.
3147 const struct bio_vec *bvec = imu->bvec;
3149 if (offset <= bvec->bv_len) {
3150 iov_iter_advance(iter, offset);
3152 unsigned long seg_skip;
3154 /* skip first vec */
3155 offset -= bvec->bv_len;
3156 seg_skip = 1 + (offset >> PAGE_SHIFT);
3158 iter->bvec = bvec + seg_skip;
3159 iter->nr_segs -= seg_skip;
3160 iter->count -= bvec->bv_len + offset;
3161 iter->iov_offset = offset & ~PAGE_MASK;
3168 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3170 struct io_mapped_ubuf *imu = req->imu;
3171 u16 index, buf_index = req->buf_index;
3174 struct io_ring_ctx *ctx = req->ctx;
3176 if (unlikely(buf_index >= ctx->nr_user_bufs))
3178 io_req_set_rsrc_node(req, ctx);
3179 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3180 imu = READ_ONCE(ctx->user_bufs[index]);
3183 return __io_import_fixed(req, rw, iter, imu);
3186 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3189 mutex_unlock(&ctx->uring_lock);
3192 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3195 * "Normal" inline submissions always hold the uring_lock, since we
3196 * grab it from the system call. Same is true for the SQPOLL offload.
3197 * The only exception is when we've detached the request and issue it
3198 * from an async worker thread, grab the lock for that case.
3201 mutex_lock(&ctx->uring_lock);
3204 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3205 int bgid, unsigned int issue_flags)
3207 struct io_buffer *kbuf = req->kbuf;
3208 struct io_buffer *head;
3209 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3211 if (req->flags & REQ_F_BUFFER_SELECTED)
3214 io_ring_submit_lock(req->ctx, needs_lock);
3216 lockdep_assert_held(&req->ctx->uring_lock);
3218 head = xa_load(&req->ctx->io_buffers, bgid);
3220 if (!list_empty(&head->list)) {
3221 kbuf = list_last_entry(&head->list, struct io_buffer,
3223 list_del(&kbuf->list);
3226 xa_erase(&req->ctx->io_buffers, bgid);
3228 if (*len > kbuf->len)
3230 req->flags |= REQ_F_BUFFER_SELECTED;
3233 kbuf = ERR_PTR(-ENOBUFS);
3236 io_ring_submit_unlock(req->ctx, needs_lock);
3240 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3241 unsigned int issue_flags)
3243 struct io_buffer *kbuf;
3246 bgid = req->buf_index;
3247 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3250 return u64_to_user_ptr(kbuf->addr);
3253 #ifdef CONFIG_COMPAT
3254 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3255 unsigned int issue_flags)
3257 struct compat_iovec __user *uiov;
3258 compat_ssize_t clen;
3262 uiov = u64_to_user_ptr(req->rw.addr);
3263 if (!access_ok(uiov, sizeof(*uiov)))
3265 if (__get_user(clen, &uiov->iov_len))
3271 buf = io_rw_buffer_select(req, &len, issue_flags);
3273 return PTR_ERR(buf);
3274 iov[0].iov_base = buf;
3275 iov[0].iov_len = (compat_size_t) len;
3280 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3281 unsigned int issue_flags)
3283 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3287 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3290 len = iov[0].iov_len;
3293 buf = io_rw_buffer_select(req, &len, issue_flags);
3295 return PTR_ERR(buf);
3296 iov[0].iov_base = buf;
3297 iov[0].iov_len = len;
3301 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3302 unsigned int issue_flags)
3304 if (req->flags & REQ_F_BUFFER_SELECTED) {
3305 struct io_buffer *kbuf = req->kbuf;
3307 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3308 iov[0].iov_len = kbuf->len;
3311 if (req->rw.len != 1)
3314 #ifdef CONFIG_COMPAT
3315 if (req->ctx->compat)
3316 return io_compat_import(req, iov, issue_flags);
3319 return __io_iov_buffer_select(req, iov, issue_flags);
3322 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3323 struct io_rw_state *s,
3324 unsigned int issue_flags)
3326 struct iov_iter *iter = &s->iter;
3327 u8 opcode = req->opcode;
3328 struct iovec *iovec;
3333 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3334 ret = io_import_fixed(req, rw, iter);
3336 return ERR_PTR(ret);
3340 /* buffer index only valid with fixed read/write, or buffer select */
3341 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3342 return ERR_PTR(-EINVAL);
3344 buf = u64_to_user_ptr(req->rw.addr);
3345 sqe_len = req->rw.len;
3347 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3348 if (req->flags & REQ_F_BUFFER_SELECT) {
3349 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3351 return ERR_CAST(buf);
3352 req->rw.len = sqe_len;
3355 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3357 return ERR_PTR(ret);
3361 iovec = s->fast_iov;
3362 if (req->flags & REQ_F_BUFFER_SELECT) {
3363 ret = io_iov_buffer_select(req, iovec, issue_flags);
3365 return ERR_PTR(ret);
3366 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3370 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3372 if (unlikely(ret < 0))
3373 return ERR_PTR(ret);
3377 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3378 struct iovec **iovec, struct io_rw_state *s,
3379 unsigned int issue_flags)
3381 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3382 if (unlikely(IS_ERR(*iovec)))
3383 return PTR_ERR(*iovec);
3385 iov_iter_save_state(&s->iter, &s->iter_state);
3389 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3391 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3395 * For files that don't have ->read_iter() and ->write_iter(), handle them
3396 * by looping over ->read() or ->write() manually.
3398 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3400 struct kiocb *kiocb = &req->rw.kiocb;
3401 struct file *file = req->file;
3405 * Don't support polled IO through this interface, and we can't
3406 * support non-blocking either. For the latter, this just causes
3407 * the kiocb to be handled from an async context.
3409 if (kiocb->ki_flags & IOCB_HIPRI)
3411 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3412 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3415 while (iov_iter_count(iter)) {
3419 if (!iov_iter_is_bvec(iter)) {
3420 iovec = iov_iter_iovec(iter);
3422 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3423 iovec.iov_len = req->rw.len;
3427 nr = file->f_op->read(file, iovec.iov_base,
3428 iovec.iov_len, io_kiocb_ppos(kiocb));
3430 nr = file->f_op->write(file, iovec.iov_base,
3431 iovec.iov_len, io_kiocb_ppos(kiocb));
3439 if (!iov_iter_is_bvec(iter)) {
3440 iov_iter_advance(iter, nr);
3446 if (nr != iovec.iov_len)
3453 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3454 const struct iovec *fast_iov, struct iov_iter *iter)
3456 struct io_async_rw *rw = req->async_data;
3458 memcpy(&rw->s.iter, iter, sizeof(*iter));
3459 rw->free_iovec = iovec;
3461 /* can only be fixed buffers, no need to do anything */
3462 if (iov_iter_is_bvec(iter))
3465 unsigned iov_off = 0;
3467 rw->s.iter.iov = rw->s.fast_iov;
3468 if (iter->iov != fast_iov) {
3469 iov_off = iter->iov - fast_iov;
3470 rw->s.iter.iov += iov_off;
3472 if (rw->s.fast_iov != fast_iov)
3473 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3474 sizeof(struct iovec) * iter->nr_segs);
3476 req->flags |= REQ_F_NEED_CLEANUP;
3480 static inline bool io_alloc_async_data(struct io_kiocb *req)
3482 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3483 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3484 if (req->async_data) {
3485 req->flags |= REQ_F_ASYNC_DATA;
3491 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3492 struct io_rw_state *s, bool force)
3494 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3496 if (!req_has_async_data(req)) {
3497 struct io_async_rw *iorw;
3499 if (io_alloc_async_data(req)) {
3504 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3505 iorw = req->async_data;
3506 /* we've copied and mapped the iter, ensure state is saved */
3507 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3512 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3514 struct io_async_rw *iorw = req->async_data;
3518 /* submission path, ->uring_lock should already be taken */
3519 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3520 if (unlikely(ret < 0))
3523 iorw->bytes_done = 0;
3524 iorw->free_iovec = iov;
3526 req->flags |= REQ_F_NEED_CLEANUP;
3530 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3532 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3534 return io_prep_rw(req, sqe);
3538 * This is our waitqueue callback handler, registered through __folio_lock_async()
3539 * when we initially tried to do the IO with the iocb armed our waitqueue.
3540 * This gets called when the page is unlocked, and we generally expect that to
3541 * happen when the page IO is completed and the page is now uptodate. This will
3542 * queue a task_work based retry of the operation, attempting to copy the data
3543 * again. If the latter fails because the page was NOT uptodate, then we will
3544 * do a thread based blocking retry of the operation. That's the unexpected
3547 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3548 int sync, void *arg)
3550 struct wait_page_queue *wpq;
3551 struct io_kiocb *req = wait->private;
3552 struct wait_page_key *key = arg;
3554 wpq = container_of(wait, struct wait_page_queue, wait);
3556 if (!wake_page_match(wpq, key))
3559 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3560 list_del_init(&wait->entry);
3561 io_req_task_queue(req);
3566 * This controls whether a given IO request should be armed for async page
3567 * based retry. If we return false here, the request is handed to the async
3568 * worker threads for retry. If we're doing buffered reads on a regular file,
3569 * we prepare a private wait_page_queue entry and retry the operation. This
3570 * will either succeed because the page is now uptodate and unlocked, or it
3571 * will register a callback when the page is unlocked at IO completion. Through
3572 * that callback, io_uring uses task_work to setup a retry of the operation.
3573 * That retry will attempt the buffered read again. The retry will generally
3574 * succeed, or in rare cases where it fails, we then fall back to using the
3575 * async worker threads for a blocking retry.
3577 static bool io_rw_should_retry(struct io_kiocb *req)
3579 struct io_async_rw *rw = req->async_data;
3580 struct wait_page_queue *wait = &rw->wpq;
3581 struct kiocb *kiocb = &req->rw.kiocb;
3583 /* never retry for NOWAIT, we just complete with -EAGAIN */
3584 if (req->flags & REQ_F_NOWAIT)
3587 /* Only for buffered IO */
3588 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3592 * just use poll if we can, and don't attempt if the fs doesn't
3593 * support callback based unlocks
3595 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3598 wait->wait.func = io_async_buf_func;
3599 wait->wait.private = req;
3600 wait->wait.flags = 0;
3601 INIT_LIST_HEAD(&wait->wait.entry);
3602 kiocb->ki_flags |= IOCB_WAITQ;
3603 kiocb->ki_flags &= ~IOCB_NOWAIT;
3604 kiocb->ki_waitq = wait;
3608 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3610 if (likely(req->file->f_op->read_iter))
3611 return call_read_iter(req->file, &req->rw.kiocb, iter);
3612 else if (req->file->f_op->read)
3613 return loop_rw_iter(READ, req, iter);
3618 static bool need_read_all(struct io_kiocb *req)
3620 return req->flags & REQ_F_ISREG ||
3621 S_ISBLK(file_inode(req->file)->i_mode);
3624 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3626 struct io_rw_state __s, *s = &__s;
3627 struct iovec *iovec;
3628 struct kiocb *kiocb = &req->rw.kiocb;
3629 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3630 struct io_async_rw *rw;
3633 if (!req_has_async_data(req)) {
3634 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3635 if (unlikely(ret < 0))
3638 rw = req->async_data;
3641 * We come here from an earlier attempt, restore our state to
3642 * match in case it doesn't. It's cheap enough that we don't
3643 * need to make this conditional.
3645 iov_iter_restore(&s->iter, &s->iter_state);
3648 req->result = iov_iter_count(&s->iter);
3650 if (force_nonblock) {
3651 /* If the file doesn't support async, just async punt */
3652 if (unlikely(!io_file_supports_nowait(req))) {
3653 ret = io_setup_async_rw(req, iovec, s, true);
3654 return ret ?: -EAGAIN;
3656 kiocb->ki_flags |= IOCB_NOWAIT;
3658 /* Ensure we clear previously set non-block flag */
3659 kiocb->ki_flags &= ~IOCB_NOWAIT;
3662 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), req->result);
3663 if (unlikely(ret)) {
3668 ret = io_iter_do_read(req, &s->iter);
3670 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3671 req->flags &= ~REQ_F_REISSUE;
3672 /* IOPOLL retry should happen for io-wq threads */
3673 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3675 /* no retry on NONBLOCK nor RWF_NOWAIT */
3676 if (req->flags & REQ_F_NOWAIT)
3679 } else if (ret == -EIOCBQUEUED) {
3681 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3682 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3683 /* read all, failed, already did sync or don't want to retry */
3688 * Don't depend on the iter state matching what was consumed, or being
3689 * untouched in case of error. Restore it and we'll advance it
3690 * manually if we need to.
3692 iov_iter_restore(&s->iter, &s->iter_state);
3694 ret2 = io_setup_async_rw(req, iovec, s, true);
3699 rw = req->async_data;
3702 * Now use our persistent iterator and state, if we aren't already.
3703 * We've restored and mapped the iter to match.
3708 * We end up here because of a partial read, either from
3709 * above or inside this loop. Advance the iter by the bytes
3710 * that were consumed.
3712 iov_iter_advance(&s->iter, ret);
3713 if (!iov_iter_count(&s->iter))
3715 rw->bytes_done += ret;
3716 iov_iter_save_state(&s->iter, &s->iter_state);
3718 /* if we can retry, do so with the callbacks armed */
3719 if (!io_rw_should_retry(req)) {
3720 kiocb->ki_flags &= ~IOCB_WAITQ;
3725 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3726 * we get -EIOCBQUEUED, then we'll get a notification when the
3727 * desired page gets unlocked. We can also get a partial read
3728 * here, and if we do, then just retry at the new offset.
3730 ret = io_iter_do_read(req, &s->iter);
3731 if (ret == -EIOCBQUEUED)
3733 /* we got some bytes, but not all. retry. */
3734 kiocb->ki_flags &= ~IOCB_WAITQ;
3735 iov_iter_restore(&s->iter, &s->iter_state);
3738 kiocb_done(req, ret, issue_flags);
3740 /* it's faster to check here then delegate to kfree */
3746 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3748 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3750 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
3751 return io_prep_rw(req, sqe);
3754 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3756 struct io_rw_state __s, *s = &__s;
3757 struct iovec *iovec;
3758 struct kiocb *kiocb = &req->rw.kiocb;
3759 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3762 if (!req_has_async_data(req)) {
3763 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3764 if (unlikely(ret < 0))
3767 struct io_async_rw *rw = req->async_data;
3770 iov_iter_restore(&s->iter, &s->iter_state);
3773 req->result = iov_iter_count(&s->iter);
3775 if (force_nonblock) {
3776 /* If the file doesn't support async, just async punt */
3777 if (unlikely(!io_file_supports_nowait(req)))
3780 /* file path doesn't support NOWAIT for non-direct_IO */
3781 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3782 (req->flags & REQ_F_ISREG))
3785 kiocb->ki_flags |= IOCB_NOWAIT;
3787 /* Ensure we clear previously set non-block flag */
3788 kiocb->ki_flags &= ~IOCB_NOWAIT;
3791 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), req->result);
3796 * Open-code file_start_write here to grab freeze protection,
3797 * which will be released by another thread in
3798 * io_complete_rw(). Fool lockdep by telling it the lock got
3799 * released so that it doesn't complain about the held lock when
3800 * we return to userspace.
3802 if (req->flags & REQ_F_ISREG) {
3803 sb_start_write(file_inode(req->file)->i_sb);
3804 __sb_writers_release(file_inode(req->file)->i_sb,
3807 kiocb->ki_flags |= IOCB_WRITE;
3809 if (likely(req->file->f_op->write_iter))
3810 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3811 else if (req->file->f_op->write)
3812 ret2 = loop_rw_iter(WRITE, req, &s->iter);
3816 if (req->flags & REQ_F_REISSUE) {
3817 req->flags &= ~REQ_F_REISSUE;
3822 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3823 * retry them without IOCB_NOWAIT.
3825 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3827 /* no retry on NONBLOCK nor RWF_NOWAIT */
3828 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3830 if (!force_nonblock || ret2 != -EAGAIN) {
3831 /* IOPOLL retry should happen for io-wq threads */
3832 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3835 kiocb_done(req, ret2, issue_flags);
3838 iov_iter_restore(&s->iter, &s->iter_state);
3839 ret = io_setup_async_rw(req, iovec, s, false);
3840 return ret ?: -EAGAIN;
3843 /* it's reportedly faster than delegating the null check to kfree() */
3849 static int io_renameat_prep(struct io_kiocb *req,
3850 const struct io_uring_sqe *sqe)
3852 struct io_rename *ren = &req->rename;
3853 const char __user *oldf, *newf;
3855 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3857 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3859 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3862 ren->old_dfd = READ_ONCE(sqe->fd);
3863 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3864 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3865 ren->new_dfd = READ_ONCE(sqe->len);
3866 ren->flags = READ_ONCE(sqe->rename_flags);
3868 ren->oldpath = getname(oldf);
3869 if (IS_ERR(ren->oldpath))
3870 return PTR_ERR(ren->oldpath);
3872 ren->newpath = getname(newf);
3873 if (IS_ERR(ren->newpath)) {
3874 putname(ren->oldpath);
3875 return PTR_ERR(ren->newpath);
3878 req->flags |= REQ_F_NEED_CLEANUP;
3882 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3884 struct io_rename *ren = &req->rename;
3887 if (issue_flags & IO_URING_F_NONBLOCK)
3890 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3891 ren->newpath, ren->flags);
3893 req->flags &= ~REQ_F_NEED_CLEANUP;
3896 io_req_complete(req, ret);
3900 static int io_unlinkat_prep(struct io_kiocb *req,
3901 const struct io_uring_sqe *sqe)
3903 struct io_unlink *un = &req->unlink;
3904 const char __user *fname;
3906 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3908 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3911 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3914 un->dfd = READ_ONCE(sqe->fd);
3916 un->flags = READ_ONCE(sqe->unlink_flags);
3917 if (un->flags & ~AT_REMOVEDIR)
3920 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3921 un->filename = getname(fname);
3922 if (IS_ERR(un->filename))
3923 return PTR_ERR(un->filename);
3925 req->flags |= REQ_F_NEED_CLEANUP;
3929 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3931 struct io_unlink *un = &req->unlink;
3934 if (issue_flags & IO_URING_F_NONBLOCK)
3937 if (un->flags & AT_REMOVEDIR)
3938 ret = do_rmdir(un->dfd, un->filename);
3940 ret = do_unlinkat(un->dfd, un->filename);
3942 req->flags &= ~REQ_F_NEED_CLEANUP;
3945 io_req_complete(req, ret);
3949 static int io_mkdirat_prep(struct io_kiocb *req,
3950 const struct io_uring_sqe *sqe)
3952 struct io_mkdir *mkd = &req->mkdir;
3953 const char __user *fname;
3955 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3957 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3960 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3963 mkd->dfd = READ_ONCE(sqe->fd);
3964 mkd->mode = READ_ONCE(sqe->len);
3966 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3967 mkd->filename = getname(fname);
3968 if (IS_ERR(mkd->filename))
3969 return PTR_ERR(mkd->filename);
3971 req->flags |= REQ_F_NEED_CLEANUP;
3975 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
3977 struct io_mkdir *mkd = &req->mkdir;
3980 if (issue_flags & IO_URING_F_NONBLOCK)
3983 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3985 req->flags &= ~REQ_F_NEED_CLEANUP;
3988 io_req_complete(req, ret);
3992 static int io_symlinkat_prep(struct io_kiocb *req,
3993 const struct io_uring_sqe *sqe)
3995 struct io_symlink *sl = &req->symlink;
3996 const char __user *oldpath, *newpath;
3998 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4000 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4003 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4006 sl->new_dfd = READ_ONCE(sqe->fd);
4007 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4008 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4010 sl->oldpath = getname(oldpath);
4011 if (IS_ERR(sl->oldpath))
4012 return PTR_ERR(sl->oldpath);
4014 sl->newpath = getname(newpath);
4015 if (IS_ERR(sl->newpath)) {
4016 putname(sl->oldpath);
4017 return PTR_ERR(sl->newpath);
4020 req->flags |= REQ_F_NEED_CLEANUP;
4024 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4026 struct io_symlink *sl = &req->symlink;
4029 if (issue_flags & IO_URING_F_NONBLOCK)
4032 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4034 req->flags &= ~REQ_F_NEED_CLEANUP;
4037 io_req_complete(req, ret);
4041 static int io_linkat_prep(struct io_kiocb *req,
4042 const struct io_uring_sqe *sqe)
4044 struct io_hardlink *lnk = &req->hardlink;
4045 const char __user *oldf, *newf;
4047 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4049 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4051 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4054 lnk->old_dfd = READ_ONCE(sqe->fd);
4055 lnk->new_dfd = READ_ONCE(sqe->len);
4056 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4057 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4058 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4060 lnk->oldpath = getname(oldf);
4061 if (IS_ERR(lnk->oldpath))
4062 return PTR_ERR(lnk->oldpath);
4064 lnk->newpath = getname(newf);
4065 if (IS_ERR(lnk->newpath)) {
4066 putname(lnk->oldpath);
4067 return PTR_ERR(lnk->newpath);
4070 req->flags |= REQ_F_NEED_CLEANUP;
4074 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4076 struct io_hardlink *lnk = &req->hardlink;
4079 if (issue_flags & IO_URING_F_NONBLOCK)
4082 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4083 lnk->newpath, lnk->flags);
4085 req->flags &= ~REQ_F_NEED_CLEANUP;
4088 io_req_complete(req, ret);
4092 static int io_shutdown_prep(struct io_kiocb *req,
4093 const struct io_uring_sqe *sqe)
4095 #if defined(CONFIG_NET)
4096 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4098 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4099 sqe->buf_index || sqe->splice_fd_in))
4102 req->shutdown.how = READ_ONCE(sqe->len);
4109 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4111 #if defined(CONFIG_NET)
4112 struct socket *sock;
4115 if (issue_flags & IO_URING_F_NONBLOCK)
4118 sock = sock_from_file(req->file);
4119 if (unlikely(!sock))
4122 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4125 io_req_complete(req, ret);
4132 static int __io_splice_prep(struct io_kiocb *req,
4133 const struct io_uring_sqe *sqe)
4135 struct io_splice *sp = &req->splice;
4136 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4138 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4142 sp->len = READ_ONCE(sqe->len);
4143 sp->flags = READ_ONCE(sqe->splice_flags);
4145 if (unlikely(sp->flags & ~valid_flags))
4148 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4149 (sp->flags & SPLICE_F_FD_IN_FIXED));
4152 req->flags |= REQ_F_NEED_CLEANUP;
4156 static int io_tee_prep(struct io_kiocb *req,
4157 const struct io_uring_sqe *sqe)
4159 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4161 return __io_splice_prep(req, sqe);
4164 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4166 struct io_splice *sp = &req->splice;
4167 struct file *in = sp->file_in;
4168 struct file *out = sp->file_out;
4169 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4172 if (issue_flags & IO_URING_F_NONBLOCK)
4175 ret = do_tee(in, out, sp->len, flags);
4177 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4179 req->flags &= ~REQ_F_NEED_CLEANUP;
4183 io_req_complete(req, ret);
4187 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4189 struct io_splice *sp = &req->splice;
4191 sp->off_in = READ_ONCE(sqe->splice_off_in);
4192 sp->off_out = READ_ONCE(sqe->off);
4193 return __io_splice_prep(req, sqe);
4196 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4198 struct io_splice *sp = &req->splice;
4199 struct file *in = sp->file_in;
4200 struct file *out = sp->file_out;
4201 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4202 loff_t *poff_in, *poff_out;
4205 if (issue_flags & IO_URING_F_NONBLOCK)
4208 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4209 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4212 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4214 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4216 req->flags &= ~REQ_F_NEED_CLEANUP;
4220 io_req_complete(req, ret);
4225 * IORING_OP_NOP just posts a completion event, nothing else.
4227 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4229 struct io_ring_ctx *ctx = req->ctx;
4231 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4234 __io_req_complete(req, issue_flags, 0, 0);
4238 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4240 struct io_ring_ctx *ctx = req->ctx;
4245 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4247 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4251 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4252 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4255 req->sync.off = READ_ONCE(sqe->off);
4256 req->sync.len = READ_ONCE(sqe->len);
4260 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4262 loff_t end = req->sync.off + req->sync.len;
4265 /* fsync always requires a blocking context */
4266 if (issue_flags & IO_URING_F_NONBLOCK)
4269 ret = vfs_fsync_range(req->file, req->sync.off,
4270 end > 0 ? end : LLONG_MAX,
4271 req->sync.flags & IORING_FSYNC_DATASYNC);
4274 io_req_complete(req, ret);
4278 static int io_fallocate_prep(struct io_kiocb *req,
4279 const struct io_uring_sqe *sqe)
4281 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4284 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4287 req->sync.off = READ_ONCE(sqe->off);
4288 req->sync.len = READ_ONCE(sqe->addr);
4289 req->sync.mode = READ_ONCE(sqe->len);
4293 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4297 /* fallocate always requiring blocking context */
4298 if (issue_flags & IO_URING_F_NONBLOCK)
4300 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4304 io_req_complete(req, ret);
4308 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4310 const char __user *fname;
4313 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4315 if (unlikely(sqe->ioprio || sqe->buf_index))
4317 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4320 /* open.how should be already initialised */
4321 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4322 req->open.how.flags |= O_LARGEFILE;
4324 req->open.dfd = READ_ONCE(sqe->fd);
4325 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4326 req->open.filename = getname(fname);
4327 if (IS_ERR(req->open.filename)) {
4328 ret = PTR_ERR(req->open.filename);
4329 req->open.filename = NULL;
4333 req->open.file_slot = READ_ONCE(sqe->file_index);
4334 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4337 req->open.nofile = rlimit(RLIMIT_NOFILE);
4338 req->flags |= REQ_F_NEED_CLEANUP;
4342 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4344 u64 mode = READ_ONCE(sqe->len);
4345 u64 flags = READ_ONCE(sqe->open_flags);
4347 req->open.how = build_open_how(flags, mode);
4348 return __io_openat_prep(req, sqe);
4351 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4353 struct open_how __user *how;
4357 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4358 len = READ_ONCE(sqe->len);
4359 if (len < OPEN_HOW_SIZE_VER0)
4362 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4367 return __io_openat_prep(req, sqe);
4370 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4372 struct open_flags op;
4374 bool resolve_nonblock, nonblock_set;
4375 bool fixed = !!req->open.file_slot;
4378 ret = build_open_flags(&req->open.how, &op);
4381 nonblock_set = op.open_flag & O_NONBLOCK;
4382 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4383 if (issue_flags & IO_URING_F_NONBLOCK) {
4385 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4386 * it'll always -EAGAIN
4388 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4390 op.lookup_flags |= LOOKUP_CACHED;
4391 op.open_flag |= O_NONBLOCK;
4395 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4400 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4403 * We could hang on to this 'fd' on retrying, but seems like
4404 * marginal gain for something that is now known to be a slower
4405 * path. So just put it, and we'll get a new one when we retry.
4410 ret = PTR_ERR(file);
4411 /* only retry if RESOLVE_CACHED wasn't already set by application */
4412 if (ret == -EAGAIN &&
4413 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4418 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4419 file->f_flags &= ~O_NONBLOCK;
4420 fsnotify_open(file);
4423 fd_install(ret, file);
4425 ret = io_install_fixed_file(req, file, issue_flags,
4426 req->open.file_slot - 1);
4428 putname(req->open.filename);
4429 req->flags &= ~REQ_F_NEED_CLEANUP;
4432 __io_req_complete(req, issue_flags, ret, 0);
4436 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4438 return io_openat2(req, issue_flags);
4441 static int io_remove_buffers_prep(struct io_kiocb *req,
4442 const struct io_uring_sqe *sqe)
4444 struct io_provide_buf *p = &req->pbuf;
4447 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4451 tmp = READ_ONCE(sqe->fd);
4452 if (!tmp || tmp > USHRT_MAX)
4455 memset(p, 0, sizeof(*p));
4457 p->bgid = READ_ONCE(sqe->buf_group);
4461 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4462 int bgid, unsigned nbufs)
4466 /* shouldn't happen */
4470 /* the head kbuf is the list itself */
4471 while (!list_empty(&buf->list)) {
4472 struct io_buffer *nxt;
4474 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4475 list_del(&nxt->list);
4483 xa_erase(&ctx->io_buffers, bgid);
4488 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4490 struct io_provide_buf *p = &req->pbuf;
4491 struct io_ring_ctx *ctx = req->ctx;
4492 struct io_buffer *head;
4494 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4496 io_ring_submit_lock(ctx, needs_lock);
4498 lockdep_assert_held(&ctx->uring_lock);
4501 head = xa_load(&ctx->io_buffers, p->bgid);
4503 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4507 /* complete before unlock, IOPOLL may need the lock */
4508 __io_req_complete(req, issue_flags, ret, 0);
4509 io_ring_submit_unlock(ctx, needs_lock);
4513 static int io_provide_buffers_prep(struct io_kiocb *req,
4514 const struct io_uring_sqe *sqe)
4516 unsigned long size, tmp_check;
4517 struct io_provide_buf *p = &req->pbuf;
4520 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4523 tmp = READ_ONCE(sqe->fd);
4524 if (!tmp || tmp > USHRT_MAX)
4527 p->addr = READ_ONCE(sqe->addr);
4528 p->len = READ_ONCE(sqe->len);
4530 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4533 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4536 size = (unsigned long)p->len * p->nbufs;
4537 if (!access_ok(u64_to_user_ptr(p->addr), size))
4540 p->bgid = READ_ONCE(sqe->buf_group);
4541 tmp = READ_ONCE(sqe->off);
4542 if (tmp > USHRT_MAX)
4548 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4550 struct io_buffer *buf;
4551 u64 addr = pbuf->addr;
4552 int i, bid = pbuf->bid;
4554 for (i = 0; i < pbuf->nbufs; i++) {
4555 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4560 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4565 INIT_LIST_HEAD(&buf->list);
4568 list_add_tail(&buf->list, &(*head)->list);
4573 return i ? i : -ENOMEM;
4576 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4578 struct io_provide_buf *p = &req->pbuf;
4579 struct io_ring_ctx *ctx = req->ctx;
4580 struct io_buffer *head, *list;
4582 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4584 io_ring_submit_lock(ctx, needs_lock);
4586 lockdep_assert_held(&ctx->uring_lock);
4588 list = head = xa_load(&ctx->io_buffers, p->bgid);
4590 ret = io_add_buffers(p, &head);
4591 if (ret >= 0 && !list) {
4592 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4594 __io_remove_buffers(ctx, head, p->bgid, -1U);
4598 /* complete before unlock, IOPOLL may need the lock */
4599 __io_req_complete(req, issue_flags, ret, 0);
4600 io_ring_submit_unlock(ctx, needs_lock);
4604 static int io_epoll_ctl_prep(struct io_kiocb *req,
4605 const struct io_uring_sqe *sqe)
4607 #if defined(CONFIG_EPOLL)
4608 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4610 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4613 req->epoll.epfd = READ_ONCE(sqe->fd);
4614 req->epoll.op = READ_ONCE(sqe->len);
4615 req->epoll.fd = READ_ONCE(sqe->off);
4617 if (ep_op_has_event(req->epoll.op)) {
4618 struct epoll_event __user *ev;
4620 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4621 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4631 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4633 #if defined(CONFIG_EPOLL)
4634 struct io_epoll *ie = &req->epoll;
4636 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4638 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4639 if (force_nonblock && ret == -EAGAIN)
4644 __io_req_complete(req, issue_flags, ret, 0);
4651 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4653 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4654 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4656 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4659 req->madvise.addr = READ_ONCE(sqe->addr);
4660 req->madvise.len = READ_ONCE(sqe->len);
4661 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4668 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4670 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4671 struct io_madvise *ma = &req->madvise;
4674 if (issue_flags & IO_URING_F_NONBLOCK)
4677 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4680 io_req_complete(req, ret);
4687 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4689 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4691 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4694 req->fadvise.offset = READ_ONCE(sqe->off);
4695 req->fadvise.len = READ_ONCE(sqe->len);
4696 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4700 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4702 struct io_fadvise *fa = &req->fadvise;
4705 if (issue_flags & IO_URING_F_NONBLOCK) {
4706 switch (fa->advice) {
4707 case POSIX_FADV_NORMAL:
4708 case POSIX_FADV_RANDOM:
4709 case POSIX_FADV_SEQUENTIAL:
4716 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4719 __io_req_complete(req, issue_flags, ret, 0);
4723 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4725 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4727 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4729 if (req->flags & REQ_F_FIXED_FILE)
4732 req->statx.dfd = READ_ONCE(sqe->fd);
4733 req->statx.mask = READ_ONCE(sqe->len);
4734 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4735 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4736 req->statx.flags = READ_ONCE(sqe->statx_flags);
4741 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4743 struct io_statx *ctx = &req->statx;
4746 if (issue_flags & IO_URING_F_NONBLOCK)
4749 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4754 io_req_complete(req, ret);
4758 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4760 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4762 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4763 sqe->rw_flags || sqe->buf_index)
4765 if (req->flags & REQ_F_FIXED_FILE)
4768 req->close.fd = READ_ONCE(sqe->fd);
4769 req->close.file_slot = READ_ONCE(sqe->file_index);
4770 if (req->close.file_slot && req->close.fd)
4776 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4778 struct files_struct *files = current->files;
4779 struct io_close *close = &req->close;
4780 struct fdtable *fdt;
4781 struct file *file = NULL;
4784 if (req->close.file_slot) {
4785 ret = io_close_fixed(req, issue_flags);
4789 spin_lock(&files->file_lock);
4790 fdt = files_fdtable(files);
4791 if (close->fd >= fdt->max_fds) {
4792 spin_unlock(&files->file_lock);
4795 file = fdt->fd[close->fd];
4796 if (!file || file->f_op == &io_uring_fops) {
4797 spin_unlock(&files->file_lock);
4802 /* if the file has a flush method, be safe and punt to async */
4803 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4804 spin_unlock(&files->file_lock);
4808 ret = __close_fd_get_file(close->fd, &file);
4809 spin_unlock(&files->file_lock);
4816 /* No ->flush() or already async, safely close from here */
4817 ret = filp_close(file, current->files);
4823 __io_req_complete(req, issue_flags, ret, 0);
4827 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4829 struct io_ring_ctx *ctx = req->ctx;
4831 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4833 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4837 req->sync.off = READ_ONCE(sqe->off);
4838 req->sync.len = READ_ONCE(sqe->len);
4839 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4843 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4847 /* sync_file_range always requires a blocking context */
4848 if (issue_flags & IO_URING_F_NONBLOCK)
4851 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4855 io_req_complete(req, ret);
4859 #if defined(CONFIG_NET)
4860 static int io_setup_async_msg(struct io_kiocb *req,
4861 struct io_async_msghdr *kmsg)
4863 struct io_async_msghdr *async_msg = req->async_data;
4867 if (io_alloc_async_data(req)) {
4868 kfree(kmsg->free_iov);
4871 async_msg = req->async_data;
4872 req->flags |= REQ_F_NEED_CLEANUP;
4873 memcpy(async_msg, kmsg, sizeof(*kmsg));
4874 async_msg->msg.msg_name = &async_msg->addr;
4875 /* if were using fast_iov, set it to the new one */
4876 if (!async_msg->free_iov)
4877 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4882 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4883 struct io_async_msghdr *iomsg)
4885 iomsg->msg.msg_name = &iomsg->addr;
4886 iomsg->free_iov = iomsg->fast_iov;
4887 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4888 req->sr_msg.msg_flags, &iomsg->free_iov);
4891 static int io_sendmsg_prep_async(struct io_kiocb *req)
4895 ret = io_sendmsg_copy_hdr(req, req->async_data);
4897 req->flags |= REQ_F_NEED_CLEANUP;
4901 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4903 struct io_sr_msg *sr = &req->sr_msg;
4905 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4908 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4909 sr->len = READ_ONCE(sqe->len);
4910 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4911 if (sr->msg_flags & MSG_DONTWAIT)
4912 req->flags |= REQ_F_NOWAIT;
4914 #ifdef CONFIG_COMPAT
4915 if (req->ctx->compat)
4916 sr->msg_flags |= MSG_CMSG_COMPAT;
4921 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4923 struct io_async_msghdr iomsg, *kmsg;
4924 struct socket *sock;
4929 sock = sock_from_file(req->file);
4930 if (unlikely(!sock))
4933 if (req_has_async_data(req)) {
4934 kmsg = req->async_data;
4936 ret = io_sendmsg_copy_hdr(req, &iomsg);
4942 flags = req->sr_msg.msg_flags;
4943 if (issue_flags & IO_URING_F_NONBLOCK)
4944 flags |= MSG_DONTWAIT;
4945 if (flags & MSG_WAITALL)
4946 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4948 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4950 if (ret < min_ret) {
4951 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4952 return io_setup_async_msg(req, kmsg);
4953 if (ret == -ERESTARTSYS)
4957 /* fast path, check for non-NULL to avoid function call */
4959 kfree(kmsg->free_iov);
4960 req->flags &= ~REQ_F_NEED_CLEANUP;
4961 __io_req_complete(req, issue_flags, ret, 0);
4965 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4967 struct io_sr_msg *sr = &req->sr_msg;
4970 struct socket *sock;
4975 sock = sock_from_file(req->file);
4976 if (unlikely(!sock))
4979 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4983 msg.msg_name = NULL;
4984 msg.msg_control = NULL;
4985 msg.msg_controllen = 0;
4986 msg.msg_namelen = 0;
4988 flags = req->sr_msg.msg_flags;
4989 if (issue_flags & IO_URING_F_NONBLOCK)
4990 flags |= MSG_DONTWAIT;
4991 if (flags & MSG_WAITALL)
4992 min_ret = iov_iter_count(&msg.msg_iter);
4994 msg.msg_flags = flags;
4995 ret = sock_sendmsg(sock, &msg);
4996 if (ret < min_ret) {
4997 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4999 if (ret == -ERESTARTSYS)
5003 __io_req_complete(req, issue_flags, ret, 0);
5007 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5008 struct io_async_msghdr *iomsg)
5010 struct io_sr_msg *sr = &req->sr_msg;
5011 struct iovec __user *uiov;
5015 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5016 &iomsg->uaddr, &uiov, &iov_len);
5020 if (req->flags & REQ_F_BUFFER_SELECT) {
5023 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5025 sr->len = iomsg->fast_iov[0].iov_len;
5026 iomsg->free_iov = NULL;
5028 iomsg->free_iov = iomsg->fast_iov;
5029 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5030 &iomsg->free_iov, &iomsg->msg.msg_iter,
5039 #ifdef CONFIG_COMPAT
5040 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5041 struct io_async_msghdr *iomsg)
5043 struct io_sr_msg *sr = &req->sr_msg;
5044 struct compat_iovec __user *uiov;
5049 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5054 uiov = compat_ptr(ptr);
5055 if (req->flags & REQ_F_BUFFER_SELECT) {
5056 compat_ssize_t clen;
5060 if (!access_ok(uiov, sizeof(*uiov)))
5062 if (__get_user(clen, &uiov->iov_len))
5067 iomsg->free_iov = NULL;
5069 iomsg->free_iov = iomsg->fast_iov;
5070 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5071 UIO_FASTIOV, &iomsg->free_iov,
5072 &iomsg->msg.msg_iter, true);
5081 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5082 struct io_async_msghdr *iomsg)
5084 iomsg->msg.msg_name = &iomsg->addr;
5086 #ifdef CONFIG_COMPAT
5087 if (req->ctx->compat)
5088 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5091 return __io_recvmsg_copy_hdr(req, iomsg);
5094 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5095 unsigned int issue_flags)
5097 struct io_sr_msg *sr = &req->sr_msg;
5099 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5102 static int io_recvmsg_prep_async(struct io_kiocb *req)
5106 ret = io_recvmsg_copy_hdr(req, req->async_data);
5108 req->flags |= REQ_F_NEED_CLEANUP;
5112 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5114 struct io_sr_msg *sr = &req->sr_msg;
5116 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5119 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5120 sr->len = READ_ONCE(sqe->len);
5121 sr->bgid = READ_ONCE(sqe->buf_group);
5122 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5123 if (sr->msg_flags & MSG_DONTWAIT)
5124 req->flags |= REQ_F_NOWAIT;
5126 #ifdef CONFIG_COMPAT
5127 if (req->ctx->compat)
5128 sr->msg_flags |= MSG_CMSG_COMPAT;
5133 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5135 struct io_async_msghdr iomsg, *kmsg;
5136 struct socket *sock;
5137 struct io_buffer *kbuf;
5139 int ret, min_ret = 0;
5140 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5142 sock = sock_from_file(req->file);
5143 if (unlikely(!sock))
5146 if (req_has_async_data(req)) {
5147 kmsg = req->async_data;
5149 ret = io_recvmsg_copy_hdr(req, &iomsg);
5155 if (req->flags & REQ_F_BUFFER_SELECT) {
5156 kbuf = io_recv_buffer_select(req, issue_flags);
5158 return PTR_ERR(kbuf);
5159 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5160 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5161 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5162 1, req->sr_msg.len);
5165 flags = req->sr_msg.msg_flags;
5167 flags |= MSG_DONTWAIT;
5168 if (flags & MSG_WAITALL)
5169 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5171 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5172 kmsg->uaddr, flags);
5173 if (ret < min_ret) {
5174 if (ret == -EAGAIN && force_nonblock)
5175 return io_setup_async_msg(req, kmsg);
5176 if (ret == -ERESTARTSYS)
5179 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5183 /* fast path, check for non-NULL to avoid function call */
5185 kfree(kmsg->free_iov);
5186 req->flags &= ~REQ_F_NEED_CLEANUP;
5187 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req));
5191 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5193 struct io_buffer *kbuf;
5194 struct io_sr_msg *sr = &req->sr_msg;
5196 void __user *buf = sr->buf;
5197 struct socket *sock;
5200 int ret, min_ret = 0;
5201 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5203 sock = sock_from_file(req->file);
5204 if (unlikely(!sock))
5207 if (req->flags & REQ_F_BUFFER_SELECT) {
5208 kbuf = io_recv_buffer_select(req, issue_flags);
5210 return PTR_ERR(kbuf);
5211 buf = u64_to_user_ptr(kbuf->addr);
5214 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5218 msg.msg_name = NULL;
5219 msg.msg_control = NULL;
5220 msg.msg_controllen = 0;
5221 msg.msg_namelen = 0;
5222 msg.msg_iocb = NULL;
5225 flags = req->sr_msg.msg_flags;
5227 flags |= MSG_DONTWAIT;
5228 if (flags & MSG_WAITALL)
5229 min_ret = iov_iter_count(&msg.msg_iter);
5231 ret = sock_recvmsg(sock, &msg, flags);
5232 if (ret < min_ret) {
5233 if (ret == -EAGAIN && force_nonblock)
5235 if (ret == -ERESTARTSYS)
5238 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5242 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req));
5246 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5248 struct io_accept *accept = &req->accept;
5250 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5252 if (sqe->ioprio || sqe->len || sqe->buf_index)
5255 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5256 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5257 accept->flags = READ_ONCE(sqe->accept_flags);
5258 accept->nofile = rlimit(RLIMIT_NOFILE);
5260 accept->file_slot = READ_ONCE(sqe->file_index);
5261 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
5262 (accept->flags & SOCK_CLOEXEC)))
5264 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5266 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5267 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5271 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5273 struct io_accept *accept = &req->accept;
5274 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5275 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5276 bool fixed = !!accept->file_slot;
5280 if (req->file->f_flags & O_NONBLOCK)
5281 req->flags |= REQ_F_NOWAIT;
5284 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5285 if (unlikely(fd < 0))
5288 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5293 ret = PTR_ERR(file);
5294 if (ret == -EAGAIN && force_nonblock)
5296 if (ret == -ERESTARTSYS)
5299 } else if (!fixed) {
5300 fd_install(fd, file);
5303 ret = io_install_fixed_file(req, file, issue_flags,
5304 accept->file_slot - 1);
5306 __io_req_complete(req, issue_flags, ret, 0);
5310 static int io_connect_prep_async(struct io_kiocb *req)
5312 struct io_async_connect *io = req->async_data;
5313 struct io_connect *conn = &req->connect;
5315 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5318 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5320 struct io_connect *conn = &req->connect;
5322 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5324 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5328 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5329 conn->addr_len = READ_ONCE(sqe->addr2);
5333 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5335 struct io_async_connect __io, *io;
5336 unsigned file_flags;
5338 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5340 if (req_has_async_data(req)) {
5341 io = req->async_data;
5343 ret = move_addr_to_kernel(req->connect.addr,
5344 req->connect.addr_len,
5351 file_flags = force_nonblock ? O_NONBLOCK : 0;
5353 ret = __sys_connect_file(req->file, &io->address,
5354 req->connect.addr_len, file_flags);
5355 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5356 if (req_has_async_data(req))
5358 if (io_alloc_async_data(req)) {
5362 memcpy(req->async_data, &__io, sizeof(__io));
5365 if (ret == -ERESTARTSYS)
5370 __io_req_complete(req, issue_flags, ret, 0);
5373 #else /* !CONFIG_NET */
5374 #define IO_NETOP_FN(op) \
5375 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5377 return -EOPNOTSUPP; \
5380 #define IO_NETOP_PREP(op) \
5382 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5384 return -EOPNOTSUPP; \
5387 #define IO_NETOP_PREP_ASYNC(op) \
5389 static int io_##op##_prep_async(struct io_kiocb *req) \
5391 return -EOPNOTSUPP; \
5394 IO_NETOP_PREP_ASYNC(sendmsg);
5395 IO_NETOP_PREP_ASYNC(recvmsg);
5396 IO_NETOP_PREP_ASYNC(connect);
5397 IO_NETOP_PREP(accept);
5400 #endif /* CONFIG_NET */
5402 struct io_poll_table {
5403 struct poll_table_struct pt;
5404 struct io_kiocb *req;
5409 #define IO_POLL_CANCEL_FLAG BIT(31)
5410 #define IO_POLL_REF_MASK ((1u << 20)-1)
5413 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5414 * bump it and acquire ownership. It's disallowed to modify requests while not
5415 * owning it, that prevents from races for enqueueing task_work's and b/w
5416 * arming poll and wakeups.
5418 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5420 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5423 static void io_poll_mark_cancelled(struct io_kiocb *req)
5425 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5428 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5430 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5431 if (req->opcode == IORING_OP_POLL_ADD)
5432 return req->async_data;
5433 return req->apoll->double_poll;
5436 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5438 if (req->opcode == IORING_OP_POLL_ADD)
5440 return &req->apoll->poll;
5443 static void io_poll_req_insert(struct io_kiocb *req)
5445 struct io_ring_ctx *ctx = req->ctx;
5446 struct hlist_head *list;
5448 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5449 hlist_add_head(&req->hash_node, list);
5452 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5453 wait_queue_func_t wake_func)
5456 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5457 /* mask in events that we always want/need */
5458 poll->events = events | IO_POLL_UNMASK;
5459 INIT_LIST_HEAD(&poll->wait.entry);
5460 init_waitqueue_func_entry(&poll->wait, wake_func);
5463 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5465 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5468 spin_lock_irq(&head->lock);
5469 list_del_init(&poll->wait.entry);
5471 spin_unlock_irq(&head->lock);
5475 static void io_poll_remove_entries(struct io_kiocb *req)
5477 struct io_poll_iocb *poll = io_poll_get_single(req);
5478 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5481 * While we hold the waitqueue lock and the waitqueue is nonempty,
5482 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5483 * lock in the first place can race with the waitqueue being freed.
5485 * We solve this as eventpoll does: by taking advantage of the fact that
5486 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5487 * we enter rcu_read_lock() and see that the pointer to the queue is
5488 * non-NULL, we can then lock it without the memory being freed out from
5491 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5492 * case the caller deletes the entry from the queue, leaving it empty.
5493 * In that case, only RCU prevents the queue memory from being freed.
5496 io_poll_remove_entry(poll);
5498 io_poll_remove_entry(poll_double);
5503 * All poll tw should go through this. Checks for poll events, manages
5504 * references, does rewait, etc.
5506 * Returns a negative error on failure. >0 when no action require, which is
5507 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5508 * the request, then the mask is stored in req->result.
5510 static int io_poll_check_events(struct io_kiocb *req)
5512 struct io_ring_ctx *ctx = req->ctx;
5513 struct io_poll_iocb *poll = io_poll_get_single(req);
5516 /* req->task == current here, checking PF_EXITING is safe */
5517 if (unlikely(req->task->flags & PF_EXITING))
5518 io_poll_mark_cancelled(req);
5521 v = atomic_read(&req->poll_refs);
5523 /* tw handler should be the owner, and so have some references */
5524 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5526 if (v & IO_POLL_CANCEL_FLAG)
5530 struct poll_table_struct pt = { ._key = poll->events };
5532 req->result = vfs_poll(req->file, &pt) & poll->events;
5535 /* multishot, just fill an CQE and proceed */
5536 if (req->result && !(poll->events & EPOLLONESHOT)) {
5537 __poll_t mask = mangle_poll(req->result & poll->events);
5540 spin_lock(&ctx->completion_lock);
5541 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5543 io_commit_cqring(ctx);
5544 spin_unlock(&ctx->completion_lock);
5545 if (unlikely(!filled))
5547 io_cqring_ev_posted(ctx);
5548 } else if (req->result) {
5553 * Release all references, retry if someone tried to restart
5554 * task_work while we were executing it.
5556 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5561 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5563 struct io_ring_ctx *ctx = req->ctx;
5566 ret = io_poll_check_events(req);
5571 req->result = mangle_poll(req->result & req->poll.events);
5577 io_poll_remove_entries(req);
5578 spin_lock(&ctx->completion_lock);
5579 hash_del(&req->hash_node);
5580 __io_req_complete_post(req, req->result, 0);
5581 io_commit_cqring(ctx);
5582 spin_unlock(&ctx->completion_lock);
5583 io_cqring_ev_posted(ctx);
5586 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5588 struct io_ring_ctx *ctx = req->ctx;
5591 ret = io_poll_check_events(req);
5595 io_poll_remove_entries(req);
5596 spin_lock(&ctx->completion_lock);
5597 hash_del(&req->hash_node);
5598 spin_unlock(&ctx->completion_lock);
5601 io_req_task_submit(req, locked);
5603 io_req_complete_failed(req, ret);
5606 static void __io_poll_execute(struct io_kiocb *req, int mask)
5609 if (req->opcode == IORING_OP_POLL_ADD)
5610 req->io_task_work.func = io_poll_task_func;
5612 req->io_task_work.func = io_apoll_task_func;
5614 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5615 io_req_task_work_add(req, false);
5618 static inline void io_poll_execute(struct io_kiocb *req, int res)
5620 if (io_poll_get_ownership(req))
5621 __io_poll_execute(req, res);
5624 static void io_poll_cancel_req(struct io_kiocb *req)
5626 io_poll_mark_cancelled(req);
5627 /* kick tw, which should complete the request */
5628 io_poll_execute(req, 0);
5631 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5634 struct io_kiocb *req = wait->private;
5635 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5637 __poll_t mask = key_to_poll(key);
5639 if (unlikely(mask & POLLFREE)) {
5640 io_poll_mark_cancelled(req);
5641 /* we have to kick tw in case it's not already */
5642 io_poll_execute(req, 0);
5645 * If the waitqueue is being freed early but someone is already
5646 * holds ownership over it, we have to tear down the request as
5647 * best we can. That means immediately removing the request from
5648 * its waitqueue and preventing all further accesses to the
5649 * waitqueue via the request.
5651 list_del_init(&poll->wait.entry);
5654 * Careful: this *must* be the last step, since as soon
5655 * as req->head is NULL'ed out, the request can be
5656 * completed and freed, since aio_poll_complete_work()
5657 * will no longer need to take the waitqueue lock.
5659 smp_store_release(&poll->head, NULL);
5663 /* for instances that support it check for an event match first */
5664 if (mask && !(mask & poll->events))
5667 if (io_poll_get_ownership(req)) {
5668 /* optional, saves extra locking for removal in tw handler */
5669 if (mask && poll->events & EPOLLONESHOT) {
5670 list_del_init(&poll->wait.entry);
5673 __io_poll_execute(req, mask);
5678 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5679 struct wait_queue_head *head,
5680 struct io_poll_iocb **poll_ptr)
5682 struct io_kiocb *req = pt->req;
5685 * The file being polled uses multiple waitqueues for poll handling
5686 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5689 if (unlikely(pt->nr_entries)) {
5690 struct io_poll_iocb *first = poll;
5692 /* double add on the same waitqueue head, ignore */
5693 if (first->head == head)
5695 /* already have a 2nd entry, fail a third attempt */
5697 if ((*poll_ptr)->head == head)
5699 pt->error = -EINVAL;
5703 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5705 pt->error = -ENOMEM;
5708 io_init_poll_iocb(poll, first->events, first->wait.func);
5710 if (req->opcode == IORING_OP_POLL_ADD)
5711 req->flags |= REQ_F_ASYNC_DATA;
5716 poll->wait.private = req;
5718 if (poll->events & EPOLLEXCLUSIVE)
5719 add_wait_queue_exclusive(head, &poll->wait);
5721 add_wait_queue(head, &poll->wait);
5724 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5725 struct poll_table_struct *p)
5727 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5729 __io_queue_proc(&pt->req->poll, pt, head,
5730 (struct io_poll_iocb **) &pt->req->async_data);
5733 static int __io_arm_poll_handler(struct io_kiocb *req,
5734 struct io_poll_iocb *poll,
5735 struct io_poll_table *ipt, __poll_t mask)
5737 struct io_ring_ctx *ctx = req->ctx;
5740 INIT_HLIST_NODE(&req->hash_node);
5741 io_init_poll_iocb(poll, mask, io_poll_wake);
5742 poll->file = req->file;
5743 poll->wait.private = req;
5745 ipt->pt._key = mask;
5748 ipt->nr_entries = 0;
5751 * Take the ownership to delay any tw execution up until we're done
5752 * with poll arming. see io_poll_get_ownership().
5754 atomic_set(&req->poll_refs, 1);
5755 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5757 if (mask && (poll->events & EPOLLONESHOT)) {
5758 io_poll_remove_entries(req);
5759 /* no one else has access to the req, forget about the ref */
5762 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5763 io_poll_remove_entries(req);
5765 ipt->error = -EINVAL;
5769 spin_lock(&ctx->completion_lock);
5770 io_poll_req_insert(req);
5771 spin_unlock(&ctx->completion_lock);
5774 /* can't multishot if failed, just queue the event we've got */
5775 if (unlikely(ipt->error || !ipt->nr_entries))
5776 poll->events |= EPOLLONESHOT;
5777 __io_poll_execute(req, mask);
5782 * Release ownership. If someone tried to queue a tw while it was
5783 * locked, kick it off for them.
5785 v = atomic_dec_return(&req->poll_refs);
5786 if (unlikely(v & IO_POLL_REF_MASK))
5787 __io_poll_execute(req, 0);
5791 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5792 struct poll_table_struct *p)
5794 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5795 struct async_poll *apoll = pt->req->apoll;
5797 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5806 static int io_arm_poll_handler(struct io_kiocb *req)
5808 const struct io_op_def *def = &io_op_defs[req->opcode];
5809 struct io_ring_ctx *ctx = req->ctx;
5810 struct async_poll *apoll;
5811 struct io_poll_table ipt;
5812 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5815 if (!def->pollin && !def->pollout)
5816 return IO_APOLL_ABORTED;
5817 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
5818 return IO_APOLL_ABORTED;
5821 mask |= POLLIN | POLLRDNORM;
5823 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5824 if ((req->opcode == IORING_OP_RECVMSG) &&
5825 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5828 mask |= POLLOUT | POLLWRNORM;
5831 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5832 if (unlikely(!apoll))
5833 return IO_APOLL_ABORTED;
5834 apoll->double_poll = NULL;
5836 req->flags |= REQ_F_POLLED;
5837 ipt.pt._qproc = io_async_queue_proc;
5839 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5840 if (ret || ipt.error)
5841 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5843 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5844 mask, apoll->poll.events);
5849 * Returns true if we found and killed one or more poll requests
5851 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5852 struct task_struct *tsk, bool cancel_all)
5854 struct hlist_node *tmp;
5855 struct io_kiocb *req;
5859 spin_lock(&ctx->completion_lock);
5860 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5861 struct hlist_head *list;
5863 list = &ctx->cancel_hash[i];
5864 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5865 if (io_match_task_safe(req, tsk, cancel_all)) {
5866 io_poll_cancel_req(req);
5871 spin_unlock(&ctx->completion_lock);
5875 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5877 __must_hold(&ctx->completion_lock)
5879 struct hlist_head *list;
5880 struct io_kiocb *req;
5882 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5883 hlist_for_each_entry(req, list, hash_node) {
5884 if (sqe_addr != req->user_data)
5886 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5893 static bool io_poll_disarm(struct io_kiocb *req)
5894 __must_hold(&ctx->completion_lock)
5896 if (!io_poll_get_ownership(req))
5898 io_poll_remove_entries(req);
5899 hash_del(&req->hash_node);
5903 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5905 __must_hold(&ctx->completion_lock)
5907 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
5911 io_poll_cancel_req(req);
5915 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5920 events = READ_ONCE(sqe->poll32_events);
5922 events = swahw32(events);
5924 if (!(flags & IORING_POLL_ADD_MULTI))
5925 events |= EPOLLONESHOT;
5926 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5929 static int io_poll_update_prep(struct io_kiocb *req,
5930 const struct io_uring_sqe *sqe)
5932 struct io_poll_update *upd = &req->poll_update;
5935 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5937 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5939 flags = READ_ONCE(sqe->len);
5940 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5941 IORING_POLL_ADD_MULTI))
5943 /* meaningless without update */
5944 if (flags == IORING_POLL_ADD_MULTI)
5947 upd->old_user_data = READ_ONCE(sqe->addr);
5948 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5949 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5951 upd->new_user_data = READ_ONCE(sqe->off);
5952 if (!upd->update_user_data && upd->new_user_data)
5954 if (upd->update_events)
5955 upd->events = io_poll_parse_events(sqe, flags);
5956 else if (sqe->poll32_events)
5962 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5964 struct io_poll_iocb *poll = &req->poll;
5967 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5969 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5971 flags = READ_ONCE(sqe->len);
5972 if (flags & ~IORING_POLL_ADD_MULTI)
5974 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
5977 io_req_set_refcount(req);
5978 poll->events = io_poll_parse_events(sqe, flags);
5982 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5984 struct io_poll_iocb *poll = &req->poll;
5985 struct io_poll_table ipt;
5988 ipt.pt._qproc = io_poll_queue_proc;
5990 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
5991 ret = ret ?: ipt.error;
5993 __io_req_complete(req, issue_flags, ret, 0);
5997 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5999 struct io_ring_ctx *ctx = req->ctx;
6000 struct io_kiocb *preq;
6004 spin_lock(&ctx->completion_lock);
6005 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6006 if (!preq || !io_poll_disarm(preq)) {
6007 spin_unlock(&ctx->completion_lock);
6008 ret = preq ? -EALREADY : -ENOENT;
6011 spin_unlock(&ctx->completion_lock);
6013 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6014 /* only mask one event flags, keep behavior flags */
6015 if (req->poll_update.update_events) {
6016 preq->poll.events &= ~0xffff;
6017 preq->poll.events |= req->poll_update.events & 0xffff;
6018 preq->poll.events |= IO_POLL_UNMASK;
6020 if (req->poll_update.update_user_data)
6021 preq->user_data = req->poll_update.new_user_data;
6023 ret2 = io_poll_add(preq, issue_flags);
6024 /* successfully updated, don't complete poll request */
6030 preq->result = -ECANCELED;
6031 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6032 io_req_task_complete(preq, &locked);
6036 /* complete update request, we're done with it */
6037 __io_req_complete(req, issue_flags, ret, 0);
6041 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6043 struct io_timeout_data *data = container_of(timer,
6044 struct io_timeout_data, timer);
6045 struct io_kiocb *req = data->req;
6046 struct io_ring_ctx *ctx = req->ctx;
6047 unsigned long flags;
6049 spin_lock_irqsave(&ctx->timeout_lock, flags);
6050 list_del_init(&req->timeout.list);
6051 atomic_set(&req->ctx->cq_timeouts,
6052 atomic_read(&req->ctx->cq_timeouts) + 1);
6053 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6055 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6058 req->result = -ETIME;
6059 req->io_task_work.func = io_req_task_complete;
6060 io_req_task_work_add(req, false);
6061 return HRTIMER_NORESTART;
6064 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6066 __must_hold(&ctx->timeout_lock)
6068 struct io_timeout_data *io;
6069 struct io_kiocb *req;
6072 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6073 found = user_data == req->user_data;
6078 return ERR_PTR(-ENOENT);
6080 io = req->async_data;
6081 if (hrtimer_try_to_cancel(&io->timer) == -1)
6082 return ERR_PTR(-EALREADY);
6083 list_del_init(&req->timeout.list);
6087 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6088 __must_hold(&ctx->completion_lock)
6089 __must_hold(&ctx->timeout_lock)
6091 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6094 return PTR_ERR(req);
6097 io_fill_cqe_req(req, -ECANCELED, 0);
6098 io_put_req_deferred(req);
6102 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6104 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6105 case IORING_TIMEOUT_BOOTTIME:
6106 return CLOCK_BOOTTIME;
6107 case IORING_TIMEOUT_REALTIME:
6108 return CLOCK_REALTIME;
6110 /* can't happen, vetted at prep time */
6114 return CLOCK_MONOTONIC;
6118 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6119 struct timespec64 *ts, enum hrtimer_mode mode)
6120 __must_hold(&ctx->timeout_lock)
6122 struct io_timeout_data *io;
6123 struct io_kiocb *req;
6126 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6127 found = user_data == req->user_data;
6134 io = req->async_data;
6135 if (hrtimer_try_to_cancel(&io->timer) == -1)
6137 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6138 io->timer.function = io_link_timeout_fn;
6139 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6143 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6144 struct timespec64 *ts, enum hrtimer_mode mode)
6145 __must_hold(&ctx->timeout_lock)
6147 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6148 struct io_timeout_data *data;
6151 return PTR_ERR(req);
6153 req->timeout.off = 0; /* noseq */
6154 data = req->async_data;
6155 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6156 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6157 data->timer.function = io_timeout_fn;
6158 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6162 static int io_timeout_remove_prep(struct io_kiocb *req,
6163 const struct io_uring_sqe *sqe)
6165 struct io_timeout_rem *tr = &req->timeout_rem;
6167 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6169 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6171 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6174 tr->ltimeout = false;
6175 tr->addr = READ_ONCE(sqe->addr);
6176 tr->flags = READ_ONCE(sqe->timeout_flags);
6177 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6178 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6180 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6181 tr->ltimeout = true;
6182 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6184 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6186 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6188 } else if (tr->flags) {
6189 /* timeout removal doesn't support flags */
6196 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6198 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6203 * Remove or update an existing timeout command
6205 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6207 struct io_timeout_rem *tr = &req->timeout_rem;
6208 struct io_ring_ctx *ctx = req->ctx;
6211 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6212 spin_lock(&ctx->completion_lock);
6213 spin_lock_irq(&ctx->timeout_lock);
6214 ret = io_timeout_cancel(ctx, tr->addr);
6215 spin_unlock_irq(&ctx->timeout_lock);
6216 spin_unlock(&ctx->completion_lock);
6218 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6220 spin_lock_irq(&ctx->timeout_lock);
6222 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6224 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6225 spin_unlock_irq(&ctx->timeout_lock);
6230 io_req_complete_post(req, ret, 0);
6234 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6235 bool is_timeout_link)
6237 struct io_timeout_data *data;
6239 u32 off = READ_ONCE(sqe->off);
6241 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6243 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6246 if (off && is_timeout_link)
6248 flags = READ_ONCE(sqe->timeout_flags);
6249 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6250 IORING_TIMEOUT_ETIME_SUCCESS))
6252 /* more than one clock specified is invalid, obviously */
6253 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6256 INIT_LIST_HEAD(&req->timeout.list);
6257 req->timeout.off = off;
6258 if (unlikely(off && !req->ctx->off_timeout_used))
6259 req->ctx->off_timeout_used = true;
6261 if (WARN_ON_ONCE(req_has_async_data(req)))
6263 if (io_alloc_async_data(req))
6266 data = req->async_data;
6268 data->flags = flags;
6270 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6273 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6276 data->mode = io_translate_timeout_mode(flags);
6277 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6279 if (is_timeout_link) {
6280 struct io_submit_link *link = &req->ctx->submit_state.link;
6284 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6286 req->timeout.head = link->last;
6287 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6292 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6294 struct io_ring_ctx *ctx = req->ctx;
6295 struct io_timeout_data *data = req->async_data;
6296 struct list_head *entry;
6297 u32 tail, off = req->timeout.off;
6299 spin_lock_irq(&ctx->timeout_lock);
6302 * sqe->off holds how many events that need to occur for this
6303 * timeout event to be satisfied. If it isn't set, then this is
6304 * a pure timeout request, sequence isn't used.
6306 if (io_is_timeout_noseq(req)) {
6307 entry = ctx->timeout_list.prev;
6311 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6312 req->timeout.target_seq = tail + off;
6314 /* Update the last seq here in case io_flush_timeouts() hasn't.
6315 * This is safe because ->completion_lock is held, and submissions
6316 * and completions are never mixed in the same ->completion_lock section.
6318 ctx->cq_last_tm_flush = tail;
6321 * Insertion sort, ensuring the first entry in the list is always
6322 * the one we need first.
6324 list_for_each_prev(entry, &ctx->timeout_list) {
6325 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6328 if (io_is_timeout_noseq(nxt))
6330 /* nxt.seq is behind @tail, otherwise would've been completed */
6331 if (off >= nxt->timeout.target_seq - tail)
6335 list_add(&req->timeout.list, entry);
6336 data->timer.function = io_timeout_fn;
6337 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6338 spin_unlock_irq(&ctx->timeout_lock);
6342 struct io_cancel_data {
6343 struct io_ring_ctx *ctx;
6347 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6349 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6350 struct io_cancel_data *cd = data;
6352 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6355 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6356 struct io_ring_ctx *ctx)
6358 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6359 enum io_wq_cancel cancel_ret;
6362 if (!tctx || !tctx->io_wq)
6365 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6366 switch (cancel_ret) {
6367 case IO_WQ_CANCEL_OK:
6370 case IO_WQ_CANCEL_RUNNING:
6373 case IO_WQ_CANCEL_NOTFOUND:
6381 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6383 struct io_ring_ctx *ctx = req->ctx;
6386 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6388 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6390 * Fall-through even for -EALREADY, as we may have poll armed
6391 * that need unarming.
6396 spin_lock(&ctx->completion_lock);
6397 ret = io_poll_cancel(ctx, sqe_addr, false);
6401 spin_lock_irq(&ctx->timeout_lock);
6402 ret = io_timeout_cancel(ctx, sqe_addr);
6403 spin_unlock_irq(&ctx->timeout_lock);
6405 spin_unlock(&ctx->completion_lock);
6409 static int io_async_cancel_prep(struct io_kiocb *req,
6410 const struct io_uring_sqe *sqe)
6412 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6414 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6416 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6420 req->cancel.addr = READ_ONCE(sqe->addr);
6424 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6426 struct io_ring_ctx *ctx = req->ctx;
6427 u64 sqe_addr = req->cancel.addr;
6428 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6429 struct io_tctx_node *node;
6432 ret = io_try_cancel_userdata(req, sqe_addr);
6436 /* slow path, try all io-wq's */
6437 io_ring_submit_lock(ctx, needs_lock);
6439 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6440 struct io_uring_task *tctx = node->task->io_uring;
6442 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6446 io_ring_submit_unlock(ctx, needs_lock);
6450 io_req_complete_post(req, ret, 0);
6454 static int io_rsrc_update_prep(struct io_kiocb *req,
6455 const struct io_uring_sqe *sqe)
6457 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6459 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6462 req->rsrc_update.offset = READ_ONCE(sqe->off);
6463 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6464 if (!req->rsrc_update.nr_args)
6466 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6470 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6472 struct io_ring_ctx *ctx = req->ctx;
6473 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6474 struct io_uring_rsrc_update2 up;
6477 up.offset = req->rsrc_update.offset;
6478 up.data = req->rsrc_update.arg;
6483 io_ring_submit_lock(ctx, needs_lock);
6484 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6485 &up, req->rsrc_update.nr_args);
6486 io_ring_submit_unlock(ctx, needs_lock);
6490 __io_req_complete(req, issue_flags, ret, 0);
6494 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6496 switch (req->opcode) {
6499 case IORING_OP_READV:
6500 case IORING_OP_READ_FIXED:
6501 case IORING_OP_READ:
6502 return io_read_prep(req, sqe);
6503 case IORING_OP_WRITEV:
6504 case IORING_OP_WRITE_FIXED:
6505 case IORING_OP_WRITE:
6506 return io_write_prep(req, sqe);
6507 case IORING_OP_POLL_ADD:
6508 return io_poll_add_prep(req, sqe);
6509 case IORING_OP_POLL_REMOVE:
6510 return io_poll_update_prep(req, sqe);
6511 case IORING_OP_FSYNC:
6512 return io_fsync_prep(req, sqe);
6513 case IORING_OP_SYNC_FILE_RANGE:
6514 return io_sfr_prep(req, sqe);
6515 case IORING_OP_SENDMSG:
6516 case IORING_OP_SEND:
6517 return io_sendmsg_prep(req, sqe);
6518 case IORING_OP_RECVMSG:
6519 case IORING_OP_RECV:
6520 return io_recvmsg_prep(req, sqe);
6521 case IORING_OP_CONNECT:
6522 return io_connect_prep(req, sqe);
6523 case IORING_OP_TIMEOUT:
6524 return io_timeout_prep(req, sqe, false);
6525 case IORING_OP_TIMEOUT_REMOVE:
6526 return io_timeout_remove_prep(req, sqe);
6527 case IORING_OP_ASYNC_CANCEL:
6528 return io_async_cancel_prep(req, sqe);
6529 case IORING_OP_LINK_TIMEOUT:
6530 return io_timeout_prep(req, sqe, true);
6531 case IORING_OP_ACCEPT:
6532 return io_accept_prep(req, sqe);
6533 case IORING_OP_FALLOCATE:
6534 return io_fallocate_prep(req, sqe);
6535 case IORING_OP_OPENAT:
6536 return io_openat_prep(req, sqe);
6537 case IORING_OP_CLOSE:
6538 return io_close_prep(req, sqe);
6539 case IORING_OP_FILES_UPDATE:
6540 return io_rsrc_update_prep(req, sqe);
6541 case IORING_OP_STATX:
6542 return io_statx_prep(req, sqe);
6543 case IORING_OP_FADVISE:
6544 return io_fadvise_prep(req, sqe);
6545 case IORING_OP_MADVISE:
6546 return io_madvise_prep(req, sqe);
6547 case IORING_OP_OPENAT2:
6548 return io_openat2_prep(req, sqe);
6549 case IORING_OP_EPOLL_CTL:
6550 return io_epoll_ctl_prep(req, sqe);
6551 case IORING_OP_SPLICE:
6552 return io_splice_prep(req, sqe);
6553 case IORING_OP_PROVIDE_BUFFERS:
6554 return io_provide_buffers_prep(req, sqe);
6555 case IORING_OP_REMOVE_BUFFERS:
6556 return io_remove_buffers_prep(req, sqe);
6558 return io_tee_prep(req, sqe);
6559 case IORING_OP_SHUTDOWN:
6560 return io_shutdown_prep(req, sqe);
6561 case IORING_OP_RENAMEAT:
6562 return io_renameat_prep(req, sqe);
6563 case IORING_OP_UNLINKAT:
6564 return io_unlinkat_prep(req, sqe);
6565 case IORING_OP_MKDIRAT:
6566 return io_mkdirat_prep(req, sqe);
6567 case IORING_OP_SYMLINKAT:
6568 return io_symlinkat_prep(req, sqe);
6569 case IORING_OP_LINKAT:
6570 return io_linkat_prep(req, sqe);
6573 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6578 static int io_req_prep_async(struct io_kiocb *req)
6580 if (!io_op_defs[req->opcode].needs_async_setup)
6582 if (WARN_ON_ONCE(req_has_async_data(req)))
6584 if (io_alloc_async_data(req))
6587 switch (req->opcode) {
6588 case IORING_OP_READV:
6589 return io_rw_prep_async(req, READ);
6590 case IORING_OP_WRITEV:
6591 return io_rw_prep_async(req, WRITE);
6592 case IORING_OP_SENDMSG:
6593 return io_sendmsg_prep_async(req);
6594 case IORING_OP_RECVMSG:
6595 return io_recvmsg_prep_async(req);
6596 case IORING_OP_CONNECT:
6597 return io_connect_prep_async(req);
6599 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6604 static u32 io_get_sequence(struct io_kiocb *req)
6606 u32 seq = req->ctx->cached_sq_head;
6608 /* need original cached_sq_head, but it was increased for each req */
6609 io_for_each_link(req, req)
6614 static __cold void io_drain_req(struct io_kiocb *req)
6616 struct io_ring_ctx *ctx = req->ctx;
6617 struct io_defer_entry *de;
6619 u32 seq = io_get_sequence(req);
6621 /* Still need defer if there is pending req in defer list. */
6622 spin_lock(&ctx->completion_lock);
6623 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6624 spin_unlock(&ctx->completion_lock);
6626 ctx->drain_active = false;
6627 io_req_task_queue(req);
6630 spin_unlock(&ctx->completion_lock);
6632 ret = io_req_prep_async(req);
6635 io_req_complete_failed(req, ret);
6638 io_prep_async_link(req);
6639 de = kmalloc(sizeof(*de), GFP_KERNEL);
6645 spin_lock(&ctx->completion_lock);
6646 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6647 spin_unlock(&ctx->completion_lock);
6652 trace_io_uring_defer(ctx, req, req->user_data);
6655 list_add_tail(&de->list, &ctx->defer_list);
6656 spin_unlock(&ctx->completion_lock);
6659 static void io_clean_op(struct io_kiocb *req)
6661 if (req->flags & REQ_F_BUFFER_SELECTED)
6664 if (req->flags & REQ_F_NEED_CLEANUP) {
6665 switch (req->opcode) {
6666 case IORING_OP_READV:
6667 case IORING_OP_READ_FIXED:
6668 case IORING_OP_READ:
6669 case IORING_OP_WRITEV:
6670 case IORING_OP_WRITE_FIXED:
6671 case IORING_OP_WRITE: {
6672 struct io_async_rw *io = req->async_data;
6674 kfree(io->free_iovec);
6677 case IORING_OP_RECVMSG:
6678 case IORING_OP_SENDMSG: {
6679 struct io_async_msghdr *io = req->async_data;
6681 kfree(io->free_iov);
6684 case IORING_OP_SPLICE:
6686 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6687 io_put_file(req->splice.file_in);
6689 case IORING_OP_OPENAT:
6690 case IORING_OP_OPENAT2:
6691 if (req->open.filename)
6692 putname(req->open.filename);
6694 case IORING_OP_RENAMEAT:
6695 putname(req->rename.oldpath);
6696 putname(req->rename.newpath);
6698 case IORING_OP_UNLINKAT:
6699 putname(req->unlink.filename);
6701 case IORING_OP_MKDIRAT:
6702 putname(req->mkdir.filename);
6704 case IORING_OP_SYMLINKAT:
6705 putname(req->symlink.oldpath);
6706 putname(req->symlink.newpath);
6708 case IORING_OP_LINKAT:
6709 putname(req->hardlink.oldpath);
6710 putname(req->hardlink.newpath);
6714 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6715 kfree(req->apoll->double_poll);
6719 if (req->flags & REQ_F_INFLIGHT) {
6720 struct io_uring_task *tctx = req->task->io_uring;
6722 atomic_dec(&tctx->inflight_tracked);
6724 if (req->flags & REQ_F_CREDS)
6725 put_cred(req->creds);
6726 if (req->flags & REQ_F_ASYNC_DATA) {
6727 kfree(req->async_data);
6728 req->async_data = NULL;
6730 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6733 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6735 const struct cred *creds = NULL;
6738 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6739 creds = override_creds(req->creds);
6741 if (!io_op_defs[req->opcode].audit_skip)
6742 audit_uring_entry(req->opcode);
6744 switch (req->opcode) {
6746 ret = io_nop(req, issue_flags);
6748 case IORING_OP_READV:
6749 case IORING_OP_READ_FIXED:
6750 case IORING_OP_READ:
6751 ret = io_read(req, issue_flags);
6753 case IORING_OP_WRITEV:
6754 case IORING_OP_WRITE_FIXED:
6755 case IORING_OP_WRITE:
6756 ret = io_write(req, issue_flags);
6758 case IORING_OP_FSYNC:
6759 ret = io_fsync(req, issue_flags);
6761 case IORING_OP_POLL_ADD:
6762 ret = io_poll_add(req, issue_flags);
6764 case IORING_OP_POLL_REMOVE:
6765 ret = io_poll_update(req, issue_flags);
6767 case IORING_OP_SYNC_FILE_RANGE:
6768 ret = io_sync_file_range(req, issue_flags);
6770 case IORING_OP_SENDMSG:
6771 ret = io_sendmsg(req, issue_flags);
6773 case IORING_OP_SEND:
6774 ret = io_send(req, issue_flags);
6776 case IORING_OP_RECVMSG:
6777 ret = io_recvmsg(req, issue_flags);
6779 case IORING_OP_RECV:
6780 ret = io_recv(req, issue_flags);
6782 case IORING_OP_TIMEOUT:
6783 ret = io_timeout(req, issue_flags);
6785 case IORING_OP_TIMEOUT_REMOVE:
6786 ret = io_timeout_remove(req, issue_flags);
6788 case IORING_OP_ACCEPT:
6789 ret = io_accept(req, issue_flags);
6791 case IORING_OP_CONNECT:
6792 ret = io_connect(req, issue_flags);
6794 case IORING_OP_ASYNC_CANCEL:
6795 ret = io_async_cancel(req, issue_flags);
6797 case IORING_OP_FALLOCATE:
6798 ret = io_fallocate(req, issue_flags);
6800 case IORING_OP_OPENAT:
6801 ret = io_openat(req, issue_flags);
6803 case IORING_OP_CLOSE:
6804 ret = io_close(req, issue_flags);
6806 case IORING_OP_FILES_UPDATE:
6807 ret = io_files_update(req, issue_flags);
6809 case IORING_OP_STATX:
6810 ret = io_statx(req, issue_flags);
6812 case IORING_OP_FADVISE:
6813 ret = io_fadvise(req, issue_flags);
6815 case IORING_OP_MADVISE:
6816 ret = io_madvise(req, issue_flags);
6818 case IORING_OP_OPENAT2:
6819 ret = io_openat2(req, issue_flags);
6821 case IORING_OP_EPOLL_CTL:
6822 ret = io_epoll_ctl(req, issue_flags);
6824 case IORING_OP_SPLICE:
6825 ret = io_splice(req, issue_flags);
6827 case IORING_OP_PROVIDE_BUFFERS:
6828 ret = io_provide_buffers(req, issue_flags);
6830 case IORING_OP_REMOVE_BUFFERS:
6831 ret = io_remove_buffers(req, issue_flags);
6834 ret = io_tee(req, issue_flags);
6836 case IORING_OP_SHUTDOWN:
6837 ret = io_shutdown(req, issue_flags);
6839 case IORING_OP_RENAMEAT:
6840 ret = io_renameat(req, issue_flags);
6842 case IORING_OP_UNLINKAT:
6843 ret = io_unlinkat(req, issue_flags);
6845 case IORING_OP_MKDIRAT:
6846 ret = io_mkdirat(req, issue_flags);
6848 case IORING_OP_SYMLINKAT:
6849 ret = io_symlinkat(req, issue_flags);
6851 case IORING_OP_LINKAT:
6852 ret = io_linkat(req, issue_flags);
6859 if (!io_op_defs[req->opcode].audit_skip)
6860 audit_uring_exit(!ret, ret);
6863 revert_creds(creds);
6866 /* If the op doesn't have a file, we're not polling for it */
6867 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6868 io_iopoll_req_issued(req, issue_flags);
6873 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6875 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6877 req = io_put_req_find_next(req);
6878 return req ? &req->work : NULL;
6881 static void io_wq_submit_work(struct io_wq_work *work)
6883 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6884 unsigned int issue_flags = IO_URING_F_UNLOCKED;
6885 bool needs_poll = false;
6886 struct io_kiocb *timeout;
6889 /* one will be dropped by ->io_free_work() after returning to io-wq */
6890 if (!(req->flags & REQ_F_REFCOUNT))
6891 __io_req_set_refcount(req, 2);
6895 timeout = io_prep_linked_timeout(req);
6897 io_queue_linked_timeout(timeout);
6899 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6900 if (work->flags & IO_WQ_WORK_CANCEL) {
6901 io_req_task_queue_fail(req, -ECANCELED);
6905 if (req->flags & REQ_F_FORCE_ASYNC) {
6906 const struct io_op_def *def = &io_op_defs[req->opcode];
6907 bool opcode_poll = def->pollin || def->pollout;
6909 if (opcode_poll && file_can_poll(req->file)) {
6911 issue_flags |= IO_URING_F_NONBLOCK;
6916 ret = io_issue_sqe(req, issue_flags);
6920 * We can get EAGAIN for iopolled IO even though we're
6921 * forcing a sync submission from here, since we can't
6922 * wait for request slots on the block side.
6929 if (io_arm_poll_handler(req) == IO_APOLL_OK)
6931 /* aborted or ready, in either case retry blocking */
6933 issue_flags &= ~IO_URING_F_NONBLOCK;
6936 /* avoid locking problems by failing it from a clean context */
6938 io_req_task_queue_fail(req, ret);
6941 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6944 return &table->files[i];
6947 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6950 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6952 return (struct file *) (slot->file_ptr & FFS_MASK);
6955 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6957 unsigned long file_ptr = (unsigned long) file;
6959 file_ptr |= io_file_get_flags(file);
6960 file_slot->file_ptr = file_ptr;
6963 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6964 struct io_kiocb *req, int fd)
6967 unsigned long file_ptr;
6969 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6971 fd = array_index_nospec(fd, ctx->nr_user_files);
6972 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6973 file = (struct file *) (file_ptr & FFS_MASK);
6974 file_ptr &= ~FFS_MASK;
6975 /* mask in overlapping REQ_F and FFS bits */
6976 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6977 io_req_set_rsrc_node(req, ctx);
6981 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6982 struct io_kiocb *req, int fd)
6984 struct file *file = fget(fd);
6986 trace_io_uring_file_get(ctx, fd);
6988 /* we don't allow fixed io_uring files */
6989 if (file && unlikely(file->f_op == &io_uring_fops))
6990 io_req_track_inflight(req);
6994 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6995 struct io_kiocb *req, int fd, bool fixed)
6998 return io_file_get_fixed(ctx, req, fd);
7000 return io_file_get_normal(ctx, req, fd);
7003 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7005 struct io_kiocb *prev = req->timeout.prev;
7009 if (!(req->task->flags & PF_EXITING))
7010 ret = io_try_cancel_userdata(req, prev->user_data);
7011 io_req_complete_post(req, ret ?: -ETIME, 0);
7014 io_req_complete_post(req, -ETIME, 0);
7018 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7020 struct io_timeout_data *data = container_of(timer,
7021 struct io_timeout_data, timer);
7022 struct io_kiocb *prev, *req = data->req;
7023 struct io_ring_ctx *ctx = req->ctx;
7024 unsigned long flags;
7026 spin_lock_irqsave(&ctx->timeout_lock, flags);
7027 prev = req->timeout.head;
7028 req->timeout.head = NULL;
7031 * We don't expect the list to be empty, that will only happen if we
7032 * race with the completion of the linked work.
7035 io_remove_next_linked(prev);
7036 if (!req_ref_inc_not_zero(prev))
7039 list_del(&req->timeout.list);
7040 req->timeout.prev = prev;
7041 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7043 req->io_task_work.func = io_req_task_link_timeout;
7044 io_req_task_work_add(req, false);
7045 return HRTIMER_NORESTART;
7048 static void io_queue_linked_timeout(struct io_kiocb *req)
7050 struct io_ring_ctx *ctx = req->ctx;
7052 spin_lock_irq(&ctx->timeout_lock);
7054 * If the back reference is NULL, then our linked request finished
7055 * before we got a chance to setup the timer
7057 if (req->timeout.head) {
7058 struct io_timeout_data *data = req->async_data;
7060 data->timer.function = io_link_timeout_fn;
7061 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7063 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7065 spin_unlock_irq(&ctx->timeout_lock);
7066 /* drop submission reference */
7070 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7071 __must_hold(&req->ctx->uring_lock)
7073 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7075 switch (io_arm_poll_handler(req)) {
7076 case IO_APOLL_READY:
7077 io_req_task_queue(req);
7079 case IO_APOLL_ABORTED:
7081 * Queued up for async execution, worker will release
7082 * submit reference when the iocb is actually submitted.
7084 io_queue_async_work(req, NULL);
7089 io_queue_linked_timeout(linked_timeout);
7092 static inline void __io_queue_sqe(struct io_kiocb *req)
7093 __must_hold(&req->ctx->uring_lock)
7095 struct io_kiocb *linked_timeout;
7098 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7100 if (req->flags & REQ_F_COMPLETE_INLINE) {
7101 io_req_add_compl_list(req);
7105 * We async punt it if the file wasn't marked NOWAIT, or if the file
7106 * doesn't support non-blocking read/write attempts
7109 linked_timeout = io_prep_linked_timeout(req);
7111 io_queue_linked_timeout(linked_timeout);
7112 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7113 io_queue_sqe_arm_apoll(req);
7115 io_req_complete_failed(req, ret);
7119 static void io_queue_sqe_fallback(struct io_kiocb *req)
7120 __must_hold(&req->ctx->uring_lock)
7122 if (req->flags & REQ_F_FAIL) {
7123 io_req_complete_fail_submit(req);
7124 } else if (unlikely(req->ctx->drain_active)) {
7127 int ret = io_req_prep_async(req);
7130 io_req_complete_failed(req, ret);
7132 io_queue_async_work(req, NULL);
7136 static inline void io_queue_sqe(struct io_kiocb *req)
7137 __must_hold(&req->ctx->uring_lock)
7139 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7140 __io_queue_sqe(req);
7142 io_queue_sqe_fallback(req);
7146 * Check SQE restrictions (opcode and flags).
7148 * Returns 'true' if SQE is allowed, 'false' otherwise.
7150 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7151 struct io_kiocb *req,
7152 unsigned int sqe_flags)
7154 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7157 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7158 ctx->restrictions.sqe_flags_required)
7161 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7162 ctx->restrictions.sqe_flags_required))
7168 static void io_init_req_drain(struct io_kiocb *req)
7170 struct io_ring_ctx *ctx = req->ctx;
7171 struct io_kiocb *head = ctx->submit_state.link.head;
7173 ctx->drain_active = true;
7176 * If we need to drain a request in the middle of a link, drain
7177 * the head request and the next request/link after the current
7178 * link. Considering sequential execution of links,
7179 * REQ_F_IO_DRAIN will be maintained for every request of our
7182 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7183 ctx->drain_next = true;
7187 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7188 const struct io_uring_sqe *sqe)
7189 __must_hold(&ctx->uring_lock)
7191 unsigned int sqe_flags;
7195 /* req is partially pre-initialised, see io_preinit_req() */
7196 req->opcode = opcode = READ_ONCE(sqe->opcode);
7197 /* same numerical values with corresponding REQ_F_*, safe to copy */
7198 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7199 req->user_data = READ_ONCE(sqe->user_data);
7201 req->fixed_rsrc_refs = NULL;
7202 req->task = current;
7204 if (unlikely(opcode >= IORING_OP_LAST)) {
7208 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7209 /* enforce forwards compatibility on users */
7210 if (sqe_flags & ~SQE_VALID_FLAGS)
7212 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7213 !io_op_defs[opcode].buffer_select)
7215 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7216 ctx->drain_disabled = true;
7217 if (sqe_flags & IOSQE_IO_DRAIN) {
7218 if (ctx->drain_disabled)
7220 io_init_req_drain(req);
7223 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7224 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7226 /* knock it to the slow queue path, will be drained there */
7227 if (ctx->drain_active)
7228 req->flags |= REQ_F_FORCE_ASYNC;
7229 /* if there is no link, we're at "next" request and need to drain */
7230 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7231 ctx->drain_next = false;
7232 ctx->drain_active = true;
7233 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7237 if (io_op_defs[opcode].needs_file) {
7238 struct io_submit_state *state = &ctx->submit_state;
7241 * Plug now if we have more than 2 IO left after this, and the
7242 * target is potentially a read/write to block based storage.
7244 if (state->need_plug && io_op_defs[opcode].plug) {
7245 state->plug_started = true;
7246 state->need_plug = false;
7247 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7250 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7251 (sqe_flags & IOSQE_FIXED_FILE));
7252 if (unlikely(!req->file))
7256 personality = READ_ONCE(sqe->personality);
7260 req->creds = xa_load(&ctx->personalities, personality);
7263 get_cred(req->creds);
7264 ret = security_uring_override_creds(req->creds);
7266 put_cred(req->creds);
7269 req->flags |= REQ_F_CREDS;
7272 return io_req_prep(req, sqe);
7275 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7276 const struct io_uring_sqe *sqe)
7277 __must_hold(&ctx->uring_lock)
7279 struct io_submit_link *link = &ctx->submit_state.link;
7282 ret = io_init_req(ctx, req, sqe);
7283 if (unlikely(ret)) {
7284 trace_io_uring_req_failed(sqe, ret);
7286 /* fail even hard links since we don't submit */
7289 * we can judge a link req is failed or cancelled by if
7290 * REQ_F_FAIL is set, but the head is an exception since
7291 * it may be set REQ_F_FAIL because of other req's failure
7292 * so let's leverage req->result to distinguish if a head
7293 * is set REQ_F_FAIL because of its failure or other req's
7294 * failure so that we can set the correct ret code for it.
7295 * init result here to avoid affecting the normal path.
7297 if (!(link->head->flags & REQ_F_FAIL))
7298 req_fail_link_node(link->head, -ECANCELED);
7299 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7301 * the current req is a normal req, we should return
7302 * error and thus break the submittion loop.
7304 io_req_complete_failed(req, ret);
7307 req_fail_link_node(req, ret);
7310 /* don't need @sqe from now on */
7311 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7313 ctx->flags & IORING_SETUP_SQPOLL);
7316 * If we already have a head request, queue this one for async
7317 * submittal once the head completes. If we don't have a head but
7318 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7319 * submitted sync once the chain is complete. If none of those
7320 * conditions are true (normal request), then just queue it.
7323 struct io_kiocb *head = link->head;
7325 if (!(req->flags & REQ_F_FAIL)) {
7326 ret = io_req_prep_async(req);
7327 if (unlikely(ret)) {
7328 req_fail_link_node(req, ret);
7329 if (!(head->flags & REQ_F_FAIL))
7330 req_fail_link_node(head, -ECANCELED);
7333 trace_io_uring_link(ctx, req, head);
7334 link->last->link = req;
7337 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7339 /* last request of a link, enqueue the link */
7342 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7353 * Batched submission is done, ensure local IO is flushed out.
7355 static void io_submit_state_end(struct io_ring_ctx *ctx)
7357 struct io_submit_state *state = &ctx->submit_state;
7359 if (state->link.head)
7360 io_queue_sqe(state->link.head);
7361 /* flush only after queuing links as they can generate completions */
7362 io_submit_flush_completions(ctx);
7363 if (state->plug_started)
7364 blk_finish_plug(&state->plug);
7368 * Start submission side cache.
7370 static void io_submit_state_start(struct io_submit_state *state,
7371 unsigned int max_ios)
7373 state->plug_started = false;
7374 state->need_plug = max_ios > 2;
7375 state->submit_nr = max_ios;
7376 /* set only head, no need to init link_last in advance */
7377 state->link.head = NULL;
7380 static void io_commit_sqring(struct io_ring_ctx *ctx)
7382 struct io_rings *rings = ctx->rings;
7385 * Ensure any loads from the SQEs are done at this point,
7386 * since once we write the new head, the application could
7387 * write new data to them.
7389 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7393 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7394 * that is mapped by userspace. This means that care needs to be taken to
7395 * ensure that reads are stable, as we cannot rely on userspace always
7396 * being a good citizen. If members of the sqe are validated and then later
7397 * used, it's important that those reads are done through READ_ONCE() to
7398 * prevent a re-load down the line.
7400 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7402 unsigned head, mask = ctx->sq_entries - 1;
7403 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7406 * The cached sq head (or cq tail) serves two purposes:
7408 * 1) allows us to batch the cost of updating the user visible
7410 * 2) allows the kernel side to track the head on its own, even
7411 * though the application is the one updating it.
7413 head = READ_ONCE(ctx->sq_array[sq_idx]);
7414 if (likely(head < ctx->sq_entries))
7415 return &ctx->sq_sqes[head];
7417 /* drop invalid entries */
7419 WRITE_ONCE(ctx->rings->sq_dropped,
7420 READ_ONCE(ctx->rings->sq_dropped) + 1);
7424 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7425 __must_hold(&ctx->uring_lock)
7427 unsigned int entries = io_sqring_entries(ctx);
7430 if (unlikely(!entries))
7432 /* make sure SQ entry isn't read before tail */
7433 nr = min3(nr, ctx->sq_entries, entries);
7434 io_get_task_refs(nr);
7436 io_submit_state_start(&ctx->submit_state, nr);
7438 const struct io_uring_sqe *sqe;
7439 struct io_kiocb *req;
7441 if (unlikely(!io_alloc_req_refill(ctx))) {
7443 submitted = -EAGAIN;
7446 req = io_alloc_req(ctx);
7447 sqe = io_get_sqe(ctx);
7448 if (unlikely(!sqe)) {
7449 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7452 /* will complete beyond this point, count as submitted */
7454 if (io_submit_sqe(ctx, req, sqe))
7456 } while (submitted < nr);
7458 if (unlikely(submitted != nr)) {
7459 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7460 int unused = nr - ref_used;
7462 current->io_uring->cached_refs += unused;
7465 io_submit_state_end(ctx);
7466 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7467 io_commit_sqring(ctx);
7472 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7474 return READ_ONCE(sqd->state);
7477 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7479 /* Tell userspace we may need a wakeup call */
7480 spin_lock(&ctx->completion_lock);
7481 WRITE_ONCE(ctx->rings->sq_flags,
7482 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7483 spin_unlock(&ctx->completion_lock);
7486 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7488 spin_lock(&ctx->completion_lock);
7489 WRITE_ONCE(ctx->rings->sq_flags,
7490 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7491 spin_unlock(&ctx->completion_lock);
7494 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7496 unsigned int to_submit;
7499 to_submit = io_sqring_entries(ctx);
7500 /* if we're handling multiple rings, cap submit size for fairness */
7501 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7502 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7504 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7505 const struct cred *creds = NULL;
7507 if (ctx->sq_creds != current_cred())
7508 creds = override_creds(ctx->sq_creds);
7510 mutex_lock(&ctx->uring_lock);
7511 if (!wq_list_empty(&ctx->iopoll_list))
7512 io_do_iopoll(ctx, true);
7515 * Don't submit if refs are dying, good for io_uring_register(),
7516 * but also it is relied upon by io_ring_exit_work()
7518 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7519 !(ctx->flags & IORING_SETUP_R_DISABLED))
7520 ret = io_submit_sqes(ctx, to_submit);
7521 mutex_unlock(&ctx->uring_lock);
7523 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7524 wake_up(&ctx->sqo_sq_wait);
7526 revert_creds(creds);
7532 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7534 struct io_ring_ctx *ctx;
7535 unsigned sq_thread_idle = 0;
7537 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7538 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7539 sqd->sq_thread_idle = sq_thread_idle;
7542 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7544 bool did_sig = false;
7545 struct ksignal ksig;
7547 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7548 signal_pending(current)) {
7549 mutex_unlock(&sqd->lock);
7550 if (signal_pending(current))
7551 did_sig = get_signal(&ksig);
7553 mutex_lock(&sqd->lock);
7555 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7558 static int io_sq_thread(void *data)
7560 struct io_sq_data *sqd = data;
7561 struct io_ring_ctx *ctx;
7562 unsigned long timeout = 0;
7563 char buf[TASK_COMM_LEN];
7566 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7567 set_task_comm(current, buf);
7569 if (sqd->sq_cpu != -1)
7570 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7572 set_cpus_allowed_ptr(current, cpu_online_mask);
7573 current->flags |= PF_NO_SETAFFINITY;
7575 audit_alloc_kernel(current);
7577 mutex_lock(&sqd->lock);
7579 bool cap_entries, sqt_spin = false;
7581 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7582 if (io_sqd_handle_event(sqd))
7584 timeout = jiffies + sqd->sq_thread_idle;
7587 cap_entries = !list_is_singular(&sqd->ctx_list);
7588 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7589 int ret = __io_sq_thread(ctx, cap_entries);
7591 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7594 if (io_run_task_work())
7597 if (sqt_spin || !time_after(jiffies, timeout)) {
7600 timeout = jiffies + sqd->sq_thread_idle;
7604 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7605 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7606 bool needs_sched = true;
7608 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7609 io_ring_set_wakeup_flag(ctx);
7611 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7612 !wq_list_empty(&ctx->iopoll_list)) {
7613 needs_sched = false;
7616 if (io_sqring_entries(ctx)) {
7617 needs_sched = false;
7623 mutex_unlock(&sqd->lock);
7625 mutex_lock(&sqd->lock);
7627 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7628 io_ring_clear_wakeup_flag(ctx);
7631 finish_wait(&sqd->wait, &wait);
7632 timeout = jiffies + sqd->sq_thread_idle;
7635 io_uring_cancel_generic(true, sqd);
7637 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7638 io_ring_set_wakeup_flag(ctx);
7640 mutex_unlock(&sqd->lock);
7642 audit_free(current);
7644 complete(&sqd->exited);
7648 struct io_wait_queue {
7649 struct wait_queue_entry wq;
7650 struct io_ring_ctx *ctx;
7652 unsigned nr_timeouts;
7655 static inline bool io_should_wake(struct io_wait_queue *iowq)
7657 struct io_ring_ctx *ctx = iowq->ctx;
7658 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7661 * Wake up if we have enough events, or if a timeout occurred since we
7662 * started waiting. For timeouts, we always want to return to userspace,
7663 * regardless of event count.
7665 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7668 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7669 int wake_flags, void *key)
7671 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7675 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7676 * the task, and the next invocation will do it.
7678 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7679 return autoremove_wake_function(curr, mode, wake_flags, key);
7683 static int io_run_task_work_sig(void)
7685 if (io_run_task_work())
7687 if (!signal_pending(current))
7689 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7690 return -ERESTARTSYS;
7694 /* when returns >0, the caller should retry */
7695 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7696 struct io_wait_queue *iowq,
7701 /* make sure we run task_work before checking for signals */
7702 ret = io_run_task_work_sig();
7703 if (ret || io_should_wake(iowq))
7705 /* let the caller flush overflows, retry */
7706 if (test_bit(0, &ctx->check_cq_overflow))
7709 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
7715 * Wait until events become available, if we don't already have some. The
7716 * application must reap them itself, as they reside on the shared cq ring.
7718 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7719 const sigset_t __user *sig, size_t sigsz,
7720 struct __kernel_timespec __user *uts)
7722 struct io_wait_queue iowq;
7723 struct io_rings *rings = ctx->rings;
7724 ktime_t timeout = KTIME_MAX;
7728 io_cqring_overflow_flush(ctx);
7729 if (io_cqring_events(ctx) >= min_events)
7731 if (!io_run_task_work())
7736 struct timespec64 ts;
7738 if (get_timespec64(&ts, uts))
7740 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7744 #ifdef CONFIG_COMPAT
7745 if (in_compat_syscall())
7746 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7750 ret = set_user_sigmask(sig, sigsz);
7756 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7757 iowq.wq.private = current;
7758 INIT_LIST_HEAD(&iowq.wq.entry);
7760 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7761 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7763 trace_io_uring_cqring_wait(ctx, min_events);
7765 /* if we can't even flush overflow, don't wait for more */
7766 if (!io_cqring_overflow_flush(ctx)) {
7770 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7771 TASK_INTERRUPTIBLE);
7772 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
7773 finish_wait(&ctx->cq_wait, &iowq.wq);
7777 restore_saved_sigmask_unless(ret == -EINTR);
7779 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7782 static void io_free_page_table(void **table, size_t size)
7784 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7786 for (i = 0; i < nr_tables; i++)
7791 static __cold void **io_alloc_page_table(size_t size)
7793 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7794 size_t init_size = size;
7797 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7801 for (i = 0; i < nr_tables; i++) {
7802 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7804 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7806 io_free_page_table(table, init_size);
7814 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7816 percpu_ref_exit(&ref_node->refs);
7820 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7822 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7823 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7824 unsigned long flags;
7825 bool first_add = false;
7826 unsigned long delay = HZ;
7828 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7831 /* if we are mid-quiesce then do not delay */
7832 if (node->rsrc_data->quiesce)
7835 while (!list_empty(&ctx->rsrc_ref_list)) {
7836 node = list_first_entry(&ctx->rsrc_ref_list,
7837 struct io_rsrc_node, node);
7838 /* recycle ref nodes in order */
7841 list_del(&node->node);
7842 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7844 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7847 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7850 static struct io_rsrc_node *io_rsrc_node_alloc(void)
7852 struct io_rsrc_node *ref_node;
7854 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7858 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7863 INIT_LIST_HEAD(&ref_node->node);
7864 INIT_LIST_HEAD(&ref_node->rsrc_list);
7865 ref_node->done = false;
7869 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7870 struct io_rsrc_data *data_to_kill)
7871 __must_hold(&ctx->uring_lock)
7873 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7874 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7876 io_rsrc_refs_drop(ctx);
7879 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7881 rsrc_node->rsrc_data = data_to_kill;
7882 spin_lock_irq(&ctx->rsrc_ref_lock);
7883 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7884 spin_unlock_irq(&ctx->rsrc_ref_lock);
7886 atomic_inc(&data_to_kill->refs);
7887 percpu_ref_kill(&rsrc_node->refs);
7888 ctx->rsrc_node = NULL;
7891 if (!ctx->rsrc_node) {
7892 ctx->rsrc_node = ctx->rsrc_backup_node;
7893 ctx->rsrc_backup_node = NULL;
7897 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7899 if (ctx->rsrc_backup_node)
7901 ctx->rsrc_backup_node = io_rsrc_node_alloc();
7902 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7905 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7906 struct io_ring_ctx *ctx)
7910 /* As we may drop ->uring_lock, other task may have started quiesce */
7914 data->quiesce = true;
7916 ret = io_rsrc_node_switch_start(ctx);
7919 io_rsrc_node_switch(ctx, data);
7921 /* kill initial ref, already quiesced if zero */
7922 if (atomic_dec_and_test(&data->refs))
7924 mutex_unlock(&ctx->uring_lock);
7925 flush_delayed_work(&ctx->rsrc_put_work);
7926 ret = wait_for_completion_interruptible(&data->done);
7928 mutex_lock(&ctx->uring_lock);
7929 if (atomic_read(&data->refs) > 0) {
7931 * it has been revived by another thread while
7934 mutex_unlock(&ctx->uring_lock);
7940 atomic_inc(&data->refs);
7941 /* wait for all works potentially completing data->done */
7942 flush_delayed_work(&ctx->rsrc_put_work);
7943 reinit_completion(&data->done);
7945 ret = io_run_task_work_sig();
7946 mutex_lock(&ctx->uring_lock);
7948 data->quiesce = false;
7953 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7955 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7956 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7958 return &data->tags[table_idx][off];
7961 static void io_rsrc_data_free(struct io_rsrc_data *data)
7963 size_t size = data->nr * sizeof(data->tags[0][0]);
7966 io_free_page_table((void **)data->tags, size);
7970 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7971 u64 __user *utags, unsigned nr,
7972 struct io_rsrc_data **pdata)
7974 struct io_rsrc_data *data;
7978 data = kzalloc(sizeof(*data), GFP_KERNEL);
7981 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7989 data->do_put = do_put;
7992 for (i = 0; i < nr; i++) {
7993 u64 *tag_slot = io_get_tag_slot(data, i);
7995 if (copy_from_user(tag_slot, &utags[i],
8001 atomic_set(&data->refs, 1);
8002 init_completion(&data->done);
8006 io_rsrc_data_free(data);
8010 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8012 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8013 GFP_KERNEL_ACCOUNT);
8014 return !!table->files;
8017 static void io_free_file_tables(struct io_file_table *table)
8019 kvfree(table->files);
8020 table->files = NULL;
8023 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8025 #if defined(CONFIG_UNIX)
8026 if (ctx->ring_sock) {
8027 struct sock *sock = ctx->ring_sock->sk;
8028 struct sk_buff *skb;
8030 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8036 for (i = 0; i < ctx->nr_user_files; i++) {
8039 file = io_file_from_index(ctx, i);
8044 io_free_file_tables(&ctx->file_table);
8045 io_rsrc_data_free(ctx->file_data);
8046 ctx->file_data = NULL;
8047 ctx->nr_user_files = 0;
8050 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8054 if (!ctx->file_data)
8056 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8058 __io_sqe_files_unregister(ctx);
8062 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8063 __releases(&sqd->lock)
8065 WARN_ON_ONCE(sqd->thread == current);
8068 * Do the dance but not conditional clear_bit() because it'd race with
8069 * other threads incrementing park_pending and setting the bit.
8071 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8072 if (atomic_dec_return(&sqd->park_pending))
8073 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8074 mutex_unlock(&sqd->lock);
8077 static void io_sq_thread_park(struct io_sq_data *sqd)
8078 __acquires(&sqd->lock)
8080 WARN_ON_ONCE(sqd->thread == current);
8082 atomic_inc(&sqd->park_pending);
8083 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8084 mutex_lock(&sqd->lock);
8086 wake_up_process(sqd->thread);
8089 static void io_sq_thread_stop(struct io_sq_data *sqd)
8091 WARN_ON_ONCE(sqd->thread == current);
8092 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8094 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8095 mutex_lock(&sqd->lock);
8097 wake_up_process(sqd->thread);
8098 mutex_unlock(&sqd->lock);
8099 wait_for_completion(&sqd->exited);
8102 static void io_put_sq_data(struct io_sq_data *sqd)
8104 if (refcount_dec_and_test(&sqd->refs)) {
8105 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8107 io_sq_thread_stop(sqd);
8112 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8114 struct io_sq_data *sqd = ctx->sq_data;
8117 io_sq_thread_park(sqd);
8118 list_del_init(&ctx->sqd_list);
8119 io_sqd_update_thread_idle(sqd);
8120 io_sq_thread_unpark(sqd);
8122 io_put_sq_data(sqd);
8123 ctx->sq_data = NULL;
8127 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8129 struct io_ring_ctx *ctx_attach;
8130 struct io_sq_data *sqd;
8133 f = fdget(p->wq_fd);
8135 return ERR_PTR(-ENXIO);
8136 if (f.file->f_op != &io_uring_fops) {
8138 return ERR_PTR(-EINVAL);
8141 ctx_attach = f.file->private_data;
8142 sqd = ctx_attach->sq_data;
8145 return ERR_PTR(-EINVAL);
8147 if (sqd->task_tgid != current->tgid) {
8149 return ERR_PTR(-EPERM);
8152 refcount_inc(&sqd->refs);
8157 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8160 struct io_sq_data *sqd;
8163 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8164 sqd = io_attach_sq_data(p);
8169 /* fall through for EPERM case, setup new sqd/task */
8170 if (PTR_ERR(sqd) != -EPERM)
8174 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8176 return ERR_PTR(-ENOMEM);
8178 atomic_set(&sqd->park_pending, 0);
8179 refcount_set(&sqd->refs, 1);
8180 INIT_LIST_HEAD(&sqd->ctx_list);
8181 mutex_init(&sqd->lock);
8182 init_waitqueue_head(&sqd->wait);
8183 init_completion(&sqd->exited);
8187 #if defined(CONFIG_UNIX)
8189 * Ensure the UNIX gc is aware of our file set, so we are certain that
8190 * the io_uring can be safely unregistered on process exit, even if we have
8191 * loops in the file referencing.
8193 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8195 struct sock *sk = ctx->ring_sock->sk;
8196 struct scm_fp_list *fpl;
8197 struct sk_buff *skb;
8200 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8204 skb = alloc_skb(0, GFP_KERNEL);
8213 fpl->user = get_uid(current_user());
8214 for (i = 0; i < nr; i++) {
8215 struct file *file = io_file_from_index(ctx, i + offset);
8219 fpl->fp[nr_files] = get_file(file);
8220 unix_inflight(fpl->user, fpl->fp[nr_files]);
8225 fpl->max = SCM_MAX_FD;
8226 fpl->count = nr_files;
8227 UNIXCB(skb).fp = fpl;
8228 skb->destructor = unix_destruct_scm;
8229 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8230 skb_queue_head(&sk->sk_receive_queue, skb);
8232 for (i = 0; i < nr_files; i++)
8243 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8244 * causes regular reference counting to break down. We rely on the UNIX
8245 * garbage collection to take care of this problem for us.
8247 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8249 unsigned left, total;
8253 left = ctx->nr_user_files;
8255 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8257 ret = __io_sqe_files_scm(ctx, this_files, total);
8261 total += this_files;
8267 while (total < ctx->nr_user_files) {
8268 struct file *file = io_file_from_index(ctx, total);
8278 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8284 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8286 struct file *file = prsrc->file;
8287 #if defined(CONFIG_UNIX)
8288 struct sock *sock = ctx->ring_sock->sk;
8289 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8290 struct sk_buff *skb;
8293 __skb_queue_head_init(&list);
8296 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8297 * remove this entry and rearrange the file array.
8299 skb = skb_dequeue(head);
8301 struct scm_fp_list *fp;
8303 fp = UNIXCB(skb).fp;
8304 for (i = 0; i < fp->count; i++) {
8307 if (fp->fp[i] != file)
8310 unix_notinflight(fp->user, fp->fp[i]);
8311 left = fp->count - 1 - i;
8313 memmove(&fp->fp[i], &fp->fp[i + 1],
8314 left * sizeof(struct file *));
8321 __skb_queue_tail(&list, skb);
8331 __skb_queue_tail(&list, skb);
8333 skb = skb_dequeue(head);
8336 if (skb_peek(&list)) {
8337 spin_lock_irq(&head->lock);
8338 while ((skb = __skb_dequeue(&list)) != NULL)
8339 __skb_queue_tail(head, skb);
8340 spin_unlock_irq(&head->lock);
8347 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8349 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8350 struct io_ring_ctx *ctx = rsrc_data->ctx;
8351 struct io_rsrc_put *prsrc, *tmp;
8353 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8354 list_del(&prsrc->list);
8357 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8359 io_ring_submit_lock(ctx, lock_ring);
8360 spin_lock(&ctx->completion_lock);
8361 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8362 io_commit_cqring(ctx);
8363 spin_unlock(&ctx->completion_lock);
8364 io_cqring_ev_posted(ctx);
8365 io_ring_submit_unlock(ctx, lock_ring);
8368 rsrc_data->do_put(ctx, prsrc);
8372 io_rsrc_node_destroy(ref_node);
8373 if (atomic_dec_and_test(&rsrc_data->refs))
8374 complete(&rsrc_data->done);
8377 static void io_rsrc_put_work(struct work_struct *work)
8379 struct io_ring_ctx *ctx;
8380 struct llist_node *node;
8382 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8383 node = llist_del_all(&ctx->rsrc_put_llist);
8386 struct io_rsrc_node *ref_node;
8387 struct llist_node *next = node->next;
8389 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8390 __io_rsrc_put_work(ref_node);
8395 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8396 unsigned nr_args, u64 __user *tags)
8398 __s32 __user *fds = (__s32 __user *) arg;
8407 if (nr_args > IORING_MAX_FIXED_FILES)
8409 if (nr_args > rlimit(RLIMIT_NOFILE))
8411 ret = io_rsrc_node_switch_start(ctx);
8414 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8420 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8423 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8424 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8428 /* allow sparse sets */
8431 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8438 if (unlikely(!file))
8442 * Don't allow io_uring instances to be registered. If UNIX
8443 * isn't enabled, then this causes a reference cycle and this
8444 * instance can never get freed. If UNIX is enabled we'll
8445 * handle it just fine, but there's still no point in allowing
8446 * a ring fd as it doesn't support regular read/write anyway.
8448 if (file->f_op == &io_uring_fops) {
8452 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8455 ret = io_sqe_files_scm(ctx);
8457 __io_sqe_files_unregister(ctx);
8461 io_rsrc_node_switch(ctx, NULL);
8464 for (i = 0; i < ctx->nr_user_files; i++) {
8465 file = io_file_from_index(ctx, i);
8469 io_free_file_tables(&ctx->file_table);
8470 ctx->nr_user_files = 0;
8472 io_rsrc_data_free(ctx->file_data);
8473 ctx->file_data = NULL;
8477 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8480 #if defined(CONFIG_UNIX)
8481 struct sock *sock = ctx->ring_sock->sk;
8482 struct sk_buff_head *head = &sock->sk_receive_queue;
8483 struct sk_buff *skb;
8486 * See if we can merge this file into an existing skb SCM_RIGHTS
8487 * file set. If there's no room, fall back to allocating a new skb
8488 * and filling it in.
8490 spin_lock_irq(&head->lock);
8491 skb = skb_peek(head);
8493 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8495 if (fpl->count < SCM_MAX_FD) {
8496 __skb_unlink(skb, head);
8497 spin_unlock_irq(&head->lock);
8498 fpl->fp[fpl->count] = get_file(file);
8499 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8501 spin_lock_irq(&head->lock);
8502 __skb_queue_head(head, skb);
8507 spin_unlock_irq(&head->lock);
8514 return __io_sqe_files_scm(ctx, 1, index);
8520 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8521 struct io_rsrc_node *node, void *rsrc)
8523 struct io_rsrc_put *prsrc;
8525 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8529 prsrc->tag = *io_get_tag_slot(data, idx);
8531 list_add(&prsrc->list, &node->rsrc_list);
8535 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8536 unsigned int issue_flags, u32 slot_index)
8538 struct io_ring_ctx *ctx = req->ctx;
8539 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8540 bool needs_switch = false;
8541 struct io_fixed_file *file_slot;
8544 io_ring_submit_lock(ctx, needs_lock);
8545 if (file->f_op == &io_uring_fops)
8548 if (!ctx->file_data)
8551 if (slot_index >= ctx->nr_user_files)
8554 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8555 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8557 if (file_slot->file_ptr) {
8558 struct file *old_file;
8560 ret = io_rsrc_node_switch_start(ctx);
8564 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8565 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8566 ctx->rsrc_node, old_file);
8569 file_slot->file_ptr = 0;
8570 needs_switch = true;
8573 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8574 io_fixed_file_set(file_slot, file);
8575 ret = io_sqe_file_register(ctx, file, slot_index);
8577 file_slot->file_ptr = 0;
8584 io_rsrc_node_switch(ctx, ctx->file_data);
8585 io_ring_submit_unlock(ctx, needs_lock);
8591 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8593 unsigned int offset = req->close.file_slot - 1;
8594 struct io_ring_ctx *ctx = req->ctx;
8595 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8596 struct io_fixed_file *file_slot;
8600 io_ring_submit_lock(ctx, needs_lock);
8602 if (unlikely(!ctx->file_data))
8605 if (offset >= ctx->nr_user_files)
8607 ret = io_rsrc_node_switch_start(ctx);
8611 i = array_index_nospec(offset, ctx->nr_user_files);
8612 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8614 if (!file_slot->file_ptr)
8617 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8618 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8622 file_slot->file_ptr = 0;
8623 io_rsrc_node_switch(ctx, ctx->file_data);
8626 io_ring_submit_unlock(ctx, needs_lock);
8630 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8631 struct io_uring_rsrc_update2 *up,
8634 u64 __user *tags = u64_to_user_ptr(up->tags);
8635 __s32 __user *fds = u64_to_user_ptr(up->data);
8636 struct io_rsrc_data *data = ctx->file_data;
8637 struct io_fixed_file *file_slot;
8641 bool needs_switch = false;
8643 if (!ctx->file_data)
8645 if (up->offset + nr_args > ctx->nr_user_files)
8648 for (done = 0; done < nr_args; done++) {
8651 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8652 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8656 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8660 if (fd == IORING_REGISTER_FILES_SKIP)
8663 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8664 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8666 if (file_slot->file_ptr) {
8667 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8668 err = io_queue_rsrc_removal(data, up->offset + done,
8669 ctx->rsrc_node, file);
8672 file_slot->file_ptr = 0;
8673 needs_switch = true;
8682 * Don't allow io_uring instances to be registered. If
8683 * UNIX isn't enabled, then this causes a reference
8684 * cycle and this instance can never get freed. If UNIX
8685 * is enabled we'll handle it just fine, but there's
8686 * still no point in allowing a ring fd as it doesn't
8687 * support regular read/write anyway.
8689 if (file->f_op == &io_uring_fops) {
8694 *io_get_tag_slot(data, up->offset + done) = tag;
8695 io_fixed_file_set(file_slot, file);
8696 err = io_sqe_file_register(ctx, file, i);
8698 file_slot->file_ptr = 0;
8706 io_rsrc_node_switch(ctx, data);
8707 return done ? done : err;
8710 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8711 struct task_struct *task)
8713 struct io_wq_hash *hash;
8714 struct io_wq_data data;
8715 unsigned int concurrency;
8717 mutex_lock(&ctx->uring_lock);
8718 hash = ctx->hash_map;
8720 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8722 mutex_unlock(&ctx->uring_lock);
8723 return ERR_PTR(-ENOMEM);
8725 refcount_set(&hash->refs, 1);
8726 init_waitqueue_head(&hash->wait);
8727 ctx->hash_map = hash;
8729 mutex_unlock(&ctx->uring_lock);
8733 data.free_work = io_wq_free_work;
8734 data.do_work = io_wq_submit_work;
8736 /* Do QD, or 4 * CPUS, whatever is smallest */
8737 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8739 return io_wq_create(concurrency, &data);
8742 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8743 struct io_ring_ctx *ctx)
8745 struct io_uring_task *tctx;
8748 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8749 if (unlikely(!tctx))
8752 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8753 if (unlikely(ret)) {
8758 tctx->io_wq = io_init_wq_offload(ctx, task);
8759 if (IS_ERR(tctx->io_wq)) {
8760 ret = PTR_ERR(tctx->io_wq);
8761 percpu_counter_destroy(&tctx->inflight);
8767 init_waitqueue_head(&tctx->wait);
8768 atomic_set(&tctx->in_idle, 0);
8769 atomic_set(&tctx->inflight_tracked, 0);
8770 task->io_uring = tctx;
8771 spin_lock_init(&tctx->task_lock);
8772 INIT_WQ_LIST(&tctx->task_list);
8773 INIT_WQ_LIST(&tctx->prior_task_list);
8774 init_task_work(&tctx->task_work, tctx_task_work);
8778 void __io_uring_free(struct task_struct *tsk)
8780 struct io_uring_task *tctx = tsk->io_uring;
8782 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8783 WARN_ON_ONCE(tctx->io_wq);
8784 WARN_ON_ONCE(tctx->cached_refs);
8786 percpu_counter_destroy(&tctx->inflight);
8788 tsk->io_uring = NULL;
8791 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8792 struct io_uring_params *p)
8796 /* Retain compatibility with failing for an invalid attach attempt */
8797 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8798 IORING_SETUP_ATTACH_WQ) {
8801 f = fdget(p->wq_fd);
8804 if (f.file->f_op != &io_uring_fops) {
8810 if (ctx->flags & IORING_SETUP_SQPOLL) {
8811 struct task_struct *tsk;
8812 struct io_sq_data *sqd;
8815 ret = security_uring_sqpoll();
8819 sqd = io_get_sq_data(p, &attached);
8825 ctx->sq_creds = get_current_cred();
8827 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8828 if (!ctx->sq_thread_idle)
8829 ctx->sq_thread_idle = HZ;
8831 io_sq_thread_park(sqd);
8832 list_add(&ctx->sqd_list, &sqd->ctx_list);
8833 io_sqd_update_thread_idle(sqd);
8834 /* don't attach to a dying SQPOLL thread, would be racy */
8835 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8836 io_sq_thread_unpark(sqd);
8843 if (p->flags & IORING_SETUP_SQ_AFF) {
8844 int cpu = p->sq_thread_cpu;
8847 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8854 sqd->task_pid = current->pid;
8855 sqd->task_tgid = current->tgid;
8856 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8863 ret = io_uring_alloc_task_context(tsk, ctx);
8864 wake_up_new_task(tsk);
8867 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8868 /* Can't have SQ_AFF without SQPOLL */
8875 complete(&ctx->sq_data->exited);
8877 io_sq_thread_finish(ctx);
8881 static inline void __io_unaccount_mem(struct user_struct *user,
8882 unsigned long nr_pages)
8884 atomic_long_sub(nr_pages, &user->locked_vm);
8887 static inline int __io_account_mem(struct user_struct *user,
8888 unsigned long nr_pages)
8890 unsigned long page_limit, cur_pages, new_pages;
8892 /* Don't allow more pages than we can safely lock */
8893 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8896 cur_pages = atomic_long_read(&user->locked_vm);
8897 new_pages = cur_pages + nr_pages;
8898 if (new_pages > page_limit)
8900 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8901 new_pages) != cur_pages);
8906 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8909 __io_unaccount_mem(ctx->user, nr_pages);
8911 if (ctx->mm_account)
8912 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8915 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8920 ret = __io_account_mem(ctx->user, nr_pages);
8925 if (ctx->mm_account)
8926 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8931 static void io_mem_free(void *ptr)
8938 page = virt_to_head_page(ptr);
8939 if (put_page_testzero(page))
8940 free_compound_page(page);
8943 static void *io_mem_alloc(size_t size)
8945 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8947 return (void *) __get_free_pages(gfp, get_order(size));
8950 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8953 struct io_rings *rings;
8954 size_t off, sq_array_size;
8956 off = struct_size(rings, cqes, cq_entries);
8957 if (off == SIZE_MAX)
8961 off = ALIGN(off, SMP_CACHE_BYTES);
8969 sq_array_size = array_size(sizeof(u32), sq_entries);
8970 if (sq_array_size == SIZE_MAX)
8973 if (check_add_overflow(off, sq_array_size, &off))
8979 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8981 struct io_mapped_ubuf *imu = *slot;
8984 if (imu != ctx->dummy_ubuf) {
8985 for (i = 0; i < imu->nr_bvecs; i++)
8986 unpin_user_page(imu->bvec[i].bv_page);
8987 if (imu->acct_pages)
8988 io_unaccount_mem(ctx, imu->acct_pages);
8994 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8996 io_buffer_unmap(ctx, &prsrc->buf);
9000 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9004 for (i = 0; i < ctx->nr_user_bufs; i++)
9005 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9006 kfree(ctx->user_bufs);
9007 io_rsrc_data_free(ctx->buf_data);
9008 ctx->user_bufs = NULL;
9009 ctx->buf_data = NULL;
9010 ctx->nr_user_bufs = 0;
9013 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9020 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9022 __io_sqe_buffers_unregister(ctx);
9026 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9027 void __user *arg, unsigned index)
9029 struct iovec __user *src;
9031 #ifdef CONFIG_COMPAT
9033 struct compat_iovec __user *ciovs;
9034 struct compat_iovec ciov;
9036 ciovs = (struct compat_iovec __user *) arg;
9037 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9040 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9041 dst->iov_len = ciov.iov_len;
9045 src = (struct iovec __user *) arg;
9046 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9052 * Not super efficient, but this is just a registration time. And we do cache
9053 * the last compound head, so generally we'll only do a full search if we don't
9056 * We check if the given compound head page has already been accounted, to
9057 * avoid double accounting it. This allows us to account the full size of the
9058 * page, not just the constituent pages of a huge page.
9060 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9061 int nr_pages, struct page *hpage)
9065 /* check current page array */
9066 for (i = 0; i < nr_pages; i++) {
9067 if (!PageCompound(pages[i]))
9069 if (compound_head(pages[i]) == hpage)
9073 /* check previously registered pages */
9074 for (i = 0; i < ctx->nr_user_bufs; i++) {
9075 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9077 for (j = 0; j < imu->nr_bvecs; j++) {
9078 if (!PageCompound(imu->bvec[j].bv_page))
9080 if (compound_head(imu->bvec[j].bv_page) == hpage)
9088 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9089 int nr_pages, struct io_mapped_ubuf *imu,
9090 struct page **last_hpage)
9094 imu->acct_pages = 0;
9095 for (i = 0; i < nr_pages; i++) {
9096 if (!PageCompound(pages[i])) {
9101 hpage = compound_head(pages[i]);
9102 if (hpage == *last_hpage)
9104 *last_hpage = hpage;
9105 if (headpage_already_acct(ctx, pages, i, hpage))
9107 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9111 if (!imu->acct_pages)
9114 ret = io_account_mem(ctx, imu->acct_pages);
9116 imu->acct_pages = 0;
9120 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9121 struct io_mapped_ubuf **pimu,
9122 struct page **last_hpage)
9124 struct io_mapped_ubuf *imu = NULL;
9125 struct vm_area_struct **vmas = NULL;
9126 struct page **pages = NULL;
9127 unsigned long off, start, end, ubuf;
9129 int ret, pret, nr_pages, i;
9131 if (!iov->iov_base) {
9132 *pimu = ctx->dummy_ubuf;
9136 ubuf = (unsigned long) iov->iov_base;
9137 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9138 start = ubuf >> PAGE_SHIFT;
9139 nr_pages = end - start;
9144 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9148 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9153 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9158 mmap_read_lock(current->mm);
9159 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9161 if (pret == nr_pages) {
9162 /* don't support file backed memory */
9163 for (i = 0; i < nr_pages; i++) {
9164 struct vm_area_struct *vma = vmas[i];
9166 if (vma_is_shmem(vma))
9169 !is_file_hugepages(vma->vm_file)) {
9175 ret = pret < 0 ? pret : -EFAULT;
9177 mmap_read_unlock(current->mm);
9180 * if we did partial map, or found file backed vmas,
9181 * release any pages we did get
9184 unpin_user_pages(pages, pret);
9188 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9190 unpin_user_pages(pages, pret);
9194 off = ubuf & ~PAGE_MASK;
9195 size = iov->iov_len;
9196 for (i = 0; i < nr_pages; i++) {
9199 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9200 imu->bvec[i].bv_page = pages[i];
9201 imu->bvec[i].bv_len = vec_len;
9202 imu->bvec[i].bv_offset = off;
9206 /* store original address for later verification */
9208 imu->ubuf_end = ubuf + iov->iov_len;
9209 imu->nr_bvecs = nr_pages;
9220 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9222 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9223 return ctx->user_bufs ? 0 : -ENOMEM;
9226 static int io_buffer_validate(struct iovec *iov)
9228 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9231 * Don't impose further limits on the size and buffer
9232 * constraints here, we'll -EINVAL later when IO is
9233 * submitted if they are wrong.
9236 return iov->iov_len ? -EFAULT : 0;
9240 /* arbitrary limit, but we need something */
9241 if (iov->iov_len > SZ_1G)
9244 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9250 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9251 unsigned int nr_args, u64 __user *tags)
9253 struct page *last_hpage = NULL;
9254 struct io_rsrc_data *data;
9260 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9262 ret = io_rsrc_node_switch_start(ctx);
9265 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9268 ret = io_buffers_map_alloc(ctx, nr_args);
9270 io_rsrc_data_free(data);
9274 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9275 ret = io_copy_iov(ctx, &iov, arg, i);
9278 ret = io_buffer_validate(&iov);
9281 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9286 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9292 WARN_ON_ONCE(ctx->buf_data);
9294 ctx->buf_data = data;
9296 __io_sqe_buffers_unregister(ctx);
9298 io_rsrc_node_switch(ctx, NULL);
9302 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9303 struct io_uring_rsrc_update2 *up,
9304 unsigned int nr_args)
9306 u64 __user *tags = u64_to_user_ptr(up->tags);
9307 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9308 struct page *last_hpage = NULL;
9309 bool needs_switch = false;
9315 if (up->offset + nr_args > ctx->nr_user_bufs)
9318 for (done = 0; done < nr_args; done++) {
9319 struct io_mapped_ubuf *imu;
9320 int offset = up->offset + done;
9323 err = io_copy_iov(ctx, &iov, iovs, done);
9326 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9330 err = io_buffer_validate(&iov);
9333 if (!iov.iov_base && tag) {
9337 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9341 i = array_index_nospec(offset, ctx->nr_user_bufs);
9342 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9343 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9344 ctx->rsrc_node, ctx->user_bufs[i]);
9345 if (unlikely(err)) {
9346 io_buffer_unmap(ctx, &imu);
9349 ctx->user_bufs[i] = NULL;
9350 needs_switch = true;
9353 ctx->user_bufs[i] = imu;
9354 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9358 io_rsrc_node_switch(ctx, ctx->buf_data);
9359 return done ? done : err;
9362 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9364 __s32 __user *fds = arg;
9370 if (copy_from_user(&fd, fds, sizeof(*fds)))
9373 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9374 if (IS_ERR(ctx->cq_ev_fd)) {
9375 int ret = PTR_ERR(ctx->cq_ev_fd);
9377 ctx->cq_ev_fd = NULL;
9384 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9386 if (ctx->cq_ev_fd) {
9387 eventfd_ctx_put(ctx->cq_ev_fd);
9388 ctx->cq_ev_fd = NULL;
9395 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9397 struct io_buffer *buf;
9398 unsigned long index;
9400 xa_for_each(&ctx->io_buffers, index, buf)
9401 __io_remove_buffers(ctx, buf, index, -1U);
9404 static void io_req_caches_free(struct io_ring_ctx *ctx)
9406 struct io_submit_state *state = &ctx->submit_state;
9409 mutex_lock(&ctx->uring_lock);
9410 io_flush_cached_locked_reqs(ctx, state);
9412 while (state->free_list.next) {
9413 struct io_wq_work_node *node;
9414 struct io_kiocb *req;
9416 node = wq_stack_extract(&state->free_list);
9417 req = container_of(node, struct io_kiocb, comp_list);
9418 kmem_cache_free(req_cachep, req);
9422 percpu_ref_put_many(&ctx->refs, nr);
9423 mutex_unlock(&ctx->uring_lock);
9426 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9428 if (data && !atomic_dec_and_test(&data->refs))
9429 wait_for_completion(&data->done);
9432 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9434 io_sq_thread_finish(ctx);
9436 if (ctx->mm_account) {
9437 mmdrop(ctx->mm_account);
9438 ctx->mm_account = NULL;
9441 io_rsrc_refs_drop(ctx);
9442 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9443 io_wait_rsrc_data(ctx->buf_data);
9444 io_wait_rsrc_data(ctx->file_data);
9446 mutex_lock(&ctx->uring_lock);
9448 __io_sqe_buffers_unregister(ctx);
9450 __io_sqe_files_unregister(ctx);
9452 __io_cqring_overflow_flush(ctx, true);
9453 mutex_unlock(&ctx->uring_lock);
9454 io_eventfd_unregister(ctx);
9455 io_destroy_buffers(ctx);
9457 put_cred(ctx->sq_creds);
9459 /* there are no registered resources left, nobody uses it */
9461 io_rsrc_node_destroy(ctx->rsrc_node);
9462 if (ctx->rsrc_backup_node)
9463 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9464 flush_delayed_work(&ctx->rsrc_put_work);
9465 flush_delayed_work(&ctx->fallback_work);
9467 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9468 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9470 #if defined(CONFIG_UNIX)
9471 if (ctx->ring_sock) {
9472 ctx->ring_sock->file = NULL; /* so that iput() is called */
9473 sock_release(ctx->ring_sock);
9476 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9478 io_mem_free(ctx->rings);
9479 io_mem_free(ctx->sq_sqes);
9481 percpu_ref_exit(&ctx->refs);
9482 free_uid(ctx->user);
9483 io_req_caches_free(ctx);
9485 io_wq_put_hash(ctx->hash_map);
9486 kfree(ctx->cancel_hash);
9487 kfree(ctx->dummy_ubuf);
9491 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9493 struct io_ring_ctx *ctx = file->private_data;
9496 poll_wait(file, &ctx->cq_wait, wait);
9498 * synchronizes with barrier from wq_has_sleeper call in
9502 if (!io_sqring_full(ctx))
9503 mask |= EPOLLOUT | EPOLLWRNORM;
9506 * Don't flush cqring overflow list here, just do a simple check.
9507 * Otherwise there could possible be ABBA deadlock:
9510 * lock(&ctx->uring_lock);
9512 * lock(&ctx->uring_lock);
9515 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9516 * pushs them to do the flush.
9518 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9519 mask |= EPOLLIN | EPOLLRDNORM;
9524 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9526 const struct cred *creds;
9528 creds = xa_erase(&ctx->personalities, id);
9537 struct io_tctx_exit {
9538 struct callback_head task_work;
9539 struct completion completion;
9540 struct io_ring_ctx *ctx;
9543 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9545 struct io_uring_task *tctx = current->io_uring;
9546 struct io_tctx_exit *work;
9548 work = container_of(cb, struct io_tctx_exit, task_work);
9550 * When @in_idle, we're in cancellation and it's racy to remove the
9551 * node. It'll be removed by the end of cancellation, just ignore it.
9553 if (!atomic_read(&tctx->in_idle))
9554 io_uring_del_tctx_node((unsigned long)work->ctx);
9555 complete(&work->completion);
9558 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9560 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9562 return req->ctx == data;
9565 static __cold void io_ring_exit_work(struct work_struct *work)
9567 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9568 unsigned long timeout = jiffies + HZ * 60 * 5;
9569 unsigned long interval = HZ / 20;
9570 struct io_tctx_exit exit;
9571 struct io_tctx_node *node;
9575 * If we're doing polled IO and end up having requests being
9576 * submitted async (out-of-line), then completions can come in while
9577 * we're waiting for refs to drop. We need to reap these manually,
9578 * as nobody else will be looking for them.
9581 io_uring_try_cancel_requests(ctx, NULL, true);
9583 struct io_sq_data *sqd = ctx->sq_data;
9584 struct task_struct *tsk;
9586 io_sq_thread_park(sqd);
9588 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9589 io_wq_cancel_cb(tsk->io_uring->io_wq,
9590 io_cancel_ctx_cb, ctx, true);
9591 io_sq_thread_unpark(sqd);
9594 io_req_caches_free(ctx);
9596 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9597 /* there is little hope left, don't run it too often */
9600 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9602 init_completion(&exit.completion);
9603 init_task_work(&exit.task_work, io_tctx_exit_cb);
9606 * Some may use context even when all refs and requests have been put,
9607 * and they are free to do so while still holding uring_lock or
9608 * completion_lock, see io_req_task_submit(). Apart from other work,
9609 * this lock/unlock section also waits them to finish.
9611 mutex_lock(&ctx->uring_lock);
9612 while (!list_empty(&ctx->tctx_list)) {
9613 WARN_ON_ONCE(time_after(jiffies, timeout));
9615 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9617 /* don't spin on a single task if cancellation failed */
9618 list_rotate_left(&ctx->tctx_list);
9619 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9620 if (WARN_ON_ONCE(ret))
9623 mutex_unlock(&ctx->uring_lock);
9624 wait_for_completion(&exit.completion);
9625 mutex_lock(&ctx->uring_lock);
9627 mutex_unlock(&ctx->uring_lock);
9628 spin_lock(&ctx->completion_lock);
9629 spin_unlock(&ctx->completion_lock);
9631 io_ring_ctx_free(ctx);
9634 /* Returns true if we found and killed one or more timeouts */
9635 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9636 struct task_struct *tsk, bool cancel_all)
9638 struct io_kiocb *req, *tmp;
9641 spin_lock(&ctx->completion_lock);
9642 spin_lock_irq(&ctx->timeout_lock);
9643 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9644 if (io_match_task(req, tsk, cancel_all)) {
9645 io_kill_timeout(req, -ECANCELED);
9649 spin_unlock_irq(&ctx->timeout_lock);
9651 io_commit_cqring(ctx);
9652 spin_unlock(&ctx->completion_lock);
9654 io_cqring_ev_posted(ctx);
9655 return canceled != 0;
9658 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9660 unsigned long index;
9661 struct creds *creds;
9663 mutex_lock(&ctx->uring_lock);
9664 percpu_ref_kill(&ctx->refs);
9666 __io_cqring_overflow_flush(ctx, true);
9667 xa_for_each(&ctx->personalities, index, creds)
9668 io_unregister_personality(ctx, index);
9669 mutex_unlock(&ctx->uring_lock);
9671 io_kill_timeouts(ctx, NULL, true);
9672 io_poll_remove_all(ctx, NULL, true);
9674 /* if we failed setting up the ctx, we might not have any rings */
9675 io_iopoll_try_reap_events(ctx);
9677 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9679 * Use system_unbound_wq to avoid spawning tons of event kworkers
9680 * if we're exiting a ton of rings at the same time. It just adds
9681 * noise and overhead, there's no discernable change in runtime
9682 * over using system_wq.
9684 queue_work(system_unbound_wq, &ctx->exit_work);
9687 static int io_uring_release(struct inode *inode, struct file *file)
9689 struct io_ring_ctx *ctx = file->private_data;
9691 file->private_data = NULL;
9692 io_ring_ctx_wait_and_kill(ctx);
9696 struct io_task_cancel {
9697 struct task_struct *task;
9701 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9703 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9704 struct io_task_cancel *cancel = data;
9706 return io_match_task_safe(req, cancel->task, cancel->all);
9709 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9710 struct task_struct *task,
9713 struct io_defer_entry *de;
9716 spin_lock(&ctx->completion_lock);
9717 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9718 if (io_match_task_safe(de->req, task, cancel_all)) {
9719 list_cut_position(&list, &ctx->defer_list, &de->list);
9723 spin_unlock(&ctx->completion_lock);
9724 if (list_empty(&list))
9727 while (!list_empty(&list)) {
9728 de = list_first_entry(&list, struct io_defer_entry, list);
9729 list_del_init(&de->list);
9730 io_req_complete_failed(de->req, -ECANCELED);
9736 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9738 struct io_tctx_node *node;
9739 enum io_wq_cancel cret;
9742 mutex_lock(&ctx->uring_lock);
9743 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9744 struct io_uring_task *tctx = node->task->io_uring;
9747 * io_wq will stay alive while we hold uring_lock, because it's
9748 * killed after ctx nodes, which requires to take the lock.
9750 if (!tctx || !tctx->io_wq)
9752 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9753 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9755 mutex_unlock(&ctx->uring_lock);
9760 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9761 struct task_struct *task,
9764 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9765 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9768 enum io_wq_cancel cret;
9772 ret |= io_uring_try_cancel_iowq(ctx);
9773 } else if (tctx && tctx->io_wq) {
9775 * Cancels requests of all rings, not only @ctx, but
9776 * it's fine as the task is in exit/exec.
9778 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9780 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9783 /* SQPOLL thread does its own polling */
9784 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9785 (ctx->sq_data && ctx->sq_data->thread == current)) {
9786 while (!wq_list_empty(&ctx->iopoll_list)) {
9787 io_iopoll_try_reap_events(ctx);
9792 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9793 ret |= io_poll_remove_all(ctx, task, cancel_all);
9794 ret |= io_kill_timeouts(ctx, task, cancel_all);
9796 ret |= io_run_task_work();
9803 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9805 struct io_uring_task *tctx = current->io_uring;
9806 struct io_tctx_node *node;
9809 if (unlikely(!tctx)) {
9810 ret = io_uring_alloc_task_context(current, ctx);
9814 tctx = current->io_uring;
9815 if (ctx->iowq_limits_set) {
9816 unsigned int limits[2] = { ctx->iowq_limits[0],
9817 ctx->iowq_limits[1], };
9819 ret = io_wq_max_workers(tctx->io_wq, limits);
9824 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9825 node = kmalloc(sizeof(*node), GFP_KERNEL);
9829 node->task = current;
9831 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9838 mutex_lock(&ctx->uring_lock);
9839 list_add(&node->ctx_node, &ctx->tctx_list);
9840 mutex_unlock(&ctx->uring_lock);
9847 * Note that this task has used io_uring. We use it for cancelation purposes.
9849 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9851 struct io_uring_task *tctx = current->io_uring;
9853 if (likely(tctx && tctx->last == ctx))
9855 return __io_uring_add_tctx_node(ctx);
9859 * Remove this io_uring_file -> task mapping.
9861 static __cold void io_uring_del_tctx_node(unsigned long index)
9863 struct io_uring_task *tctx = current->io_uring;
9864 struct io_tctx_node *node;
9868 node = xa_erase(&tctx->xa, index);
9872 WARN_ON_ONCE(current != node->task);
9873 WARN_ON_ONCE(list_empty(&node->ctx_node));
9875 mutex_lock(&node->ctx->uring_lock);
9876 list_del(&node->ctx_node);
9877 mutex_unlock(&node->ctx->uring_lock);
9879 if (tctx->last == node->ctx)
9884 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9886 struct io_wq *wq = tctx->io_wq;
9887 struct io_tctx_node *node;
9888 unsigned long index;
9890 xa_for_each(&tctx->xa, index, node) {
9891 io_uring_del_tctx_node(index);
9896 * Must be after io_uring_del_tctx_node() (removes nodes under
9897 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9899 io_wq_put_and_exit(wq);
9904 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9907 return atomic_read(&tctx->inflight_tracked);
9908 return percpu_counter_sum(&tctx->inflight);
9912 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9913 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9915 static __cold void io_uring_cancel_generic(bool cancel_all,
9916 struct io_sq_data *sqd)
9918 struct io_uring_task *tctx = current->io_uring;
9919 struct io_ring_ctx *ctx;
9923 WARN_ON_ONCE(sqd && sqd->thread != current);
9925 if (!current->io_uring)
9928 io_wq_exit_start(tctx->io_wq);
9930 atomic_inc(&tctx->in_idle);
9932 io_uring_drop_tctx_refs(current);
9933 /* read completions before cancelations */
9934 inflight = tctx_inflight(tctx, !cancel_all);
9939 struct io_tctx_node *node;
9940 unsigned long index;
9942 xa_for_each(&tctx->xa, index, node) {
9943 /* sqpoll task will cancel all its requests */
9944 if (node->ctx->sq_data)
9946 io_uring_try_cancel_requests(node->ctx, current,
9950 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9951 io_uring_try_cancel_requests(ctx, current,
9955 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9957 io_uring_drop_tctx_refs(current);
9960 * If we've seen completions, retry without waiting. This
9961 * avoids a race where a completion comes in before we did
9962 * prepare_to_wait().
9964 if (inflight == tctx_inflight(tctx, !cancel_all))
9966 finish_wait(&tctx->wait, &wait);
9969 io_uring_clean_tctx(tctx);
9972 * We shouldn't run task_works after cancel, so just leave
9973 * ->in_idle set for normal exit.
9975 atomic_dec(&tctx->in_idle);
9976 /* for exec all current's requests should be gone, kill tctx */
9977 __io_uring_free(current);
9981 void __io_uring_cancel(bool cancel_all)
9983 io_uring_cancel_generic(cancel_all, NULL);
9986 static void *io_uring_validate_mmap_request(struct file *file,
9987 loff_t pgoff, size_t sz)
9989 struct io_ring_ctx *ctx = file->private_data;
9990 loff_t offset = pgoff << PAGE_SHIFT;
9995 case IORING_OFF_SQ_RING:
9996 case IORING_OFF_CQ_RING:
9999 case IORING_OFF_SQES:
10000 ptr = ctx->sq_sqes;
10003 return ERR_PTR(-EINVAL);
10006 page = virt_to_head_page(ptr);
10007 if (sz > page_size(page))
10008 return ERR_PTR(-EINVAL);
10015 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10017 size_t sz = vma->vm_end - vma->vm_start;
10021 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10023 return PTR_ERR(ptr);
10025 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10026 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10029 #else /* !CONFIG_MMU */
10031 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10033 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10036 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10038 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10041 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10042 unsigned long addr, unsigned long len,
10043 unsigned long pgoff, unsigned long flags)
10047 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10049 return PTR_ERR(ptr);
10051 return (unsigned long) ptr;
10054 #endif /* !CONFIG_MMU */
10056 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10061 if (!io_sqring_full(ctx))
10063 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10065 if (!io_sqring_full(ctx))
10068 } while (!signal_pending(current));
10070 finish_wait(&ctx->sqo_sq_wait, &wait);
10074 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10075 struct __kernel_timespec __user **ts,
10076 const sigset_t __user **sig)
10078 struct io_uring_getevents_arg arg;
10081 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10082 * is just a pointer to the sigset_t.
10084 if (!(flags & IORING_ENTER_EXT_ARG)) {
10085 *sig = (const sigset_t __user *) argp;
10091 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10092 * timespec and sigset_t pointers if good.
10094 if (*argsz != sizeof(arg))
10096 if (copy_from_user(&arg, argp, sizeof(arg)))
10098 *sig = u64_to_user_ptr(arg.sigmask);
10099 *argsz = arg.sigmask_sz;
10100 *ts = u64_to_user_ptr(arg.ts);
10104 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10105 u32, min_complete, u32, flags, const void __user *, argp,
10108 struct io_ring_ctx *ctx;
10113 io_run_task_work();
10115 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10116 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10120 if (unlikely(!f.file))
10124 if (unlikely(f.file->f_op != &io_uring_fops))
10128 ctx = f.file->private_data;
10129 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10133 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10137 * For SQ polling, the thread will do all submissions and completions.
10138 * Just return the requested submit count, and wake the thread if
10139 * we were asked to.
10142 if (ctx->flags & IORING_SETUP_SQPOLL) {
10143 io_cqring_overflow_flush(ctx);
10145 if (unlikely(ctx->sq_data->thread == NULL)) {
10149 if (flags & IORING_ENTER_SQ_WAKEUP)
10150 wake_up(&ctx->sq_data->wait);
10151 if (flags & IORING_ENTER_SQ_WAIT) {
10152 ret = io_sqpoll_wait_sq(ctx);
10156 submitted = to_submit;
10157 } else if (to_submit) {
10158 ret = io_uring_add_tctx_node(ctx);
10161 mutex_lock(&ctx->uring_lock);
10162 submitted = io_submit_sqes(ctx, to_submit);
10163 mutex_unlock(&ctx->uring_lock);
10165 if (submitted != to_submit)
10168 if (flags & IORING_ENTER_GETEVENTS) {
10169 const sigset_t __user *sig;
10170 struct __kernel_timespec __user *ts;
10172 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10176 min_complete = min(min_complete, ctx->cq_entries);
10179 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10180 * space applications don't need to do io completion events
10181 * polling again, they can rely on io_sq_thread to do polling
10182 * work, which can reduce cpu usage and uring_lock contention.
10184 if (ctx->flags & IORING_SETUP_IOPOLL &&
10185 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10186 ret = io_iopoll_check(ctx, min_complete);
10188 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10193 percpu_ref_put(&ctx->refs);
10196 return submitted ? submitted : ret;
10199 #ifdef CONFIG_PROC_FS
10200 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10201 const struct cred *cred)
10203 struct user_namespace *uns = seq_user_ns(m);
10204 struct group_info *gi;
10209 seq_printf(m, "%5d\n", id);
10210 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10211 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10212 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10213 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10214 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10215 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10216 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10217 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10218 seq_puts(m, "\n\tGroups:\t");
10219 gi = cred->group_info;
10220 for (g = 0; g < gi->ngroups; g++) {
10221 seq_put_decimal_ull(m, g ? " " : "",
10222 from_kgid_munged(uns, gi->gid[g]));
10224 seq_puts(m, "\n\tCapEff:\t");
10225 cap = cred->cap_effective;
10226 CAP_FOR_EACH_U32(__capi)
10227 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10232 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10233 struct seq_file *m)
10235 struct io_sq_data *sq = NULL;
10236 struct io_overflow_cqe *ocqe;
10237 struct io_rings *r = ctx->rings;
10238 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10239 unsigned int sq_head = READ_ONCE(r->sq.head);
10240 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10241 unsigned int cq_head = READ_ONCE(r->cq.head);
10242 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10243 unsigned int sq_entries, cq_entries;
10248 * we may get imprecise sqe and cqe info if uring is actively running
10249 * since we get cached_sq_head and cached_cq_tail without uring_lock
10250 * and sq_tail and cq_head are changed by userspace. But it's ok since
10251 * we usually use these info when it is stuck.
10253 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10254 seq_printf(m, "SqHead:\t%u\n", sq_head);
10255 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10256 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10257 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10258 seq_printf(m, "CqHead:\t%u\n", cq_head);
10259 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10260 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10261 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10262 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10263 for (i = 0; i < sq_entries; i++) {
10264 unsigned int entry = i + sq_head;
10265 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10266 struct io_uring_sqe *sqe;
10268 if (sq_idx > sq_mask)
10270 sqe = &ctx->sq_sqes[sq_idx];
10271 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10272 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10275 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10276 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10277 for (i = 0; i < cq_entries; i++) {
10278 unsigned int entry = i + cq_head;
10279 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10281 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10282 entry & cq_mask, cqe->user_data, cqe->res,
10287 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10288 * since fdinfo case grabs it in the opposite direction of normal use
10289 * cases. If we fail to get the lock, we just don't iterate any
10290 * structures that could be going away outside the io_uring mutex.
10292 has_lock = mutex_trylock(&ctx->uring_lock);
10294 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10300 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10301 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10302 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10303 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10304 struct file *f = io_file_from_index(ctx, i);
10307 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10309 seq_printf(m, "%5u: <none>\n", i);
10311 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10312 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10313 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10314 unsigned int len = buf->ubuf_end - buf->ubuf;
10316 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10318 if (has_lock && !xa_empty(&ctx->personalities)) {
10319 unsigned long index;
10320 const struct cred *cred;
10322 seq_printf(m, "Personalities:\n");
10323 xa_for_each(&ctx->personalities, index, cred)
10324 io_uring_show_cred(m, index, cred);
10327 mutex_unlock(&ctx->uring_lock);
10329 seq_puts(m, "PollList:\n");
10330 spin_lock(&ctx->completion_lock);
10331 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10332 struct hlist_head *list = &ctx->cancel_hash[i];
10333 struct io_kiocb *req;
10335 hlist_for_each_entry(req, list, hash_node)
10336 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10337 req->task->task_works != NULL);
10340 seq_puts(m, "CqOverflowList:\n");
10341 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10342 struct io_uring_cqe *cqe = &ocqe->cqe;
10344 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10345 cqe->user_data, cqe->res, cqe->flags);
10349 spin_unlock(&ctx->completion_lock);
10352 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10354 struct io_ring_ctx *ctx = f->private_data;
10356 if (percpu_ref_tryget(&ctx->refs)) {
10357 __io_uring_show_fdinfo(ctx, m);
10358 percpu_ref_put(&ctx->refs);
10363 static const struct file_operations io_uring_fops = {
10364 .release = io_uring_release,
10365 .mmap = io_uring_mmap,
10367 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10368 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10370 .poll = io_uring_poll,
10371 #ifdef CONFIG_PROC_FS
10372 .show_fdinfo = io_uring_show_fdinfo,
10376 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10377 struct io_uring_params *p)
10379 struct io_rings *rings;
10380 size_t size, sq_array_offset;
10382 /* make sure these are sane, as we already accounted them */
10383 ctx->sq_entries = p->sq_entries;
10384 ctx->cq_entries = p->cq_entries;
10386 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10387 if (size == SIZE_MAX)
10390 rings = io_mem_alloc(size);
10394 ctx->rings = rings;
10395 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10396 rings->sq_ring_mask = p->sq_entries - 1;
10397 rings->cq_ring_mask = p->cq_entries - 1;
10398 rings->sq_ring_entries = p->sq_entries;
10399 rings->cq_ring_entries = p->cq_entries;
10401 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10402 if (size == SIZE_MAX) {
10403 io_mem_free(ctx->rings);
10408 ctx->sq_sqes = io_mem_alloc(size);
10409 if (!ctx->sq_sqes) {
10410 io_mem_free(ctx->rings);
10418 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10422 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10426 ret = io_uring_add_tctx_node(ctx);
10431 fd_install(fd, file);
10436 * Allocate an anonymous fd, this is what constitutes the application
10437 * visible backing of an io_uring instance. The application mmaps this
10438 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10439 * we have to tie this fd to a socket for file garbage collection purposes.
10441 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10444 #if defined(CONFIG_UNIX)
10447 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10450 return ERR_PTR(ret);
10453 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10454 O_RDWR | O_CLOEXEC, NULL);
10455 #if defined(CONFIG_UNIX)
10456 if (IS_ERR(file)) {
10457 sock_release(ctx->ring_sock);
10458 ctx->ring_sock = NULL;
10460 ctx->ring_sock->file = file;
10466 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10467 struct io_uring_params __user *params)
10469 struct io_ring_ctx *ctx;
10475 if (entries > IORING_MAX_ENTRIES) {
10476 if (!(p->flags & IORING_SETUP_CLAMP))
10478 entries = IORING_MAX_ENTRIES;
10482 * Use twice as many entries for the CQ ring. It's possible for the
10483 * application to drive a higher depth than the size of the SQ ring,
10484 * since the sqes are only used at submission time. This allows for
10485 * some flexibility in overcommitting a bit. If the application has
10486 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10487 * of CQ ring entries manually.
10489 p->sq_entries = roundup_pow_of_two(entries);
10490 if (p->flags & IORING_SETUP_CQSIZE) {
10492 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10493 * to a power-of-two, if it isn't already. We do NOT impose
10494 * any cq vs sq ring sizing.
10496 if (!p->cq_entries)
10498 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10499 if (!(p->flags & IORING_SETUP_CLAMP))
10501 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10503 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10504 if (p->cq_entries < p->sq_entries)
10507 p->cq_entries = 2 * p->sq_entries;
10510 ctx = io_ring_ctx_alloc(p);
10513 ctx->compat = in_compat_syscall();
10514 if (!capable(CAP_IPC_LOCK))
10515 ctx->user = get_uid(current_user());
10518 * This is just grabbed for accounting purposes. When a process exits,
10519 * the mm is exited and dropped before the files, hence we need to hang
10520 * on to this mm purely for the purposes of being able to unaccount
10521 * memory (locked/pinned vm). It's not used for anything else.
10523 mmgrab(current->mm);
10524 ctx->mm_account = current->mm;
10526 ret = io_allocate_scq_urings(ctx, p);
10530 ret = io_sq_offload_create(ctx, p);
10533 /* always set a rsrc node */
10534 ret = io_rsrc_node_switch_start(ctx);
10537 io_rsrc_node_switch(ctx, NULL);
10539 memset(&p->sq_off, 0, sizeof(p->sq_off));
10540 p->sq_off.head = offsetof(struct io_rings, sq.head);
10541 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10542 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10543 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10544 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10545 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10546 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10548 memset(&p->cq_off, 0, sizeof(p->cq_off));
10549 p->cq_off.head = offsetof(struct io_rings, cq.head);
10550 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10551 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10552 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10553 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10554 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10555 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10557 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10558 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10559 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10560 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10561 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10562 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
10564 if (copy_to_user(params, p, sizeof(*p))) {
10569 file = io_uring_get_file(ctx);
10570 if (IS_ERR(file)) {
10571 ret = PTR_ERR(file);
10576 * Install ring fd as the very last thing, so we don't risk someone
10577 * having closed it before we finish setup
10579 ret = io_uring_install_fd(ctx, file);
10581 /* fput will clean it up */
10586 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10589 io_ring_ctx_wait_and_kill(ctx);
10594 * Sets up an aio uring context, and returns the fd. Applications asks for a
10595 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10596 * params structure passed in.
10598 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10600 struct io_uring_params p;
10603 if (copy_from_user(&p, params, sizeof(p)))
10605 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10610 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10611 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10612 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10613 IORING_SETUP_R_DISABLED))
10616 return io_uring_create(entries, &p, params);
10619 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10620 struct io_uring_params __user *, params)
10622 return io_uring_setup(entries, params);
10625 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10628 struct io_uring_probe *p;
10632 size = struct_size(p, ops, nr_args);
10633 if (size == SIZE_MAX)
10635 p = kzalloc(size, GFP_KERNEL);
10640 if (copy_from_user(p, arg, size))
10643 if (memchr_inv(p, 0, size))
10646 p->last_op = IORING_OP_LAST - 1;
10647 if (nr_args > IORING_OP_LAST)
10648 nr_args = IORING_OP_LAST;
10650 for (i = 0; i < nr_args; i++) {
10652 if (!io_op_defs[i].not_supported)
10653 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10658 if (copy_to_user(arg, p, size))
10665 static int io_register_personality(struct io_ring_ctx *ctx)
10667 const struct cred *creds;
10671 creds = get_current_cred();
10673 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10674 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10682 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10683 void __user *arg, unsigned int nr_args)
10685 struct io_uring_restriction *res;
10689 /* Restrictions allowed only if rings started disabled */
10690 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10693 /* We allow only a single restrictions registration */
10694 if (ctx->restrictions.registered)
10697 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10700 size = array_size(nr_args, sizeof(*res));
10701 if (size == SIZE_MAX)
10704 res = memdup_user(arg, size);
10706 return PTR_ERR(res);
10710 for (i = 0; i < nr_args; i++) {
10711 switch (res[i].opcode) {
10712 case IORING_RESTRICTION_REGISTER_OP:
10713 if (res[i].register_op >= IORING_REGISTER_LAST) {
10718 __set_bit(res[i].register_op,
10719 ctx->restrictions.register_op);
10721 case IORING_RESTRICTION_SQE_OP:
10722 if (res[i].sqe_op >= IORING_OP_LAST) {
10727 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10729 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10730 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10732 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10733 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10742 /* Reset all restrictions if an error happened */
10744 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10746 ctx->restrictions.registered = true;
10752 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10754 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10757 if (ctx->restrictions.registered)
10758 ctx->restricted = 1;
10760 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10761 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10762 wake_up(&ctx->sq_data->wait);
10766 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10767 struct io_uring_rsrc_update2 *up,
10775 if (check_add_overflow(up->offset, nr_args, &tmp))
10777 err = io_rsrc_node_switch_start(ctx);
10782 case IORING_RSRC_FILE:
10783 return __io_sqe_files_update(ctx, up, nr_args);
10784 case IORING_RSRC_BUFFER:
10785 return __io_sqe_buffers_update(ctx, up, nr_args);
10790 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10793 struct io_uring_rsrc_update2 up;
10797 memset(&up, 0, sizeof(up));
10798 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10800 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10803 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10804 unsigned size, unsigned type)
10806 struct io_uring_rsrc_update2 up;
10808 if (size != sizeof(up))
10810 if (copy_from_user(&up, arg, sizeof(up)))
10812 if (!up.nr || up.resv)
10814 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10817 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10818 unsigned int size, unsigned int type)
10820 struct io_uring_rsrc_register rr;
10822 /* keep it extendible */
10823 if (size != sizeof(rr))
10826 memset(&rr, 0, sizeof(rr));
10827 if (copy_from_user(&rr, arg, size))
10829 if (!rr.nr || rr.resv || rr.resv2)
10833 case IORING_RSRC_FILE:
10834 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10835 rr.nr, u64_to_user_ptr(rr.tags));
10836 case IORING_RSRC_BUFFER:
10837 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10838 rr.nr, u64_to_user_ptr(rr.tags));
10843 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
10844 void __user *arg, unsigned len)
10846 struct io_uring_task *tctx = current->io_uring;
10847 cpumask_var_t new_mask;
10850 if (!tctx || !tctx->io_wq)
10853 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10856 cpumask_clear(new_mask);
10857 if (len > cpumask_size())
10858 len = cpumask_size();
10860 if (copy_from_user(new_mask, arg, len)) {
10861 free_cpumask_var(new_mask);
10865 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10866 free_cpumask_var(new_mask);
10870 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10872 struct io_uring_task *tctx = current->io_uring;
10874 if (!tctx || !tctx->io_wq)
10877 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10880 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10882 __must_hold(&ctx->uring_lock)
10884 struct io_tctx_node *node;
10885 struct io_uring_task *tctx = NULL;
10886 struct io_sq_data *sqd = NULL;
10887 __u32 new_count[2];
10890 if (copy_from_user(new_count, arg, sizeof(new_count)))
10892 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10893 if (new_count[i] > INT_MAX)
10896 if (ctx->flags & IORING_SETUP_SQPOLL) {
10897 sqd = ctx->sq_data;
10900 * Observe the correct sqd->lock -> ctx->uring_lock
10901 * ordering. Fine to drop uring_lock here, we hold
10902 * a ref to the ctx.
10904 refcount_inc(&sqd->refs);
10905 mutex_unlock(&ctx->uring_lock);
10906 mutex_lock(&sqd->lock);
10907 mutex_lock(&ctx->uring_lock);
10909 tctx = sqd->thread->io_uring;
10912 tctx = current->io_uring;
10915 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10917 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10919 ctx->iowq_limits[i] = new_count[i];
10920 ctx->iowq_limits_set = true;
10922 if (tctx && tctx->io_wq) {
10923 ret = io_wq_max_workers(tctx->io_wq, new_count);
10927 memset(new_count, 0, sizeof(new_count));
10931 mutex_unlock(&sqd->lock);
10932 io_put_sq_data(sqd);
10935 if (copy_to_user(arg, new_count, sizeof(new_count)))
10938 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10942 /* now propagate the restriction to all registered users */
10943 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10944 struct io_uring_task *tctx = node->task->io_uring;
10946 if (WARN_ON_ONCE(!tctx->io_wq))
10949 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10950 new_count[i] = ctx->iowq_limits[i];
10951 /* ignore errors, it always returns zero anyway */
10952 (void)io_wq_max_workers(tctx->io_wq, new_count);
10957 mutex_unlock(&sqd->lock);
10958 io_put_sq_data(sqd);
10963 static bool io_register_op_must_quiesce(int op)
10966 case IORING_REGISTER_BUFFERS:
10967 case IORING_UNREGISTER_BUFFERS:
10968 case IORING_REGISTER_FILES:
10969 case IORING_UNREGISTER_FILES:
10970 case IORING_REGISTER_FILES_UPDATE:
10971 case IORING_REGISTER_PROBE:
10972 case IORING_REGISTER_PERSONALITY:
10973 case IORING_UNREGISTER_PERSONALITY:
10974 case IORING_REGISTER_FILES2:
10975 case IORING_REGISTER_FILES_UPDATE2:
10976 case IORING_REGISTER_BUFFERS2:
10977 case IORING_REGISTER_BUFFERS_UPDATE:
10978 case IORING_REGISTER_IOWQ_AFF:
10979 case IORING_UNREGISTER_IOWQ_AFF:
10980 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10987 static __cold int io_ctx_quiesce(struct io_ring_ctx *ctx)
10991 percpu_ref_kill(&ctx->refs);
10994 * Drop uring mutex before waiting for references to exit. If another
10995 * thread is currently inside io_uring_enter() it might need to grab the
10996 * uring_lock to make progress. If we hold it here across the drain
10997 * wait, then we can deadlock. It's safe to drop the mutex here, since
10998 * no new references will come in after we've killed the percpu ref.
11000 mutex_unlock(&ctx->uring_lock);
11002 ret = wait_for_completion_interruptible_timeout(&ctx->ref_comp, HZ);
11004 ret = min(0L, ret);
11008 ret = io_run_task_work_sig();
11009 io_req_caches_free(ctx);
11010 } while (ret >= 0);
11011 mutex_lock(&ctx->uring_lock);
11014 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
11018 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11019 void __user *arg, unsigned nr_args)
11020 __releases(ctx->uring_lock)
11021 __acquires(ctx->uring_lock)
11026 * We're inside the ring mutex, if the ref is already dying, then
11027 * someone else killed the ctx or is already going through
11028 * io_uring_register().
11030 if (percpu_ref_is_dying(&ctx->refs))
11033 if (ctx->restricted) {
11034 if (opcode >= IORING_REGISTER_LAST)
11036 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11037 if (!test_bit(opcode, ctx->restrictions.register_op))
11041 if (io_register_op_must_quiesce(opcode)) {
11042 ret = io_ctx_quiesce(ctx);
11048 case IORING_REGISTER_BUFFERS:
11049 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11051 case IORING_UNREGISTER_BUFFERS:
11053 if (arg || nr_args)
11055 ret = io_sqe_buffers_unregister(ctx);
11057 case IORING_REGISTER_FILES:
11058 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11060 case IORING_UNREGISTER_FILES:
11062 if (arg || nr_args)
11064 ret = io_sqe_files_unregister(ctx);
11066 case IORING_REGISTER_FILES_UPDATE:
11067 ret = io_register_files_update(ctx, arg, nr_args);
11069 case IORING_REGISTER_EVENTFD:
11070 case IORING_REGISTER_EVENTFD_ASYNC:
11074 ret = io_eventfd_register(ctx, arg);
11077 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
11078 ctx->eventfd_async = 1;
11080 ctx->eventfd_async = 0;
11082 case IORING_UNREGISTER_EVENTFD:
11084 if (arg || nr_args)
11086 ret = io_eventfd_unregister(ctx);
11088 case IORING_REGISTER_PROBE:
11090 if (!arg || nr_args > 256)
11092 ret = io_probe(ctx, arg, nr_args);
11094 case IORING_REGISTER_PERSONALITY:
11096 if (arg || nr_args)
11098 ret = io_register_personality(ctx);
11100 case IORING_UNREGISTER_PERSONALITY:
11104 ret = io_unregister_personality(ctx, nr_args);
11106 case IORING_REGISTER_ENABLE_RINGS:
11108 if (arg || nr_args)
11110 ret = io_register_enable_rings(ctx);
11112 case IORING_REGISTER_RESTRICTIONS:
11113 ret = io_register_restrictions(ctx, arg, nr_args);
11115 case IORING_REGISTER_FILES2:
11116 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11118 case IORING_REGISTER_FILES_UPDATE2:
11119 ret = io_register_rsrc_update(ctx, arg, nr_args,
11122 case IORING_REGISTER_BUFFERS2:
11123 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11125 case IORING_REGISTER_BUFFERS_UPDATE:
11126 ret = io_register_rsrc_update(ctx, arg, nr_args,
11127 IORING_RSRC_BUFFER);
11129 case IORING_REGISTER_IOWQ_AFF:
11131 if (!arg || !nr_args)
11133 ret = io_register_iowq_aff(ctx, arg, nr_args);
11135 case IORING_UNREGISTER_IOWQ_AFF:
11137 if (arg || nr_args)
11139 ret = io_unregister_iowq_aff(ctx);
11141 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11143 if (!arg || nr_args != 2)
11145 ret = io_register_iowq_max_workers(ctx, arg);
11152 if (io_register_op_must_quiesce(opcode)) {
11153 /* bring the ctx back to life */
11154 percpu_ref_reinit(&ctx->refs);
11155 reinit_completion(&ctx->ref_comp);
11160 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11161 void __user *, arg, unsigned int, nr_args)
11163 struct io_ring_ctx *ctx;
11172 if (f.file->f_op != &io_uring_fops)
11175 ctx = f.file->private_data;
11177 io_run_task_work();
11179 mutex_lock(&ctx->uring_lock);
11180 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11181 mutex_unlock(&ctx->uring_lock);
11182 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11183 ctx->cq_ev_fd != NULL, ret);
11189 static int __init io_uring_init(void)
11191 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11192 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11193 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11196 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11197 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11198 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11199 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11200 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11201 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11202 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11203 BUILD_BUG_SQE_ELEM(8, __u64, off);
11204 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11205 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11206 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11207 BUILD_BUG_SQE_ELEM(24, __u32, len);
11208 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11209 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11210 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11211 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11212 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11213 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11214 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11215 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11216 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11217 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11218 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11219 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11220 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11221 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11222 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11223 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11224 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11225 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11226 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11227 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11228 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11230 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11231 sizeof(struct io_uring_rsrc_update));
11232 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11233 sizeof(struct io_uring_rsrc_update2));
11235 /* ->buf_index is u16 */
11236 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11238 /* should fit into one byte */
11239 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11240 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11241 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11243 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11244 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11246 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11250 __initcall(io_uring_init);