1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/tracehook.h>
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|IOSQE_IO_DRAIN)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
117 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
120 u32 head ____cacheline_aligned_in_smp;
121 u32 tail ____cacheline_aligned_in_smp;
125 * This data is shared with the application through the mmap at offsets
126 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
128 * The offsets to the member fields are published through struct
129 * io_sqring_offsets when calling io_uring_setup.
133 * Head and tail offsets into the ring; the offsets need to be
134 * masked to get valid indices.
136 * The kernel controls head of the sq ring and the tail of the cq ring,
137 * and the application controls tail of the sq ring and the head of the
140 struct io_uring sq, cq;
142 * Bitmasks to apply to head and tail offsets (constant, equals
145 u32 sq_ring_mask, cq_ring_mask;
146 /* Ring sizes (constant, power of 2) */
147 u32 sq_ring_entries, cq_ring_entries;
149 * Number of invalid entries dropped by the kernel due to
150 * invalid index stored in array
152 * Written by the kernel, shouldn't be modified by the
153 * application (i.e. get number of "new events" by comparing to
156 * After a new SQ head value was read by the application this
157 * counter includes all submissions that were dropped reaching
158 * the new SQ head (and possibly more).
164 * Written by the kernel, shouldn't be modified by the
167 * The application needs a full memory barrier before checking
168 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
174 * Written by the application, shouldn't be modified by the
179 * Number of completion events lost because the queue was full;
180 * this should be avoided by the application by making sure
181 * there are not more requests pending than there is space in
182 * the completion queue.
184 * Written by the kernel, shouldn't be modified by the
185 * application (i.e. get number of "new events" by comparing to
188 * As completion events come in out of order this counter is not
189 * ordered with any other data.
193 * Ring buffer of completion events.
195 * The kernel writes completion events fresh every time they are
196 * produced, so the application is allowed to modify pending
199 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
202 enum io_uring_cmd_flags {
203 IO_URING_F_COMPLETE_DEFER = 1,
204 IO_URING_F_UNLOCKED = 2,
205 /* int's last bit, sign checks are usually faster than a bit test */
206 IO_URING_F_NONBLOCK = INT_MIN,
209 struct io_mapped_ubuf {
212 unsigned int nr_bvecs;
213 unsigned long acct_pages;
214 struct bio_vec bvec[];
219 struct io_overflow_cqe {
220 struct io_uring_cqe cqe;
221 struct list_head list;
224 struct io_fixed_file {
225 /* file * with additional FFS_* flags */
226 unsigned long file_ptr;
230 struct list_head list;
235 struct io_mapped_ubuf *buf;
239 struct io_file_table {
240 struct io_fixed_file *files;
243 struct io_rsrc_node {
244 struct percpu_ref refs;
245 struct list_head node;
246 struct list_head rsrc_list;
247 struct io_rsrc_data *rsrc_data;
248 struct llist_node llist;
252 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
254 struct io_rsrc_data {
255 struct io_ring_ctx *ctx;
261 struct completion done;
266 struct list_head list;
272 struct io_restriction {
273 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
274 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
275 u8 sqe_flags_allowed;
276 u8 sqe_flags_required;
281 IO_SQ_THREAD_SHOULD_STOP = 0,
282 IO_SQ_THREAD_SHOULD_PARK,
287 atomic_t park_pending;
290 /* ctx's that are using this sqd */
291 struct list_head ctx_list;
293 struct task_struct *thread;
294 struct wait_queue_head wait;
296 unsigned sq_thread_idle;
302 struct completion exited;
305 #define IO_COMPL_BATCH 32
306 #define IO_REQ_CACHE_SIZE 32
307 #define IO_REQ_ALLOC_BATCH 8
309 struct io_submit_link {
310 struct io_kiocb *head;
311 struct io_kiocb *last;
314 struct io_submit_state {
315 /* inline/task_work completion list, under ->uring_lock */
316 struct io_wq_work_node free_list;
317 /* batch completion logic */
318 struct io_wq_work_list compl_reqs;
319 struct io_submit_link link;
323 unsigned short submit_nr;
324 struct blk_plug plug;
328 /* const or read-mostly hot data */
330 struct percpu_ref refs;
332 struct io_rings *rings;
334 unsigned int compat: 1;
335 unsigned int drain_next: 1;
336 unsigned int eventfd_async: 1;
337 unsigned int restricted: 1;
338 unsigned int off_timeout_used: 1;
339 unsigned int drain_active: 1;
340 } ____cacheline_aligned_in_smp;
342 /* submission data */
344 struct mutex uring_lock;
347 * Ring buffer of indices into array of io_uring_sqe, which is
348 * mmapped by the application using the IORING_OFF_SQES offset.
350 * This indirection could e.g. be used to assign fixed
351 * io_uring_sqe entries to operations and only submit them to
352 * the queue when needed.
354 * The kernel modifies neither the indices array nor the entries
358 struct io_uring_sqe *sq_sqes;
359 unsigned cached_sq_head;
361 struct list_head defer_list;
364 * Fixed resources fast path, should be accessed only under
365 * uring_lock, and updated through io_uring_register(2)
367 struct io_rsrc_node *rsrc_node;
368 int rsrc_cached_refs;
369 struct io_file_table file_table;
370 unsigned nr_user_files;
371 unsigned nr_user_bufs;
372 struct io_mapped_ubuf **user_bufs;
374 struct io_submit_state submit_state;
375 struct list_head timeout_list;
376 struct list_head ltimeout_list;
377 struct list_head cq_overflow_list;
378 struct xarray io_buffers;
379 struct xarray personalities;
381 unsigned sq_thread_idle;
382 } ____cacheline_aligned_in_smp;
384 /* IRQ completion list, under ->completion_lock */
385 struct io_wq_work_list locked_free_list;
386 unsigned int locked_free_nr;
388 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
389 struct io_sq_data *sq_data; /* if using sq thread polling */
391 struct wait_queue_head sqo_sq_wait;
392 struct list_head sqd_list;
394 unsigned long check_cq_overflow;
397 unsigned cached_cq_tail;
399 struct eventfd_ctx *cq_ev_fd;
400 struct wait_queue_head cq_wait;
402 atomic_t cq_timeouts;
403 unsigned cq_last_tm_flush;
404 } ____cacheline_aligned_in_smp;
407 spinlock_t completion_lock;
409 spinlock_t timeout_lock;
412 * ->iopoll_list is protected by the ctx->uring_lock for
413 * io_uring instances that don't use IORING_SETUP_SQPOLL.
414 * For SQPOLL, only the single threaded io_sq_thread() will
415 * manipulate the list, hence no extra locking is needed there.
417 struct io_wq_work_list iopoll_list;
418 struct hlist_head *cancel_hash;
419 unsigned cancel_hash_bits;
420 bool poll_multi_queue;
421 } ____cacheline_aligned_in_smp;
423 struct io_restriction restrictions;
425 /* slow path rsrc auxilary data, used by update/register */
427 struct io_rsrc_node *rsrc_backup_node;
428 struct io_mapped_ubuf *dummy_ubuf;
429 struct io_rsrc_data *file_data;
430 struct io_rsrc_data *buf_data;
432 struct delayed_work rsrc_put_work;
433 struct llist_head rsrc_put_llist;
434 struct list_head rsrc_ref_list;
435 spinlock_t rsrc_ref_lock;
438 /* Keep this last, we don't need it for the fast path */
440 #if defined(CONFIG_UNIX)
441 struct socket *ring_sock;
443 /* hashed buffered write serialization */
444 struct io_wq_hash *hash_map;
446 /* Only used for accounting purposes */
447 struct user_struct *user;
448 struct mm_struct *mm_account;
450 /* ctx exit and cancelation */
451 struct llist_head fallback_llist;
452 struct delayed_work fallback_work;
453 struct work_struct exit_work;
454 struct list_head tctx_list;
455 struct completion ref_comp;
457 bool iowq_limits_set;
461 struct io_uring_task {
462 /* submission side */
465 struct wait_queue_head wait;
466 const struct io_ring_ctx *last;
468 struct percpu_counter inflight;
469 atomic_t inflight_tracked;
472 spinlock_t task_lock;
473 struct io_wq_work_list task_list;
474 struct callback_head task_work;
479 * First field must be the file pointer in all the
480 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
482 struct io_poll_iocb {
484 struct wait_queue_head *head;
488 struct wait_queue_entry wait;
491 struct io_poll_update {
497 bool update_user_data;
506 struct io_timeout_data {
507 struct io_kiocb *req;
508 struct hrtimer timer;
509 struct timespec64 ts;
510 enum hrtimer_mode mode;
516 struct sockaddr __user *addr;
517 int __user *addr_len;
520 unsigned long nofile;
540 struct list_head list;
541 /* head of the link, used by linked timeouts only */
542 struct io_kiocb *head;
543 /* for linked completions */
544 struct io_kiocb *prev;
547 struct io_timeout_rem {
552 struct timespec64 ts;
558 /* NOTE: kiocb has the file as the first member, so don't do it here */
566 struct sockaddr __user *addr;
573 struct compat_msghdr __user *umsg_compat;
574 struct user_msghdr __user *umsg;
586 struct filename *filename;
588 unsigned long nofile;
591 struct io_rsrc_update {
617 struct epoll_event event;
621 struct file *file_out;
622 struct file *file_in;
629 struct io_provide_buf {
643 const char __user *filename;
644 struct statx __user *buffer;
656 struct filename *oldpath;
657 struct filename *newpath;
665 struct filename *filename;
672 struct filename *filename;
678 struct filename *oldpath;
679 struct filename *newpath;
686 struct filename *oldpath;
687 struct filename *newpath;
691 struct io_async_connect {
692 struct sockaddr_storage address;
695 struct io_async_msghdr {
696 struct iovec fast_iov[UIO_FASTIOV];
697 /* points to an allocated iov, if NULL we use fast_iov instead */
698 struct iovec *free_iov;
699 struct sockaddr __user *uaddr;
701 struct sockaddr_storage addr;
705 struct iov_iter iter;
706 struct iov_iter_state iter_state;
707 struct iovec fast_iov[UIO_FASTIOV];
711 struct io_rw_state s;
712 const struct iovec *free_iovec;
714 struct wait_page_queue wpq;
718 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
719 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
720 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
721 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
722 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
723 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
725 /* first byte is taken by user flags, shift it to not overlap */
730 REQ_F_LINK_TIMEOUT_BIT,
731 REQ_F_NEED_CLEANUP_BIT,
733 REQ_F_BUFFER_SELECTED_BIT,
734 REQ_F_COMPLETE_INLINE_BIT,
738 REQ_F_ARM_LTIMEOUT_BIT,
739 REQ_F_ASYNC_DATA_BIT,
740 /* keep async read/write and isreg together and in order */
741 REQ_F_SUPPORT_NOWAIT_BIT,
744 /* not a real bit, just to check we're not overflowing the space */
750 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
751 /* drain existing IO first */
752 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
754 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
755 /* doesn't sever on completion < 0 */
756 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
758 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
759 /* IOSQE_BUFFER_SELECT */
760 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
762 /* fail rest of links */
763 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
764 /* on inflight list, should be cancelled and waited on exit reliably */
765 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
766 /* read/write uses file position */
767 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
768 /* must not punt to workers */
769 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
770 /* has or had linked timeout */
771 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
773 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
774 /* already went through poll handler */
775 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
776 /* buffer already selected */
777 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
778 /* completion is deferred through io_comp_state */
779 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
780 /* caller should reissue async */
781 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
782 /* supports async reads/writes */
783 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
785 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
786 /* has creds assigned */
787 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
788 /* skip refcounting if not set */
789 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
790 /* there is a linked timeout that has to be armed */
791 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
792 /* ->async_data allocated */
793 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
797 struct io_poll_iocb poll;
798 struct io_poll_iocb *double_poll;
801 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
803 struct io_task_work {
805 struct io_wq_work_node node;
806 struct llist_node fallback_node;
808 io_req_tw_func_t func;
812 IORING_RSRC_FILE = 0,
813 IORING_RSRC_BUFFER = 1,
817 * NOTE! Each of the iocb union members has the file pointer
818 * as the first entry in their struct definition. So you can
819 * access the file pointer through any of the sub-structs,
820 * or directly as just 'ki_filp' in this struct.
826 struct io_poll_iocb poll;
827 struct io_poll_update poll_update;
828 struct io_accept accept;
830 struct io_cancel cancel;
831 struct io_timeout timeout;
832 struct io_timeout_rem timeout_rem;
833 struct io_connect connect;
834 struct io_sr_msg sr_msg;
836 struct io_close close;
837 struct io_rsrc_update rsrc_update;
838 struct io_fadvise fadvise;
839 struct io_madvise madvise;
840 struct io_epoll epoll;
841 struct io_splice splice;
842 struct io_provide_buf pbuf;
843 struct io_statx statx;
844 struct io_shutdown shutdown;
845 struct io_rename rename;
846 struct io_unlink unlink;
847 struct io_mkdir mkdir;
848 struct io_symlink symlink;
849 struct io_hardlink hardlink;
853 /* polled IO has completed */
862 struct io_ring_ctx *ctx;
863 struct task_struct *task;
865 struct percpu_ref *fixed_rsrc_refs;
866 /* store used ubuf, so we can prevent reloading */
867 struct io_mapped_ubuf *imu;
869 /* used by request caches, completion batching and iopoll */
870 struct io_wq_work_node comp_list;
872 struct io_kiocb *link;
873 struct io_task_work io_task_work;
874 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
875 struct hlist_node hash_node;
876 /* internal polling, see IORING_FEAT_FAST_POLL */
877 struct async_poll *apoll;
878 /* opcode allocated if it needs to store data for async defer */
880 struct io_wq_work work;
881 /* custom credentials, valid IFF REQ_F_CREDS is set */
882 const struct cred *creds;
883 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
884 struct io_buffer *kbuf;
887 struct io_tctx_node {
888 struct list_head ctx_node;
889 struct task_struct *task;
890 struct io_ring_ctx *ctx;
893 struct io_defer_entry {
894 struct list_head list;
895 struct io_kiocb *req;
900 /* needs req->file assigned */
901 unsigned needs_file : 1;
902 /* should block plug */
904 /* hash wq insertion if file is a regular file */
905 unsigned hash_reg_file : 1;
906 /* unbound wq insertion if file is a non-regular file */
907 unsigned unbound_nonreg_file : 1;
908 /* set if opcode supports polled "wait" */
910 unsigned pollout : 1;
911 /* op supports buffer selection */
912 unsigned buffer_select : 1;
913 /* do prep async if is going to be punted */
914 unsigned needs_async_setup : 1;
915 /* opcode is not supported by this kernel */
916 unsigned not_supported : 1;
918 unsigned audit_skip : 1;
919 /* size of async data needed, if any */
920 unsigned short async_size;
923 static const struct io_op_def io_op_defs[] = {
924 [IORING_OP_NOP] = {},
925 [IORING_OP_READV] = {
927 .unbound_nonreg_file = 1,
930 .needs_async_setup = 1,
933 .async_size = sizeof(struct io_async_rw),
935 [IORING_OP_WRITEV] = {
938 .unbound_nonreg_file = 1,
940 .needs_async_setup = 1,
943 .async_size = sizeof(struct io_async_rw),
945 [IORING_OP_FSYNC] = {
949 [IORING_OP_READ_FIXED] = {
951 .unbound_nonreg_file = 1,
955 .async_size = sizeof(struct io_async_rw),
957 [IORING_OP_WRITE_FIXED] = {
960 .unbound_nonreg_file = 1,
964 .async_size = sizeof(struct io_async_rw),
966 [IORING_OP_POLL_ADD] = {
968 .unbound_nonreg_file = 1,
971 [IORING_OP_POLL_REMOVE] = {
974 [IORING_OP_SYNC_FILE_RANGE] = {
978 [IORING_OP_SENDMSG] = {
980 .unbound_nonreg_file = 1,
982 .needs_async_setup = 1,
983 .async_size = sizeof(struct io_async_msghdr),
985 [IORING_OP_RECVMSG] = {
987 .unbound_nonreg_file = 1,
990 .needs_async_setup = 1,
991 .async_size = sizeof(struct io_async_msghdr),
993 [IORING_OP_TIMEOUT] = {
995 .async_size = sizeof(struct io_timeout_data),
997 [IORING_OP_TIMEOUT_REMOVE] = {
998 /* used by timeout updates' prep() */
1001 [IORING_OP_ACCEPT] = {
1003 .unbound_nonreg_file = 1,
1006 [IORING_OP_ASYNC_CANCEL] = {
1009 [IORING_OP_LINK_TIMEOUT] = {
1011 .async_size = sizeof(struct io_timeout_data),
1013 [IORING_OP_CONNECT] = {
1015 .unbound_nonreg_file = 1,
1017 .needs_async_setup = 1,
1018 .async_size = sizeof(struct io_async_connect),
1020 [IORING_OP_FALLOCATE] = {
1023 [IORING_OP_OPENAT] = {},
1024 [IORING_OP_CLOSE] = {},
1025 [IORING_OP_FILES_UPDATE] = {
1028 [IORING_OP_STATX] = {
1031 [IORING_OP_READ] = {
1033 .unbound_nonreg_file = 1,
1038 .async_size = sizeof(struct io_async_rw),
1040 [IORING_OP_WRITE] = {
1043 .unbound_nonreg_file = 1,
1047 .async_size = sizeof(struct io_async_rw),
1049 [IORING_OP_FADVISE] = {
1053 [IORING_OP_MADVISE] = {},
1054 [IORING_OP_SEND] = {
1056 .unbound_nonreg_file = 1,
1060 [IORING_OP_RECV] = {
1062 .unbound_nonreg_file = 1,
1067 [IORING_OP_OPENAT2] = {
1069 [IORING_OP_EPOLL_CTL] = {
1070 .unbound_nonreg_file = 1,
1073 [IORING_OP_SPLICE] = {
1076 .unbound_nonreg_file = 1,
1079 [IORING_OP_PROVIDE_BUFFERS] = {
1082 [IORING_OP_REMOVE_BUFFERS] = {
1088 .unbound_nonreg_file = 1,
1091 [IORING_OP_SHUTDOWN] = {
1094 [IORING_OP_RENAMEAT] = {},
1095 [IORING_OP_UNLINKAT] = {},
1096 [IORING_OP_MKDIRAT] = {},
1097 [IORING_OP_SYMLINKAT] = {},
1098 [IORING_OP_LINKAT] = {},
1101 /* requests with any of those set should undergo io_disarm_next() */
1102 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1104 static bool io_disarm_next(struct io_kiocb *req);
1105 static void io_uring_del_tctx_node(unsigned long index);
1106 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1107 struct task_struct *task,
1109 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1111 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1112 s32 res, u32 cflags);
1113 static void io_put_req(struct io_kiocb *req);
1114 static void io_put_req_deferred(struct io_kiocb *req);
1115 static void io_dismantle_req(struct io_kiocb *req);
1116 static void io_queue_linked_timeout(struct io_kiocb *req);
1117 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1118 struct io_uring_rsrc_update2 *up,
1120 static void io_clean_op(struct io_kiocb *req);
1121 static struct file *io_file_get(struct io_ring_ctx *ctx,
1122 struct io_kiocb *req, int fd, bool fixed);
1123 static void __io_queue_sqe(struct io_kiocb *req);
1124 static void io_rsrc_put_work(struct work_struct *work);
1126 static void io_req_task_queue(struct io_kiocb *req);
1127 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1128 static int io_req_prep_async(struct io_kiocb *req);
1130 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1131 unsigned int issue_flags, u32 slot_index);
1132 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1134 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1136 static struct kmem_cache *req_cachep;
1138 static const struct file_operations io_uring_fops;
1140 struct sock *io_uring_get_socket(struct file *file)
1142 #if defined(CONFIG_UNIX)
1143 if (file->f_op == &io_uring_fops) {
1144 struct io_ring_ctx *ctx = file->private_data;
1146 return ctx->ring_sock->sk;
1151 EXPORT_SYMBOL(io_uring_get_socket);
1153 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1156 mutex_lock(&ctx->uring_lock);
1161 #define io_for_each_link(pos, head) \
1162 for (pos = (head); pos; pos = pos->link)
1165 * Shamelessly stolen from the mm implementation of page reference checking,
1166 * see commit f958d7b528b1 for details.
1168 #define req_ref_zero_or_close_to_overflow(req) \
1169 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1171 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1173 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1174 return atomic_inc_not_zero(&req->refs);
1177 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1179 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1182 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1183 return atomic_dec_and_test(&req->refs);
1186 static inline void req_ref_put(struct io_kiocb *req)
1188 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1189 WARN_ON_ONCE(req_ref_put_and_test(req));
1192 static inline void req_ref_get(struct io_kiocb *req)
1194 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1195 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1196 atomic_inc(&req->refs);
1199 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1201 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1202 __io_submit_flush_completions(ctx);
1205 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1207 if (!(req->flags & REQ_F_REFCOUNT)) {
1208 req->flags |= REQ_F_REFCOUNT;
1209 atomic_set(&req->refs, nr);
1213 static inline void io_req_set_refcount(struct io_kiocb *req)
1215 __io_req_set_refcount(req, 1);
1218 #define IO_RSRC_REF_BATCH 100
1220 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1221 struct io_ring_ctx *ctx)
1222 __must_hold(&ctx->uring_lock)
1224 struct percpu_ref *ref = req->fixed_rsrc_refs;
1227 if (ref == &ctx->rsrc_node->refs)
1228 ctx->rsrc_cached_refs++;
1230 percpu_ref_put(ref);
1234 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1236 if (req->fixed_rsrc_refs)
1237 percpu_ref_put(req->fixed_rsrc_refs);
1240 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1241 __must_hold(&ctx->uring_lock)
1243 if (ctx->rsrc_cached_refs) {
1244 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1245 ctx->rsrc_cached_refs = 0;
1249 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1250 __must_hold(&ctx->uring_lock)
1252 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1253 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1256 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1257 struct io_ring_ctx *ctx)
1259 if (!req->fixed_rsrc_refs) {
1260 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1261 ctx->rsrc_cached_refs--;
1262 if (unlikely(ctx->rsrc_cached_refs < 0))
1263 io_rsrc_refs_refill(ctx);
1267 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1269 bool got = percpu_ref_tryget(ref);
1271 /* already at zero, wait for ->release() */
1273 wait_for_completion(compl);
1274 percpu_ref_resurrect(ref);
1276 percpu_ref_put(ref);
1279 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1281 __must_hold(&req->ctx->timeout_lock)
1283 struct io_kiocb *req;
1285 if (task && head->task != task)
1290 io_for_each_link(req, head) {
1291 if (req->flags & REQ_F_INFLIGHT)
1297 static bool io_match_linked(struct io_kiocb *head)
1299 struct io_kiocb *req;
1301 io_for_each_link(req, head) {
1302 if (req->flags & REQ_F_INFLIGHT)
1309 * As io_match_task() but protected against racing with linked timeouts.
1310 * User must not hold timeout_lock.
1312 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1317 if (task && head->task != task)
1322 if (head->flags & REQ_F_LINK_TIMEOUT) {
1323 struct io_ring_ctx *ctx = head->ctx;
1325 /* protect against races with linked timeouts */
1326 spin_lock_irq(&ctx->timeout_lock);
1327 matched = io_match_linked(head);
1328 spin_unlock_irq(&ctx->timeout_lock);
1330 matched = io_match_linked(head);
1335 static inline bool req_has_async_data(struct io_kiocb *req)
1337 return req->flags & REQ_F_ASYNC_DATA;
1340 static inline void req_set_fail(struct io_kiocb *req)
1342 req->flags |= REQ_F_FAIL;
1345 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1351 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1353 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1355 complete(&ctx->ref_comp);
1358 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1360 return !req->timeout.off;
1363 static __cold void io_fallback_req_func(struct work_struct *work)
1365 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1366 fallback_work.work);
1367 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1368 struct io_kiocb *req, *tmp;
1369 bool locked = false;
1371 percpu_ref_get(&ctx->refs);
1372 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1373 req->io_task_work.func(req, &locked);
1376 io_submit_flush_completions(ctx);
1377 mutex_unlock(&ctx->uring_lock);
1379 percpu_ref_put(&ctx->refs);
1382 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1384 struct io_ring_ctx *ctx;
1387 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1392 * Use 5 bits less than the max cq entries, that should give us around
1393 * 32 entries per hash list if totally full and uniformly spread.
1395 hash_bits = ilog2(p->cq_entries);
1399 ctx->cancel_hash_bits = hash_bits;
1400 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1402 if (!ctx->cancel_hash)
1404 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1406 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1407 if (!ctx->dummy_ubuf)
1409 /* set invalid range, so io_import_fixed() fails meeting it */
1410 ctx->dummy_ubuf->ubuf = -1UL;
1412 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1413 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1416 ctx->flags = p->flags;
1417 init_waitqueue_head(&ctx->sqo_sq_wait);
1418 INIT_LIST_HEAD(&ctx->sqd_list);
1419 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1420 init_completion(&ctx->ref_comp);
1421 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1422 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1423 mutex_init(&ctx->uring_lock);
1424 init_waitqueue_head(&ctx->cq_wait);
1425 spin_lock_init(&ctx->completion_lock);
1426 spin_lock_init(&ctx->timeout_lock);
1427 INIT_WQ_LIST(&ctx->iopoll_list);
1428 INIT_LIST_HEAD(&ctx->defer_list);
1429 INIT_LIST_HEAD(&ctx->timeout_list);
1430 INIT_LIST_HEAD(&ctx->ltimeout_list);
1431 spin_lock_init(&ctx->rsrc_ref_lock);
1432 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1433 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1434 init_llist_head(&ctx->rsrc_put_llist);
1435 INIT_LIST_HEAD(&ctx->tctx_list);
1436 ctx->submit_state.free_list.next = NULL;
1437 INIT_WQ_LIST(&ctx->locked_free_list);
1438 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1439 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1442 kfree(ctx->dummy_ubuf);
1443 kfree(ctx->cancel_hash);
1448 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1450 struct io_rings *r = ctx->rings;
1452 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1456 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1458 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1459 struct io_ring_ctx *ctx = req->ctx;
1461 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1467 #define FFS_NOWAIT 0x1UL
1468 #define FFS_ISREG 0x2UL
1469 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1471 static inline bool io_req_ffs_set(struct io_kiocb *req)
1473 return req->flags & REQ_F_FIXED_FILE;
1476 static inline void io_req_track_inflight(struct io_kiocb *req)
1478 if (!(req->flags & REQ_F_INFLIGHT)) {
1479 req->flags |= REQ_F_INFLIGHT;
1480 atomic_inc(¤t->io_uring->inflight_tracked);
1484 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1486 if (WARN_ON_ONCE(!req->link))
1489 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1490 req->flags |= REQ_F_LINK_TIMEOUT;
1492 /* linked timeouts should have two refs once prep'ed */
1493 io_req_set_refcount(req);
1494 __io_req_set_refcount(req->link, 2);
1498 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1500 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1502 return __io_prep_linked_timeout(req);
1505 static void io_prep_async_work(struct io_kiocb *req)
1507 const struct io_op_def *def = &io_op_defs[req->opcode];
1508 struct io_ring_ctx *ctx = req->ctx;
1510 if (!(req->flags & REQ_F_CREDS)) {
1511 req->flags |= REQ_F_CREDS;
1512 req->creds = get_current_cred();
1515 req->work.list.next = NULL;
1516 req->work.flags = 0;
1517 if (req->flags & REQ_F_FORCE_ASYNC)
1518 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1520 if (req->flags & REQ_F_ISREG) {
1521 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1522 io_wq_hash_work(&req->work, file_inode(req->file));
1523 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1524 if (def->unbound_nonreg_file)
1525 req->work.flags |= IO_WQ_WORK_UNBOUND;
1528 switch (req->opcode) {
1529 case IORING_OP_SPLICE:
1531 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1532 req->work.flags |= IO_WQ_WORK_UNBOUND;
1537 static void io_prep_async_link(struct io_kiocb *req)
1539 struct io_kiocb *cur;
1541 if (req->flags & REQ_F_LINK_TIMEOUT) {
1542 struct io_ring_ctx *ctx = req->ctx;
1544 spin_lock_irq(&ctx->timeout_lock);
1545 io_for_each_link(cur, req)
1546 io_prep_async_work(cur);
1547 spin_unlock_irq(&ctx->timeout_lock);
1549 io_for_each_link(cur, req)
1550 io_prep_async_work(cur);
1554 static inline void io_req_add_compl_list(struct io_kiocb *req)
1556 struct io_submit_state *state = &req->ctx->submit_state;
1558 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1561 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1563 struct io_ring_ctx *ctx = req->ctx;
1564 struct io_kiocb *link = io_prep_linked_timeout(req);
1565 struct io_uring_task *tctx = req->task->io_uring;
1568 BUG_ON(!tctx->io_wq);
1570 /* init ->work of the whole link before punting */
1571 io_prep_async_link(req);
1574 * Not expected to happen, but if we do have a bug where this _can_
1575 * happen, catch it here and ensure the request is marked as
1576 * canceled. That will make io-wq go through the usual work cancel
1577 * procedure rather than attempt to run this request (or create a new
1580 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1581 req->work.flags |= IO_WQ_WORK_CANCEL;
1583 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1584 &req->work, req->flags);
1585 io_wq_enqueue(tctx->io_wq, &req->work);
1587 io_queue_linked_timeout(link);
1590 static void io_kill_timeout(struct io_kiocb *req, int status)
1591 __must_hold(&req->ctx->completion_lock)
1592 __must_hold(&req->ctx->timeout_lock)
1594 struct io_timeout_data *io = req->async_data;
1596 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1599 atomic_set(&req->ctx->cq_timeouts,
1600 atomic_read(&req->ctx->cq_timeouts) + 1);
1601 list_del_init(&req->timeout.list);
1602 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1603 io_put_req_deferred(req);
1607 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1609 while (!list_empty(&ctx->defer_list)) {
1610 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1611 struct io_defer_entry, list);
1613 if (req_need_defer(de->req, de->seq))
1615 list_del_init(&de->list);
1616 io_req_task_queue(de->req);
1621 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1622 __must_hold(&ctx->completion_lock)
1624 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1626 spin_lock_irq(&ctx->timeout_lock);
1627 while (!list_empty(&ctx->timeout_list)) {
1628 u32 events_needed, events_got;
1629 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1630 struct io_kiocb, timeout.list);
1632 if (io_is_timeout_noseq(req))
1636 * Since seq can easily wrap around over time, subtract
1637 * the last seq at which timeouts were flushed before comparing.
1638 * Assuming not more than 2^31-1 events have happened since,
1639 * these subtractions won't have wrapped, so we can check if
1640 * target is in [last_seq, current_seq] by comparing the two.
1642 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1643 events_got = seq - ctx->cq_last_tm_flush;
1644 if (events_got < events_needed)
1647 list_del_init(&req->timeout.list);
1648 io_kill_timeout(req, 0);
1650 ctx->cq_last_tm_flush = seq;
1651 spin_unlock_irq(&ctx->timeout_lock);
1654 static __cold void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1656 if (ctx->off_timeout_used)
1657 io_flush_timeouts(ctx);
1658 if (ctx->drain_active)
1659 io_queue_deferred(ctx);
1662 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1664 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1665 __io_commit_cqring_flush(ctx);
1666 /* order cqe stores with ring update */
1667 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1670 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1672 struct io_rings *r = ctx->rings;
1674 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1677 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1679 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1682 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1684 struct io_rings *rings = ctx->rings;
1685 unsigned tail, mask = ctx->cq_entries - 1;
1688 * writes to the cq entry need to come after reading head; the
1689 * control dependency is enough as we're using WRITE_ONCE to
1692 if (__io_cqring_events(ctx) == ctx->cq_entries)
1695 tail = ctx->cached_cq_tail++;
1696 return &rings->cqes[tail & mask];
1699 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1701 if (likely(!ctx->cq_ev_fd))
1703 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1705 return !ctx->eventfd_async || io_wq_current_is_worker();
1709 * This should only get called when at least one event has been posted.
1710 * Some applications rely on the eventfd notification count only changing
1711 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1712 * 1:1 relationship between how many times this function is called (and
1713 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1715 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1718 * wake_up_all() may seem excessive, but io_wake_function() and
1719 * io_should_wake() handle the termination of the loop and only
1720 * wake as many waiters as we need to.
1722 if (wq_has_sleeper(&ctx->cq_wait))
1723 wake_up_all(&ctx->cq_wait);
1724 if (io_should_trigger_evfd(ctx))
1725 eventfd_signal(ctx->cq_ev_fd, 1);
1728 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1730 /* see waitqueue_active() comment */
1733 if (ctx->flags & IORING_SETUP_SQPOLL) {
1734 if (waitqueue_active(&ctx->cq_wait))
1735 wake_up_all(&ctx->cq_wait);
1737 if (io_should_trigger_evfd(ctx))
1738 eventfd_signal(ctx->cq_ev_fd, 1);
1741 /* Returns true if there are no backlogged entries after the flush */
1742 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1744 bool all_flushed, posted;
1746 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1750 spin_lock(&ctx->completion_lock);
1751 while (!list_empty(&ctx->cq_overflow_list)) {
1752 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1753 struct io_overflow_cqe *ocqe;
1757 ocqe = list_first_entry(&ctx->cq_overflow_list,
1758 struct io_overflow_cqe, list);
1760 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1762 io_account_cq_overflow(ctx);
1765 list_del(&ocqe->list);
1769 all_flushed = list_empty(&ctx->cq_overflow_list);
1771 clear_bit(0, &ctx->check_cq_overflow);
1772 WRITE_ONCE(ctx->rings->sq_flags,
1773 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1777 io_commit_cqring(ctx);
1778 spin_unlock(&ctx->completion_lock);
1780 io_cqring_ev_posted(ctx);
1784 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1788 if (test_bit(0, &ctx->check_cq_overflow)) {
1789 /* iopoll syncs against uring_lock, not completion_lock */
1790 if (ctx->flags & IORING_SETUP_IOPOLL)
1791 mutex_lock(&ctx->uring_lock);
1792 ret = __io_cqring_overflow_flush(ctx, false);
1793 if (ctx->flags & IORING_SETUP_IOPOLL)
1794 mutex_unlock(&ctx->uring_lock);
1800 /* must to be called somewhat shortly after putting a request */
1801 static inline void io_put_task(struct task_struct *task, int nr)
1803 struct io_uring_task *tctx = task->io_uring;
1805 if (likely(task == current)) {
1806 tctx->cached_refs += nr;
1808 percpu_counter_sub(&tctx->inflight, nr);
1809 if (unlikely(atomic_read(&tctx->in_idle)))
1810 wake_up(&tctx->wait);
1811 put_task_struct_many(task, nr);
1815 static void io_task_refs_refill(struct io_uring_task *tctx)
1817 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1819 percpu_counter_add(&tctx->inflight, refill);
1820 refcount_add(refill, ¤t->usage);
1821 tctx->cached_refs += refill;
1824 static inline void io_get_task_refs(int nr)
1826 struct io_uring_task *tctx = current->io_uring;
1828 tctx->cached_refs -= nr;
1829 if (unlikely(tctx->cached_refs < 0))
1830 io_task_refs_refill(tctx);
1833 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1834 s32 res, u32 cflags)
1836 struct io_overflow_cqe *ocqe;
1838 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1841 * If we're in ring overflow flush mode, or in task cancel mode,
1842 * or cannot allocate an overflow entry, then we need to drop it
1845 io_account_cq_overflow(ctx);
1848 if (list_empty(&ctx->cq_overflow_list)) {
1849 set_bit(0, &ctx->check_cq_overflow);
1850 WRITE_ONCE(ctx->rings->sq_flags,
1851 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1854 ocqe->cqe.user_data = user_data;
1855 ocqe->cqe.res = res;
1856 ocqe->cqe.flags = cflags;
1857 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1861 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1862 s32 res, u32 cflags)
1864 struct io_uring_cqe *cqe;
1866 trace_io_uring_complete(ctx, user_data, res, cflags);
1869 * If we can't get a cq entry, userspace overflowed the
1870 * submission (by quite a lot). Increment the overflow count in
1873 cqe = io_get_cqe(ctx);
1875 WRITE_ONCE(cqe->user_data, user_data);
1876 WRITE_ONCE(cqe->res, res);
1877 WRITE_ONCE(cqe->flags, cflags);
1880 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1883 /* not as hot to bloat with inlining */
1884 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1885 s32 res, u32 cflags)
1887 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1890 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1893 struct io_ring_ctx *ctx = req->ctx;
1895 spin_lock(&ctx->completion_lock);
1896 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1898 * If we're the last reference to this request, add to our locked
1901 if (req_ref_put_and_test(req)) {
1902 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1903 if (req->flags & IO_DISARM_MASK)
1904 io_disarm_next(req);
1906 io_req_task_queue(req->link);
1910 io_req_put_rsrc(req, ctx);
1911 io_dismantle_req(req);
1912 io_put_task(req->task, 1);
1913 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1914 ctx->locked_free_nr++;
1916 io_commit_cqring(ctx);
1917 spin_unlock(&ctx->completion_lock);
1918 io_cqring_ev_posted(ctx);
1921 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1925 req->cflags = cflags;
1926 req->flags |= REQ_F_COMPLETE_INLINE;
1929 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1930 s32 res, u32 cflags)
1932 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1933 io_req_complete_state(req, res, cflags);
1935 io_req_complete_post(req, res, cflags);
1938 static inline void io_req_complete(struct io_kiocb *req, s32 res)
1940 __io_req_complete(req, 0, res, 0);
1943 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1946 io_req_complete_post(req, res, 0);
1949 static void io_req_complete_fail_submit(struct io_kiocb *req)
1952 * We don't submit, fail them all, for that replace hardlinks with
1953 * normal links. Extra REQ_F_LINK is tolerated.
1955 req->flags &= ~REQ_F_HARDLINK;
1956 req->flags |= REQ_F_LINK;
1957 io_req_complete_failed(req, req->result);
1961 * Don't initialise the fields below on every allocation, but do that in
1962 * advance and keep them valid across allocations.
1964 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1968 req->async_data = NULL;
1969 /* not necessary, but safer to zero */
1973 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1974 struct io_submit_state *state)
1976 spin_lock(&ctx->completion_lock);
1977 wq_list_splice(&ctx->locked_free_list, &state->free_list);
1978 ctx->locked_free_nr = 0;
1979 spin_unlock(&ctx->completion_lock);
1982 /* Returns true IFF there are requests in the cache */
1983 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1985 struct io_submit_state *state = &ctx->submit_state;
1988 * If we have more than a batch's worth of requests in our IRQ side
1989 * locked cache, grab the lock and move them over to our submission
1992 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1993 io_flush_cached_locked_reqs(ctx, state);
1994 return !!state->free_list.next;
1998 * A request might get retired back into the request caches even before opcode
1999 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2000 * Because of that, io_alloc_req() should be called only under ->uring_lock
2001 * and with extra caution to not get a request that is still worked on.
2003 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2004 __must_hold(&ctx->uring_lock)
2006 struct io_submit_state *state = &ctx->submit_state;
2007 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2008 void *reqs[IO_REQ_ALLOC_BATCH];
2009 struct io_kiocb *req;
2012 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2015 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2018 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2019 * retry single alloc to be on the safe side.
2021 if (unlikely(ret <= 0)) {
2022 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2028 percpu_ref_get_many(&ctx->refs, ret);
2029 for (i = 0; i < ret; i++) {
2032 io_preinit_req(req, ctx);
2033 wq_stack_add_head(&req->comp_list, &state->free_list);
2038 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2040 if (unlikely(!ctx->submit_state.free_list.next))
2041 return __io_alloc_req_refill(ctx);
2045 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2047 struct io_wq_work_node *node;
2049 node = wq_stack_extract(&ctx->submit_state.free_list);
2050 return container_of(node, struct io_kiocb, comp_list);
2053 static inline void io_put_file(struct file *file)
2059 static inline void io_dismantle_req(struct io_kiocb *req)
2061 unsigned int flags = req->flags;
2063 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2065 if (!(flags & REQ_F_FIXED_FILE))
2066 io_put_file(req->file);
2069 static __cold void __io_free_req(struct io_kiocb *req)
2071 struct io_ring_ctx *ctx = req->ctx;
2073 io_req_put_rsrc(req, ctx);
2074 io_dismantle_req(req);
2075 io_put_task(req->task, 1);
2077 spin_lock(&ctx->completion_lock);
2078 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2079 ctx->locked_free_nr++;
2080 spin_unlock(&ctx->completion_lock);
2083 static inline void io_remove_next_linked(struct io_kiocb *req)
2085 struct io_kiocb *nxt = req->link;
2087 req->link = nxt->link;
2091 static bool io_kill_linked_timeout(struct io_kiocb *req)
2092 __must_hold(&req->ctx->completion_lock)
2093 __must_hold(&req->ctx->timeout_lock)
2095 struct io_kiocb *link = req->link;
2097 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2098 struct io_timeout_data *io = link->async_data;
2100 io_remove_next_linked(req);
2101 link->timeout.head = NULL;
2102 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2103 list_del(&link->timeout.list);
2104 io_cqring_fill_event(link->ctx, link->user_data,
2106 io_put_req_deferred(link);
2113 static void io_fail_links(struct io_kiocb *req)
2114 __must_hold(&req->ctx->completion_lock)
2116 struct io_kiocb *nxt, *link = req->link;
2120 long res = -ECANCELED;
2122 if (link->flags & REQ_F_FAIL)
2128 trace_io_uring_fail_link(req, link);
2129 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2130 io_put_req_deferred(link);
2135 static bool io_disarm_next(struct io_kiocb *req)
2136 __must_hold(&req->ctx->completion_lock)
2138 bool posted = false;
2140 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2141 struct io_kiocb *link = req->link;
2143 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2144 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2145 io_remove_next_linked(req);
2146 io_cqring_fill_event(link->ctx, link->user_data,
2148 io_put_req_deferred(link);
2151 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2152 struct io_ring_ctx *ctx = req->ctx;
2154 spin_lock_irq(&ctx->timeout_lock);
2155 posted = io_kill_linked_timeout(req);
2156 spin_unlock_irq(&ctx->timeout_lock);
2158 if (unlikely((req->flags & REQ_F_FAIL) &&
2159 !(req->flags & REQ_F_HARDLINK))) {
2160 posted |= (req->link != NULL);
2166 static void __io_req_find_next_prep(struct io_kiocb *req)
2168 struct io_ring_ctx *ctx = req->ctx;
2171 spin_lock(&ctx->completion_lock);
2172 posted = io_disarm_next(req);
2174 io_commit_cqring(req->ctx);
2175 spin_unlock(&ctx->completion_lock);
2177 io_cqring_ev_posted(ctx);
2180 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2182 struct io_kiocb *nxt;
2184 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2187 * If LINK is set, we have dependent requests in this chain. If we
2188 * didn't fail this request, queue the first one up, moving any other
2189 * dependencies to the next request. In case of failure, fail the rest
2192 if (unlikely(req->flags & IO_DISARM_MASK))
2193 __io_req_find_next_prep(req);
2199 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2204 io_submit_flush_completions(ctx);
2205 mutex_unlock(&ctx->uring_lock);
2208 percpu_ref_put(&ctx->refs);
2211 static void tctx_task_work(struct callback_head *cb)
2213 bool locked = false;
2214 struct io_ring_ctx *ctx = NULL;
2215 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2219 struct io_wq_work_node *node;
2221 if (!tctx->task_list.first && locked)
2222 io_submit_flush_completions(ctx);
2224 spin_lock_irq(&tctx->task_lock);
2225 node = tctx->task_list.first;
2226 INIT_WQ_LIST(&tctx->task_list);
2228 tctx->task_running = false;
2229 spin_unlock_irq(&tctx->task_lock);
2234 struct io_wq_work_node *next = node->next;
2235 struct io_kiocb *req = container_of(node, struct io_kiocb,
2238 if (req->ctx != ctx) {
2239 ctx_flush_and_put(ctx, &locked);
2241 /* if not contended, grab and improve batching */
2242 locked = mutex_trylock(&ctx->uring_lock);
2243 percpu_ref_get(&ctx->refs);
2245 req->io_task_work.func(req, &locked);
2252 ctx_flush_and_put(ctx, &locked);
2255 static void io_req_task_work_add(struct io_kiocb *req)
2257 struct task_struct *tsk = req->task;
2258 struct io_uring_task *tctx = tsk->io_uring;
2259 enum task_work_notify_mode notify;
2260 struct io_wq_work_node *node;
2261 unsigned long flags;
2264 WARN_ON_ONCE(!tctx);
2266 spin_lock_irqsave(&tctx->task_lock, flags);
2267 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2268 running = tctx->task_running;
2270 tctx->task_running = true;
2271 spin_unlock_irqrestore(&tctx->task_lock, flags);
2273 /* task_work already pending, we're done */
2278 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2279 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2280 * processing task_work. There's no reliable way to tell if TWA_RESUME
2283 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2284 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2285 if (notify == TWA_NONE)
2286 wake_up_process(tsk);
2290 spin_lock_irqsave(&tctx->task_lock, flags);
2291 tctx->task_running = false;
2292 node = tctx->task_list.first;
2293 INIT_WQ_LIST(&tctx->task_list);
2294 spin_unlock_irqrestore(&tctx->task_lock, flags);
2297 req = container_of(node, struct io_kiocb, io_task_work.node);
2299 if (llist_add(&req->io_task_work.fallback_node,
2300 &req->ctx->fallback_llist))
2301 schedule_delayed_work(&req->ctx->fallback_work, 1);
2305 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2307 struct io_ring_ctx *ctx = req->ctx;
2309 /* not needed for normal modes, but SQPOLL depends on it */
2310 io_tw_lock(ctx, locked);
2311 io_req_complete_failed(req, req->result);
2314 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2316 struct io_ring_ctx *ctx = req->ctx;
2318 io_tw_lock(ctx, locked);
2319 /* req->task == current here, checking PF_EXITING is safe */
2320 if (likely(!(req->task->flags & PF_EXITING)))
2321 __io_queue_sqe(req);
2323 io_req_complete_failed(req, -EFAULT);
2326 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2329 req->io_task_work.func = io_req_task_cancel;
2330 io_req_task_work_add(req);
2333 static void io_req_task_queue(struct io_kiocb *req)
2335 req->io_task_work.func = io_req_task_submit;
2336 io_req_task_work_add(req);
2339 static void io_req_task_queue_reissue(struct io_kiocb *req)
2341 req->io_task_work.func = io_queue_async_work;
2342 io_req_task_work_add(req);
2345 static inline void io_queue_next(struct io_kiocb *req)
2347 struct io_kiocb *nxt = io_req_find_next(req);
2350 io_req_task_queue(nxt);
2353 static void io_free_req(struct io_kiocb *req)
2359 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2364 static void io_free_batch_list(struct io_ring_ctx *ctx,
2365 struct io_wq_work_node *node)
2366 __must_hold(&ctx->uring_lock)
2368 struct task_struct *task = NULL;
2372 struct io_kiocb *req = container_of(node, struct io_kiocb,
2375 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2376 node = req->comp_list.next;
2377 if (!req_ref_put_and_test(req))
2381 io_req_put_rsrc_locked(req, ctx);
2383 io_dismantle_req(req);
2385 if (req->task != task) {
2387 io_put_task(task, task_refs);
2392 node = req->comp_list.next;
2393 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2397 io_put_task(task, task_refs);
2400 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2401 __must_hold(&ctx->uring_lock)
2403 struct io_wq_work_node *node, *prev;
2404 struct io_submit_state *state = &ctx->submit_state;
2406 spin_lock(&ctx->completion_lock);
2407 wq_list_for_each(node, prev, &state->compl_reqs) {
2408 struct io_kiocb *req = container_of(node, struct io_kiocb,
2411 __io_cqring_fill_event(ctx, req->user_data, req->result,
2414 io_commit_cqring(ctx);
2415 spin_unlock(&ctx->completion_lock);
2416 io_cqring_ev_posted(ctx);
2418 io_free_batch_list(ctx, state->compl_reqs.first);
2419 INIT_WQ_LIST(&state->compl_reqs);
2423 * Drop reference to request, return next in chain (if there is one) if this
2424 * was the last reference to this request.
2426 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2428 struct io_kiocb *nxt = NULL;
2430 if (req_ref_put_and_test(req)) {
2431 nxt = io_req_find_next(req);
2437 static inline void io_put_req(struct io_kiocb *req)
2439 if (req_ref_put_and_test(req))
2443 static inline void io_put_req_deferred(struct io_kiocb *req)
2445 if (req_ref_put_and_test(req)) {
2446 req->io_task_work.func = io_free_req_work;
2447 io_req_task_work_add(req);
2451 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2453 /* See comment at the top of this file */
2455 return __io_cqring_events(ctx);
2458 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2460 struct io_rings *rings = ctx->rings;
2462 /* make sure SQ entry isn't read before tail */
2463 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2466 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2468 unsigned int cflags;
2470 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2471 cflags |= IORING_CQE_F_BUFFER;
2472 req->flags &= ~REQ_F_BUFFER_SELECTED;
2477 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2479 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2481 return io_put_kbuf(req, req->kbuf);
2484 static inline bool io_run_task_work(void)
2486 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2487 __set_current_state(TASK_RUNNING);
2488 tracehook_notify_signal();
2495 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2497 struct io_wq_work_node *pos, *start, *prev;
2498 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2499 DEFINE_IO_COMP_BATCH(iob);
2503 * Only spin for completions if we don't have multiple devices hanging
2504 * off our complete list.
2506 if (ctx->poll_multi_queue || force_nonspin)
2507 poll_flags |= BLK_POLL_ONESHOT;
2509 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2510 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2511 struct kiocb *kiocb = &req->rw.kiocb;
2515 * Move completed and retryable entries to our local lists.
2516 * If we find a request that requires polling, break out
2517 * and complete those lists first, if we have entries there.
2519 if (READ_ONCE(req->iopoll_completed))
2522 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2523 if (unlikely(ret < 0))
2526 poll_flags |= BLK_POLL_ONESHOT;
2528 /* iopoll may have completed current req */
2529 if (!rq_list_empty(iob.req_list) ||
2530 READ_ONCE(req->iopoll_completed))
2534 if (!rq_list_empty(iob.req_list))
2540 wq_list_for_each_resume(pos, prev) {
2541 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2543 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2544 if (!smp_load_acquire(&req->iopoll_completed))
2546 __io_cqring_fill_event(ctx, req->user_data, req->result,
2547 io_put_rw_kbuf(req));
2551 if (unlikely(!nr_events))
2554 io_commit_cqring(ctx);
2555 io_cqring_ev_posted_iopoll(ctx);
2556 pos = start ? start->next : ctx->iopoll_list.first;
2557 wq_list_cut(&ctx->iopoll_list, prev, start);
2558 io_free_batch_list(ctx, pos);
2563 * We can't just wait for polled events to come to us, we have to actively
2564 * find and complete them.
2566 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2568 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2571 mutex_lock(&ctx->uring_lock);
2572 while (!wq_list_empty(&ctx->iopoll_list)) {
2573 /* let it sleep and repeat later if can't complete a request */
2574 if (io_do_iopoll(ctx, true) == 0)
2577 * Ensure we allow local-to-the-cpu processing to take place,
2578 * in this case we need to ensure that we reap all events.
2579 * Also let task_work, etc. to progress by releasing the mutex
2581 if (need_resched()) {
2582 mutex_unlock(&ctx->uring_lock);
2584 mutex_lock(&ctx->uring_lock);
2587 mutex_unlock(&ctx->uring_lock);
2590 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2592 unsigned int nr_events = 0;
2596 * We disallow the app entering submit/complete with polling, but we
2597 * still need to lock the ring to prevent racing with polled issue
2598 * that got punted to a workqueue.
2600 mutex_lock(&ctx->uring_lock);
2602 * Don't enter poll loop if we already have events pending.
2603 * If we do, we can potentially be spinning for commands that
2604 * already triggered a CQE (eg in error).
2606 if (test_bit(0, &ctx->check_cq_overflow))
2607 __io_cqring_overflow_flush(ctx, false);
2608 if (io_cqring_events(ctx))
2612 * If a submit got punted to a workqueue, we can have the
2613 * application entering polling for a command before it gets
2614 * issued. That app will hold the uring_lock for the duration
2615 * of the poll right here, so we need to take a breather every
2616 * now and then to ensure that the issue has a chance to add
2617 * the poll to the issued list. Otherwise we can spin here
2618 * forever, while the workqueue is stuck trying to acquire the
2621 if (wq_list_empty(&ctx->iopoll_list)) {
2622 u32 tail = ctx->cached_cq_tail;
2624 mutex_unlock(&ctx->uring_lock);
2626 mutex_lock(&ctx->uring_lock);
2628 /* some requests don't go through iopoll_list */
2629 if (tail != ctx->cached_cq_tail ||
2630 wq_list_empty(&ctx->iopoll_list))
2633 ret = io_do_iopoll(ctx, !min);
2638 } while (nr_events < min && !need_resched());
2640 mutex_unlock(&ctx->uring_lock);
2644 static void kiocb_end_write(struct io_kiocb *req)
2647 * Tell lockdep we inherited freeze protection from submission
2650 if (req->flags & REQ_F_ISREG) {
2651 struct super_block *sb = file_inode(req->file)->i_sb;
2653 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2659 static bool io_resubmit_prep(struct io_kiocb *req)
2661 struct io_async_rw *rw = req->async_data;
2663 if (!req_has_async_data(req))
2664 return !io_req_prep_async(req);
2665 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2669 static bool io_rw_should_reissue(struct io_kiocb *req)
2671 umode_t mode = file_inode(req->file)->i_mode;
2672 struct io_ring_ctx *ctx = req->ctx;
2674 if (!S_ISBLK(mode) && !S_ISREG(mode))
2676 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2677 !(ctx->flags & IORING_SETUP_IOPOLL)))
2680 * If ref is dying, we might be running poll reap from the exit work.
2681 * Don't attempt to reissue from that path, just let it fail with
2684 if (percpu_ref_is_dying(&ctx->refs))
2687 * Play it safe and assume not safe to re-import and reissue if we're
2688 * not in the original thread group (or in task context).
2690 if (!same_thread_group(req->task, current) || !in_task())
2695 static bool io_resubmit_prep(struct io_kiocb *req)
2699 static bool io_rw_should_reissue(struct io_kiocb *req)
2705 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2707 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2708 kiocb_end_write(req);
2709 if (unlikely(res != req->result)) {
2710 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2711 io_rw_should_reissue(req)) {
2712 req->flags |= REQ_F_REISSUE;
2721 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2723 unsigned int cflags = io_put_rw_kbuf(req);
2724 int res = req->result;
2727 io_req_complete_state(req, res, cflags);
2728 io_req_add_compl_list(req);
2730 io_req_complete_post(req, res, cflags);
2734 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2735 unsigned int issue_flags)
2737 if (__io_complete_rw_common(req, res))
2739 __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2742 static void io_complete_rw(struct kiocb *kiocb, long res)
2744 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2746 if (__io_complete_rw_common(req, res))
2749 req->io_task_work.func = io_req_task_complete;
2750 io_req_task_work_add(req);
2753 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
2755 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2757 if (kiocb->ki_flags & IOCB_WRITE)
2758 kiocb_end_write(req);
2759 if (unlikely(res != req->result)) {
2760 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2761 req->flags |= REQ_F_REISSUE;
2767 /* order with io_iopoll_complete() checking ->iopoll_completed */
2768 smp_store_release(&req->iopoll_completed, 1);
2772 * After the iocb has been issued, it's safe to be found on the poll list.
2773 * Adding the kiocb to the list AFTER submission ensures that we don't
2774 * find it from a io_do_iopoll() thread before the issuer is done
2775 * accessing the kiocb cookie.
2777 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2779 struct io_ring_ctx *ctx = req->ctx;
2780 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2782 /* workqueue context doesn't hold uring_lock, grab it now */
2783 if (unlikely(needs_lock))
2784 mutex_lock(&ctx->uring_lock);
2787 * Track whether we have multiple files in our lists. This will impact
2788 * how we do polling eventually, not spinning if we're on potentially
2789 * different devices.
2791 if (wq_list_empty(&ctx->iopoll_list)) {
2792 ctx->poll_multi_queue = false;
2793 } else if (!ctx->poll_multi_queue) {
2794 struct io_kiocb *list_req;
2796 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2798 if (list_req->file != req->file)
2799 ctx->poll_multi_queue = true;
2803 * For fast devices, IO may have already completed. If it has, add
2804 * it to the front so we find it first.
2806 if (READ_ONCE(req->iopoll_completed))
2807 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2809 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2811 if (unlikely(needs_lock)) {
2813 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2814 * in sq thread task context or in io worker task context. If
2815 * current task context is sq thread, we don't need to check
2816 * whether should wake up sq thread.
2818 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2819 wq_has_sleeper(&ctx->sq_data->wait))
2820 wake_up(&ctx->sq_data->wait);
2822 mutex_unlock(&ctx->uring_lock);
2826 static bool io_bdev_nowait(struct block_device *bdev)
2828 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2832 * If we tracked the file through the SCM inflight mechanism, we could support
2833 * any file. For now, just ensure that anything potentially problematic is done
2836 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2838 if (S_ISBLK(mode)) {
2839 if (IS_ENABLED(CONFIG_BLOCK) &&
2840 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2846 if (S_ISREG(mode)) {
2847 if (IS_ENABLED(CONFIG_BLOCK) &&
2848 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2849 file->f_op != &io_uring_fops)
2854 /* any ->read/write should understand O_NONBLOCK */
2855 if (file->f_flags & O_NONBLOCK)
2857 return file->f_mode & FMODE_NOWAIT;
2861 * If we tracked the file through the SCM inflight mechanism, we could support
2862 * any file. For now, just ensure that anything potentially problematic is done
2865 static unsigned int io_file_get_flags(struct file *file)
2867 umode_t mode = file_inode(file)->i_mode;
2868 unsigned int res = 0;
2872 if (__io_file_supports_nowait(file, mode))
2877 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2879 return req->flags & REQ_F_SUPPORT_NOWAIT;
2882 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2884 struct io_ring_ctx *ctx = req->ctx;
2885 struct kiocb *kiocb = &req->rw.kiocb;
2886 struct file *file = req->file;
2890 if (!io_req_ffs_set(req))
2891 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
2893 kiocb->ki_pos = READ_ONCE(sqe->off);
2894 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2895 req->flags |= REQ_F_CUR_POS;
2896 kiocb->ki_pos = file->f_pos;
2898 kiocb->ki_flags = iocb_flags(file);
2899 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2904 * If the file is marked O_NONBLOCK, still allow retry for it if it
2905 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2906 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2908 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2909 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
2910 req->flags |= REQ_F_NOWAIT;
2912 if (ctx->flags & IORING_SETUP_IOPOLL) {
2913 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
2916 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2917 kiocb->ki_complete = io_complete_rw_iopoll;
2918 req->iopoll_completed = 0;
2920 if (kiocb->ki_flags & IOCB_HIPRI)
2922 kiocb->ki_complete = io_complete_rw;
2925 ioprio = READ_ONCE(sqe->ioprio);
2927 ret = ioprio_check_cap(ioprio);
2931 kiocb->ki_ioprio = ioprio;
2933 kiocb->ki_ioprio = get_current_ioprio();
2937 req->rw.addr = READ_ONCE(sqe->addr);
2938 req->rw.len = READ_ONCE(sqe->len);
2939 req->buf_index = READ_ONCE(sqe->buf_index);
2943 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2949 case -ERESTARTNOINTR:
2950 case -ERESTARTNOHAND:
2951 case -ERESTART_RESTARTBLOCK:
2953 * We can't just restart the syscall, since previously
2954 * submitted sqes may already be in progress. Just fail this
2960 kiocb->ki_complete(kiocb, ret);
2964 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2965 unsigned int issue_flags)
2967 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2968 struct io_async_rw *io = req->async_data;
2970 /* add previously done IO, if any */
2971 if (req_has_async_data(req) && io->bytes_done > 0) {
2973 ret = io->bytes_done;
2975 ret += io->bytes_done;
2978 if (req->flags & REQ_F_CUR_POS)
2979 req->file->f_pos = kiocb->ki_pos;
2980 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw))
2981 __io_complete_rw(req, ret, 0, issue_flags);
2983 io_rw_done(kiocb, ret);
2985 if (req->flags & REQ_F_REISSUE) {
2986 req->flags &= ~REQ_F_REISSUE;
2987 if (io_resubmit_prep(req)) {
2988 io_req_task_queue_reissue(req);
2990 unsigned int cflags = io_put_rw_kbuf(req);
2991 struct io_ring_ctx *ctx = req->ctx;
2994 if (issue_flags & IO_URING_F_UNLOCKED) {
2995 mutex_lock(&ctx->uring_lock);
2996 __io_req_complete(req, issue_flags, ret, cflags);
2997 mutex_unlock(&ctx->uring_lock);
2999 __io_req_complete(req, issue_flags, ret, cflags);
3005 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3006 struct io_mapped_ubuf *imu)
3008 size_t len = req->rw.len;
3009 u64 buf_end, buf_addr = req->rw.addr;
3012 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3014 /* not inside the mapped region */
3015 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3019 * May not be a start of buffer, set size appropriately
3020 * and advance us to the beginning.
3022 offset = buf_addr - imu->ubuf;
3023 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3027 * Don't use iov_iter_advance() here, as it's really slow for
3028 * using the latter parts of a big fixed buffer - it iterates
3029 * over each segment manually. We can cheat a bit here, because
3032 * 1) it's a BVEC iter, we set it up
3033 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3034 * first and last bvec
3036 * So just find our index, and adjust the iterator afterwards.
3037 * If the offset is within the first bvec (or the whole first
3038 * bvec, just use iov_iter_advance(). This makes it easier
3039 * since we can just skip the first segment, which may not
3040 * be PAGE_SIZE aligned.
3042 const struct bio_vec *bvec = imu->bvec;
3044 if (offset <= bvec->bv_len) {
3045 iov_iter_advance(iter, offset);
3047 unsigned long seg_skip;
3049 /* skip first vec */
3050 offset -= bvec->bv_len;
3051 seg_skip = 1 + (offset >> PAGE_SHIFT);
3053 iter->bvec = bvec + seg_skip;
3054 iter->nr_segs -= seg_skip;
3055 iter->count -= bvec->bv_len + offset;
3056 iter->iov_offset = offset & ~PAGE_MASK;
3063 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3065 struct io_mapped_ubuf *imu = req->imu;
3066 u16 index, buf_index = req->buf_index;
3069 struct io_ring_ctx *ctx = req->ctx;
3071 if (unlikely(buf_index >= ctx->nr_user_bufs))
3073 io_req_set_rsrc_node(req, ctx);
3074 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3075 imu = READ_ONCE(ctx->user_bufs[index]);
3078 return __io_import_fixed(req, rw, iter, imu);
3081 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3084 mutex_unlock(&ctx->uring_lock);
3087 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3090 * "Normal" inline submissions always hold the uring_lock, since we
3091 * grab it from the system call. Same is true for the SQPOLL offload.
3092 * The only exception is when we've detached the request and issue it
3093 * from an async worker thread, grab the lock for that case.
3096 mutex_lock(&ctx->uring_lock);
3099 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3100 int bgid, unsigned int issue_flags)
3102 struct io_buffer *kbuf = req->kbuf;
3103 struct io_buffer *head;
3104 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3106 if (req->flags & REQ_F_BUFFER_SELECTED)
3109 io_ring_submit_lock(req->ctx, needs_lock);
3111 lockdep_assert_held(&req->ctx->uring_lock);
3113 head = xa_load(&req->ctx->io_buffers, bgid);
3115 if (!list_empty(&head->list)) {
3116 kbuf = list_last_entry(&head->list, struct io_buffer,
3118 list_del(&kbuf->list);
3121 xa_erase(&req->ctx->io_buffers, bgid);
3123 if (*len > kbuf->len)
3125 req->flags |= REQ_F_BUFFER_SELECTED;
3128 kbuf = ERR_PTR(-ENOBUFS);
3131 io_ring_submit_unlock(req->ctx, needs_lock);
3135 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3136 unsigned int issue_flags)
3138 struct io_buffer *kbuf;
3141 bgid = req->buf_index;
3142 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3145 return u64_to_user_ptr(kbuf->addr);
3148 #ifdef CONFIG_COMPAT
3149 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3150 unsigned int issue_flags)
3152 struct compat_iovec __user *uiov;
3153 compat_ssize_t clen;
3157 uiov = u64_to_user_ptr(req->rw.addr);
3158 if (!access_ok(uiov, sizeof(*uiov)))
3160 if (__get_user(clen, &uiov->iov_len))
3166 buf = io_rw_buffer_select(req, &len, issue_flags);
3168 return PTR_ERR(buf);
3169 iov[0].iov_base = buf;
3170 iov[0].iov_len = (compat_size_t) len;
3175 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3176 unsigned int issue_flags)
3178 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3182 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3185 len = iov[0].iov_len;
3188 buf = io_rw_buffer_select(req, &len, issue_flags);
3190 return PTR_ERR(buf);
3191 iov[0].iov_base = buf;
3192 iov[0].iov_len = len;
3196 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3197 unsigned int issue_flags)
3199 if (req->flags & REQ_F_BUFFER_SELECTED) {
3200 struct io_buffer *kbuf = req->kbuf;
3202 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3203 iov[0].iov_len = kbuf->len;
3206 if (req->rw.len != 1)
3209 #ifdef CONFIG_COMPAT
3210 if (req->ctx->compat)
3211 return io_compat_import(req, iov, issue_flags);
3214 return __io_iov_buffer_select(req, iov, issue_flags);
3217 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3218 struct io_rw_state *s,
3219 unsigned int issue_flags)
3221 struct iov_iter *iter = &s->iter;
3222 u8 opcode = req->opcode;
3223 struct iovec *iovec;
3228 BUILD_BUG_ON(ERR_PTR(0) != NULL);
3230 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED)
3231 return ERR_PTR(io_import_fixed(req, rw, iter));
3233 /* buffer index only valid with fixed read/write, or buffer select */
3234 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3235 return ERR_PTR(-EINVAL);
3237 buf = u64_to_user_ptr(req->rw.addr);
3238 sqe_len = req->rw.len;
3240 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3241 if (req->flags & REQ_F_BUFFER_SELECT) {
3242 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3244 return ERR_CAST(buf);
3245 req->rw.len = sqe_len;
3248 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3249 return ERR_PTR(ret);
3252 iovec = s->fast_iov;
3253 if (req->flags & REQ_F_BUFFER_SELECT) {
3254 ret = io_iov_buffer_select(req, iovec, issue_flags);
3256 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3257 return ERR_PTR(ret);
3260 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3262 if (unlikely(ret < 0))
3263 return ERR_PTR(ret);
3267 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3268 struct iovec **iovec, struct io_rw_state *s,
3269 unsigned int issue_flags)
3271 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3272 if (unlikely(IS_ERR(*iovec)))
3273 return PTR_ERR(*iovec);
3275 iov_iter_save_state(&s->iter, &s->iter_state);
3279 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3281 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3285 * For files that don't have ->read_iter() and ->write_iter(), handle them
3286 * by looping over ->read() or ->write() manually.
3288 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3290 struct kiocb *kiocb = &req->rw.kiocb;
3291 struct file *file = req->file;
3295 * Don't support polled IO through this interface, and we can't
3296 * support non-blocking either. For the latter, this just causes
3297 * the kiocb to be handled from an async context.
3299 if (kiocb->ki_flags & IOCB_HIPRI)
3301 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3302 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3305 while (iov_iter_count(iter)) {
3309 if (!iov_iter_is_bvec(iter)) {
3310 iovec = iov_iter_iovec(iter);
3312 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3313 iovec.iov_len = req->rw.len;
3317 nr = file->f_op->read(file, iovec.iov_base,
3318 iovec.iov_len, io_kiocb_ppos(kiocb));
3320 nr = file->f_op->write(file, iovec.iov_base,
3321 iovec.iov_len, io_kiocb_ppos(kiocb));
3329 if (!iov_iter_is_bvec(iter)) {
3330 iov_iter_advance(iter, nr);
3336 if (nr != iovec.iov_len)
3343 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3344 const struct iovec *fast_iov, struct iov_iter *iter)
3346 struct io_async_rw *rw = req->async_data;
3348 memcpy(&rw->s.iter, iter, sizeof(*iter));
3349 rw->free_iovec = iovec;
3351 /* can only be fixed buffers, no need to do anything */
3352 if (iov_iter_is_bvec(iter))
3355 unsigned iov_off = 0;
3357 rw->s.iter.iov = rw->s.fast_iov;
3358 if (iter->iov != fast_iov) {
3359 iov_off = iter->iov - fast_iov;
3360 rw->s.iter.iov += iov_off;
3362 if (rw->s.fast_iov != fast_iov)
3363 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3364 sizeof(struct iovec) * iter->nr_segs);
3366 req->flags |= REQ_F_NEED_CLEANUP;
3370 static inline bool io_alloc_async_data(struct io_kiocb *req)
3372 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3373 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3374 if (req->async_data) {
3375 req->flags |= REQ_F_ASYNC_DATA;
3381 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3382 struct io_rw_state *s, bool force)
3384 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3386 if (!req_has_async_data(req)) {
3387 struct io_async_rw *iorw;
3389 if (io_alloc_async_data(req)) {
3394 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3395 iorw = req->async_data;
3396 /* we've copied and mapped the iter, ensure state is saved */
3397 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3402 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3404 struct io_async_rw *iorw = req->async_data;
3408 /* submission path, ->uring_lock should already be taken */
3409 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3410 if (unlikely(ret < 0))
3413 iorw->bytes_done = 0;
3414 iorw->free_iovec = iov;
3416 req->flags |= REQ_F_NEED_CLEANUP;
3420 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3422 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3424 return io_prep_rw(req, sqe);
3428 * This is our waitqueue callback handler, registered through __folio_lock_async()
3429 * when we initially tried to do the IO with the iocb armed our waitqueue.
3430 * This gets called when the page is unlocked, and we generally expect that to
3431 * happen when the page IO is completed and the page is now uptodate. This will
3432 * queue a task_work based retry of the operation, attempting to copy the data
3433 * again. If the latter fails because the page was NOT uptodate, then we will
3434 * do a thread based blocking retry of the operation. That's the unexpected
3437 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3438 int sync, void *arg)
3440 struct wait_page_queue *wpq;
3441 struct io_kiocb *req = wait->private;
3442 struct wait_page_key *key = arg;
3444 wpq = container_of(wait, struct wait_page_queue, wait);
3446 if (!wake_page_match(wpq, key))
3449 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3450 list_del_init(&wait->entry);
3451 io_req_task_queue(req);
3456 * This controls whether a given IO request should be armed for async page
3457 * based retry. If we return false here, the request is handed to the async
3458 * worker threads for retry. If we're doing buffered reads on a regular file,
3459 * we prepare a private wait_page_queue entry and retry the operation. This
3460 * will either succeed because the page is now uptodate and unlocked, or it
3461 * will register a callback when the page is unlocked at IO completion. Through
3462 * that callback, io_uring uses task_work to setup a retry of the operation.
3463 * That retry will attempt the buffered read again. The retry will generally
3464 * succeed, or in rare cases where it fails, we then fall back to using the
3465 * async worker threads for a blocking retry.
3467 static bool io_rw_should_retry(struct io_kiocb *req)
3469 struct io_async_rw *rw = req->async_data;
3470 struct wait_page_queue *wait = &rw->wpq;
3471 struct kiocb *kiocb = &req->rw.kiocb;
3473 /* never retry for NOWAIT, we just complete with -EAGAIN */
3474 if (req->flags & REQ_F_NOWAIT)
3477 /* Only for buffered IO */
3478 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3482 * just use poll if we can, and don't attempt if the fs doesn't
3483 * support callback based unlocks
3485 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3488 wait->wait.func = io_async_buf_func;
3489 wait->wait.private = req;
3490 wait->wait.flags = 0;
3491 INIT_LIST_HEAD(&wait->wait.entry);
3492 kiocb->ki_flags |= IOCB_WAITQ;
3493 kiocb->ki_flags &= ~IOCB_NOWAIT;
3494 kiocb->ki_waitq = wait;
3498 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3500 if (likely(req->file->f_op->read_iter))
3501 return call_read_iter(req->file, &req->rw.kiocb, iter);
3502 else if (req->file->f_op->read)
3503 return loop_rw_iter(READ, req, iter);
3508 static bool need_read_all(struct io_kiocb *req)
3510 return req->flags & REQ_F_ISREG ||
3511 S_ISBLK(file_inode(req->file)->i_mode);
3514 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3516 struct io_rw_state __s, *s = &__s;
3517 struct iovec *iovec;
3518 struct kiocb *kiocb = &req->rw.kiocb;
3519 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3520 struct io_async_rw *rw;
3523 if (!req_has_async_data(req)) {
3524 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3525 if (unlikely(ret < 0))
3528 rw = req->async_data;
3531 * We come here from an earlier attempt, restore our state to
3532 * match in case it doesn't. It's cheap enough that we don't
3533 * need to make this conditional.
3535 iov_iter_restore(&s->iter, &s->iter_state);
3538 req->result = iov_iter_count(&s->iter);
3540 if (force_nonblock) {
3541 /* If the file doesn't support async, just async punt */
3542 if (unlikely(!io_file_supports_nowait(req))) {
3543 ret = io_setup_async_rw(req, iovec, s, true);
3544 return ret ?: -EAGAIN;
3546 kiocb->ki_flags |= IOCB_NOWAIT;
3548 /* Ensure we clear previously set non-block flag */
3549 kiocb->ki_flags &= ~IOCB_NOWAIT;
3552 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), req->result);
3553 if (unlikely(ret)) {
3558 ret = io_iter_do_read(req, &s->iter);
3560 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3561 req->flags &= ~REQ_F_REISSUE;
3562 /* IOPOLL retry should happen for io-wq threads */
3563 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3565 /* no retry on NONBLOCK nor RWF_NOWAIT */
3566 if (req->flags & REQ_F_NOWAIT)
3569 } else if (ret == -EIOCBQUEUED) {
3571 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3572 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3573 /* read all, failed, already did sync or don't want to retry */
3578 * Don't depend on the iter state matching what was consumed, or being
3579 * untouched in case of error. Restore it and we'll advance it
3580 * manually if we need to.
3582 iov_iter_restore(&s->iter, &s->iter_state);
3584 ret2 = io_setup_async_rw(req, iovec, s, true);
3589 rw = req->async_data;
3592 * Now use our persistent iterator and state, if we aren't already.
3593 * We've restored and mapped the iter to match.
3598 * We end up here because of a partial read, either from
3599 * above or inside this loop. Advance the iter by the bytes
3600 * that were consumed.
3602 iov_iter_advance(&s->iter, ret);
3603 if (!iov_iter_count(&s->iter))
3605 rw->bytes_done += ret;
3606 iov_iter_save_state(&s->iter, &s->iter_state);
3608 /* if we can retry, do so with the callbacks armed */
3609 if (!io_rw_should_retry(req)) {
3610 kiocb->ki_flags &= ~IOCB_WAITQ;
3615 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3616 * we get -EIOCBQUEUED, then we'll get a notification when the
3617 * desired page gets unlocked. We can also get a partial read
3618 * here, and if we do, then just retry at the new offset.
3620 ret = io_iter_do_read(req, &s->iter);
3621 if (ret == -EIOCBQUEUED)
3623 /* we got some bytes, but not all. retry. */
3624 kiocb->ki_flags &= ~IOCB_WAITQ;
3625 iov_iter_restore(&s->iter, &s->iter_state);
3628 kiocb_done(kiocb, ret, issue_flags);
3630 /* it's faster to check here then delegate to kfree */
3636 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3638 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3640 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
3641 return io_prep_rw(req, sqe);
3644 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3646 struct io_rw_state __s, *s = &__s;
3647 struct iovec *iovec;
3648 struct kiocb *kiocb = &req->rw.kiocb;
3649 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3652 if (!req_has_async_data(req)) {
3653 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3654 if (unlikely(ret < 0))
3657 struct io_async_rw *rw = req->async_data;
3660 iov_iter_restore(&s->iter, &s->iter_state);
3663 req->result = iov_iter_count(&s->iter);
3665 if (force_nonblock) {
3666 /* If the file doesn't support async, just async punt */
3667 if (unlikely(!io_file_supports_nowait(req)))
3670 /* file path doesn't support NOWAIT for non-direct_IO */
3671 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3672 (req->flags & REQ_F_ISREG))
3675 kiocb->ki_flags |= IOCB_NOWAIT;
3677 /* Ensure we clear previously set non-block flag */
3678 kiocb->ki_flags &= ~IOCB_NOWAIT;
3681 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), req->result);
3686 * Open-code file_start_write here to grab freeze protection,
3687 * which will be released by another thread in
3688 * io_complete_rw(). Fool lockdep by telling it the lock got
3689 * released so that it doesn't complain about the held lock when
3690 * we return to userspace.
3692 if (req->flags & REQ_F_ISREG) {
3693 sb_start_write(file_inode(req->file)->i_sb);
3694 __sb_writers_release(file_inode(req->file)->i_sb,
3697 kiocb->ki_flags |= IOCB_WRITE;
3699 if (likely(req->file->f_op->write_iter))
3700 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3701 else if (req->file->f_op->write)
3702 ret2 = loop_rw_iter(WRITE, req, &s->iter);
3706 if (req->flags & REQ_F_REISSUE) {
3707 req->flags &= ~REQ_F_REISSUE;
3712 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3713 * retry them without IOCB_NOWAIT.
3715 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3717 /* no retry on NONBLOCK nor RWF_NOWAIT */
3718 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3720 if (!force_nonblock || ret2 != -EAGAIN) {
3721 /* IOPOLL retry should happen for io-wq threads */
3722 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3725 kiocb_done(kiocb, ret2, issue_flags);
3728 iov_iter_restore(&s->iter, &s->iter_state);
3729 ret = io_setup_async_rw(req, iovec, s, false);
3730 return ret ?: -EAGAIN;
3733 /* it's reportedly faster than delegating the null check to kfree() */
3739 static int io_renameat_prep(struct io_kiocb *req,
3740 const struct io_uring_sqe *sqe)
3742 struct io_rename *ren = &req->rename;
3743 const char __user *oldf, *newf;
3745 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3747 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3749 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3752 ren->old_dfd = READ_ONCE(sqe->fd);
3753 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3754 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3755 ren->new_dfd = READ_ONCE(sqe->len);
3756 ren->flags = READ_ONCE(sqe->rename_flags);
3758 ren->oldpath = getname(oldf);
3759 if (IS_ERR(ren->oldpath))
3760 return PTR_ERR(ren->oldpath);
3762 ren->newpath = getname(newf);
3763 if (IS_ERR(ren->newpath)) {
3764 putname(ren->oldpath);
3765 return PTR_ERR(ren->newpath);
3768 req->flags |= REQ_F_NEED_CLEANUP;
3772 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3774 struct io_rename *ren = &req->rename;
3777 if (issue_flags & IO_URING_F_NONBLOCK)
3780 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3781 ren->newpath, ren->flags);
3783 req->flags &= ~REQ_F_NEED_CLEANUP;
3786 io_req_complete(req, ret);
3790 static int io_unlinkat_prep(struct io_kiocb *req,
3791 const struct io_uring_sqe *sqe)
3793 struct io_unlink *un = &req->unlink;
3794 const char __user *fname;
3796 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3798 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3801 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3804 un->dfd = READ_ONCE(sqe->fd);
3806 un->flags = READ_ONCE(sqe->unlink_flags);
3807 if (un->flags & ~AT_REMOVEDIR)
3810 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3811 un->filename = getname(fname);
3812 if (IS_ERR(un->filename))
3813 return PTR_ERR(un->filename);
3815 req->flags |= REQ_F_NEED_CLEANUP;
3819 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3821 struct io_unlink *un = &req->unlink;
3824 if (issue_flags & IO_URING_F_NONBLOCK)
3827 if (un->flags & AT_REMOVEDIR)
3828 ret = do_rmdir(un->dfd, un->filename);
3830 ret = do_unlinkat(un->dfd, un->filename);
3832 req->flags &= ~REQ_F_NEED_CLEANUP;
3835 io_req_complete(req, ret);
3839 static int io_mkdirat_prep(struct io_kiocb *req,
3840 const struct io_uring_sqe *sqe)
3842 struct io_mkdir *mkd = &req->mkdir;
3843 const char __user *fname;
3845 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3847 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3850 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3853 mkd->dfd = READ_ONCE(sqe->fd);
3854 mkd->mode = READ_ONCE(sqe->len);
3856 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3857 mkd->filename = getname(fname);
3858 if (IS_ERR(mkd->filename))
3859 return PTR_ERR(mkd->filename);
3861 req->flags |= REQ_F_NEED_CLEANUP;
3865 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
3867 struct io_mkdir *mkd = &req->mkdir;
3870 if (issue_flags & IO_URING_F_NONBLOCK)
3873 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3875 req->flags &= ~REQ_F_NEED_CLEANUP;
3878 io_req_complete(req, ret);
3882 static int io_symlinkat_prep(struct io_kiocb *req,
3883 const struct io_uring_sqe *sqe)
3885 struct io_symlink *sl = &req->symlink;
3886 const char __user *oldpath, *newpath;
3888 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3890 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3893 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3896 sl->new_dfd = READ_ONCE(sqe->fd);
3897 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3898 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3900 sl->oldpath = getname(oldpath);
3901 if (IS_ERR(sl->oldpath))
3902 return PTR_ERR(sl->oldpath);
3904 sl->newpath = getname(newpath);
3905 if (IS_ERR(sl->newpath)) {
3906 putname(sl->oldpath);
3907 return PTR_ERR(sl->newpath);
3910 req->flags |= REQ_F_NEED_CLEANUP;
3914 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
3916 struct io_symlink *sl = &req->symlink;
3919 if (issue_flags & IO_URING_F_NONBLOCK)
3922 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
3924 req->flags &= ~REQ_F_NEED_CLEANUP;
3927 io_req_complete(req, ret);
3931 static int io_linkat_prep(struct io_kiocb *req,
3932 const struct io_uring_sqe *sqe)
3934 struct io_hardlink *lnk = &req->hardlink;
3935 const char __user *oldf, *newf;
3937 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3939 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
3941 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3944 lnk->old_dfd = READ_ONCE(sqe->fd);
3945 lnk->new_dfd = READ_ONCE(sqe->len);
3946 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3947 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3948 lnk->flags = READ_ONCE(sqe->hardlink_flags);
3950 lnk->oldpath = getname(oldf);
3951 if (IS_ERR(lnk->oldpath))
3952 return PTR_ERR(lnk->oldpath);
3954 lnk->newpath = getname(newf);
3955 if (IS_ERR(lnk->newpath)) {
3956 putname(lnk->oldpath);
3957 return PTR_ERR(lnk->newpath);
3960 req->flags |= REQ_F_NEED_CLEANUP;
3964 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
3966 struct io_hardlink *lnk = &req->hardlink;
3969 if (issue_flags & IO_URING_F_NONBLOCK)
3972 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
3973 lnk->newpath, lnk->flags);
3975 req->flags &= ~REQ_F_NEED_CLEANUP;
3978 io_req_complete(req, ret);
3982 static int io_shutdown_prep(struct io_kiocb *req,
3983 const struct io_uring_sqe *sqe)
3985 #if defined(CONFIG_NET)
3986 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3988 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3989 sqe->buf_index || sqe->splice_fd_in))
3992 req->shutdown.how = READ_ONCE(sqe->len);
3999 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4001 #if defined(CONFIG_NET)
4002 struct socket *sock;
4005 if (issue_flags & IO_URING_F_NONBLOCK)
4008 sock = sock_from_file(req->file);
4009 if (unlikely(!sock))
4012 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4015 io_req_complete(req, ret);
4022 static int __io_splice_prep(struct io_kiocb *req,
4023 const struct io_uring_sqe *sqe)
4025 struct io_splice *sp = &req->splice;
4026 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4028 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4032 sp->len = READ_ONCE(sqe->len);
4033 sp->flags = READ_ONCE(sqe->splice_flags);
4035 if (unlikely(sp->flags & ~valid_flags))
4038 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4039 (sp->flags & SPLICE_F_FD_IN_FIXED));
4042 req->flags |= REQ_F_NEED_CLEANUP;
4046 static int io_tee_prep(struct io_kiocb *req,
4047 const struct io_uring_sqe *sqe)
4049 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4051 return __io_splice_prep(req, sqe);
4054 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4056 struct io_splice *sp = &req->splice;
4057 struct file *in = sp->file_in;
4058 struct file *out = sp->file_out;
4059 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4062 if (issue_flags & IO_URING_F_NONBLOCK)
4065 ret = do_tee(in, out, sp->len, flags);
4067 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4069 req->flags &= ~REQ_F_NEED_CLEANUP;
4073 io_req_complete(req, ret);
4077 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4079 struct io_splice *sp = &req->splice;
4081 sp->off_in = READ_ONCE(sqe->splice_off_in);
4082 sp->off_out = READ_ONCE(sqe->off);
4083 return __io_splice_prep(req, sqe);
4086 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4088 struct io_splice *sp = &req->splice;
4089 struct file *in = sp->file_in;
4090 struct file *out = sp->file_out;
4091 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4092 loff_t *poff_in, *poff_out;
4095 if (issue_flags & IO_URING_F_NONBLOCK)
4098 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4099 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4102 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4104 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4106 req->flags &= ~REQ_F_NEED_CLEANUP;
4110 io_req_complete(req, ret);
4115 * IORING_OP_NOP just posts a completion event, nothing else.
4117 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4119 struct io_ring_ctx *ctx = req->ctx;
4121 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4124 __io_req_complete(req, issue_flags, 0, 0);
4128 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4130 struct io_ring_ctx *ctx = req->ctx;
4135 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4137 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4141 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4142 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4145 req->sync.off = READ_ONCE(sqe->off);
4146 req->sync.len = READ_ONCE(sqe->len);
4150 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4152 loff_t end = req->sync.off + req->sync.len;
4155 /* fsync always requires a blocking context */
4156 if (issue_flags & IO_URING_F_NONBLOCK)
4159 ret = vfs_fsync_range(req->file, req->sync.off,
4160 end > 0 ? end : LLONG_MAX,
4161 req->sync.flags & IORING_FSYNC_DATASYNC);
4164 io_req_complete(req, ret);
4168 static int io_fallocate_prep(struct io_kiocb *req,
4169 const struct io_uring_sqe *sqe)
4171 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4174 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4177 req->sync.off = READ_ONCE(sqe->off);
4178 req->sync.len = READ_ONCE(sqe->addr);
4179 req->sync.mode = READ_ONCE(sqe->len);
4183 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4187 /* fallocate always requiring blocking context */
4188 if (issue_flags & IO_URING_F_NONBLOCK)
4190 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4194 io_req_complete(req, ret);
4198 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4200 const char __user *fname;
4203 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4205 if (unlikely(sqe->ioprio || sqe->buf_index))
4207 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4210 /* open.how should be already initialised */
4211 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4212 req->open.how.flags |= O_LARGEFILE;
4214 req->open.dfd = READ_ONCE(sqe->fd);
4215 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4216 req->open.filename = getname(fname);
4217 if (IS_ERR(req->open.filename)) {
4218 ret = PTR_ERR(req->open.filename);
4219 req->open.filename = NULL;
4223 req->open.file_slot = READ_ONCE(sqe->file_index);
4224 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4227 req->open.nofile = rlimit(RLIMIT_NOFILE);
4228 req->flags |= REQ_F_NEED_CLEANUP;
4232 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4234 u64 mode = READ_ONCE(sqe->len);
4235 u64 flags = READ_ONCE(sqe->open_flags);
4237 req->open.how = build_open_how(flags, mode);
4238 return __io_openat_prep(req, sqe);
4241 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4243 struct open_how __user *how;
4247 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4248 len = READ_ONCE(sqe->len);
4249 if (len < OPEN_HOW_SIZE_VER0)
4252 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4257 return __io_openat_prep(req, sqe);
4260 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4262 struct open_flags op;
4264 bool resolve_nonblock, nonblock_set;
4265 bool fixed = !!req->open.file_slot;
4268 ret = build_open_flags(&req->open.how, &op);
4271 nonblock_set = op.open_flag & O_NONBLOCK;
4272 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4273 if (issue_flags & IO_URING_F_NONBLOCK) {
4275 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4276 * it'll always -EAGAIN
4278 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4280 op.lookup_flags |= LOOKUP_CACHED;
4281 op.open_flag |= O_NONBLOCK;
4285 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4290 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4293 * We could hang on to this 'fd' on retrying, but seems like
4294 * marginal gain for something that is now known to be a slower
4295 * path. So just put it, and we'll get a new one when we retry.
4300 ret = PTR_ERR(file);
4301 /* only retry if RESOLVE_CACHED wasn't already set by application */
4302 if (ret == -EAGAIN &&
4303 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4308 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4309 file->f_flags &= ~O_NONBLOCK;
4310 fsnotify_open(file);
4313 fd_install(ret, file);
4315 ret = io_install_fixed_file(req, file, issue_flags,
4316 req->open.file_slot - 1);
4318 putname(req->open.filename);
4319 req->flags &= ~REQ_F_NEED_CLEANUP;
4322 __io_req_complete(req, issue_flags, ret, 0);
4326 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4328 return io_openat2(req, issue_flags);
4331 static int io_remove_buffers_prep(struct io_kiocb *req,
4332 const struct io_uring_sqe *sqe)
4334 struct io_provide_buf *p = &req->pbuf;
4337 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4341 tmp = READ_ONCE(sqe->fd);
4342 if (!tmp || tmp > USHRT_MAX)
4345 memset(p, 0, sizeof(*p));
4347 p->bgid = READ_ONCE(sqe->buf_group);
4351 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4352 int bgid, unsigned nbufs)
4356 /* shouldn't happen */
4360 /* the head kbuf is the list itself */
4361 while (!list_empty(&buf->list)) {
4362 struct io_buffer *nxt;
4364 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4365 list_del(&nxt->list);
4373 xa_erase(&ctx->io_buffers, bgid);
4378 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4380 struct io_provide_buf *p = &req->pbuf;
4381 struct io_ring_ctx *ctx = req->ctx;
4382 struct io_buffer *head;
4384 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4386 io_ring_submit_lock(ctx, needs_lock);
4388 lockdep_assert_held(&ctx->uring_lock);
4391 head = xa_load(&ctx->io_buffers, p->bgid);
4393 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4397 /* complete before unlock, IOPOLL may need the lock */
4398 __io_req_complete(req, issue_flags, ret, 0);
4399 io_ring_submit_unlock(ctx, needs_lock);
4403 static int io_provide_buffers_prep(struct io_kiocb *req,
4404 const struct io_uring_sqe *sqe)
4406 unsigned long size, tmp_check;
4407 struct io_provide_buf *p = &req->pbuf;
4410 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4413 tmp = READ_ONCE(sqe->fd);
4414 if (!tmp || tmp > USHRT_MAX)
4417 p->addr = READ_ONCE(sqe->addr);
4418 p->len = READ_ONCE(sqe->len);
4420 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4423 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4426 size = (unsigned long)p->len * p->nbufs;
4427 if (!access_ok(u64_to_user_ptr(p->addr), size))
4430 p->bgid = READ_ONCE(sqe->buf_group);
4431 tmp = READ_ONCE(sqe->off);
4432 if (tmp > USHRT_MAX)
4438 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4440 struct io_buffer *buf;
4441 u64 addr = pbuf->addr;
4442 int i, bid = pbuf->bid;
4444 for (i = 0; i < pbuf->nbufs; i++) {
4445 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4450 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4455 INIT_LIST_HEAD(&buf->list);
4458 list_add_tail(&buf->list, &(*head)->list);
4462 return i ? i : -ENOMEM;
4465 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4467 struct io_provide_buf *p = &req->pbuf;
4468 struct io_ring_ctx *ctx = req->ctx;
4469 struct io_buffer *head, *list;
4471 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4473 io_ring_submit_lock(ctx, needs_lock);
4475 lockdep_assert_held(&ctx->uring_lock);
4477 list = head = xa_load(&ctx->io_buffers, p->bgid);
4479 ret = io_add_buffers(p, &head);
4480 if (ret >= 0 && !list) {
4481 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4483 __io_remove_buffers(ctx, head, p->bgid, -1U);
4487 /* complete before unlock, IOPOLL may need the lock */
4488 __io_req_complete(req, issue_flags, ret, 0);
4489 io_ring_submit_unlock(ctx, needs_lock);
4493 static int io_epoll_ctl_prep(struct io_kiocb *req,
4494 const struct io_uring_sqe *sqe)
4496 #if defined(CONFIG_EPOLL)
4497 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4499 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4502 req->epoll.epfd = READ_ONCE(sqe->fd);
4503 req->epoll.op = READ_ONCE(sqe->len);
4504 req->epoll.fd = READ_ONCE(sqe->off);
4506 if (ep_op_has_event(req->epoll.op)) {
4507 struct epoll_event __user *ev;
4509 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4510 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4520 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4522 #if defined(CONFIG_EPOLL)
4523 struct io_epoll *ie = &req->epoll;
4525 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4527 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4528 if (force_nonblock && ret == -EAGAIN)
4533 __io_req_complete(req, issue_flags, ret, 0);
4540 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4542 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4543 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4545 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4548 req->madvise.addr = READ_ONCE(sqe->addr);
4549 req->madvise.len = READ_ONCE(sqe->len);
4550 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4557 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4559 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4560 struct io_madvise *ma = &req->madvise;
4563 if (issue_flags & IO_URING_F_NONBLOCK)
4566 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4569 io_req_complete(req, ret);
4576 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4578 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4580 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4583 req->fadvise.offset = READ_ONCE(sqe->off);
4584 req->fadvise.len = READ_ONCE(sqe->len);
4585 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4589 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4591 struct io_fadvise *fa = &req->fadvise;
4594 if (issue_flags & IO_URING_F_NONBLOCK) {
4595 switch (fa->advice) {
4596 case POSIX_FADV_NORMAL:
4597 case POSIX_FADV_RANDOM:
4598 case POSIX_FADV_SEQUENTIAL:
4605 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4608 __io_req_complete(req, issue_flags, ret, 0);
4612 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4614 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4616 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4618 if (req->flags & REQ_F_FIXED_FILE)
4621 req->statx.dfd = READ_ONCE(sqe->fd);
4622 req->statx.mask = READ_ONCE(sqe->len);
4623 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4624 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4625 req->statx.flags = READ_ONCE(sqe->statx_flags);
4630 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4632 struct io_statx *ctx = &req->statx;
4635 if (issue_flags & IO_URING_F_NONBLOCK)
4638 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4643 io_req_complete(req, ret);
4647 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4649 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4651 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4652 sqe->rw_flags || sqe->buf_index)
4654 if (req->flags & REQ_F_FIXED_FILE)
4657 req->close.fd = READ_ONCE(sqe->fd);
4658 req->close.file_slot = READ_ONCE(sqe->file_index);
4659 if (req->close.file_slot && req->close.fd)
4665 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4667 struct files_struct *files = current->files;
4668 struct io_close *close = &req->close;
4669 struct fdtable *fdt;
4670 struct file *file = NULL;
4673 if (req->close.file_slot) {
4674 ret = io_close_fixed(req, issue_flags);
4678 spin_lock(&files->file_lock);
4679 fdt = files_fdtable(files);
4680 if (close->fd >= fdt->max_fds) {
4681 spin_unlock(&files->file_lock);
4684 file = fdt->fd[close->fd];
4685 if (!file || file->f_op == &io_uring_fops) {
4686 spin_unlock(&files->file_lock);
4691 /* if the file has a flush method, be safe and punt to async */
4692 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4693 spin_unlock(&files->file_lock);
4697 ret = __close_fd_get_file(close->fd, &file);
4698 spin_unlock(&files->file_lock);
4705 /* No ->flush() or already async, safely close from here */
4706 ret = filp_close(file, current->files);
4712 __io_req_complete(req, issue_flags, ret, 0);
4716 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4718 struct io_ring_ctx *ctx = req->ctx;
4720 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4722 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4726 req->sync.off = READ_ONCE(sqe->off);
4727 req->sync.len = READ_ONCE(sqe->len);
4728 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4732 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4736 /* sync_file_range always requires a blocking context */
4737 if (issue_flags & IO_URING_F_NONBLOCK)
4740 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4744 io_req_complete(req, ret);
4748 #if defined(CONFIG_NET)
4749 static int io_setup_async_msg(struct io_kiocb *req,
4750 struct io_async_msghdr *kmsg)
4752 struct io_async_msghdr *async_msg = req->async_data;
4756 if (io_alloc_async_data(req)) {
4757 kfree(kmsg->free_iov);
4760 async_msg = req->async_data;
4761 req->flags |= REQ_F_NEED_CLEANUP;
4762 memcpy(async_msg, kmsg, sizeof(*kmsg));
4763 async_msg->msg.msg_name = &async_msg->addr;
4764 /* if were using fast_iov, set it to the new one */
4765 if (!async_msg->free_iov)
4766 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4771 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4772 struct io_async_msghdr *iomsg)
4774 iomsg->msg.msg_name = &iomsg->addr;
4775 iomsg->free_iov = iomsg->fast_iov;
4776 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4777 req->sr_msg.msg_flags, &iomsg->free_iov);
4780 static int io_sendmsg_prep_async(struct io_kiocb *req)
4784 ret = io_sendmsg_copy_hdr(req, req->async_data);
4786 req->flags |= REQ_F_NEED_CLEANUP;
4790 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4792 struct io_sr_msg *sr = &req->sr_msg;
4794 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4797 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4798 sr->len = READ_ONCE(sqe->len);
4799 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4800 if (sr->msg_flags & MSG_DONTWAIT)
4801 req->flags |= REQ_F_NOWAIT;
4803 #ifdef CONFIG_COMPAT
4804 if (req->ctx->compat)
4805 sr->msg_flags |= MSG_CMSG_COMPAT;
4810 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4812 struct io_async_msghdr iomsg, *kmsg;
4813 struct socket *sock;
4818 sock = sock_from_file(req->file);
4819 if (unlikely(!sock))
4822 if (req_has_async_data(req)) {
4823 kmsg = req->async_data;
4825 ret = io_sendmsg_copy_hdr(req, &iomsg);
4831 flags = req->sr_msg.msg_flags;
4832 if (issue_flags & IO_URING_F_NONBLOCK)
4833 flags |= MSG_DONTWAIT;
4834 if (flags & MSG_WAITALL)
4835 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4837 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4838 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4839 return io_setup_async_msg(req, kmsg);
4840 if (ret == -ERESTARTSYS)
4843 /* fast path, check for non-NULL to avoid function call */
4845 kfree(kmsg->free_iov);
4846 req->flags &= ~REQ_F_NEED_CLEANUP;
4849 __io_req_complete(req, issue_flags, ret, 0);
4853 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4855 struct io_sr_msg *sr = &req->sr_msg;
4858 struct socket *sock;
4863 sock = sock_from_file(req->file);
4864 if (unlikely(!sock))
4867 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4871 msg.msg_name = NULL;
4872 msg.msg_control = NULL;
4873 msg.msg_controllen = 0;
4874 msg.msg_namelen = 0;
4876 flags = req->sr_msg.msg_flags;
4877 if (issue_flags & IO_URING_F_NONBLOCK)
4878 flags |= MSG_DONTWAIT;
4879 if (flags & MSG_WAITALL)
4880 min_ret = iov_iter_count(&msg.msg_iter);
4882 msg.msg_flags = flags;
4883 ret = sock_sendmsg(sock, &msg);
4884 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4886 if (ret == -ERESTARTSYS)
4891 __io_req_complete(req, issue_flags, ret, 0);
4895 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4896 struct io_async_msghdr *iomsg)
4898 struct io_sr_msg *sr = &req->sr_msg;
4899 struct iovec __user *uiov;
4903 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4904 &iomsg->uaddr, &uiov, &iov_len);
4908 if (req->flags & REQ_F_BUFFER_SELECT) {
4911 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4913 sr->len = iomsg->fast_iov[0].iov_len;
4914 iomsg->free_iov = NULL;
4916 iomsg->free_iov = iomsg->fast_iov;
4917 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4918 &iomsg->free_iov, &iomsg->msg.msg_iter,
4927 #ifdef CONFIG_COMPAT
4928 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4929 struct io_async_msghdr *iomsg)
4931 struct io_sr_msg *sr = &req->sr_msg;
4932 struct compat_iovec __user *uiov;
4937 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4942 uiov = compat_ptr(ptr);
4943 if (req->flags & REQ_F_BUFFER_SELECT) {
4944 compat_ssize_t clen;
4948 if (!access_ok(uiov, sizeof(*uiov)))
4950 if (__get_user(clen, &uiov->iov_len))
4955 iomsg->free_iov = NULL;
4957 iomsg->free_iov = iomsg->fast_iov;
4958 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4959 UIO_FASTIOV, &iomsg->free_iov,
4960 &iomsg->msg.msg_iter, true);
4969 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4970 struct io_async_msghdr *iomsg)
4972 iomsg->msg.msg_name = &iomsg->addr;
4974 #ifdef CONFIG_COMPAT
4975 if (req->ctx->compat)
4976 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4979 return __io_recvmsg_copy_hdr(req, iomsg);
4982 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4983 unsigned int issue_flags)
4985 struct io_sr_msg *sr = &req->sr_msg;
4987 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
4990 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4992 return io_put_kbuf(req, req->kbuf);
4995 static int io_recvmsg_prep_async(struct io_kiocb *req)
4999 ret = io_recvmsg_copy_hdr(req, req->async_data);
5001 req->flags |= REQ_F_NEED_CLEANUP;
5005 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5007 struct io_sr_msg *sr = &req->sr_msg;
5009 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5012 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5013 sr->len = READ_ONCE(sqe->len);
5014 sr->bgid = READ_ONCE(sqe->buf_group);
5015 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5016 if (sr->msg_flags & MSG_DONTWAIT)
5017 req->flags |= REQ_F_NOWAIT;
5019 #ifdef CONFIG_COMPAT
5020 if (req->ctx->compat)
5021 sr->msg_flags |= MSG_CMSG_COMPAT;
5026 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5028 struct io_async_msghdr iomsg, *kmsg;
5029 struct socket *sock;
5030 struct io_buffer *kbuf;
5033 int ret, cflags = 0;
5034 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5036 sock = sock_from_file(req->file);
5037 if (unlikely(!sock))
5040 if (req_has_async_data(req)) {
5041 kmsg = req->async_data;
5043 ret = io_recvmsg_copy_hdr(req, &iomsg);
5049 if (req->flags & REQ_F_BUFFER_SELECT) {
5050 kbuf = io_recv_buffer_select(req, issue_flags);
5052 return PTR_ERR(kbuf);
5053 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5054 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5055 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5056 1, req->sr_msg.len);
5059 flags = req->sr_msg.msg_flags;
5061 flags |= MSG_DONTWAIT;
5062 if (flags & MSG_WAITALL)
5063 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5065 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5066 kmsg->uaddr, flags);
5067 if (force_nonblock && ret == -EAGAIN)
5068 return io_setup_async_msg(req, kmsg);
5069 if (ret == -ERESTARTSYS)
5072 if (req->flags & REQ_F_BUFFER_SELECTED)
5073 cflags = io_put_recv_kbuf(req);
5074 /* fast path, check for non-NULL to avoid function call */
5076 kfree(kmsg->free_iov);
5077 req->flags &= ~REQ_F_NEED_CLEANUP;
5078 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5080 __io_req_complete(req, issue_flags, ret, cflags);
5084 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5086 struct io_buffer *kbuf;
5087 struct io_sr_msg *sr = &req->sr_msg;
5089 void __user *buf = sr->buf;
5090 struct socket *sock;
5094 int ret, cflags = 0;
5095 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5097 sock = sock_from_file(req->file);
5098 if (unlikely(!sock))
5101 if (req->flags & REQ_F_BUFFER_SELECT) {
5102 kbuf = io_recv_buffer_select(req, issue_flags);
5104 return PTR_ERR(kbuf);
5105 buf = u64_to_user_ptr(kbuf->addr);
5108 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5112 msg.msg_name = NULL;
5113 msg.msg_control = NULL;
5114 msg.msg_controllen = 0;
5115 msg.msg_namelen = 0;
5116 msg.msg_iocb = NULL;
5119 flags = req->sr_msg.msg_flags;
5121 flags |= MSG_DONTWAIT;
5122 if (flags & MSG_WAITALL)
5123 min_ret = iov_iter_count(&msg.msg_iter);
5125 ret = sock_recvmsg(sock, &msg, flags);
5126 if (force_nonblock && ret == -EAGAIN)
5128 if (ret == -ERESTARTSYS)
5131 if (req->flags & REQ_F_BUFFER_SELECTED)
5132 cflags = io_put_recv_kbuf(req);
5133 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5135 __io_req_complete(req, issue_flags, ret, cflags);
5139 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5141 struct io_accept *accept = &req->accept;
5143 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5145 if (sqe->ioprio || sqe->len || sqe->buf_index)
5148 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5149 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5150 accept->flags = READ_ONCE(sqe->accept_flags);
5151 accept->nofile = rlimit(RLIMIT_NOFILE);
5153 accept->file_slot = READ_ONCE(sqe->file_index);
5154 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
5155 (accept->flags & SOCK_CLOEXEC)))
5157 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5159 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5160 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5164 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5166 struct io_accept *accept = &req->accept;
5167 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5168 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5169 bool fixed = !!accept->file_slot;
5173 if (req->file->f_flags & O_NONBLOCK)
5174 req->flags |= REQ_F_NOWAIT;
5177 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5178 if (unlikely(fd < 0))
5181 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5186 ret = PTR_ERR(file);
5187 if (ret == -EAGAIN && force_nonblock)
5189 if (ret == -ERESTARTSYS)
5192 } else if (!fixed) {
5193 fd_install(fd, file);
5196 ret = io_install_fixed_file(req, file, issue_flags,
5197 accept->file_slot - 1);
5199 __io_req_complete(req, issue_flags, ret, 0);
5203 static int io_connect_prep_async(struct io_kiocb *req)
5205 struct io_async_connect *io = req->async_data;
5206 struct io_connect *conn = &req->connect;
5208 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5211 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5213 struct io_connect *conn = &req->connect;
5215 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5217 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5221 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5222 conn->addr_len = READ_ONCE(sqe->addr2);
5226 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5228 struct io_async_connect __io, *io;
5229 unsigned file_flags;
5231 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5233 if (req_has_async_data(req)) {
5234 io = req->async_data;
5236 ret = move_addr_to_kernel(req->connect.addr,
5237 req->connect.addr_len,
5244 file_flags = force_nonblock ? O_NONBLOCK : 0;
5246 ret = __sys_connect_file(req->file, &io->address,
5247 req->connect.addr_len, file_flags);
5248 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5249 if (req_has_async_data(req))
5251 if (io_alloc_async_data(req)) {
5255 memcpy(req->async_data, &__io, sizeof(__io));
5258 if (ret == -ERESTARTSYS)
5263 __io_req_complete(req, issue_flags, ret, 0);
5266 #else /* !CONFIG_NET */
5267 #define IO_NETOP_FN(op) \
5268 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5270 return -EOPNOTSUPP; \
5273 #define IO_NETOP_PREP(op) \
5275 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5277 return -EOPNOTSUPP; \
5280 #define IO_NETOP_PREP_ASYNC(op) \
5282 static int io_##op##_prep_async(struct io_kiocb *req) \
5284 return -EOPNOTSUPP; \
5287 IO_NETOP_PREP_ASYNC(sendmsg);
5288 IO_NETOP_PREP_ASYNC(recvmsg);
5289 IO_NETOP_PREP_ASYNC(connect);
5290 IO_NETOP_PREP(accept);
5293 #endif /* CONFIG_NET */
5295 struct io_poll_table {
5296 struct poll_table_struct pt;
5297 struct io_kiocb *req;
5302 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5303 __poll_t mask, io_req_tw_func_t func)
5305 /* for instances that support it check for an event match first: */
5306 if (mask && !(mask & poll->events))
5309 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5311 list_del_init(&poll->wait.entry);
5314 req->io_task_work.func = func;
5317 * If this fails, then the task is exiting. When a task exits, the
5318 * work gets canceled, so just cancel this request as well instead
5319 * of executing it. We can't safely execute it anyway, as we may not
5320 * have the needed state needed for it anyway.
5322 io_req_task_work_add(req);
5326 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5327 __acquires(&req->ctx->completion_lock)
5329 struct io_ring_ctx *ctx = req->ctx;
5331 /* req->task == current here, checking PF_EXITING is safe */
5332 if (unlikely(req->task->flags & PF_EXITING))
5333 WRITE_ONCE(poll->canceled, true);
5335 if (!req->result && !READ_ONCE(poll->canceled)) {
5336 struct poll_table_struct pt = { ._key = poll->events };
5338 req->result = vfs_poll(req->file, &pt) & poll->events;
5341 spin_lock(&ctx->completion_lock);
5342 if (!req->result && !READ_ONCE(poll->canceled)) {
5343 add_wait_queue(poll->head, &poll->wait);
5350 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5352 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5353 if (req->opcode == IORING_OP_POLL_ADD)
5354 return req->async_data;
5355 return req->apoll->double_poll;
5358 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5360 if (req->opcode == IORING_OP_POLL_ADD)
5362 return &req->apoll->poll;
5365 static void io_poll_remove_double(struct io_kiocb *req)
5366 __must_hold(&req->ctx->completion_lock)
5368 struct io_poll_iocb *poll = io_poll_get_double(req);
5370 lockdep_assert_held(&req->ctx->completion_lock);
5372 if (poll && poll->head) {
5373 struct wait_queue_head *head = poll->head;
5375 spin_lock_irq(&head->lock);
5376 list_del_init(&poll->wait.entry);
5377 if (poll->wait.private)
5380 spin_unlock_irq(&head->lock);
5384 static bool __io_poll_complete(struct io_kiocb *req, __poll_t mask)
5385 __must_hold(&req->ctx->completion_lock)
5387 struct io_ring_ctx *ctx = req->ctx;
5388 unsigned flags = IORING_CQE_F_MORE;
5391 if (READ_ONCE(req->poll.canceled)) {
5393 req->poll.events |= EPOLLONESHOT;
5395 error = mangle_poll(mask);
5397 if (req->poll.events & EPOLLONESHOT)
5399 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5400 req->poll.events |= EPOLLONESHOT;
5403 if (flags & IORING_CQE_F_MORE)
5406 return !(flags & IORING_CQE_F_MORE);
5409 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5411 struct io_ring_ctx *ctx = req->ctx;
5412 struct io_kiocb *nxt;
5414 if (io_poll_rewait(req, &req->poll)) {
5415 spin_unlock(&ctx->completion_lock);
5419 if (req->poll.done) {
5420 spin_unlock(&ctx->completion_lock);
5423 done = __io_poll_complete(req, req->result);
5425 io_poll_remove_double(req);
5426 hash_del(&req->hash_node);
5427 req->poll.done = true;
5430 add_wait_queue(req->poll.head, &req->poll.wait);
5432 io_commit_cqring(ctx);
5433 spin_unlock(&ctx->completion_lock);
5434 io_cqring_ev_posted(ctx);
5437 nxt = io_put_req_find_next(req);
5439 io_req_task_submit(nxt, locked);
5444 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5445 int sync, void *key)
5447 struct io_kiocb *req = wait->private;
5448 struct io_poll_iocb *poll = io_poll_get_single(req);
5449 __poll_t mask = key_to_poll(key);
5450 unsigned long flags;
5452 /* for instances that support it check for an event match first: */
5453 if (mask && !(mask & poll->events))
5455 if (!(poll->events & EPOLLONESHOT))
5456 return poll->wait.func(&poll->wait, mode, sync, key);
5458 list_del_init(&wait->entry);
5463 spin_lock_irqsave(&poll->head->lock, flags);
5464 done = list_empty(&poll->wait.entry);
5466 list_del_init(&poll->wait.entry);
5467 /* make sure double remove sees this as being gone */
5468 wait->private = NULL;
5469 spin_unlock_irqrestore(&poll->head->lock, flags);
5471 /* use wait func handler, so it matches the rq type */
5472 poll->wait.func(&poll->wait, mode, sync, key);
5479 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5480 wait_queue_func_t wake_func)
5484 poll->canceled = false;
5485 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5486 /* mask in events that we always want/need */
5487 poll->events = events | IO_POLL_UNMASK;
5488 INIT_LIST_HEAD(&poll->wait.entry);
5489 init_waitqueue_func_entry(&poll->wait, wake_func);
5492 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5493 struct wait_queue_head *head,
5494 struct io_poll_iocb **poll_ptr)
5496 struct io_kiocb *req = pt->req;
5499 * The file being polled uses multiple waitqueues for poll handling
5500 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5503 if (unlikely(pt->nr_entries)) {
5504 struct io_poll_iocb *poll_one = poll;
5506 /* double add on the same waitqueue head, ignore */
5507 if (poll_one->head == head)
5509 /* already have a 2nd entry, fail a third attempt */
5511 if ((*poll_ptr)->head == head)
5513 pt->error = -EINVAL;
5517 * Can't handle multishot for double wait for now, turn it
5518 * into one-shot mode.
5520 if (!(poll_one->events & EPOLLONESHOT))
5521 poll_one->events |= EPOLLONESHOT;
5522 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5524 pt->error = -ENOMEM;
5527 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5529 poll->wait.private = req;
5532 if (req->opcode == IORING_OP_POLL_ADD)
5533 req->flags |= REQ_F_ASYNC_DATA;
5539 if (poll->events & EPOLLEXCLUSIVE)
5540 add_wait_queue_exclusive(head, &poll->wait);
5542 add_wait_queue(head, &poll->wait);
5545 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5546 struct poll_table_struct *p)
5548 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5549 struct async_poll *apoll = pt->req->apoll;
5551 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5554 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5556 struct async_poll *apoll = req->apoll;
5557 struct io_ring_ctx *ctx = req->ctx;
5559 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5561 if (io_poll_rewait(req, &apoll->poll)) {
5562 spin_unlock(&ctx->completion_lock);
5566 hash_del(&req->hash_node);
5567 io_poll_remove_double(req);
5568 apoll->poll.done = true;
5569 spin_unlock(&ctx->completion_lock);
5571 if (!READ_ONCE(apoll->poll.canceled))
5572 io_req_task_submit(req, locked);
5574 io_req_complete_failed(req, -ECANCELED);
5577 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5580 struct io_kiocb *req = wait->private;
5581 struct io_poll_iocb *poll = &req->apoll->poll;
5583 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5586 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5589 static void io_poll_req_insert(struct io_kiocb *req)
5591 struct io_ring_ctx *ctx = req->ctx;
5592 struct hlist_head *list;
5594 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5595 hlist_add_head(&req->hash_node, list);
5598 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5599 struct io_poll_iocb *poll,
5600 struct io_poll_table *ipt, __poll_t mask,
5601 wait_queue_func_t wake_func)
5602 __acquires(&ctx->completion_lock)
5604 struct io_ring_ctx *ctx = req->ctx;
5605 bool cancel = false;
5607 INIT_HLIST_NODE(&req->hash_node);
5608 io_init_poll_iocb(poll, mask, wake_func);
5609 poll->file = req->file;
5610 poll->wait.private = req;
5612 ipt->pt._key = mask;
5615 ipt->nr_entries = 0;
5617 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5618 if (unlikely(!ipt->nr_entries) && !ipt->error)
5619 ipt->error = -EINVAL;
5621 spin_lock(&ctx->completion_lock);
5622 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5623 io_poll_remove_double(req);
5624 if (likely(poll->head)) {
5625 spin_lock_irq(&poll->head->lock);
5626 if (unlikely(list_empty(&poll->wait.entry))) {
5632 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5633 list_del_init(&poll->wait.entry);
5635 WRITE_ONCE(poll->canceled, true);
5636 else if (!poll->done) /* actually waiting for an event */
5637 io_poll_req_insert(req);
5638 spin_unlock_irq(&poll->head->lock);
5650 static int io_arm_poll_handler(struct io_kiocb *req)
5652 const struct io_op_def *def = &io_op_defs[req->opcode];
5653 struct io_ring_ctx *ctx = req->ctx;
5654 struct async_poll *apoll;
5655 struct io_poll_table ipt;
5656 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5658 if (!def->pollin && !def->pollout)
5659 return IO_APOLL_ABORTED;
5660 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
5661 return IO_APOLL_ABORTED;
5664 mask |= POLLIN | POLLRDNORM;
5666 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5667 if ((req->opcode == IORING_OP_RECVMSG) &&
5668 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5671 mask |= POLLOUT | POLLWRNORM;
5674 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5675 if (unlikely(!apoll))
5676 return IO_APOLL_ABORTED;
5677 apoll->double_poll = NULL;
5679 req->flags |= REQ_F_POLLED;
5680 ipt.pt._qproc = io_async_queue_proc;
5681 io_req_set_refcount(req);
5683 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5685 spin_unlock(&ctx->completion_lock);
5686 if (ret || ipt.error)
5687 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5689 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5690 mask, apoll->poll.events);
5694 static bool __io_poll_remove_one(struct io_kiocb *req,
5695 struct io_poll_iocb *poll, bool do_cancel)
5696 __must_hold(&req->ctx->completion_lock)
5698 bool do_complete = false;
5702 spin_lock_irq(&poll->head->lock);
5704 WRITE_ONCE(poll->canceled, true);
5705 if (!list_empty(&poll->wait.entry)) {
5706 list_del_init(&poll->wait.entry);
5709 spin_unlock_irq(&poll->head->lock);
5710 hash_del(&req->hash_node);
5714 static bool io_poll_remove_one(struct io_kiocb *req)
5715 __must_hold(&req->ctx->completion_lock)
5719 io_poll_remove_double(req);
5720 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5723 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5724 io_commit_cqring(req->ctx);
5726 io_put_req_deferred(req);
5732 * Returns true if we found and killed one or more poll requests
5734 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5735 struct task_struct *tsk, bool cancel_all)
5737 struct hlist_node *tmp;
5738 struct io_kiocb *req;
5741 spin_lock(&ctx->completion_lock);
5742 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5743 struct hlist_head *list;
5745 list = &ctx->cancel_hash[i];
5746 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5747 if (io_match_task_safe(req, tsk, cancel_all))
5748 posted += io_poll_remove_one(req);
5751 spin_unlock(&ctx->completion_lock);
5754 io_cqring_ev_posted(ctx);
5759 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5761 __must_hold(&ctx->completion_lock)
5763 struct hlist_head *list;
5764 struct io_kiocb *req;
5766 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5767 hlist_for_each_entry(req, list, hash_node) {
5768 if (sqe_addr != req->user_data)
5770 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5777 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5779 __must_hold(&ctx->completion_lock)
5781 struct io_kiocb *req;
5783 req = io_poll_find(ctx, sqe_addr, poll_only);
5786 if (io_poll_remove_one(req))
5792 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5797 events = READ_ONCE(sqe->poll32_events);
5799 events = swahw32(events);
5801 if (!(flags & IORING_POLL_ADD_MULTI))
5802 events |= EPOLLONESHOT;
5803 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5806 static int io_poll_update_prep(struct io_kiocb *req,
5807 const struct io_uring_sqe *sqe)
5809 struct io_poll_update *upd = &req->poll_update;
5812 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5814 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5816 flags = READ_ONCE(sqe->len);
5817 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5818 IORING_POLL_ADD_MULTI))
5820 /* meaningless without update */
5821 if (flags == IORING_POLL_ADD_MULTI)
5824 upd->old_user_data = READ_ONCE(sqe->addr);
5825 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5826 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5828 upd->new_user_data = READ_ONCE(sqe->off);
5829 if (!upd->update_user_data && upd->new_user_data)
5831 if (upd->update_events)
5832 upd->events = io_poll_parse_events(sqe, flags);
5833 else if (sqe->poll32_events)
5839 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5842 struct io_kiocb *req = wait->private;
5843 struct io_poll_iocb *poll = &req->poll;
5845 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5848 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5849 struct poll_table_struct *p)
5851 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5853 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5856 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5858 struct io_poll_iocb *poll = &req->poll;
5861 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5863 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5865 flags = READ_ONCE(sqe->len);
5866 if (flags & ~IORING_POLL_ADD_MULTI)
5869 io_req_set_refcount(req);
5870 poll->events = io_poll_parse_events(sqe, flags);
5874 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5876 struct io_poll_iocb *poll = &req->poll;
5877 struct io_ring_ctx *ctx = req->ctx;
5878 struct io_poll_table ipt;
5882 ipt.pt._qproc = io_poll_queue_proc;
5884 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5887 if (mask) { /* no async, we'd stolen it */
5889 done = __io_poll_complete(req, mask);
5890 io_commit_cqring(req->ctx);
5892 spin_unlock(&ctx->completion_lock);
5895 io_cqring_ev_posted(ctx);
5902 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5904 struct io_ring_ctx *ctx = req->ctx;
5905 struct io_kiocb *preq;
5909 spin_lock(&ctx->completion_lock);
5910 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5916 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5918 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5923 * Don't allow racy completion with singleshot, as we cannot safely
5924 * update those. For multishot, if we're racing with completion, just
5925 * let completion re-add it.
5927 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5928 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5932 /* we now have a detached poll request. reissue. */
5936 spin_unlock(&ctx->completion_lock);
5938 io_req_complete(req, ret);
5941 /* only mask one event flags, keep behavior flags */
5942 if (req->poll_update.update_events) {
5943 preq->poll.events &= ~0xffff;
5944 preq->poll.events |= req->poll_update.events & 0xffff;
5945 preq->poll.events |= IO_POLL_UNMASK;
5947 if (req->poll_update.update_user_data)
5948 preq->user_data = req->poll_update.new_user_data;
5949 spin_unlock(&ctx->completion_lock);
5951 /* complete update request, we're done with it */
5952 io_req_complete(req, ret);
5955 ret = io_poll_add(preq, issue_flags);
5958 io_req_complete(preq, ret);
5964 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5966 struct io_timeout_data *data = req->async_data;
5968 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
5970 io_req_complete_post(req, -ETIME, 0);
5973 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5975 struct io_timeout_data *data = container_of(timer,
5976 struct io_timeout_data, timer);
5977 struct io_kiocb *req = data->req;
5978 struct io_ring_ctx *ctx = req->ctx;
5979 unsigned long flags;
5981 spin_lock_irqsave(&ctx->timeout_lock, flags);
5982 list_del_init(&req->timeout.list);
5983 atomic_set(&req->ctx->cq_timeouts,
5984 atomic_read(&req->ctx->cq_timeouts) + 1);
5985 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5987 req->io_task_work.func = io_req_task_timeout;
5988 io_req_task_work_add(req);
5989 return HRTIMER_NORESTART;
5992 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5994 __must_hold(&ctx->timeout_lock)
5996 struct io_timeout_data *io;
5997 struct io_kiocb *req;
6000 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6001 found = user_data == req->user_data;
6006 return ERR_PTR(-ENOENT);
6008 io = req->async_data;
6009 if (hrtimer_try_to_cancel(&io->timer) == -1)
6010 return ERR_PTR(-EALREADY);
6011 list_del_init(&req->timeout.list);
6015 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6016 __must_hold(&ctx->completion_lock)
6017 __must_hold(&ctx->timeout_lock)
6019 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6022 return PTR_ERR(req);
6025 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
6026 io_put_req_deferred(req);
6030 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6032 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6033 case IORING_TIMEOUT_BOOTTIME:
6034 return CLOCK_BOOTTIME;
6035 case IORING_TIMEOUT_REALTIME:
6036 return CLOCK_REALTIME;
6038 /* can't happen, vetted at prep time */
6042 return CLOCK_MONOTONIC;
6046 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6047 struct timespec64 *ts, enum hrtimer_mode mode)
6048 __must_hold(&ctx->timeout_lock)
6050 struct io_timeout_data *io;
6051 struct io_kiocb *req;
6054 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6055 found = user_data == req->user_data;
6062 io = req->async_data;
6063 if (hrtimer_try_to_cancel(&io->timer) == -1)
6065 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6066 io->timer.function = io_link_timeout_fn;
6067 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6071 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6072 struct timespec64 *ts, enum hrtimer_mode mode)
6073 __must_hold(&ctx->timeout_lock)
6075 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6076 struct io_timeout_data *data;
6079 return PTR_ERR(req);
6081 req->timeout.off = 0; /* noseq */
6082 data = req->async_data;
6083 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6084 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6085 data->timer.function = io_timeout_fn;
6086 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6090 static int io_timeout_remove_prep(struct io_kiocb *req,
6091 const struct io_uring_sqe *sqe)
6093 struct io_timeout_rem *tr = &req->timeout_rem;
6095 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6097 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6099 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6102 tr->ltimeout = false;
6103 tr->addr = READ_ONCE(sqe->addr);
6104 tr->flags = READ_ONCE(sqe->timeout_flags);
6105 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6106 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6108 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6109 tr->ltimeout = true;
6110 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6112 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6114 } else if (tr->flags) {
6115 /* timeout removal doesn't support flags */
6122 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6124 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6129 * Remove or update an existing timeout command
6131 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6133 struct io_timeout_rem *tr = &req->timeout_rem;
6134 struct io_ring_ctx *ctx = req->ctx;
6137 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6138 spin_lock(&ctx->completion_lock);
6139 spin_lock_irq(&ctx->timeout_lock);
6140 ret = io_timeout_cancel(ctx, tr->addr);
6141 spin_unlock_irq(&ctx->timeout_lock);
6142 spin_unlock(&ctx->completion_lock);
6144 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6146 spin_lock_irq(&ctx->timeout_lock);
6148 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6150 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6151 spin_unlock_irq(&ctx->timeout_lock);
6156 io_req_complete_post(req, ret, 0);
6160 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6161 bool is_timeout_link)
6163 struct io_timeout_data *data;
6165 u32 off = READ_ONCE(sqe->off);
6167 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6169 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6172 if (off && is_timeout_link)
6174 flags = READ_ONCE(sqe->timeout_flags);
6175 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6176 IORING_TIMEOUT_ETIME_SUCCESS))
6178 /* more than one clock specified is invalid, obviously */
6179 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6182 INIT_LIST_HEAD(&req->timeout.list);
6183 req->timeout.off = off;
6184 if (unlikely(off && !req->ctx->off_timeout_used))
6185 req->ctx->off_timeout_used = true;
6187 if (WARN_ON_ONCE(req_has_async_data(req)))
6189 if (io_alloc_async_data(req))
6192 data = req->async_data;
6194 data->flags = flags;
6196 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6199 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6202 data->mode = io_translate_timeout_mode(flags);
6203 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6205 if (is_timeout_link) {
6206 struct io_submit_link *link = &req->ctx->submit_state.link;
6210 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6212 req->timeout.head = link->last;
6213 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6218 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6220 struct io_ring_ctx *ctx = req->ctx;
6221 struct io_timeout_data *data = req->async_data;
6222 struct list_head *entry;
6223 u32 tail, off = req->timeout.off;
6225 spin_lock_irq(&ctx->timeout_lock);
6228 * sqe->off holds how many events that need to occur for this
6229 * timeout event to be satisfied. If it isn't set, then this is
6230 * a pure timeout request, sequence isn't used.
6232 if (io_is_timeout_noseq(req)) {
6233 entry = ctx->timeout_list.prev;
6237 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6238 req->timeout.target_seq = tail + off;
6240 /* Update the last seq here in case io_flush_timeouts() hasn't.
6241 * This is safe because ->completion_lock is held, and submissions
6242 * and completions are never mixed in the same ->completion_lock section.
6244 ctx->cq_last_tm_flush = tail;
6247 * Insertion sort, ensuring the first entry in the list is always
6248 * the one we need first.
6250 list_for_each_prev(entry, &ctx->timeout_list) {
6251 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6254 if (io_is_timeout_noseq(nxt))
6256 /* nxt.seq is behind @tail, otherwise would've been completed */
6257 if (off >= nxt->timeout.target_seq - tail)
6261 list_add(&req->timeout.list, entry);
6262 data->timer.function = io_timeout_fn;
6263 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6264 spin_unlock_irq(&ctx->timeout_lock);
6268 struct io_cancel_data {
6269 struct io_ring_ctx *ctx;
6273 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6275 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6276 struct io_cancel_data *cd = data;
6278 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6281 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6282 struct io_ring_ctx *ctx)
6284 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6285 enum io_wq_cancel cancel_ret;
6288 if (!tctx || !tctx->io_wq)
6291 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6292 switch (cancel_ret) {
6293 case IO_WQ_CANCEL_OK:
6296 case IO_WQ_CANCEL_RUNNING:
6299 case IO_WQ_CANCEL_NOTFOUND:
6307 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6309 struct io_ring_ctx *ctx = req->ctx;
6312 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6314 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6318 spin_lock(&ctx->completion_lock);
6319 spin_lock_irq(&ctx->timeout_lock);
6320 ret = io_timeout_cancel(ctx, sqe_addr);
6321 spin_unlock_irq(&ctx->timeout_lock);
6324 ret = io_poll_cancel(ctx, sqe_addr, false);
6326 spin_unlock(&ctx->completion_lock);
6330 static int io_async_cancel_prep(struct io_kiocb *req,
6331 const struct io_uring_sqe *sqe)
6333 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6335 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6337 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6341 req->cancel.addr = READ_ONCE(sqe->addr);
6345 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6347 struct io_ring_ctx *ctx = req->ctx;
6348 u64 sqe_addr = req->cancel.addr;
6349 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6350 struct io_tctx_node *node;
6353 ret = io_try_cancel_userdata(req, sqe_addr);
6357 /* slow path, try all io-wq's */
6358 io_ring_submit_lock(ctx, needs_lock);
6360 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6361 struct io_uring_task *tctx = node->task->io_uring;
6363 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6367 io_ring_submit_unlock(ctx, needs_lock);
6371 io_req_complete_post(req, ret, 0);
6375 static int io_rsrc_update_prep(struct io_kiocb *req,
6376 const struct io_uring_sqe *sqe)
6378 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6380 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6383 req->rsrc_update.offset = READ_ONCE(sqe->off);
6384 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6385 if (!req->rsrc_update.nr_args)
6387 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6391 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6393 struct io_ring_ctx *ctx = req->ctx;
6394 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6395 struct io_uring_rsrc_update2 up;
6398 up.offset = req->rsrc_update.offset;
6399 up.data = req->rsrc_update.arg;
6404 io_ring_submit_lock(ctx, needs_lock);
6405 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6406 &up, req->rsrc_update.nr_args);
6407 io_ring_submit_unlock(ctx, needs_lock);
6411 __io_req_complete(req, issue_flags, ret, 0);
6415 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6417 switch (req->opcode) {
6420 case IORING_OP_READV:
6421 case IORING_OP_READ_FIXED:
6422 case IORING_OP_READ:
6423 return io_read_prep(req, sqe);
6424 case IORING_OP_WRITEV:
6425 case IORING_OP_WRITE_FIXED:
6426 case IORING_OP_WRITE:
6427 return io_write_prep(req, sqe);
6428 case IORING_OP_POLL_ADD:
6429 return io_poll_add_prep(req, sqe);
6430 case IORING_OP_POLL_REMOVE:
6431 return io_poll_update_prep(req, sqe);
6432 case IORING_OP_FSYNC:
6433 return io_fsync_prep(req, sqe);
6434 case IORING_OP_SYNC_FILE_RANGE:
6435 return io_sfr_prep(req, sqe);
6436 case IORING_OP_SENDMSG:
6437 case IORING_OP_SEND:
6438 return io_sendmsg_prep(req, sqe);
6439 case IORING_OP_RECVMSG:
6440 case IORING_OP_RECV:
6441 return io_recvmsg_prep(req, sqe);
6442 case IORING_OP_CONNECT:
6443 return io_connect_prep(req, sqe);
6444 case IORING_OP_TIMEOUT:
6445 return io_timeout_prep(req, sqe, false);
6446 case IORING_OP_TIMEOUT_REMOVE:
6447 return io_timeout_remove_prep(req, sqe);
6448 case IORING_OP_ASYNC_CANCEL:
6449 return io_async_cancel_prep(req, sqe);
6450 case IORING_OP_LINK_TIMEOUT:
6451 return io_timeout_prep(req, sqe, true);
6452 case IORING_OP_ACCEPT:
6453 return io_accept_prep(req, sqe);
6454 case IORING_OP_FALLOCATE:
6455 return io_fallocate_prep(req, sqe);
6456 case IORING_OP_OPENAT:
6457 return io_openat_prep(req, sqe);
6458 case IORING_OP_CLOSE:
6459 return io_close_prep(req, sqe);
6460 case IORING_OP_FILES_UPDATE:
6461 return io_rsrc_update_prep(req, sqe);
6462 case IORING_OP_STATX:
6463 return io_statx_prep(req, sqe);
6464 case IORING_OP_FADVISE:
6465 return io_fadvise_prep(req, sqe);
6466 case IORING_OP_MADVISE:
6467 return io_madvise_prep(req, sqe);
6468 case IORING_OP_OPENAT2:
6469 return io_openat2_prep(req, sqe);
6470 case IORING_OP_EPOLL_CTL:
6471 return io_epoll_ctl_prep(req, sqe);
6472 case IORING_OP_SPLICE:
6473 return io_splice_prep(req, sqe);
6474 case IORING_OP_PROVIDE_BUFFERS:
6475 return io_provide_buffers_prep(req, sqe);
6476 case IORING_OP_REMOVE_BUFFERS:
6477 return io_remove_buffers_prep(req, sqe);
6479 return io_tee_prep(req, sqe);
6480 case IORING_OP_SHUTDOWN:
6481 return io_shutdown_prep(req, sqe);
6482 case IORING_OP_RENAMEAT:
6483 return io_renameat_prep(req, sqe);
6484 case IORING_OP_UNLINKAT:
6485 return io_unlinkat_prep(req, sqe);
6486 case IORING_OP_MKDIRAT:
6487 return io_mkdirat_prep(req, sqe);
6488 case IORING_OP_SYMLINKAT:
6489 return io_symlinkat_prep(req, sqe);
6490 case IORING_OP_LINKAT:
6491 return io_linkat_prep(req, sqe);
6494 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6499 static int io_req_prep_async(struct io_kiocb *req)
6501 if (!io_op_defs[req->opcode].needs_async_setup)
6503 if (WARN_ON_ONCE(req_has_async_data(req)))
6505 if (io_alloc_async_data(req))
6508 switch (req->opcode) {
6509 case IORING_OP_READV:
6510 return io_rw_prep_async(req, READ);
6511 case IORING_OP_WRITEV:
6512 return io_rw_prep_async(req, WRITE);
6513 case IORING_OP_SENDMSG:
6514 return io_sendmsg_prep_async(req);
6515 case IORING_OP_RECVMSG:
6516 return io_recvmsg_prep_async(req);
6517 case IORING_OP_CONNECT:
6518 return io_connect_prep_async(req);
6520 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6525 static u32 io_get_sequence(struct io_kiocb *req)
6527 u32 seq = req->ctx->cached_sq_head;
6529 /* need original cached_sq_head, but it was increased for each req */
6530 io_for_each_link(req, req)
6535 static __cold void io_drain_req(struct io_kiocb *req)
6537 struct io_ring_ctx *ctx = req->ctx;
6538 struct io_defer_entry *de;
6540 u32 seq = io_get_sequence(req);
6542 /* Still need defer if there is pending req in defer list. */
6543 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6545 ctx->drain_active = false;
6546 io_req_task_queue(req);
6550 ret = io_req_prep_async(req);
6553 io_req_complete_failed(req, ret);
6556 io_prep_async_link(req);
6557 de = kmalloc(sizeof(*de), GFP_KERNEL);
6563 spin_lock(&ctx->completion_lock);
6564 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6565 spin_unlock(&ctx->completion_lock);
6570 trace_io_uring_defer(ctx, req, req->user_data);
6573 list_add_tail(&de->list, &ctx->defer_list);
6574 spin_unlock(&ctx->completion_lock);
6577 static void io_clean_op(struct io_kiocb *req)
6579 if (req->flags & REQ_F_BUFFER_SELECTED) {
6584 if (req->flags & REQ_F_NEED_CLEANUP) {
6585 switch (req->opcode) {
6586 case IORING_OP_READV:
6587 case IORING_OP_READ_FIXED:
6588 case IORING_OP_READ:
6589 case IORING_OP_WRITEV:
6590 case IORING_OP_WRITE_FIXED:
6591 case IORING_OP_WRITE: {
6592 struct io_async_rw *io = req->async_data;
6594 kfree(io->free_iovec);
6597 case IORING_OP_RECVMSG:
6598 case IORING_OP_SENDMSG: {
6599 struct io_async_msghdr *io = req->async_data;
6601 kfree(io->free_iov);
6604 case IORING_OP_SPLICE:
6606 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6607 io_put_file(req->splice.file_in);
6609 case IORING_OP_OPENAT:
6610 case IORING_OP_OPENAT2:
6611 if (req->open.filename)
6612 putname(req->open.filename);
6614 case IORING_OP_RENAMEAT:
6615 putname(req->rename.oldpath);
6616 putname(req->rename.newpath);
6618 case IORING_OP_UNLINKAT:
6619 putname(req->unlink.filename);
6621 case IORING_OP_MKDIRAT:
6622 putname(req->mkdir.filename);
6624 case IORING_OP_SYMLINKAT:
6625 putname(req->symlink.oldpath);
6626 putname(req->symlink.newpath);
6628 case IORING_OP_LINKAT:
6629 putname(req->hardlink.oldpath);
6630 putname(req->hardlink.newpath);
6634 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6635 kfree(req->apoll->double_poll);
6639 if (req->flags & REQ_F_INFLIGHT) {
6640 struct io_uring_task *tctx = req->task->io_uring;
6642 atomic_dec(&tctx->inflight_tracked);
6644 if (req->flags & REQ_F_CREDS)
6645 put_cred(req->creds);
6646 if (req->flags & REQ_F_ASYNC_DATA) {
6647 kfree(req->async_data);
6648 req->async_data = NULL;
6650 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6653 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6655 const struct cred *creds = NULL;
6658 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6659 creds = override_creds(req->creds);
6661 if (!io_op_defs[req->opcode].audit_skip)
6662 audit_uring_entry(req->opcode);
6664 switch (req->opcode) {
6666 ret = io_nop(req, issue_flags);
6668 case IORING_OP_READV:
6669 case IORING_OP_READ_FIXED:
6670 case IORING_OP_READ:
6671 ret = io_read(req, issue_flags);
6673 case IORING_OP_WRITEV:
6674 case IORING_OP_WRITE_FIXED:
6675 case IORING_OP_WRITE:
6676 ret = io_write(req, issue_flags);
6678 case IORING_OP_FSYNC:
6679 ret = io_fsync(req, issue_flags);
6681 case IORING_OP_POLL_ADD:
6682 ret = io_poll_add(req, issue_flags);
6684 case IORING_OP_POLL_REMOVE:
6685 ret = io_poll_update(req, issue_flags);
6687 case IORING_OP_SYNC_FILE_RANGE:
6688 ret = io_sync_file_range(req, issue_flags);
6690 case IORING_OP_SENDMSG:
6691 ret = io_sendmsg(req, issue_flags);
6693 case IORING_OP_SEND:
6694 ret = io_send(req, issue_flags);
6696 case IORING_OP_RECVMSG:
6697 ret = io_recvmsg(req, issue_flags);
6699 case IORING_OP_RECV:
6700 ret = io_recv(req, issue_flags);
6702 case IORING_OP_TIMEOUT:
6703 ret = io_timeout(req, issue_flags);
6705 case IORING_OP_TIMEOUT_REMOVE:
6706 ret = io_timeout_remove(req, issue_flags);
6708 case IORING_OP_ACCEPT:
6709 ret = io_accept(req, issue_flags);
6711 case IORING_OP_CONNECT:
6712 ret = io_connect(req, issue_flags);
6714 case IORING_OP_ASYNC_CANCEL:
6715 ret = io_async_cancel(req, issue_flags);
6717 case IORING_OP_FALLOCATE:
6718 ret = io_fallocate(req, issue_flags);
6720 case IORING_OP_OPENAT:
6721 ret = io_openat(req, issue_flags);
6723 case IORING_OP_CLOSE:
6724 ret = io_close(req, issue_flags);
6726 case IORING_OP_FILES_UPDATE:
6727 ret = io_files_update(req, issue_flags);
6729 case IORING_OP_STATX:
6730 ret = io_statx(req, issue_flags);
6732 case IORING_OP_FADVISE:
6733 ret = io_fadvise(req, issue_flags);
6735 case IORING_OP_MADVISE:
6736 ret = io_madvise(req, issue_flags);
6738 case IORING_OP_OPENAT2:
6739 ret = io_openat2(req, issue_flags);
6741 case IORING_OP_EPOLL_CTL:
6742 ret = io_epoll_ctl(req, issue_flags);
6744 case IORING_OP_SPLICE:
6745 ret = io_splice(req, issue_flags);
6747 case IORING_OP_PROVIDE_BUFFERS:
6748 ret = io_provide_buffers(req, issue_flags);
6750 case IORING_OP_REMOVE_BUFFERS:
6751 ret = io_remove_buffers(req, issue_flags);
6754 ret = io_tee(req, issue_flags);
6756 case IORING_OP_SHUTDOWN:
6757 ret = io_shutdown(req, issue_flags);
6759 case IORING_OP_RENAMEAT:
6760 ret = io_renameat(req, issue_flags);
6762 case IORING_OP_UNLINKAT:
6763 ret = io_unlinkat(req, issue_flags);
6765 case IORING_OP_MKDIRAT:
6766 ret = io_mkdirat(req, issue_flags);
6768 case IORING_OP_SYMLINKAT:
6769 ret = io_symlinkat(req, issue_flags);
6771 case IORING_OP_LINKAT:
6772 ret = io_linkat(req, issue_flags);
6779 if (!io_op_defs[req->opcode].audit_skip)
6780 audit_uring_exit(!ret, ret);
6783 revert_creds(creds);
6786 /* If the op doesn't have a file, we're not polling for it */
6787 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6788 io_iopoll_req_issued(req, issue_flags);
6793 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6795 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6797 req = io_put_req_find_next(req);
6798 return req ? &req->work : NULL;
6801 static void io_wq_submit_work(struct io_wq_work *work)
6803 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6804 unsigned int issue_flags = IO_URING_F_UNLOCKED;
6805 bool needs_poll = false;
6806 struct io_kiocb *timeout;
6809 /* one will be dropped by ->io_free_work() after returning to io-wq */
6810 if (!(req->flags & REQ_F_REFCOUNT))
6811 __io_req_set_refcount(req, 2);
6815 timeout = io_prep_linked_timeout(req);
6817 io_queue_linked_timeout(timeout);
6819 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6820 if (work->flags & IO_WQ_WORK_CANCEL) {
6821 io_req_task_queue_fail(req, -ECANCELED);
6825 if (req->flags & REQ_F_FORCE_ASYNC) {
6826 const struct io_op_def *def = &io_op_defs[req->opcode];
6827 bool opcode_poll = def->pollin || def->pollout;
6829 if (opcode_poll && file_can_poll(req->file)) {
6831 issue_flags |= IO_URING_F_NONBLOCK;
6836 ret = io_issue_sqe(req, issue_flags);
6840 * We can get EAGAIN for iopolled IO even though we're
6841 * forcing a sync submission from here, since we can't
6842 * wait for request slots on the block side.
6849 if (io_arm_poll_handler(req) == IO_APOLL_OK)
6851 /* aborted or ready, in either case retry blocking */
6853 issue_flags &= ~IO_URING_F_NONBLOCK;
6856 /* avoid locking problems by failing it from a clean context */
6858 io_req_task_queue_fail(req, ret);
6861 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6864 return &table->files[i];
6867 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6870 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6872 return (struct file *) (slot->file_ptr & FFS_MASK);
6875 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6877 unsigned long file_ptr = (unsigned long) file;
6879 file_ptr |= io_file_get_flags(file);
6880 file_slot->file_ptr = file_ptr;
6883 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6884 struct io_kiocb *req, int fd)
6887 unsigned long file_ptr;
6889 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6891 fd = array_index_nospec(fd, ctx->nr_user_files);
6892 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6893 file = (struct file *) (file_ptr & FFS_MASK);
6894 file_ptr &= ~FFS_MASK;
6895 /* mask in overlapping REQ_F and FFS bits */
6896 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6897 io_req_set_rsrc_node(req, ctx);
6901 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6902 struct io_kiocb *req, int fd)
6904 struct file *file = fget(fd);
6906 trace_io_uring_file_get(ctx, fd);
6908 /* we don't allow fixed io_uring files */
6909 if (file && unlikely(file->f_op == &io_uring_fops))
6910 io_req_track_inflight(req);
6914 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6915 struct io_kiocb *req, int fd, bool fixed)
6918 return io_file_get_fixed(ctx, req, fd);
6920 return io_file_get_normal(ctx, req, fd);
6923 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6925 struct io_kiocb *prev = req->timeout.prev;
6929 if (!(req->task->flags & PF_EXITING))
6930 ret = io_try_cancel_userdata(req, prev->user_data);
6931 io_req_complete_post(req, ret ?: -ETIME, 0);
6934 io_req_complete_post(req, -ETIME, 0);
6938 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6940 struct io_timeout_data *data = container_of(timer,
6941 struct io_timeout_data, timer);
6942 struct io_kiocb *prev, *req = data->req;
6943 struct io_ring_ctx *ctx = req->ctx;
6944 unsigned long flags;
6946 spin_lock_irqsave(&ctx->timeout_lock, flags);
6947 prev = req->timeout.head;
6948 req->timeout.head = NULL;
6951 * We don't expect the list to be empty, that will only happen if we
6952 * race with the completion of the linked work.
6955 io_remove_next_linked(prev);
6956 if (!req_ref_inc_not_zero(prev))
6959 list_del(&req->timeout.list);
6960 req->timeout.prev = prev;
6961 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6963 req->io_task_work.func = io_req_task_link_timeout;
6964 io_req_task_work_add(req);
6965 return HRTIMER_NORESTART;
6968 static void io_queue_linked_timeout(struct io_kiocb *req)
6970 struct io_ring_ctx *ctx = req->ctx;
6972 spin_lock_irq(&ctx->timeout_lock);
6974 * If the back reference is NULL, then our linked request finished
6975 * before we got a chance to setup the timer
6977 if (req->timeout.head) {
6978 struct io_timeout_data *data = req->async_data;
6980 data->timer.function = io_link_timeout_fn;
6981 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6983 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6985 spin_unlock_irq(&ctx->timeout_lock);
6986 /* drop submission reference */
6990 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
6991 __must_hold(&req->ctx->uring_lock)
6993 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6995 switch (io_arm_poll_handler(req)) {
6996 case IO_APOLL_READY:
6997 io_req_task_queue(req);
6999 case IO_APOLL_ABORTED:
7001 * Queued up for async execution, worker will release
7002 * submit reference when the iocb is actually submitted.
7004 io_queue_async_work(req, NULL);
7009 io_queue_linked_timeout(linked_timeout);
7012 static inline void __io_queue_sqe(struct io_kiocb *req)
7013 __must_hold(&req->ctx->uring_lock)
7015 struct io_kiocb *linked_timeout;
7018 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7020 if (req->flags & REQ_F_COMPLETE_INLINE) {
7021 io_req_add_compl_list(req);
7025 * We async punt it if the file wasn't marked NOWAIT, or if the file
7026 * doesn't support non-blocking read/write attempts
7029 linked_timeout = io_prep_linked_timeout(req);
7031 io_queue_linked_timeout(linked_timeout);
7032 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7033 io_queue_sqe_arm_apoll(req);
7035 io_req_complete_failed(req, ret);
7039 static void io_queue_sqe_fallback(struct io_kiocb *req)
7040 __must_hold(&req->ctx->uring_lock)
7042 if (req->flags & REQ_F_FAIL) {
7043 io_req_complete_fail_submit(req);
7044 } else if (unlikely(req->ctx->drain_active)) {
7047 int ret = io_req_prep_async(req);
7050 io_req_complete_failed(req, ret);
7052 io_queue_async_work(req, NULL);
7056 static inline void io_queue_sqe(struct io_kiocb *req)
7057 __must_hold(&req->ctx->uring_lock)
7059 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7060 __io_queue_sqe(req);
7062 io_queue_sqe_fallback(req);
7066 * Check SQE restrictions (opcode and flags).
7068 * Returns 'true' if SQE is allowed, 'false' otherwise.
7070 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7071 struct io_kiocb *req,
7072 unsigned int sqe_flags)
7074 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7077 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7078 ctx->restrictions.sqe_flags_required)
7081 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7082 ctx->restrictions.sqe_flags_required))
7088 static void io_init_req_drain(struct io_kiocb *req)
7090 struct io_ring_ctx *ctx = req->ctx;
7091 struct io_kiocb *head = ctx->submit_state.link.head;
7093 ctx->drain_active = true;
7096 * If we need to drain a request in the middle of a link, drain
7097 * the head request and the next request/link after the current
7098 * link. Considering sequential execution of links,
7099 * IOSQE_IO_DRAIN will be maintained for every request of our
7102 head->flags |= IOSQE_IO_DRAIN | REQ_F_FORCE_ASYNC;
7103 ctx->drain_next = true;
7107 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7108 const struct io_uring_sqe *sqe)
7109 __must_hold(&ctx->uring_lock)
7111 unsigned int sqe_flags;
7115 /* req is partially pre-initialised, see io_preinit_req() */
7116 req->opcode = opcode = READ_ONCE(sqe->opcode);
7117 /* same numerical values with corresponding REQ_F_*, safe to copy */
7118 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7119 req->user_data = READ_ONCE(sqe->user_data);
7121 req->fixed_rsrc_refs = NULL;
7122 req->task = current;
7124 if (unlikely(opcode >= IORING_OP_LAST)) {
7128 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7129 /* enforce forwards compatibility on users */
7130 if (sqe_flags & ~SQE_VALID_FLAGS)
7132 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7133 !io_op_defs[opcode].buffer_select)
7135 if (sqe_flags & IOSQE_IO_DRAIN)
7136 io_init_req_drain(req);
7138 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7139 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7141 /* knock it to the slow queue path, will be drained there */
7142 if (ctx->drain_active)
7143 req->flags |= REQ_F_FORCE_ASYNC;
7144 /* if there is no link, we're at "next" request and need to drain */
7145 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7146 ctx->drain_next = false;
7147 ctx->drain_active = true;
7148 req->flags |= IOSQE_IO_DRAIN | REQ_F_FORCE_ASYNC;
7152 if (io_op_defs[opcode].needs_file) {
7153 struct io_submit_state *state = &ctx->submit_state;
7156 * Plug now if we have more than 2 IO left after this, and the
7157 * target is potentially a read/write to block based storage.
7159 if (state->need_plug && io_op_defs[opcode].plug) {
7160 state->plug_started = true;
7161 state->need_plug = false;
7162 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7165 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7166 (sqe_flags & IOSQE_FIXED_FILE));
7167 if (unlikely(!req->file))
7171 personality = READ_ONCE(sqe->personality);
7175 req->creds = xa_load(&ctx->personalities, personality);
7178 get_cred(req->creds);
7179 ret = security_uring_override_creds(req->creds);
7181 put_cred(req->creds);
7184 req->flags |= REQ_F_CREDS;
7187 return io_req_prep(req, sqe);
7190 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7191 const struct io_uring_sqe *sqe)
7192 __must_hold(&ctx->uring_lock)
7194 struct io_submit_link *link = &ctx->submit_state.link;
7197 ret = io_init_req(ctx, req, sqe);
7198 if (unlikely(ret)) {
7199 trace_io_uring_req_failed(sqe, ret);
7201 /* fail even hard links since we don't submit */
7204 * we can judge a link req is failed or cancelled by if
7205 * REQ_F_FAIL is set, but the head is an exception since
7206 * it may be set REQ_F_FAIL because of other req's failure
7207 * so let's leverage req->result to distinguish if a head
7208 * is set REQ_F_FAIL because of its failure or other req's
7209 * failure so that we can set the correct ret code for it.
7210 * init result here to avoid affecting the normal path.
7212 if (!(link->head->flags & REQ_F_FAIL))
7213 req_fail_link_node(link->head, -ECANCELED);
7214 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7216 * the current req is a normal req, we should return
7217 * error and thus break the submittion loop.
7219 io_req_complete_failed(req, ret);
7222 req_fail_link_node(req, ret);
7225 /* don't need @sqe from now on */
7226 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7228 ctx->flags & IORING_SETUP_SQPOLL);
7231 * If we already have a head request, queue this one for async
7232 * submittal once the head completes. If we don't have a head but
7233 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7234 * submitted sync once the chain is complete. If none of those
7235 * conditions are true (normal request), then just queue it.
7238 struct io_kiocb *head = link->head;
7240 if (!(req->flags & REQ_F_FAIL)) {
7241 ret = io_req_prep_async(req);
7242 if (unlikely(ret)) {
7243 req_fail_link_node(req, ret);
7244 if (!(head->flags & REQ_F_FAIL))
7245 req_fail_link_node(head, -ECANCELED);
7248 trace_io_uring_link(ctx, req, head);
7249 link->last->link = req;
7252 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7254 /* last request of a link, enqueue the link */
7257 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7268 * Batched submission is done, ensure local IO is flushed out.
7270 static void io_submit_state_end(struct io_ring_ctx *ctx)
7272 struct io_submit_state *state = &ctx->submit_state;
7274 if (state->link.head)
7275 io_queue_sqe(state->link.head);
7276 /* flush only after queuing links as they can generate completions */
7277 io_submit_flush_completions(ctx);
7278 if (state->plug_started)
7279 blk_finish_plug(&state->plug);
7283 * Start submission side cache.
7285 static void io_submit_state_start(struct io_submit_state *state,
7286 unsigned int max_ios)
7288 state->plug_started = false;
7289 state->need_plug = max_ios > 2;
7290 state->submit_nr = max_ios;
7291 /* set only head, no need to init link_last in advance */
7292 state->link.head = NULL;
7295 static void io_commit_sqring(struct io_ring_ctx *ctx)
7297 struct io_rings *rings = ctx->rings;
7300 * Ensure any loads from the SQEs are done at this point,
7301 * since once we write the new head, the application could
7302 * write new data to them.
7304 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7308 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7309 * that is mapped by userspace. This means that care needs to be taken to
7310 * ensure that reads are stable, as we cannot rely on userspace always
7311 * being a good citizen. If members of the sqe are validated and then later
7312 * used, it's important that those reads are done through READ_ONCE() to
7313 * prevent a re-load down the line.
7315 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7317 unsigned head, mask = ctx->sq_entries - 1;
7318 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7321 * The cached sq head (or cq tail) serves two purposes:
7323 * 1) allows us to batch the cost of updating the user visible
7325 * 2) allows the kernel side to track the head on its own, even
7326 * though the application is the one updating it.
7328 head = READ_ONCE(ctx->sq_array[sq_idx]);
7329 if (likely(head < ctx->sq_entries))
7330 return &ctx->sq_sqes[head];
7332 /* drop invalid entries */
7334 WRITE_ONCE(ctx->rings->sq_dropped,
7335 READ_ONCE(ctx->rings->sq_dropped) + 1);
7339 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7340 __must_hold(&ctx->uring_lock)
7342 unsigned int entries = io_sqring_entries(ctx);
7345 if (unlikely(!entries))
7347 /* make sure SQ entry isn't read before tail */
7348 nr = min3(nr, ctx->sq_entries, entries);
7349 io_get_task_refs(nr);
7351 io_submit_state_start(&ctx->submit_state, nr);
7353 const struct io_uring_sqe *sqe;
7354 struct io_kiocb *req;
7356 if (unlikely(!io_alloc_req_refill(ctx))) {
7358 submitted = -EAGAIN;
7361 req = io_alloc_req(ctx);
7362 sqe = io_get_sqe(ctx);
7363 if (unlikely(!sqe)) {
7364 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7367 /* will complete beyond this point, count as submitted */
7369 if (io_submit_sqe(ctx, req, sqe))
7371 } while (submitted < nr);
7373 if (unlikely(submitted != nr)) {
7374 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7375 int unused = nr - ref_used;
7377 current->io_uring->cached_refs += unused;
7380 io_submit_state_end(ctx);
7381 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7382 io_commit_sqring(ctx);
7387 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7389 return READ_ONCE(sqd->state);
7392 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7394 /* Tell userspace we may need a wakeup call */
7395 spin_lock(&ctx->completion_lock);
7396 WRITE_ONCE(ctx->rings->sq_flags,
7397 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7398 spin_unlock(&ctx->completion_lock);
7401 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7403 spin_lock(&ctx->completion_lock);
7404 WRITE_ONCE(ctx->rings->sq_flags,
7405 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7406 spin_unlock(&ctx->completion_lock);
7409 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7411 unsigned int to_submit;
7414 to_submit = io_sqring_entries(ctx);
7415 /* if we're handling multiple rings, cap submit size for fairness */
7416 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7417 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7419 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7420 const struct cred *creds = NULL;
7422 if (ctx->sq_creds != current_cred())
7423 creds = override_creds(ctx->sq_creds);
7425 mutex_lock(&ctx->uring_lock);
7426 if (!wq_list_empty(&ctx->iopoll_list))
7427 io_do_iopoll(ctx, true);
7430 * Don't submit if refs are dying, good for io_uring_register(),
7431 * but also it is relied upon by io_ring_exit_work()
7433 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7434 !(ctx->flags & IORING_SETUP_R_DISABLED))
7435 ret = io_submit_sqes(ctx, to_submit);
7436 mutex_unlock(&ctx->uring_lock);
7438 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7439 wake_up(&ctx->sqo_sq_wait);
7441 revert_creds(creds);
7447 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7449 struct io_ring_ctx *ctx;
7450 unsigned sq_thread_idle = 0;
7452 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7453 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7454 sqd->sq_thread_idle = sq_thread_idle;
7457 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7459 bool did_sig = false;
7460 struct ksignal ksig;
7462 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7463 signal_pending(current)) {
7464 mutex_unlock(&sqd->lock);
7465 if (signal_pending(current))
7466 did_sig = get_signal(&ksig);
7468 mutex_lock(&sqd->lock);
7470 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7473 static int io_sq_thread(void *data)
7475 struct io_sq_data *sqd = data;
7476 struct io_ring_ctx *ctx;
7477 unsigned long timeout = 0;
7478 char buf[TASK_COMM_LEN];
7481 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7482 set_task_comm(current, buf);
7484 if (sqd->sq_cpu != -1)
7485 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7487 set_cpus_allowed_ptr(current, cpu_online_mask);
7488 current->flags |= PF_NO_SETAFFINITY;
7490 audit_alloc_kernel(current);
7492 mutex_lock(&sqd->lock);
7494 bool cap_entries, sqt_spin = false;
7496 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7497 if (io_sqd_handle_event(sqd))
7499 timeout = jiffies + sqd->sq_thread_idle;
7502 cap_entries = !list_is_singular(&sqd->ctx_list);
7503 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7504 int ret = __io_sq_thread(ctx, cap_entries);
7506 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7509 if (io_run_task_work())
7512 if (sqt_spin || !time_after(jiffies, timeout)) {
7515 timeout = jiffies + sqd->sq_thread_idle;
7519 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7520 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7521 bool needs_sched = true;
7523 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7524 io_ring_set_wakeup_flag(ctx);
7526 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7527 !wq_list_empty(&ctx->iopoll_list)) {
7528 needs_sched = false;
7531 if (io_sqring_entries(ctx)) {
7532 needs_sched = false;
7538 mutex_unlock(&sqd->lock);
7540 mutex_lock(&sqd->lock);
7542 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7543 io_ring_clear_wakeup_flag(ctx);
7546 finish_wait(&sqd->wait, &wait);
7547 timeout = jiffies + sqd->sq_thread_idle;
7550 io_uring_cancel_generic(true, sqd);
7552 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7553 io_ring_set_wakeup_flag(ctx);
7555 mutex_unlock(&sqd->lock);
7557 audit_free(current);
7559 complete(&sqd->exited);
7563 struct io_wait_queue {
7564 struct wait_queue_entry wq;
7565 struct io_ring_ctx *ctx;
7567 unsigned nr_timeouts;
7570 static inline bool io_should_wake(struct io_wait_queue *iowq)
7572 struct io_ring_ctx *ctx = iowq->ctx;
7573 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7576 * Wake up if we have enough events, or if a timeout occurred since we
7577 * started waiting. For timeouts, we always want to return to userspace,
7578 * regardless of event count.
7580 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7583 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7584 int wake_flags, void *key)
7586 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7590 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7591 * the task, and the next invocation will do it.
7593 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7594 return autoremove_wake_function(curr, mode, wake_flags, key);
7598 static int io_run_task_work_sig(void)
7600 if (io_run_task_work())
7602 if (!signal_pending(current))
7604 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7605 return -ERESTARTSYS;
7609 /* when returns >0, the caller should retry */
7610 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7611 struct io_wait_queue *iowq,
7612 signed long *timeout)
7616 /* make sure we run task_work before checking for signals */
7617 ret = io_run_task_work_sig();
7618 if (ret || io_should_wake(iowq))
7620 /* let the caller flush overflows, retry */
7621 if (test_bit(0, &ctx->check_cq_overflow))
7624 *timeout = schedule_timeout(*timeout);
7625 return !*timeout ? -ETIME : 1;
7629 * Wait until events become available, if we don't already have some. The
7630 * application must reap them itself, as they reside on the shared cq ring.
7632 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7633 const sigset_t __user *sig, size_t sigsz,
7634 struct __kernel_timespec __user *uts)
7636 struct io_wait_queue iowq;
7637 struct io_rings *rings = ctx->rings;
7638 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7642 io_cqring_overflow_flush(ctx);
7643 if (io_cqring_events(ctx) >= min_events)
7645 if (!io_run_task_work())
7650 struct timespec64 ts;
7652 if (get_timespec64(&ts, uts))
7654 timeout = timespec64_to_jiffies(&ts);
7658 #ifdef CONFIG_COMPAT
7659 if (in_compat_syscall())
7660 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7664 ret = set_user_sigmask(sig, sigsz);
7670 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7671 iowq.wq.private = current;
7672 INIT_LIST_HEAD(&iowq.wq.entry);
7674 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7675 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7677 trace_io_uring_cqring_wait(ctx, min_events);
7679 /* if we can't even flush overflow, don't wait for more */
7680 if (!io_cqring_overflow_flush(ctx)) {
7684 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7685 TASK_INTERRUPTIBLE);
7686 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7687 finish_wait(&ctx->cq_wait, &iowq.wq);
7691 restore_saved_sigmask_unless(ret == -EINTR);
7693 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7696 static void io_free_page_table(void **table, size_t size)
7698 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7700 for (i = 0; i < nr_tables; i++)
7705 static __cold void **io_alloc_page_table(size_t size)
7707 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7708 size_t init_size = size;
7711 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7715 for (i = 0; i < nr_tables; i++) {
7716 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7718 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7720 io_free_page_table(table, init_size);
7728 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7730 percpu_ref_exit(&ref_node->refs);
7734 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7736 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7737 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7738 unsigned long flags;
7739 bool first_add = false;
7741 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7744 while (!list_empty(&ctx->rsrc_ref_list)) {
7745 node = list_first_entry(&ctx->rsrc_ref_list,
7746 struct io_rsrc_node, node);
7747 /* recycle ref nodes in order */
7750 list_del(&node->node);
7751 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7753 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7756 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7759 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7761 struct io_rsrc_node *ref_node;
7763 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7767 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7772 INIT_LIST_HEAD(&ref_node->node);
7773 INIT_LIST_HEAD(&ref_node->rsrc_list);
7774 ref_node->done = false;
7778 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7779 struct io_rsrc_data *data_to_kill)
7780 __must_hold(&ctx->uring_lock)
7782 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7783 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7785 io_rsrc_refs_drop(ctx);
7788 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7790 rsrc_node->rsrc_data = data_to_kill;
7791 spin_lock_irq(&ctx->rsrc_ref_lock);
7792 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7793 spin_unlock_irq(&ctx->rsrc_ref_lock);
7795 atomic_inc(&data_to_kill->refs);
7796 percpu_ref_kill(&rsrc_node->refs);
7797 ctx->rsrc_node = NULL;
7800 if (!ctx->rsrc_node) {
7801 ctx->rsrc_node = ctx->rsrc_backup_node;
7802 ctx->rsrc_backup_node = NULL;
7806 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7808 if (ctx->rsrc_backup_node)
7810 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7811 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7814 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7815 struct io_ring_ctx *ctx)
7819 /* As we may drop ->uring_lock, other task may have started quiesce */
7823 data->quiesce = true;
7825 ret = io_rsrc_node_switch_start(ctx);
7828 io_rsrc_node_switch(ctx, data);
7830 /* kill initial ref, already quiesced if zero */
7831 if (atomic_dec_and_test(&data->refs))
7833 mutex_unlock(&ctx->uring_lock);
7834 flush_delayed_work(&ctx->rsrc_put_work);
7835 ret = wait_for_completion_interruptible(&data->done);
7837 mutex_lock(&ctx->uring_lock);
7841 atomic_inc(&data->refs);
7842 /* wait for all works potentially completing data->done */
7843 flush_delayed_work(&ctx->rsrc_put_work);
7844 reinit_completion(&data->done);
7846 ret = io_run_task_work_sig();
7847 mutex_lock(&ctx->uring_lock);
7849 data->quiesce = false;
7854 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7856 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7857 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7859 return &data->tags[table_idx][off];
7862 static void io_rsrc_data_free(struct io_rsrc_data *data)
7864 size_t size = data->nr * sizeof(data->tags[0][0]);
7867 io_free_page_table((void **)data->tags, size);
7871 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7872 u64 __user *utags, unsigned nr,
7873 struct io_rsrc_data **pdata)
7875 struct io_rsrc_data *data;
7879 data = kzalloc(sizeof(*data), GFP_KERNEL);
7882 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7890 data->do_put = do_put;
7893 for (i = 0; i < nr; i++) {
7894 u64 *tag_slot = io_get_tag_slot(data, i);
7896 if (copy_from_user(tag_slot, &utags[i],
7902 atomic_set(&data->refs, 1);
7903 init_completion(&data->done);
7907 io_rsrc_data_free(data);
7911 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7913 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7914 GFP_KERNEL_ACCOUNT);
7915 return !!table->files;
7918 static void io_free_file_tables(struct io_file_table *table)
7920 kvfree(table->files);
7921 table->files = NULL;
7924 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7926 #if defined(CONFIG_UNIX)
7927 if (ctx->ring_sock) {
7928 struct sock *sock = ctx->ring_sock->sk;
7929 struct sk_buff *skb;
7931 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7937 for (i = 0; i < ctx->nr_user_files; i++) {
7940 file = io_file_from_index(ctx, i);
7945 io_free_file_tables(&ctx->file_table);
7946 io_rsrc_data_free(ctx->file_data);
7947 ctx->file_data = NULL;
7948 ctx->nr_user_files = 0;
7951 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7955 if (!ctx->file_data)
7957 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7959 __io_sqe_files_unregister(ctx);
7963 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7964 __releases(&sqd->lock)
7966 WARN_ON_ONCE(sqd->thread == current);
7969 * Do the dance but not conditional clear_bit() because it'd race with
7970 * other threads incrementing park_pending and setting the bit.
7972 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7973 if (atomic_dec_return(&sqd->park_pending))
7974 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7975 mutex_unlock(&sqd->lock);
7978 static void io_sq_thread_park(struct io_sq_data *sqd)
7979 __acquires(&sqd->lock)
7981 WARN_ON_ONCE(sqd->thread == current);
7983 atomic_inc(&sqd->park_pending);
7984 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7985 mutex_lock(&sqd->lock);
7987 wake_up_process(sqd->thread);
7990 static void io_sq_thread_stop(struct io_sq_data *sqd)
7992 WARN_ON_ONCE(sqd->thread == current);
7993 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7995 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7996 mutex_lock(&sqd->lock);
7998 wake_up_process(sqd->thread);
7999 mutex_unlock(&sqd->lock);
8000 wait_for_completion(&sqd->exited);
8003 static void io_put_sq_data(struct io_sq_data *sqd)
8005 if (refcount_dec_and_test(&sqd->refs)) {
8006 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8008 io_sq_thread_stop(sqd);
8013 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8015 struct io_sq_data *sqd = ctx->sq_data;
8018 io_sq_thread_park(sqd);
8019 list_del_init(&ctx->sqd_list);
8020 io_sqd_update_thread_idle(sqd);
8021 io_sq_thread_unpark(sqd);
8023 io_put_sq_data(sqd);
8024 ctx->sq_data = NULL;
8028 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8030 struct io_ring_ctx *ctx_attach;
8031 struct io_sq_data *sqd;
8034 f = fdget(p->wq_fd);
8036 return ERR_PTR(-ENXIO);
8037 if (f.file->f_op != &io_uring_fops) {
8039 return ERR_PTR(-EINVAL);
8042 ctx_attach = f.file->private_data;
8043 sqd = ctx_attach->sq_data;
8046 return ERR_PTR(-EINVAL);
8048 if (sqd->task_tgid != current->tgid) {
8050 return ERR_PTR(-EPERM);
8053 refcount_inc(&sqd->refs);
8058 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8061 struct io_sq_data *sqd;
8064 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8065 sqd = io_attach_sq_data(p);
8070 /* fall through for EPERM case, setup new sqd/task */
8071 if (PTR_ERR(sqd) != -EPERM)
8075 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8077 return ERR_PTR(-ENOMEM);
8079 atomic_set(&sqd->park_pending, 0);
8080 refcount_set(&sqd->refs, 1);
8081 INIT_LIST_HEAD(&sqd->ctx_list);
8082 mutex_init(&sqd->lock);
8083 init_waitqueue_head(&sqd->wait);
8084 init_completion(&sqd->exited);
8088 #if defined(CONFIG_UNIX)
8090 * Ensure the UNIX gc is aware of our file set, so we are certain that
8091 * the io_uring can be safely unregistered on process exit, even if we have
8092 * loops in the file referencing.
8094 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8096 struct sock *sk = ctx->ring_sock->sk;
8097 struct scm_fp_list *fpl;
8098 struct sk_buff *skb;
8101 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8105 skb = alloc_skb(0, GFP_KERNEL);
8114 fpl->user = get_uid(current_user());
8115 for (i = 0; i < nr; i++) {
8116 struct file *file = io_file_from_index(ctx, i + offset);
8120 fpl->fp[nr_files] = get_file(file);
8121 unix_inflight(fpl->user, fpl->fp[nr_files]);
8126 fpl->max = SCM_MAX_FD;
8127 fpl->count = nr_files;
8128 UNIXCB(skb).fp = fpl;
8129 skb->destructor = unix_destruct_scm;
8130 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8131 skb_queue_head(&sk->sk_receive_queue, skb);
8133 for (i = 0; i < nr_files; i++)
8144 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8145 * causes regular reference counting to break down. We rely on the UNIX
8146 * garbage collection to take care of this problem for us.
8148 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8150 unsigned left, total;
8154 left = ctx->nr_user_files;
8156 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8158 ret = __io_sqe_files_scm(ctx, this_files, total);
8162 total += this_files;
8168 while (total < ctx->nr_user_files) {
8169 struct file *file = io_file_from_index(ctx, total);
8179 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8185 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8187 struct file *file = prsrc->file;
8188 #if defined(CONFIG_UNIX)
8189 struct sock *sock = ctx->ring_sock->sk;
8190 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8191 struct sk_buff *skb;
8194 __skb_queue_head_init(&list);
8197 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8198 * remove this entry and rearrange the file array.
8200 skb = skb_dequeue(head);
8202 struct scm_fp_list *fp;
8204 fp = UNIXCB(skb).fp;
8205 for (i = 0; i < fp->count; i++) {
8208 if (fp->fp[i] != file)
8211 unix_notinflight(fp->user, fp->fp[i]);
8212 left = fp->count - 1 - i;
8214 memmove(&fp->fp[i], &fp->fp[i + 1],
8215 left * sizeof(struct file *));
8222 __skb_queue_tail(&list, skb);
8232 __skb_queue_tail(&list, skb);
8234 skb = skb_dequeue(head);
8237 if (skb_peek(&list)) {
8238 spin_lock_irq(&head->lock);
8239 while ((skb = __skb_dequeue(&list)) != NULL)
8240 __skb_queue_tail(head, skb);
8241 spin_unlock_irq(&head->lock);
8248 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8250 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8251 struct io_ring_ctx *ctx = rsrc_data->ctx;
8252 struct io_rsrc_put *prsrc, *tmp;
8254 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8255 list_del(&prsrc->list);
8258 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8260 io_ring_submit_lock(ctx, lock_ring);
8261 spin_lock(&ctx->completion_lock);
8262 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
8264 io_commit_cqring(ctx);
8265 spin_unlock(&ctx->completion_lock);
8266 io_cqring_ev_posted(ctx);
8267 io_ring_submit_unlock(ctx, lock_ring);
8270 rsrc_data->do_put(ctx, prsrc);
8274 io_rsrc_node_destroy(ref_node);
8275 if (atomic_dec_and_test(&rsrc_data->refs))
8276 complete(&rsrc_data->done);
8279 static void io_rsrc_put_work(struct work_struct *work)
8281 struct io_ring_ctx *ctx;
8282 struct llist_node *node;
8284 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8285 node = llist_del_all(&ctx->rsrc_put_llist);
8288 struct io_rsrc_node *ref_node;
8289 struct llist_node *next = node->next;
8291 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8292 __io_rsrc_put_work(ref_node);
8297 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8298 unsigned nr_args, u64 __user *tags)
8300 __s32 __user *fds = (__s32 __user *) arg;
8309 if (nr_args > IORING_MAX_FIXED_FILES)
8311 if (nr_args > rlimit(RLIMIT_NOFILE))
8313 ret = io_rsrc_node_switch_start(ctx);
8316 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8322 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8325 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8326 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8330 /* allow sparse sets */
8333 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8340 if (unlikely(!file))
8344 * Don't allow io_uring instances to be registered. If UNIX
8345 * isn't enabled, then this causes a reference cycle and this
8346 * instance can never get freed. If UNIX is enabled we'll
8347 * handle it just fine, but there's still no point in allowing
8348 * a ring fd as it doesn't support regular read/write anyway.
8350 if (file->f_op == &io_uring_fops) {
8354 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8357 ret = io_sqe_files_scm(ctx);
8359 __io_sqe_files_unregister(ctx);
8363 io_rsrc_node_switch(ctx, NULL);
8366 for (i = 0; i < ctx->nr_user_files; i++) {
8367 file = io_file_from_index(ctx, i);
8371 io_free_file_tables(&ctx->file_table);
8372 ctx->nr_user_files = 0;
8374 io_rsrc_data_free(ctx->file_data);
8375 ctx->file_data = NULL;
8379 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8382 #if defined(CONFIG_UNIX)
8383 struct sock *sock = ctx->ring_sock->sk;
8384 struct sk_buff_head *head = &sock->sk_receive_queue;
8385 struct sk_buff *skb;
8388 * See if we can merge this file into an existing skb SCM_RIGHTS
8389 * file set. If there's no room, fall back to allocating a new skb
8390 * and filling it in.
8392 spin_lock_irq(&head->lock);
8393 skb = skb_peek(head);
8395 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8397 if (fpl->count < SCM_MAX_FD) {
8398 __skb_unlink(skb, head);
8399 spin_unlock_irq(&head->lock);
8400 fpl->fp[fpl->count] = get_file(file);
8401 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8403 spin_lock_irq(&head->lock);
8404 __skb_queue_head(head, skb);
8409 spin_unlock_irq(&head->lock);
8416 return __io_sqe_files_scm(ctx, 1, index);
8422 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8423 struct io_rsrc_node *node, void *rsrc)
8425 struct io_rsrc_put *prsrc;
8427 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8431 prsrc->tag = *io_get_tag_slot(data, idx);
8433 list_add(&prsrc->list, &node->rsrc_list);
8437 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8438 unsigned int issue_flags, u32 slot_index)
8440 struct io_ring_ctx *ctx = req->ctx;
8441 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8442 bool needs_switch = false;
8443 struct io_fixed_file *file_slot;
8446 io_ring_submit_lock(ctx, needs_lock);
8447 if (file->f_op == &io_uring_fops)
8450 if (!ctx->file_data)
8453 if (slot_index >= ctx->nr_user_files)
8456 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8457 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8459 if (file_slot->file_ptr) {
8460 struct file *old_file;
8462 ret = io_rsrc_node_switch_start(ctx);
8466 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8467 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8468 ctx->rsrc_node, old_file);
8471 file_slot->file_ptr = 0;
8472 needs_switch = true;
8475 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8476 io_fixed_file_set(file_slot, file);
8477 ret = io_sqe_file_register(ctx, file, slot_index);
8479 file_slot->file_ptr = 0;
8486 io_rsrc_node_switch(ctx, ctx->file_data);
8487 io_ring_submit_unlock(ctx, needs_lock);
8493 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8495 unsigned int offset = req->close.file_slot - 1;
8496 struct io_ring_ctx *ctx = req->ctx;
8497 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8498 struct io_fixed_file *file_slot;
8502 io_ring_submit_lock(ctx, needs_lock);
8504 if (unlikely(!ctx->file_data))
8507 if (offset >= ctx->nr_user_files)
8509 ret = io_rsrc_node_switch_start(ctx);
8513 i = array_index_nospec(offset, ctx->nr_user_files);
8514 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8516 if (!file_slot->file_ptr)
8519 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8520 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8524 file_slot->file_ptr = 0;
8525 io_rsrc_node_switch(ctx, ctx->file_data);
8528 io_ring_submit_unlock(ctx, needs_lock);
8532 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8533 struct io_uring_rsrc_update2 *up,
8536 u64 __user *tags = u64_to_user_ptr(up->tags);
8537 __s32 __user *fds = u64_to_user_ptr(up->data);
8538 struct io_rsrc_data *data = ctx->file_data;
8539 struct io_fixed_file *file_slot;
8543 bool needs_switch = false;
8545 if (!ctx->file_data)
8547 if (up->offset + nr_args > ctx->nr_user_files)
8550 for (done = 0; done < nr_args; done++) {
8553 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8554 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8558 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8562 if (fd == IORING_REGISTER_FILES_SKIP)
8565 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8566 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8568 if (file_slot->file_ptr) {
8569 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8570 err = io_queue_rsrc_removal(data, up->offset + done,
8571 ctx->rsrc_node, file);
8574 file_slot->file_ptr = 0;
8575 needs_switch = true;
8584 * Don't allow io_uring instances to be registered. If
8585 * UNIX isn't enabled, then this causes a reference
8586 * cycle and this instance can never get freed. If UNIX
8587 * is enabled we'll handle it just fine, but there's
8588 * still no point in allowing a ring fd as it doesn't
8589 * support regular read/write anyway.
8591 if (file->f_op == &io_uring_fops) {
8596 *io_get_tag_slot(data, up->offset + done) = tag;
8597 io_fixed_file_set(file_slot, file);
8598 err = io_sqe_file_register(ctx, file, i);
8600 file_slot->file_ptr = 0;
8608 io_rsrc_node_switch(ctx, data);
8609 return done ? done : err;
8612 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8613 struct task_struct *task)
8615 struct io_wq_hash *hash;
8616 struct io_wq_data data;
8617 unsigned int concurrency;
8619 mutex_lock(&ctx->uring_lock);
8620 hash = ctx->hash_map;
8622 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8624 mutex_unlock(&ctx->uring_lock);
8625 return ERR_PTR(-ENOMEM);
8627 refcount_set(&hash->refs, 1);
8628 init_waitqueue_head(&hash->wait);
8629 ctx->hash_map = hash;
8631 mutex_unlock(&ctx->uring_lock);
8635 data.free_work = io_wq_free_work;
8636 data.do_work = io_wq_submit_work;
8638 /* Do QD, or 4 * CPUS, whatever is smallest */
8639 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8641 return io_wq_create(concurrency, &data);
8644 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8645 struct io_ring_ctx *ctx)
8647 struct io_uring_task *tctx;
8650 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8651 if (unlikely(!tctx))
8654 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8655 if (unlikely(ret)) {
8660 tctx->io_wq = io_init_wq_offload(ctx, task);
8661 if (IS_ERR(tctx->io_wq)) {
8662 ret = PTR_ERR(tctx->io_wq);
8663 percpu_counter_destroy(&tctx->inflight);
8669 init_waitqueue_head(&tctx->wait);
8670 atomic_set(&tctx->in_idle, 0);
8671 atomic_set(&tctx->inflight_tracked, 0);
8672 task->io_uring = tctx;
8673 spin_lock_init(&tctx->task_lock);
8674 INIT_WQ_LIST(&tctx->task_list);
8675 init_task_work(&tctx->task_work, tctx_task_work);
8679 void __io_uring_free(struct task_struct *tsk)
8681 struct io_uring_task *tctx = tsk->io_uring;
8683 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8684 WARN_ON_ONCE(tctx->io_wq);
8685 WARN_ON_ONCE(tctx->cached_refs);
8687 percpu_counter_destroy(&tctx->inflight);
8689 tsk->io_uring = NULL;
8692 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8693 struct io_uring_params *p)
8697 /* Retain compatibility with failing for an invalid attach attempt */
8698 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8699 IORING_SETUP_ATTACH_WQ) {
8702 f = fdget(p->wq_fd);
8705 if (f.file->f_op != &io_uring_fops) {
8711 if (ctx->flags & IORING_SETUP_SQPOLL) {
8712 struct task_struct *tsk;
8713 struct io_sq_data *sqd;
8716 ret = security_uring_sqpoll();
8720 sqd = io_get_sq_data(p, &attached);
8726 ctx->sq_creds = get_current_cred();
8728 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8729 if (!ctx->sq_thread_idle)
8730 ctx->sq_thread_idle = HZ;
8732 io_sq_thread_park(sqd);
8733 list_add(&ctx->sqd_list, &sqd->ctx_list);
8734 io_sqd_update_thread_idle(sqd);
8735 /* don't attach to a dying SQPOLL thread, would be racy */
8736 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8737 io_sq_thread_unpark(sqd);
8744 if (p->flags & IORING_SETUP_SQ_AFF) {
8745 int cpu = p->sq_thread_cpu;
8748 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8755 sqd->task_pid = current->pid;
8756 sqd->task_tgid = current->tgid;
8757 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8764 ret = io_uring_alloc_task_context(tsk, ctx);
8765 wake_up_new_task(tsk);
8768 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8769 /* Can't have SQ_AFF without SQPOLL */
8776 complete(&ctx->sq_data->exited);
8778 io_sq_thread_finish(ctx);
8782 static inline void __io_unaccount_mem(struct user_struct *user,
8783 unsigned long nr_pages)
8785 atomic_long_sub(nr_pages, &user->locked_vm);
8788 static inline int __io_account_mem(struct user_struct *user,
8789 unsigned long nr_pages)
8791 unsigned long page_limit, cur_pages, new_pages;
8793 /* Don't allow more pages than we can safely lock */
8794 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8797 cur_pages = atomic_long_read(&user->locked_vm);
8798 new_pages = cur_pages + nr_pages;
8799 if (new_pages > page_limit)
8801 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8802 new_pages) != cur_pages);
8807 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8810 __io_unaccount_mem(ctx->user, nr_pages);
8812 if (ctx->mm_account)
8813 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8816 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8821 ret = __io_account_mem(ctx->user, nr_pages);
8826 if (ctx->mm_account)
8827 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8832 static void io_mem_free(void *ptr)
8839 page = virt_to_head_page(ptr);
8840 if (put_page_testzero(page))
8841 free_compound_page(page);
8844 static void *io_mem_alloc(size_t size)
8846 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8847 __GFP_NORETRY | __GFP_ACCOUNT;
8849 return (void *) __get_free_pages(gfp_flags, get_order(size));
8852 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8855 struct io_rings *rings;
8856 size_t off, sq_array_size;
8858 off = struct_size(rings, cqes, cq_entries);
8859 if (off == SIZE_MAX)
8863 off = ALIGN(off, SMP_CACHE_BYTES);
8871 sq_array_size = array_size(sizeof(u32), sq_entries);
8872 if (sq_array_size == SIZE_MAX)
8875 if (check_add_overflow(off, sq_array_size, &off))
8881 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8883 struct io_mapped_ubuf *imu = *slot;
8886 if (imu != ctx->dummy_ubuf) {
8887 for (i = 0; i < imu->nr_bvecs; i++)
8888 unpin_user_page(imu->bvec[i].bv_page);
8889 if (imu->acct_pages)
8890 io_unaccount_mem(ctx, imu->acct_pages);
8896 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8898 io_buffer_unmap(ctx, &prsrc->buf);
8902 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8906 for (i = 0; i < ctx->nr_user_bufs; i++)
8907 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8908 kfree(ctx->user_bufs);
8909 io_rsrc_data_free(ctx->buf_data);
8910 ctx->user_bufs = NULL;
8911 ctx->buf_data = NULL;
8912 ctx->nr_user_bufs = 0;
8915 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8922 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8924 __io_sqe_buffers_unregister(ctx);
8928 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8929 void __user *arg, unsigned index)
8931 struct iovec __user *src;
8933 #ifdef CONFIG_COMPAT
8935 struct compat_iovec __user *ciovs;
8936 struct compat_iovec ciov;
8938 ciovs = (struct compat_iovec __user *) arg;
8939 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8942 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8943 dst->iov_len = ciov.iov_len;
8947 src = (struct iovec __user *) arg;
8948 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8954 * Not super efficient, but this is just a registration time. And we do cache
8955 * the last compound head, so generally we'll only do a full search if we don't
8958 * We check if the given compound head page has already been accounted, to
8959 * avoid double accounting it. This allows us to account the full size of the
8960 * page, not just the constituent pages of a huge page.
8962 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8963 int nr_pages, struct page *hpage)
8967 /* check current page array */
8968 for (i = 0; i < nr_pages; i++) {
8969 if (!PageCompound(pages[i]))
8971 if (compound_head(pages[i]) == hpage)
8975 /* check previously registered pages */
8976 for (i = 0; i < ctx->nr_user_bufs; i++) {
8977 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8979 for (j = 0; j < imu->nr_bvecs; j++) {
8980 if (!PageCompound(imu->bvec[j].bv_page))
8982 if (compound_head(imu->bvec[j].bv_page) == hpage)
8990 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8991 int nr_pages, struct io_mapped_ubuf *imu,
8992 struct page **last_hpage)
8996 imu->acct_pages = 0;
8997 for (i = 0; i < nr_pages; i++) {
8998 if (!PageCompound(pages[i])) {
9003 hpage = compound_head(pages[i]);
9004 if (hpage == *last_hpage)
9006 *last_hpage = hpage;
9007 if (headpage_already_acct(ctx, pages, i, hpage))
9009 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9013 if (!imu->acct_pages)
9016 ret = io_account_mem(ctx, imu->acct_pages);
9018 imu->acct_pages = 0;
9022 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9023 struct io_mapped_ubuf **pimu,
9024 struct page **last_hpage)
9026 struct io_mapped_ubuf *imu = NULL;
9027 struct vm_area_struct **vmas = NULL;
9028 struct page **pages = NULL;
9029 unsigned long off, start, end, ubuf;
9031 int ret, pret, nr_pages, i;
9033 if (!iov->iov_base) {
9034 *pimu = ctx->dummy_ubuf;
9038 ubuf = (unsigned long) iov->iov_base;
9039 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9040 start = ubuf >> PAGE_SHIFT;
9041 nr_pages = end - start;
9046 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9050 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9055 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9060 mmap_read_lock(current->mm);
9061 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9063 if (pret == nr_pages) {
9064 /* don't support file backed memory */
9065 for (i = 0; i < nr_pages; i++) {
9066 struct vm_area_struct *vma = vmas[i];
9068 if (vma_is_shmem(vma))
9071 !is_file_hugepages(vma->vm_file)) {
9077 ret = pret < 0 ? pret : -EFAULT;
9079 mmap_read_unlock(current->mm);
9082 * if we did partial map, or found file backed vmas,
9083 * release any pages we did get
9086 unpin_user_pages(pages, pret);
9090 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9092 unpin_user_pages(pages, pret);
9096 off = ubuf & ~PAGE_MASK;
9097 size = iov->iov_len;
9098 for (i = 0; i < nr_pages; i++) {
9101 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9102 imu->bvec[i].bv_page = pages[i];
9103 imu->bvec[i].bv_len = vec_len;
9104 imu->bvec[i].bv_offset = off;
9108 /* store original address for later verification */
9110 imu->ubuf_end = ubuf + iov->iov_len;
9111 imu->nr_bvecs = nr_pages;
9122 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9124 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9125 return ctx->user_bufs ? 0 : -ENOMEM;
9128 static int io_buffer_validate(struct iovec *iov)
9130 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9133 * Don't impose further limits on the size and buffer
9134 * constraints here, we'll -EINVAL later when IO is
9135 * submitted if they are wrong.
9138 return iov->iov_len ? -EFAULT : 0;
9142 /* arbitrary limit, but we need something */
9143 if (iov->iov_len > SZ_1G)
9146 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9152 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9153 unsigned int nr_args, u64 __user *tags)
9155 struct page *last_hpage = NULL;
9156 struct io_rsrc_data *data;
9162 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9164 ret = io_rsrc_node_switch_start(ctx);
9167 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9170 ret = io_buffers_map_alloc(ctx, nr_args);
9172 io_rsrc_data_free(data);
9176 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9177 ret = io_copy_iov(ctx, &iov, arg, i);
9180 ret = io_buffer_validate(&iov);
9183 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9188 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9194 WARN_ON_ONCE(ctx->buf_data);
9196 ctx->buf_data = data;
9198 __io_sqe_buffers_unregister(ctx);
9200 io_rsrc_node_switch(ctx, NULL);
9204 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9205 struct io_uring_rsrc_update2 *up,
9206 unsigned int nr_args)
9208 u64 __user *tags = u64_to_user_ptr(up->tags);
9209 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9210 struct page *last_hpage = NULL;
9211 bool needs_switch = false;
9217 if (up->offset + nr_args > ctx->nr_user_bufs)
9220 for (done = 0; done < nr_args; done++) {
9221 struct io_mapped_ubuf *imu;
9222 int offset = up->offset + done;
9225 err = io_copy_iov(ctx, &iov, iovs, done);
9228 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9232 err = io_buffer_validate(&iov);
9235 if (!iov.iov_base && tag) {
9239 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9243 i = array_index_nospec(offset, ctx->nr_user_bufs);
9244 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9245 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9246 ctx->rsrc_node, ctx->user_bufs[i]);
9247 if (unlikely(err)) {
9248 io_buffer_unmap(ctx, &imu);
9251 ctx->user_bufs[i] = NULL;
9252 needs_switch = true;
9255 ctx->user_bufs[i] = imu;
9256 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9260 io_rsrc_node_switch(ctx, ctx->buf_data);
9261 return done ? done : err;
9264 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9266 __s32 __user *fds = arg;
9272 if (copy_from_user(&fd, fds, sizeof(*fds)))
9275 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9276 if (IS_ERR(ctx->cq_ev_fd)) {
9277 int ret = PTR_ERR(ctx->cq_ev_fd);
9279 ctx->cq_ev_fd = NULL;
9286 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9288 if (ctx->cq_ev_fd) {
9289 eventfd_ctx_put(ctx->cq_ev_fd);
9290 ctx->cq_ev_fd = NULL;
9297 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9299 struct io_buffer *buf;
9300 unsigned long index;
9302 xa_for_each(&ctx->io_buffers, index, buf)
9303 __io_remove_buffers(ctx, buf, index, -1U);
9306 static void io_req_caches_free(struct io_ring_ctx *ctx)
9308 struct io_submit_state *state = &ctx->submit_state;
9311 mutex_lock(&ctx->uring_lock);
9312 io_flush_cached_locked_reqs(ctx, state);
9314 while (state->free_list.next) {
9315 struct io_wq_work_node *node;
9316 struct io_kiocb *req;
9318 node = wq_stack_extract(&state->free_list);
9319 req = container_of(node, struct io_kiocb, comp_list);
9320 kmem_cache_free(req_cachep, req);
9324 percpu_ref_put_many(&ctx->refs, nr);
9325 mutex_unlock(&ctx->uring_lock);
9328 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9330 if (data && !atomic_dec_and_test(&data->refs))
9331 wait_for_completion(&data->done);
9334 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9336 io_sq_thread_finish(ctx);
9338 if (ctx->mm_account) {
9339 mmdrop(ctx->mm_account);
9340 ctx->mm_account = NULL;
9343 io_rsrc_refs_drop(ctx);
9344 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9345 io_wait_rsrc_data(ctx->buf_data);
9346 io_wait_rsrc_data(ctx->file_data);
9348 mutex_lock(&ctx->uring_lock);
9350 __io_sqe_buffers_unregister(ctx);
9352 __io_sqe_files_unregister(ctx);
9354 __io_cqring_overflow_flush(ctx, true);
9355 mutex_unlock(&ctx->uring_lock);
9356 io_eventfd_unregister(ctx);
9357 io_destroy_buffers(ctx);
9359 put_cred(ctx->sq_creds);
9361 /* there are no registered resources left, nobody uses it */
9363 io_rsrc_node_destroy(ctx->rsrc_node);
9364 if (ctx->rsrc_backup_node)
9365 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9366 flush_delayed_work(&ctx->rsrc_put_work);
9367 flush_delayed_work(&ctx->fallback_work);
9369 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9370 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9372 #if defined(CONFIG_UNIX)
9373 if (ctx->ring_sock) {
9374 ctx->ring_sock->file = NULL; /* so that iput() is called */
9375 sock_release(ctx->ring_sock);
9378 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9380 io_mem_free(ctx->rings);
9381 io_mem_free(ctx->sq_sqes);
9383 percpu_ref_exit(&ctx->refs);
9384 free_uid(ctx->user);
9385 io_req_caches_free(ctx);
9387 io_wq_put_hash(ctx->hash_map);
9388 kfree(ctx->cancel_hash);
9389 kfree(ctx->dummy_ubuf);
9393 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9395 struct io_ring_ctx *ctx = file->private_data;
9398 poll_wait(file, &ctx->cq_wait, wait);
9400 * synchronizes with barrier from wq_has_sleeper call in
9404 if (!io_sqring_full(ctx))
9405 mask |= EPOLLOUT | EPOLLWRNORM;
9408 * Don't flush cqring overflow list here, just do a simple check.
9409 * Otherwise there could possible be ABBA deadlock:
9412 * lock(&ctx->uring_lock);
9414 * lock(&ctx->uring_lock);
9417 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9418 * pushs them to do the flush.
9420 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9421 mask |= EPOLLIN | EPOLLRDNORM;
9426 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9428 const struct cred *creds;
9430 creds = xa_erase(&ctx->personalities, id);
9439 struct io_tctx_exit {
9440 struct callback_head task_work;
9441 struct completion completion;
9442 struct io_ring_ctx *ctx;
9445 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9447 struct io_uring_task *tctx = current->io_uring;
9448 struct io_tctx_exit *work;
9450 work = container_of(cb, struct io_tctx_exit, task_work);
9452 * When @in_idle, we're in cancellation and it's racy to remove the
9453 * node. It'll be removed by the end of cancellation, just ignore it.
9455 if (!atomic_read(&tctx->in_idle))
9456 io_uring_del_tctx_node((unsigned long)work->ctx);
9457 complete(&work->completion);
9460 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9462 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9464 return req->ctx == data;
9467 static __cold void io_ring_exit_work(struct work_struct *work)
9469 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9470 unsigned long timeout = jiffies + HZ * 60 * 5;
9471 unsigned long interval = HZ / 20;
9472 struct io_tctx_exit exit;
9473 struct io_tctx_node *node;
9477 * If we're doing polled IO and end up having requests being
9478 * submitted async (out-of-line), then completions can come in while
9479 * we're waiting for refs to drop. We need to reap these manually,
9480 * as nobody else will be looking for them.
9483 io_uring_try_cancel_requests(ctx, NULL, true);
9485 struct io_sq_data *sqd = ctx->sq_data;
9486 struct task_struct *tsk;
9488 io_sq_thread_park(sqd);
9490 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9491 io_wq_cancel_cb(tsk->io_uring->io_wq,
9492 io_cancel_ctx_cb, ctx, true);
9493 io_sq_thread_unpark(sqd);
9496 io_req_caches_free(ctx);
9498 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9499 /* there is little hope left, don't run it too often */
9502 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9504 init_completion(&exit.completion);
9505 init_task_work(&exit.task_work, io_tctx_exit_cb);
9508 * Some may use context even when all refs and requests have been put,
9509 * and they are free to do so while still holding uring_lock or
9510 * completion_lock, see io_req_task_submit(). Apart from other work,
9511 * this lock/unlock section also waits them to finish.
9513 mutex_lock(&ctx->uring_lock);
9514 while (!list_empty(&ctx->tctx_list)) {
9515 WARN_ON_ONCE(time_after(jiffies, timeout));
9517 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9519 /* don't spin on a single task if cancellation failed */
9520 list_rotate_left(&ctx->tctx_list);
9521 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9522 if (WARN_ON_ONCE(ret))
9525 mutex_unlock(&ctx->uring_lock);
9526 wait_for_completion(&exit.completion);
9527 mutex_lock(&ctx->uring_lock);
9529 mutex_unlock(&ctx->uring_lock);
9530 spin_lock(&ctx->completion_lock);
9531 spin_unlock(&ctx->completion_lock);
9533 io_ring_ctx_free(ctx);
9536 /* Returns true if we found and killed one or more timeouts */
9537 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9538 struct task_struct *tsk, bool cancel_all)
9540 struct io_kiocb *req, *tmp;
9543 spin_lock(&ctx->completion_lock);
9544 spin_lock_irq(&ctx->timeout_lock);
9545 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9546 if (io_match_task(req, tsk, cancel_all)) {
9547 io_kill_timeout(req, -ECANCELED);
9551 spin_unlock_irq(&ctx->timeout_lock);
9553 io_commit_cqring(ctx);
9554 spin_unlock(&ctx->completion_lock);
9556 io_cqring_ev_posted(ctx);
9557 return canceled != 0;
9560 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9562 unsigned long index;
9563 struct creds *creds;
9565 mutex_lock(&ctx->uring_lock);
9566 percpu_ref_kill(&ctx->refs);
9568 __io_cqring_overflow_flush(ctx, true);
9569 xa_for_each(&ctx->personalities, index, creds)
9570 io_unregister_personality(ctx, index);
9571 mutex_unlock(&ctx->uring_lock);
9573 io_kill_timeouts(ctx, NULL, true);
9574 io_poll_remove_all(ctx, NULL, true);
9576 /* if we failed setting up the ctx, we might not have any rings */
9577 io_iopoll_try_reap_events(ctx);
9579 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9581 * Use system_unbound_wq to avoid spawning tons of event kworkers
9582 * if we're exiting a ton of rings at the same time. It just adds
9583 * noise and overhead, there's no discernable change in runtime
9584 * over using system_wq.
9586 queue_work(system_unbound_wq, &ctx->exit_work);
9589 static int io_uring_release(struct inode *inode, struct file *file)
9591 struct io_ring_ctx *ctx = file->private_data;
9593 file->private_data = NULL;
9594 io_ring_ctx_wait_and_kill(ctx);
9598 struct io_task_cancel {
9599 struct task_struct *task;
9603 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9605 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9606 struct io_task_cancel *cancel = data;
9608 return io_match_task_safe(req, cancel->task, cancel->all);
9611 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9612 struct task_struct *task,
9615 struct io_defer_entry *de;
9618 spin_lock(&ctx->completion_lock);
9619 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9620 if (io_match_task_safe(de->req, task, cancel_all)) {
9621 list_cut_position(&list, &ctx->defer_list, &de->list);
9625 spin_unlock(&ctx->completion_lock);
9626 if (list_empty(&list))
9629 while (!list_empty(&list)) {
9630 de = list_first_entry(&list, struct io_defer_entry, list);
9631 list_del_init(&de->list);
9632 io_req_complete_failed(de->req, -ECANCELED);
9638 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9640 struct io_tctx_node *node;
9641 enum io_wq_cancel cret;
9644 mutex_lock(&ctx->uring_lock);
9645 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9646 struct io_uring_task *tctx = node->task->io_uring;
9649 * io_wq will stay alive while we hold uring_lock, because it's
9650 * killed after ctx nodes, which requires to take the lock.
9652 if (!tctx || !tctx->io_wq)
9654 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9655 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9657 mutex_unlock(&ctx->uring_lock);
9662 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9663 struct task_struct *task,
9666 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9667 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9670 enum io_wq_cancel cret;
9674 ret |= io_uring_try_cancel_iowq(ctx);
9675 } else if (tctx && tctx->io_wq) {
9677 * Cancels requests of all rings, not only @ctx, but
9678 * it's fine as the task is in exit/exec.
9680 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9682 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9685 /* SQPOLL thread does its own polling */
9686 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9687 (ctx->sq_data && ctx->sq_data->thread == current)) {
9688 while (!wq_list_empty(&ctx->iopoll_list)) {
9689 io_iopoll_try_reap_events(ctx);
9694 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9695 ret |= io_poll_remove_all(ctx, task, cancel_all);
9696 ret |= io_kill_timeouts(ctx, task, cancel_all);
9698 ret |= io_run_task_work();
9705 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9707 struct io_uring_task *tctx = current->io_uring;
9708 struct io_tctx_node *node;
9711 if (unlikely(!tctx)) {
9712 ret = io_uring_alloc_task_context(current, ctx);
9716 tctx = current->io_uring;
9717 if (ctx->iowq_limits_set) {
9718 unsigned int limits[2] = { ctx->iowq_limits[0],
9719 ctx->iowq_limits[1], };
9721 ret = io_wq_max_workers(tctx->io_wq, limits);
9726 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9727 node = kmalloc(sizeof(*node), GFP_KERNEL);
9731 node->task = current;
9733 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9740 mutex_lock(&ctx->uring_lock);
9741 list_add(&node->ctx_node, &ctx->tctx_list);
9742 mutex_unlock(&ctx->uring_lock);
9749 * Note that this task has used io_uring. We use it for cancelation purposes.
9751 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9753 struct io_uring_task *tctx = current->io_uring;
9755 if (likely(tctx && tctx->last == ctx))
9757 return __io_uring_add_tctx_node(ctx);
9761 * Remove this io_uring_file -> task mapping.
9763 static __cold void io_uring_del_tctx_node(unsigned long index)
9765 struct io_uring_task *tctx = current->io_uring;
9766 struct io_tctx_node *node;
9770 node = xa_erase(&tctx->xa, index);
9774 WARN_ON_ONCE(current != node->task);
9775 WARN_ON_ONCE(list_empty(&node->ctx_node));
9777 mutex_lock(&node->ctx->uring_lock);
9778 list_del(&node->ctx_node);
9779 mutex_unlock(&node->ctx->uring_lock);
9781 if (tctx->last == node->ctx)
9786 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9788 struct io_wq *wq = tctx->io_wq;
9789 struct io_tctx_node *node;
9790 unsigned long index;
9792 xa_for_each(&tctx->xa, index, node) {
9793 io_uring_del_tctx_node(index);
9798 * Must be after io_uring_del_tctx_node() (removes nodes under
9799 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9801 io_wq_put_and_exit(wq);
9806 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9809 return atomic_read(&tctx->inflight_tracked);
9810 return percpu_counter_sum(&tctx->inflight);
9813 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
9815 struct io_uring_task *tctx = task->io_uring;
9816 unsigned int refs = tctx->cached_refs;
9819 tctx->cached_refs = 0;
9820 percpu_counter_sub(&tctx->inflight, refs);
9821 put_task_struct_many(task, refs);
9826 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9827 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9829 static __cold void io_uring_cancel_generic(bool cancel_all,
9830 struct io_sq_data *sqd)
9832 struct io_uring_task *tctx = current->io_uring;
9833 struct io_ring_ctx *ctx;
9837 WARN_ON_ONCE(sqd && sqd->thread != current);
9839 if (!current->io_uring)
9842 io_wq_exit_start(tctx->io_wq);
9844 atomic_inc(&tctx->in_idle);
9846 io_uring_drop_tctx_refs(current);
9847 /* read completions before cancelations */
9848 inflight = tctx_inflight(tctx, !cancel_all);
9853 struct io_tctx_node *node;
9854 unsigned long index;
9856 xa_for_each(&tctx->xa, index, node) {
9857 /* sqpoll task will cancel all its requests */
9858 if (node->ctx->sq_data)
9860 io_uring_try_cancel_requests(node->ctx, current,
9864 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9865 io_uring_try_cancel_requests(ctx, current,
9869 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9870 io_uring_drop_tctx_refs(current);
9872 * If we've seen completions, retry without waiting. This
9873 * avoids a race where a completion comes in before we did
9874 * prepare_to_wait().
9876 if (inflight == tctx_inflight(tctx, !cancel_all))
9878 finish_wait(&tctx->wait, &wait);
9880 atomic_dec(&tctx->in_idle);
9882 io_uring_clean_tctx(tctx);
9884 /* for exec all current's requests should be gone, kill tctx */
9885 __io_uring_free(current);
9889 void __io_uring_cancel(bool cancel_all)
9891 io_uring_cancel_generic(cancel_all, NULL);
9894 static void *io_uring_validate_mmap_request(struct file *file,
9895 loff_t pgoff, size_t sz)
9897 struct io_ring_ctx *ctx = file->private_data;
9898 loff_t offset = pgoff << PAGE_SHIFT;
9903 case IORING_OFF_SQ_RING:
9904 case IORING_OFF_CQ_RING:
9907 case IORING_OFF_SQES:
9911 return ERR_PTR(-EINVAL);
9914 page = virt_to_head_page(ptr);
9915 if (sz > page_size(page))
9916 return ERR_PTR(-EINVAL);
9923 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9925 size_t sz = vma->vm_end - vma->vm_start;
9929 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9931 return PTR_ERR(ptr);
9933 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9934 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9937 #else /* !CONFIG_MMU */
9939 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9941 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9944 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9946 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9949 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9950 unsigned long addr, unsigned long len,
9951 unsigned long pgoff, unsigned long flags)
9955 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9957 return PTR_ERR(ptr);
9959 return (unsigned long) ptr;
9962 #endif /* !CONFIG_MMU */
9964 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9969 if (!io_sqring_full(ctx))
9971 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9973 if (!io_sqring_full(ctx))
9976 } while (!signal_pending(current));
9978 finish_wait(&ctx->sqo_sq_wait, &wait);
9982 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9983 struct __kernel_timespec __user **ts,
9984 const sigset_t __user **sig)
9986 struct io_uring_getevents_arg arg;
9989 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9990 * is just a pointer to the sigset_t.
9992 if (!(flags & IORING_ENTER_EXT_ARG)) {
9993 *sig = (const sigset_t __user *) argp;
9999 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10000 * timespec and sigset_t pointers if good.
10002 if (*argsz != sizeof(arg))
10004 if (copy_from_user(&arg, argp, sizeof(arg)))
10006 *sig = u64_to_user_ptr(arg.sigmask);
10007 *argsz = arg.sigmask_sz;
10008 *ts = u64_to_user_ptr(arg.ts);
10012 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10013 u32, min_complete, u32, flags, const void __user *, argp,
10016 struct io_ring_ctx *ctx;
10021 io_run_task_work();
10023 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10024 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10028 if (unlikely(!f.file))
10032 if (unlikely(f.file->f_op != &io_uring_fops))
10036 ctx = f.file->private_data;
10037 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10041 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10045 * For SQ polling, the thread will do all submissions and completions.
10046 * Just return the requested submit count, and wake the thread if
10047 * we were asked to.
10050 if (ctx->flags & IORING_SETUP_SQPOLL) {
10051 io_cqring_overflow_flush(ctx);
10053 if (unlikely(ctx->sq_data->thread == NULL)) {
10057 if (flags & IORING_ENTER_SQ_WAKEUP)
10058 wake_up(&ctx->sq_data->wait);
10059 if (flags & IORING_ENTER_SQ_WAIT) {
10060 ret = io_sqpoll_wait_sq(ctx);
10064 submitted = to_submit;
10065 } else if (to_submit) {
10066 ret = io_uring_add_tctx_node(ctx);
10069 mutex_lock(&ctx->uring_lock);
10070 submitted = io_submit_sqes(ctx, to_submit);
10071 mutex_unlock(&ctx->uring_lock);
10073 if (submitted != to_submit)
10076 if (flags & IORING_ENTER_GETEVENTS) {
10077 const sigset_t __user *sig;
10078 struct __kernel_timespec __user *ts;
10080 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10084 min_complete = min(min_complete, ctx->cq_entries);
10087 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10088 * space applications don't need to do io completion events
10089 * polling again, they can rely on io_sq_thread to do polling
10090 * work, which can reduce cpu usage and uring_lock contention.
10092 if (ctx->flags & IORING_SETUP_IOPOLL &&
10093 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10094 ret = io_iopoll_check(ctx, min_complete);
10096 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10101 percpu_ref_put(&ctx->refs);
10104 return submitted ? submitted : ret;
10107 #ifdef CONFIG_PROC_FS
10108 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10109 const struct cred *cred)
10111 struct user_namespace *uns = seq_user_ns(m);
10112 struct group_info *gi;
10117 seq_printf(m, "%5d\n", id);
10118 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10119 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10120 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10121 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10122 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10123 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10124 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10125 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10126 seq_puts(m, "\n\tGroups:\t");
10127 gi = cred->group_info;
10128 for (g = 0; g < gi->ngroups; g++) {
10129 seq_put_decimal_ull(m, g ? " " : "",
10130 from_kgid_munged(uns, gi->gid[g]));
10132 seq_puts(m, "\n\tCapEff:\t");
10133 cap = cred->cap_effective;
10134 CAP_FOR_EACH_U32(__capi)
10135 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10140 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10141 struct seq_file *m)
10143 struct io_sq_data *sq = NULL;
10144 struct io_overflow_cqe *ocqe;
10145 struct io_rings *r = ctx->rings;
10146 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10147 unsigned int sq_head = READ_ONCE(r->sq.head);
10148 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10149 unsigned int cq_head = READ_ONCE(r->cq.head);
10150 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10151 unsigned int sq_entries, cq_entries;
10156 * we may get imprecise sqe and cqe info if uring is actively running
10157 * since we get cached_sq_head and cached_cq_tail without uring_lock
10158 * and sq_tail and cq_head are changed by userspace. But it's ok since
10159 * we usually use these info when it is stuck.
10161 seq_printf(m, "SqMask:\t\t0x%x\n", sq_mask);
10162 seq_printf(m, "SqHead:\t%u\n", sq_head);
10163 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10164 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10165 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10166 seq_printf(m, "CqHead:\t%u\n", cq_head);
10167 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10168 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10169 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10170 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10171 for (i = 0; i < sq_entries; i++) {
10172 unsigned int entry = i + sq_head;
10173 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10174 struct io_uring_sqe *sqe;
10176 if (sq_idx > sq_mask)
10178 sqe = &ctx->sq_sqes[sq_idx];
10179 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10180 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10183 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10184 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10185 for (i = 0; i < cq_entries; i++) {
10186 unsigned int entry = i + cq_head;
10187 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10189 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10190 entry & cq_mask, cqe->user_data, cqe->res,
10195 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10196 * since fdinfo case grabs it in the opposite direction of normal use
10197 * cases. If we fail to get the lock, we just don't iterate any
10198 * structures that could be going away outside the io_uring mutex.
10200 has_lock = mutex_trylock(&ctx->uring_lock);
10202 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10208 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10209 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10210 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10211 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10212 struct file *f = io_file_from_index(ctx, i);
10215 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10217 seq_printf(m, "%5u: <none>\n", i);
10219 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10220 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10221 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10222 unsigned int len = buf->ubuf_end - buf->ubuf;
10224 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10226 if (has_lock && !xa_empty(&ctx->personalities)) {
10227 unsigned long index;
10228 const struct cred *cred;
10230 seq_printf(m, "Personalities:\n");
10231 xa_for_each(&ctx->personalities, index, cred)
10232 io_uring_show_cred(m, index, cred);
10235 mutex_unlock(&ctx->uring_lock);
10237 seq_puts(m, "PollList:\n");
10238 spin_lock(&ctx->completion_lock);
10239 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10240 struct hlist_head *list = &ctx->cancel_hash[i];
10241 struct io_kiocb *req;
10243 hlist_for_each_entry(req, list, hash_node)
10244 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10245 req->task->task_works != NULL);
10248 seq_puts(m, "CqOverflowList:\n");
10249 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10250 struct io_uring_cqe *cqe = &ocqe->cqe;
10252 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10253 cqe->user_data, cqe->res, cqe->flags);
10257 spin_unlock(&ctx->completion_lock);
10260 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10262 struct io_ring_ctx *ctx = f->private_data;
10264 if (percpu_ref_tryget(&ctx->refs)) {
10265 __io_uring_show_fdinfo(ctx, m);
10266 percpu_ref_put(&ctx->refs);
10271 static const struct file_operations io_uring_fops = {
10272 .release = io_uring_release,
10273 .mmap = io_uring_mmap,
10275 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10276 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10278 .poll = io_uring_poll,
10279 #ifdef CONFIG_PROC_FS
10280 .show_fdinfo = io_uring_show_fdinfo,
10284 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10285 struct io_uring_params *p)
10287 struct io_rings *rings;
10288 size_t size, sq_array_offset;
10290 /* make sure these are sane, as we already accounted them */
10291 ctx->sq_entries = p->sq_entries;
10292 ctx->cq_entries = p->cq_entries;
10294 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10295 if (size == SIZE_MAX)
10298 rings = io_mem_alloc(size);
10302 ctx->rings = rings;
10303 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10304 rings->sq_ring_mask = p->sq_entries - 1;
10305 rings->cq_ring_mask = p->cq_entries - 1;
10306 rings->sq_ring_entries = p->sq_entries;
10307 rings->cq_ring_entries = p->cq_entries;
10309 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10310 if (size == SIZE_MAX) {
10311 io_mem_free(ctx->rings);
10316 ctx->sq_sqes = io_mem_alloc(size);
10317 if (!ctx->sq_sqes) {
10318 io_mem_free(ctx->rings);
10326 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10330 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10334 ret = io_uring_add_tctx_node(ctx);
10339 fd_install(fd, file);
10344 * Allocate an anonymous fd, this is what constitutes the application
10345 * visible backing of an io_uring instance. The application mmaps this
10346 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10347 * we have to tie this fd to a socket for file garbage collection purposes.
10349 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10352 #if defined(CONFIG_UNIX)
10355 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10358 return ERR_PTR(ret);
10361 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10362 O_RDWR | O_CLOEXEC, NULL);
10363 #if defined(CONFIG_UNIX)
10364 if (IS_ERR(file)) {
10365 sock_release(ctx->ring_sock);
10366 ctx->ring_sock = NULL;
10368 ctx->ring_sock->file = file;
10374 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10375 struct io_uring_params __user *params)
10377 struct io_ring_ctx *ctx;
10383 if (entries > IORING_MAX_ENTRIES) {
10384 if (!(p->flags & IORING_SETUP_CLAMP))
10386 entries = IORING_MAX_ENTRIES;
10390 * Use twice as many entries for the CQ ring. It's possible for the
10391 * application to drive a higher depth than the size of the SQ ring,
10392 * since the sqes are only used at submission time. This allows for
10393 * some flexibility in overcommitting a bit. If the application has
10394 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10395 * of CQ ring entries manually.
10397 p->sq_entries = roundup_pow_of_two(entries);
10398 if (p->flags & IORING_SETUP_CQSIZE) {
10400 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10401 * to a power-of-two, if it isn't already. We do NOT impose
10402 * any cq vs sq ring sizing.
10404 if (!p->cq_entries)
10406 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10407 if (!(p->flags & IORING_SETUP_CLAMP))
10409 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10411 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10412 if (p->cq_entries < p->sq_entries)
10415 p->cq_entries = 2 * p->sq_entries;
10418 ctx = io_ring_ctx_alloc(p);
10421 ctx->compat = in_compat_syscall();
10422 if (!capable(CAP_IPC_LOCK))
10423 ctx->user = get_uid(current_user());
10426 * This is just grabbed for accounting purposes. When a process exits,
10427 * the mm is exited and dropped before the files, hence we need to hang
10428 * on to this mm purely for the purposes of being able to unaccount
10429 * memory (locked/pinned vm). It's not used for anything else.
10431 mmgrab(current->mm);
10432 ctx->mm_account = current->mm;
10434 ret = io_allocate_scq_urings(ctx, p);
10438 ret = io_sq_offload_create(ctx, p);
10441 /* always set a rsrc node */
10442 ret = io_rsrc_node_switch_start(ctx);
10445 io_rsrc_node_switch(ctx, NULL);
10447 memset(&p->sq_off, 0, sizeof(p->sq_off));
10448 p->sq_off.head = offsetof(struct io_rings, sq.head);
10449 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10450 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10451 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10452 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10453 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10454 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10456 memset(&p->cq_off, 0, sizeof(p->cq_off));
10457 p->cq_off.head = offsetof(struct io_rings, cq.head);
10458 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10459 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10460 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10461 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10462 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10463 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10465 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10466 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10467 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10468 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10469 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10470 IORING_FEAT_RSRC_TAGS;
10472 if (copy_to_user(params, p, sizeof(*p))) {
10477 file = io_uring_get_file(ctx);
10478 if (IS_ERR(file)) {
10479 ret = PTR_ERR(file);
10484 * Install ring fd as the very last thing, so we don't risk someone
10485 * having closed it before we finish setup
10487 ret = io_uring_install_fd(ctx, file);
10489 /* fput will clean it up */
10494 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10497 io_ring_ctx_wait_and_kill(ctx);
10502 * Sets up an aio uring context, and returns the fd. Applications asks for a
10503 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10504 * params structure passed in.
10506 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10508 struct io_uring_params p;
10511 if (copy_from_user(&p, params, sizeof(p)))
10513 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10518 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10519 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10520 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10521 IORING_SETUP_R_DISABLED))
10524 return io_uring_create(entries, &p, params);
10527 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10528 struct io_uring_params __user *, params)
10530 return io_uring_setup(entries, params);
10533 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10536 struct io_uring_probe *p;
10540 size = struct_size(p, ops, nr_args);
10541 if (size == SIZE_MAX)
10543 p = kzalloc(size, GFP_KERNEL);
10548 if (copy_from_user(p, arg, size))
10551 if (memchr_inv(p, 0, size))
10554 p->last_op = IORING_OP_LAST - 1;
10555 if (nr_args > IORING_OP_LAST)
10556 nr_args = IORING_OP_LAST;
10558 for (i = 0; i < nr_args; i++) {
10560 if (!io_op_defs[i].not_supported)
10561 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10566 if (copy_to_user(arg, p, size))
10573 static int io_register_personality(struct io_ring_ctx *ctx)
10575 const struct cred *creds;
10579 creds = get_current_cred();
10581 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10582 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10590 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10591 void __user *arg, unsigned int nr_args)
10593 struct io_uring_restriction *res;
10597 /* Restrictions allowed only if rings started disabled */
10598 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10601 /* We allow only a single restrictions registration */
10602 if (ctx->restrictions.registered)
10605 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10608 size = array_size(nr_args, sizeof(*res));
10609 if (size == SIZE_MAX)
10612 res = memdup_user(arg, size);
10614 return PTR_ERR(res);
10618 for (i = 0; i < nr_args; i++) {
10619 switch (res[i].opcode) {
10620 case IORING_RESTRICTION_REGISTER_OP:
10621 if (res[i].register_op >= IORING_REGISTER_LAST) {
10626 __set_bit(res[i].register_op,
10627 ctx->restrictions.register_op);
10629 case IORING_RESTRICTION_SQE_OP:
10630 if (res[i].sqe_op >= IORING_OP_LAST) {
10635 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10637 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10638 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10640 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10641 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10650 /* Reset all restrictions if an error happened */
10652 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10654 ctx->restrictions.registered = true;
10660 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10662 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10665 if (ctx->restrictions.registered)
10666 ctx->restricted = 1;
10668 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10669 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10670 wake_up(&ctx->sq_data->wait);
10674 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10675 struct io_uring_rsrc_update2 *up,
10683 if (check_add_overflow(up->offset, nr_args, &tmp))
10685 err = io_rsrc_node_switch_start(ctx);
10690 case IORING_RSRC_FILE:
10691 return __io_sqe_files_update(ctx, up, nr_args);
10692 case IORING_RSRC_BUFFER:
10693 return __io_sqe_buffers_update(ctx, up, nr_args);
10698 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10701 struct io_uring_rsrc_update2 up;
10705 memset(&up, 0, sizeof(up));
10706 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10708 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10711 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10712 unsigned size, unsigned type)
10714 struct io_uring_rsrc_update2 up;
10716 if (size != sizeof(up))
10718 if (copy_from_user(&up, arg, sizeof(up)))
10720 if (!up.nr || up.resv)
10722 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10725 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10726 unsigned int size, unsigned int type)
10728 struct io_uring_rsrc_register rr;
10730 /* keep it extendible */
10731 if (size != sizeof(rr))
10734 memset(&rr, 0, sizeof(rr));
10735 if (copy_from_user(&rr, arg, size))
10737 if (!rr.nr || rr.resv || rr.resv2)
10741 case IORING_RSRC_FILE:
10742 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10743 rr.nr, u64_to_user_ptr(rr.tags));
10744 case IORING_RSRC_BUFFER:
10745 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10746 rr.nr, u64_to_user_ptr(rr.tags));
10751 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
10752 void __user *arg, unsigned len)
10754 struct io_uring_task *tctx = current->io_uring;
10755 cpumask_var_t new_mask;
10758 if (!tctx || !tctx->io_wq)
10761 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10764 cpumask_clear(new_mask);
10765 if (len > cpumask_size())
10766 len = cpumask_size();
10768 if (copy_from_user(new_mask, arg, len)) {
10769 free_cpumask_var(new_mask);
10773 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10774 free_cpumask_var(new_mask);
10778 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10780 struct io_uring_task *tctx = current->io_uring;
10782 if (!tctx || !tctx->io_wq)
10785 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10788 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10790 __must_hold(&ctx->uring_lock)
10792 struct io_tctx_node *node;
10793 struct io_uring_task *tctx = NULL;
10794 struct io_sq_data *sqd = NULL;
10795 __u32 new_count[2];
10798 if (copy_from_user(new_count, arg, sizeof(new_count)))
10800 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10801 if (new_count[i] > INT_MAX)
10804 if (ctx->flags & IORING_SETUP_SQPOLL) {
10805 sqd = ctx->sq_data;
10808 * Observe the correct sqd->lock -> ctx->uring_lock
10809 * ordering. Fine to drop uring_lock here, we hold
10810 * a ref to the ctx.
10812 refcount_inc(&sqd->refs);
10813 mutex_unlock(&ctx->uring_lock);
10814 mutex_lock(&sqd->lock);
10815 mutex_lock(&ctx->uring_lock);
10817 tctx = sqd->thread->io_uring;
10820 tctx = current->io_uring;
10823 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10825 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10827 ctx->iowq_limits[i] = new_count[i];
10828 ctx->iowq_limits_set = true;
10830 if (tctx && tctx->io_wq) {
10831 ret = io_wq_max_workers(tctx->io_wq, new_count);
10835 memset(new_count, 0, sizeof(new_count));
10839 mutex_unlock(&sqd->lock);
10840 io_put_sq_data(sqd);
10843 if (copy_to_user(arg, new_count, sizeof(new_count)))
10846 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10850 /* now propagate the restriction to all registered users */
10851 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10852 struct io_uring_task *tctx = node->task->io_uring;
10854 if (WARN_ON_ONCE(!tctx->io_wq))
10857 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10858 new_count[i] = ctx->iowq_limits[i];
10859 /* ignore errors, it always returns zero anyway */
10860 (void)io_wq_max_workers(tctx->io_wq, new_count);
10865 mutex_unlock(&sqd->lock);
10866 io_put_sq_data(sqd);
10871 static bool io_register_op_must_quiesce(int op)
10874 case IORING_REGISTER_BUFFERS:
10875 case IORING_UNREGISTER_BUFFERS:
10876 case IORING_REGISTER_FILES:
10877 case IORING_UNREGISTER_FILES:
10878 case IORING_REGISTER_FILES_UPDATE:
10879 case IORING_REGISTER_PROBE:
10880 case IORING_REGISTER_PERSONALITY:
10881 case IORING_UNREGISTER_PERSONALITY:
10882 case IORING_REGISTER_FILES2:
10883 case IORING_REGISTER_FILES_UPDATE2:
10884 case IORING_REGISTER_BUFFERS2:
10885 case IORING_REGISTER_BUFFERS_UPDATE:
10886 case IORING_REGISTER_IOWQ_AFF:
10887 case IORING_UNREGISTER_IOWQ_AFF:
10888 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10895 static __cold int io_ctx_quiesce(struct io_ring_ctx *ctx)
10899 percpu_ref_kill(&ctx->refs);
10902 * Drop uring mutex before waiting for references to exit. If another
10903 * thread is currently inside io_uring_enter() it might need to grab the
10904 * uring_lock to make progress. If we hold it here across the drain
10905 * wait, then we can deadlock. It's safe to drop the mutex here, since
10906 * no new references will come in after we've killed the percpu ref.
10908 mutex_unlock(&ctx->uring_lock);
10910 ret = wait_for_completion_interruptible_timeout(&ctx->ref_comp, HZ);
10912 ret = min(0L, ret);
10916 ret = io_run_task_work_sig();
10917 io_req_caches_free(ctx);
10918 } while (ret >= 0);
10919 mutex_lock(&ctx->uring_lock);
10922 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10926 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10927 void __user *arg, unsigned nr_args)
10928 __releases(ctx->uring_lock)
10929 __acquires(ctx->uring_lock)
10934 * We're inside the ring mutex, if the ref is already dying, then
10935 * someone else killed the ctx or is already going through
10936 * io_uring_register().
10938 if (percpu_ref_is_dying(&ctx->refs))
10941 if (ctx->restricted) {
10942 if (opcode >= IORING_REGISTER_LAST)
10944 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10945 if (!test_bit(opcode, ctx->restrictions.register_op))
10949 if (io_register_op_must_quiesce(opcode)) {
10950 ret = io_ctx_quiesce(ctx);
10956 case IORING_REGISTER_BUFFERS:
10957 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10959 case IORING_UNREGISTER_BUFFERS:
10961 if (arg || nr_args)
10963 ret = io_sqe_buffers_unregister(ctx);
10965 case IORING_REGISTER_FILES:
10966 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10968 case IORING_UNREGISTER_FILES:
10970 if (arg || nr_args)
10972 ret = io_sqe_files_unregister(ctx);
10974 case IORING_REGISTER_FILES_UPDATE:
10975 ret = io_register_files_update(ctx, arg, nr_args);
10977 case IORING_REGISTER_EVENTFD:
10978 case IORING_REGISTER_EVENTFD_ASYNC:
10982 ret = io_eventfd_register(ctx, arg);
10985 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10986 ctx->eventfd_async = 1;
10988 ctx->eventfd_async = 0;
10990 case IORING_UNREGISTER_EVENTFD:
10992 if (arg || nr_args)
10994 ret = io_eventfd_unregister(ctx);
10996 case IORING_REGISTER_PROBE:
10998 if (!arg || nr_args > 256)
11000 ret = io_probe(ctx, arg, nr_args);
11002 case IORING_REGISTER_PERSONALITY:
11004 if (arg || nr_args)
11006 ret = io_register_personality(ctx);
11008 case IORING_UNREGISTER_PERSONALITY:
11012 ret = io_unregister_personality(ctx, nr_args);
11014 case IORING_REGISTER_ENABLE_RINGS:
11016 if (arg || nr_args)
11018 ret = io_register_enable_rings(ctx);
11020 case IORING_REGISTER_RESTRICTIONS:
11021 ret = io_register_restrictions(ctx, arg, nr_args);
11023 case IORING_REGISTER_FILES2:
11024 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11026 case IORING_REGISTER_FILES_UPDATE2:
11027 ret = io_register_rsrc_update(ctx, arg, nr_args,
11030 case IORING_REGISTER_BUFFERS2:
11031 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11033 case IORING_REGISTER_BUFFERS_UPDATE:
11034 ret = io_register_rsrc_update(ctx, arg, nr_args,
11035 IORING_RSRC_BUFFER);
11037 case IORING_REGISTER_IOWQ_AFF:
11039 if (!arg || !nr_args)
11041 ret = io_register_iowq_aff(ctx, arg, nr_args);
11043 case IORING_UNREGISTER_IOWQ_AFF:
11045 if (arg || nr_args)
11047 ret = io_unregister_iowq_aff(ctx);
11049 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11051 if (!arg || nr_args != 2)
11053 ret = io_register_iowq_max_workers(ctx, arg);
11060 if (io_register_op_must_quiesce(opcode)) {
11061 /* bring the ctx back to life */
11062 percpu_ref_reinit(&ctx->refs);
11063 reinit_completion(&ctx->ref_comp);
11068 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11069 void __user *, arg, unsigned int, nr_args)
11071 struct io_ring_ctx *ctx;
11080 if (f.file->f_op != &io_uring_fops)
11083 ctx = f.file->private_data;
11085 io_run_task_work();
11087 mutex_lock(&ctx->uring_lock);
11088 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11089 mutex_unlock(&ctx->uring_lock);
11090 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11091 ctx->cq_ev_fd != NULL, ret);
11097 static int __init io_uring_init(void)
11099 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11100 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11101 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11104 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11105 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11106 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11107 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11108 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11109 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11110 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11111 BUILD_BUG_SQE_ELEM(8, __u64, off);
11112 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11113 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11114 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11115 BUILD_BUG_SQE_ELEM(24, __u32, len);
11116 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11117 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11118 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11119 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11120 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11121 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11122 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11123 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11124 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11125 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11126 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11127 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11128 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11129 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11130 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11131 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11132 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11133 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11134 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11135 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11136 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11138 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11139 sizeof(struct io_uring_rsrc_update));
11140 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11141 sizeof(struct io_uring_rsrc_update2));
11143 /* ->buf_index is u16 */
11144 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11146 /* should fit into one byte */
11147 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11148 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11149 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11151 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11152 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11154 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11158 __initcall(io_uring_init);