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) {
2895 if (!(file->f_mode & FMODE_STREAM)) {
2896 req->flags |= REQ_F_CUR_POS;
2897 kiocb->ki_pos = file->f_pos;
2902 kiocb->ki_flags = iocb_flags(file);
2903 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2908 * If the file is marked O_NONBLOCK, still allow retry for it if it
2909 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2910 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2912 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2913 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
2914 req->flags |= REQ_F_NOWAIT;
2916 if (ctx->flags & IORING_SETUP_IOPOLL) {
2917 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
2920 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2921 kiocb->ki_complete = io_complete_rw_iopoll;
2922 req->iopoll_completed = 0;
2924 if (kiocb->ki_flags & IOCB_HIPRI)
2926 kiocb->ki_complete = io_complete_rw;
2929 ioprio = READ_ONCE(sqe->ioprio);
2931 ret = ioprio_check_cap(ioprio);
2935 kiocb->ki_ioprio = ioprio;
2937 kiocb->ki_ioprio = get_current_ioprio();
2941 req->rw.addr = READ_ONCE(sqe->addr);
2942 req->rw.len = READ_ONCE(sqe->len);
2943 req->buf_index = READ_ONCE(sqe->buf_index);
2947 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2953 case -ERESTARTNOINTR:
2954 case -ERESTARTNOHAND:
2955 case -ERESTART_RESTARTBLOCK:
2957 * We can't just restart the syscall, since previously
2958 * submitted sqes may already be in progress. Just fail this
2964 kiocb->ki_complete(kiocb, ret);
2968 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2969 unsigned int issue_flags)
2971 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2972 struct io_async_rw *io = req->async_data;
2974 /* add previously done IO, if any */
2975 if (req_has_async_data(req) && io->bytes_done > 0) {
2977 ret = io->bytes_done;
2979 ret += io->bytes_done;
2982 if (req->flags & REQ_F_CUR_POS)
2983 req->file->f_pos = kiocb->ki_pos;
2984 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw))
2985 __io_complete_rw(req, ret, 0, issue_flags);
2987 io_rw_done(kiocb, ret);
2989 if (req->flags & REQ_F_REISSUE) {
2990 req->flags &= ~REQ_F_REISSUE;
2991 if (io_resubmit_prep(req)) {
2992 io_req_task_queue_reissue(req);
2994 unsigned int cflags = io_put_rw_kbuf(req);
2995 struct io_ring_ctx *ctx = req->ctx;
2998 if (issue_flags & IO_URING_F_UNLOCKED) {
2999 mutex_lock(&ctx->uring_lock);
3000 __io_req_complete(req, issue_flags, ret, cflags);
3001 mutex_unlock(&ctx->uring_lock);
3003 __io_req_complete(req, issue_flags, ret, cflags);
3009 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3010 struct io_mapped_ubuf *imu)
3012 size_t len = req->rw.len;
3013 u64 buf_end, buf_addr = req->rw.addr;
3016 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3018 /* not inside the mapped region */
3019 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3023 * May not be a start of buffer, set size appropriately
3024 * and advance us to the beginning.
3026 offset = buf_addr - imu->ubuf;
3027 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3031 * Don't use iov_iter_advance() here, as it's really slow for
3032 * using the latter parts of a big fixed buffer - it iterates
3033 * over each segment manually. We can cheat a bit here, because
3036 * 1) it's a BVEC iter, we set it up
3037 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3038 * first and last bvec
3040 * So just find our index, and adjust the iterator afterwards.
3041 * If the offset is within the first bvec (or the whole first
3042 * bvec, just use iov_iter_advance(). This makes it easier
3043 * since we can just skip the first segment, which may not
3044 * be PAGE_SIZE aligned.
3046 const struct bio_vec *bvec = imu->bvec;
3048 if (offset <= bvec->bv_len) {
3049 iov_iter_advance(iter, offset);
3051 unsigned long seg_skip;
3053 /* skip first vec */
3054 offset -= bvec->bv_len;
3055 seg_skip = 1 + (offset >> PAGE_SHIFT);
3057 iter->bvec = bvec + seg_skip;
3058 iter->nr_segs -= seg_skip;
3059 iter->count -= bvec->bv_len + offset;
3060 iter->iov_offset = offset & ~PAGE_MASK;
3067 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3069 struct io_mapped_ubuf *imu = req->imu;
3070 u16 index, buf_index = req->buf_index;
3073 struct io_ring_ctx *ctx = req->ctx;
3075 if (unlikely(buf_index >= ctx->nr_user_bufs))
3077 io_req_set_rsrc_node(req, ctx);
3078 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3079 imu = READ_ONCE(ctx->user_bufs[index]);
3082 return __io_import_fixed(req, rw, iter, imu);
3085 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3088 mutex_unlock(&ctx->uring_lock);
3091 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3094 * "Normal" inline submissions always hold the uring_lock, since we
3095 * grab it from the system call. Same is true for the SQPOLL offload.
3096 * The only exception is when we've detached the request and issue it
3097 * from an async worker thread, grab the lock for that case.
3100 mutex_lock(&ctx->uring_lock);
3103 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3104 int bgid, unsigned int issue_flags)
3106 struct io_buffer *kbuf = req->kbuf;
3107 struct io_buffer *head;
3108 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3110 if (req->flags & REQ_F_BUFFER_SELECTED)
3113 io_ring_submit_lock(req->ctx, needs_lock);
3115 lockdep_assert_held(&req->ctx->uring_lock);
3117 head = xa_load(&req->ctx->io_buffers, bgid);
3119 if (!list_empty(&head->list)) {
3120 kbuf = list_last_entry(&head->list, struct io_buffer,
3122 list_del(&kbuf->list);
3125 xa_erase(&req->ctx->io_buffers, bgid);
3127 if (*len > kbuf->len)
3129 req->flags |= REQ_F_BUFFER_SELECTED;
3132 kbuf = ERR_PTR(-ENOBUFS);
3135 io_ring_submit_unlock(req->ctx, needs_lock);
3139 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3140 unsigned int issue_flags)
3142 struct io_buffer *kbuf;
3145 bgid = req->buf_index;
3146 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3149 return u64_to_user_ptr(kbuf->addr);
3152 #ifdef CONFIG_COMPAT
3153 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3154 unsigned int issue_flags)
3156 struct compat_iovec __user *uiov;
3157 compat_ssize_t clen;
3161 uiov = u64_to_user_ptr(req->rw.addr);
3162 if (!access_ok(uiov, sizeof(*uiov)))
3164 if (__get_user(clen, &uiov->iov_len))
3170 buf = io_rw_buffer_select(req, &len, issue_flags);
3172 return PTR_ERR(buf);
3173 iov[0].iov_base = buf;
3174 iov[0].iov_len = (compat_size_t) len;
3179 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3180 unsigned int issue_flags)
3182 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3186 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3189 len = iov[0].iov_len;
3192 buf = io_rw_buffer_select(req, &len, issue_flags);
3194 return PTR_ERR(buf);
3195 iov[0].iov_base = buf;
3196 iov[0].iov_len = len;
3200 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3201 unsigned int issue_flags)
3203 if (req->flags & REQ_F_BUFFER_SELECTED) {
3204 struct io_buffer *kbuf = req->kbuf;
3206 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3207 iov[0].iov_len = kbuf->len;
3210 if (req->rw.len != 1)
3213 #ifdef CONFIG_COMPAT
3214 if (req->ctx->compat)
3215 return io_compat_import(req, iov, issue_flags);
3218 return __io_iov_buffer_select(req, iov, issue_flags);
3221 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3222 struct io_rw_state *s,
3223 unsigned int issue_flags)
3225 struct iov_iter *iter = &s->iter;
3226 u8 opcode = req->opcode;
3227 struct iovec *iovec;
3232 BUILD_BUG_ON(ERR_PTR(0) != NULL);
3234 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED)
3235 return ERR_PTR(io_import_fixed(req, rw, iter));
3237 /* buffer index only valid with fixed read/write, or buffer select */
3238 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3239 return ERR_PTR(-EINVAL);
3241 buf = u64_to_user_ptr(req->rw.addr);
3242 sqe_len = req->rw.len;
3244 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3245 if (req->flags & REQ_F_BUFFER_SELECT) {
3246 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3248 return ERR_CAST(buf);
3249 req->rw.len = sqe_len;
3252 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3253 return ERR_PTR(ret);
3256 iovec = s->fast_iov;
3257 if (req->flags & REQ_F_BUFFER_SELECT) {
3258 ret = io_iov_buffer_select(req, iovec, issue_flags);
3260 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3261 return ERR_PTR(ret);
3264 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3266 if (unlikely(ret < 0))
3267 return ERR_PTR(ret);
3271 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3272 struct iovec **iovec, struct io_rw_state *s,
3273 unsigned int issue_flags)
3275 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3276 if (unlikely(IS_ERR(*iovec)))
3277 return PTR_ERR(*iovec);
3279 iov_iter_save_state(&s->iter, &s->iter_state);
3283 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3285 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3289 * For files that don't have ->read_iter() and ->write_iter(), handle them
3290 * by looping over ->read() or ->write() manually.
3292 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3294 struct kiocb *kiocb = &req->rw.kiocb;
3295 struct file *file = req->file;
3299 * Don't support polled IO through this interface, and we can't
3300 * support non-blocking either. For the latter, this just causes
3301 * the kiocb to be handled from an async context.
3303 if (kiocb->ki_flags & IOCB_HIPRI)
3305 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3306 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3309 while (iov_iter_count(iter)) {
3313 if (!iov_iter_is_bvec(iter)) {
3314 iovec = iov_iter_iovec(iter);
3316 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3317 iovec.iov_len = req->rw.len;
3321 nr = file->f_op->read(file, iovec.iov_base,
3322 iovec.iov_len, io_kiocb_ppos(kiocb));
3324 nr = file->f_op->write(file, iovec.iov_base,
3325 iovec.iov_len, io_kiocb_ppos(kiocb));
3333 if (!iov_iter_is_bvec(iter)) {
3334 iov_iter_advance(iter, nr);
3340 if (nr != iovec.iov_len)
3347 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3348 const struct iovec *fast_iov, struct iov_iter *iter)
3350 struct io_async_rw *rw = req->async_data;
3352 memcpy(&rw->s.iter, iter, sizeof(*iter));
3353 rw->free_iovec = iovec;
3355 /* can only be fixed buffers, no need to do anything */
3356 if (iov_iter_is_bvec(iter))
3359 unsigned iov_off = 0;
3361 rw->s.iter.iov = rw->s.fast_iov;
3362 if (iter->iov != fast_iov) {
3363 iov_off = iter->iov - fast_iov;
3364 rw->s.iter.iov += iov_off;
3366 if (rw->s.fast_iov != fast_iov)
3367 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3368 sizeof(struct iovec) * iter->nr_segs);
3370 req->flags |= REQ_F_NEED_CLEANUP;
3374 static inline bool io_alloc_async_data(struct io_kiocb *req)
3376 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3377 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3378 if (req->async_data) {
3379 req->flags |= REQ_F_ASYNC_DATA;
3385 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3386 struct io_rw_state *s, bool force)
3388 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3390 if (!req_has_async_data(req)) {
3391 struct io_async_rw *iorw;
3393 if (io_alloc_async_data(req)) {
3398 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3399 iorw = req->async_data;
3400 /* we've copied and mapped the iter, ensure state is saved */
3401 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3406 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3408 struct io_async_rw *iorw = req->async_data;
3412 /* submission path, ->uring_lock should already be taken */
3413 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3414 if (unlikely(ret < 0))
3417 iorw->bytes_done = 0;
3418 iorw->free_iovec = iov;
3420 req->flags |= REQ_F_NEED_CLEANUP;
3424 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3426 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3428 return io_prep_rw(req, sqe);
3432 * This is our waitqueue callback handler, registered through __folio_lock_async()
3433 * when we initially tried to do the IO with the iocb armed our waitqueue.
3434 * This gets called when the page is unlocked, and we generally expect that to
3435 * happen when the page IO is completed and the page is now uptodate. This will
3436 * queue a task_work based retry of the operation, attempting to copy the data
3437 * again. If the latter fails because the page was NOT uptodate, then we will
3438 * do a thread based blocking retry of the operation. That's the unexpected
3441 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3442 int sync, void *arg)
3444 struct wait_page_queue *wpq;
3445 struct io_kiocb *req = wait->private;
3446 struct wait_page_key *key = arg;
3448 wpq = container_of(wait, struct wait_page_queue, wait);
3450 if (!wake_page_match(wpq, key))
3453 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3454 list_del_init(&wait->entry);
3455 io_req_task_queue(req);
3460 * This controls whether a given IO request should be armed for async page
3461 * based retry. If we return false here, the request is handed to the async
3462 * worker threads for retry. If we're doing buffered reads on a regular file,
3463 * we prepare a private wait_page_queue entry and retry the operation. This
3464 * will either succeed because the page is now uptodate and unlocked, or it
3465 * will register a callback when the page is unlocked at IO completion. Through
3466 * that callback, io_uring uses task_work to setup a retry of the operation.
3467 * That retry will attempt the buffered read again. The retry will generally
3468 * succeed, or in rare cases where it fails, we then fall back to using the
3469 * async worker threads for a blocking retry.
3471 static bool io_rw_should_retry(struct io_kiocb *req)
3473 struct io_async_rw *rw = req->async_data;
3474 struct wait_page_queue *wait = &rw->wpq;
3475 struct kiocb *kiocb = &req->rw.kiocb;
3477 /* never retry for NOWAIT, we just complete with -EAGAIN */
3478 if (req->flags & REQ_F_NOWAIT)
3481 /* Only for buffered IO */
3482 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3486 * just use poll if we can, and don't attempt if the fs doesn't
3487 * support callback based unlocks
3489 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3492 wait->wait.func = io_async_buf_func;
3493 wait->wait.private = req;
3494 wait->wait.flags = 0;
3495 INIT_LIST_HEAD(&wait->wait.entry);
3496 kiocb->ki_flags |= IOCB_WAITQ;
3497 kiocb->ki_flags &= ~IOCB_NOWAIT;
3498 kiocb->ki_waitq = wait;
3502 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3504 if (likely(req->file->f_op->read_iter))
3505 return call_read_iter(req->file, &req->rw.kiocb, iter);
3506 else if (req->file->f_op->read)
3507 return loop_rw_iter(READ, req, iter);
3512 static bool need_read_all(struct io_kiocb *req)
3514 return req->flags & REQ_F_ISREG ||
3515 S_ISBLK(file_inode(req->file)->i_mode);
3518 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3520 struct io_rw_state __s, *s = &__s;
3521 struct iovec *iovec;
3522 struct kiocb *kiocb = &req->rw.kiocb;
3523 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3524 struct io_async_rw *rw;
3527 if (!req_has_async_data(req)) {
3528 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3529 if (unlikely(ret < 0))
3532 rw = req->async_data;
3535 * We come here from an earlier attempt, restore our state to
3536 * match in case it doesn't. It's cheap enough that we don't
3537 * need to make this conditional.
3539 iov_iter_restore(&s->iter, &s->iter_state);
3542 req->result = iov_iter_count(&s->iter);
3544 if (force_nonblock) {
3545 /* If the file doesn't support async, just async punt */
3546 if (unlikely(!io_file_supports_nowait(req))) {
3547 ret = io_setup_async_rw(req, iovec, s, true);
3548 return ret ?: -EAGAIN;
3550 kiocb->ki_flags |= IOCB_NOWAIT;
3552 /* Ensure we clear previously set non-block flag */
3553 kiocb->ki_flags &= ~IOCB_NOWAIT;
3556 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), req->result);
3557 if (unlikely(ret)) {
3562 ret = io_iter_do_read(req, &s->iter);
3564 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3565 req->flags &= ~REQ_F_REISSUE;
3566 /* IOPOLL retry should happen for io-wq threads */
3567 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3569 /* no retry on NONBLOCK nor RWF_NOWAIT */
3570 if (req->flags & REQ_F_NOWAIT)
3573 } else if (ret == -EIOCBQUEUED) {
3575 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3576 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3577 /* read all, failed, already did sync or don't want to retry */
3582 * Don't depend on the iter state matching what was consumed, or being
3583 * untouched in case of error. Restore it and we'll advance it
3584 * manually if we need to.
3586 iov_iter_restore(&s->iter, &s->iter_state);
3588 ret2 = io_setup_async_rw(req, iovec, s, true);
3593 rw = req->async_data;
3596 * Now use our persistent iterator and state, if we aren't already.
3597 * We've restored and mapped the iter to match.
3602 * We end up here because of a partial read, either from
3603 * above or inside this loop. Advance the iter by the bytes
3604 * that were consumed.
3606 iov_iter_advance(&s->iter, ret);
3607 if (!iov_iter_count(&s->iter))
3609 rw->bytes_done += ret;
3610 iov_iter_save_state(&s->iter, &s->iter_state);
3612 /* if we can retry, do so with the callbacks armed */
3613 if (!io_rw_should_retry(req)) {
3614 kiocb->ki_flags &= ~IOCB_WAITQ;
3619 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3620 * we get -EIOCBQUEUED, then we'll get a notification when the
3621 * desired page gets unlocked. We can also get a partial read
3622 * here, and if we do, then just retry at the new offset.
3624 ret = io_iter_do_read(req, &s->iter);
3625 if (ret == -EIOCBQUEUED)
3627 /* we got some bytes, but not all. retry. */
3628 kiocb->ki_flags &= ~IOCB_WAITQ;
3629 iov_iter_restore(&s->iter, &s->iter_state);
3632 kiocb_done(kiocb, ret, issue_flags);
3634 /* it's faster to check here then delegate to kfree */
3640 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3642 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3644 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
3645 return io_prep_rw(req, sqe);
3648 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3650 struct io_rw_state __s, *s = &__s;
3651 struct iovec *iovec;
3652 struct kiocb *kiocb = &req->rw.kiocb;
3653 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3656 if (!req_has_async_data(req)) {
3657 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3658 if (unlikely(ret < 0))
3661 struct io_async_rw *rw = req->async_data;
3664 iov_iter_restore(&s->iter, &s->iter_state);
3667 req->result = iov_iter_count(&s->iter);
3669 if (force_nonblock) {
3670 /* If the file doesn't support async, just async punt */
3671 if (unlikely(!io_file_supports_nowait(req)))
3674 /* file path doesn't support NOWAIT for non-direct_IO */
3675 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3676 (req->flags & REQ_F_ISREG))
3679 kiocb->ki_flags |= IOCB_NOWAIT;
3681 /* Ensure we clear previously set non-block flag */
3682 kiocb->ki_flags &= ~IOCB_NOWAIT;
3685 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), req->result);
3690 * Open-code file_start_write here to grab freeze protection,
3691 * which will be released by another thread in
3692 * io_complete_rw(). Fool lockdep by telling it the lock got
3693 * released so that it doesn't complain about the held lock when
3694 * we return to userspace.
3696 if (req->flags & REQ_F_ISREG) {
3697 sb_start_write(file_inode(req->file)->i_sb);
3698 __sb_writers_release(file_inode(req->file)->i_sb,
3701 kiocb->ki_flags |= IOCB_WRITE;
3703 if (likely(req->file->f_op->write_iter))
3704 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3705 else if (req->file->f_op->write)
3706 ret2 = loop_rw_iter(WRITE, req, &s->iter);
3710 if (req->flags & REQ_F_REISSUE) {
3711 req->flags &= ~REQ_F_REISSUE;
3716 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3717 * retry them without IOCB_NOWAIT.
3719 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3721 /* no retry on NONBLOCK nor RWF_NOWAIT */
3722 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3724 if (!force_nonblock || ret2 != -EAGAIN) {
3725 /* IOPOLL retry should happen for io-wq threads */
3726 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3729 kiocb_done(kiocb, ret2, issue_flags);
3732 iov_iter_restore(&s->iter, &s->iter_state);
3733 ret = io_setup_async_rw(req, iovec, s, false);
3734 return ret ?: -EAGAIN;
3737 /* it's reportedly faster than delegating the null check to kfree() */
3743 static int io_renameat_prep(struct io_kiocb *req,
3744 const struct io_uring_sqe *sqe)
3746 struct io_rename *ren = &req->rename;
3747 const char __user *oldf, *newf;
3749 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3751 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3753 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3756 ren->old_dfd = READ_ONCE(sqe->fd);
3757 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3758 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3759 ren->new_dfd = READ_ONCE(sqe->len);
3760 ren->flags = READ_ONCE(sqe->rename_flags);
3762 ren->oldpath = getname(oldf);
3763 if (IS_ERR(ren->oldpath))
3764 return PTR_ERR(ren->oldpath);
3766 ren->newpath = getname(newf);
3767 if (IS_ERR(ren->newpath)) {
3768 putname(ren->oldpath);
3769 return PTR_ERR(ren->newpath);
3772 req->flags |= REQ_F_NEED_CLEANUP;
3776 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3778 struct io_rename *ren = &req->rename;
3781 if (issue_flags & IO_URING_F_NONBLOCK)
3784 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3785 ren->newpath, ren->flags);
3787 req->flags &= ~REQ_F_NEED_CLEANUP;
3790 io_req_complete(req, ret);
3794 static int io_unlinkat_prep(struct io_kiocb *req,
3795 const struct io_uring_sqe *sqe)
3797 struct io_unlink *un = &req->unlink;
3798 const char __user *fname;
3800 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3802 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3805 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3808 un->dfd = READ_ONCE(sqe->fd);
3810 un->flags = READ_ONCE(sqe->unlink_flags);
3811 if (un->flags & ~AT_REMOVEDIR)
3814 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3815 un->filename = getname(fname);
3816 if (IS_ERR(un->filename))
3817 return PTR_ERR(un->filename);
3819 req->flags |= REQ_F_NEED_CLEANUP;
3823 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3825 struct io_unlink *un = &req->unlink;
3828 if (issue_flags & IO_URING_F_NONBLOCK)
3831 if (un->flags & AT_REMOVEDIR)
3832 ret = do_rmdir(un->dfd, un->filename);
3834 ret = do_unlinkat(un->dfd, un->filename);
3836 req->flags &= ~REQ_F_NEED_CLEANUP;
3839 io_req_complete(req, ret);
3843 static int io_mkdirat_prep(struct io_kiocb *req,
3844 const struct io_uring_sqe *sqe)
3846 struct io_mkdir *mkd = &req->mkdir;
3847 const char __user *fname;
3849 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3851 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3854 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3857 mkd->dfd = READ_ONCE(sqe->fd);
3858 mkd->mode = READ_ONCE(sqe->len);
3860 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3861 mkd->filename = getname(fname);
3862 if (IS_ERR(mkd->filename))
3863 return PTR_ERR(mkd->filename);
3865 req->flags |= REQ_F_NEED_CLEANUP;
3869 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
3871 struct io_mkdir *mkd = &req->mkdir;
3874 if (issue_flags & IO_URING_F_NONBLOCK)
3877 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3879 req->flags &= ~REQ_F_NEED_CLEANUP;
3882 io_req_complete(req, ret);
3886 static int io_symlinkat_prep(struct io_kiocb *req,
3887 const struct io_uring_sqe *sqe)
3889 struct io_symlink *sl = &req->symlink;
3890 const char __user *oldpath, *newpath;
3892 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3894 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3897 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3900 sl->new_dfd = READ_ONCE(sqe->fd);
3901 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3902 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3904 sl->oldpath = getname(oldpath);
3905 if (IS_ERR(sl->oldpath))
3906 return PTR_ERR(sl->oldpath);
3908 sl->newpath = getname(newpath);
3909 if (IS_ERR(sl->newpath)) {
3910 putname(sl->oldpath);
3911 return PTR_ERR(sl->newpath);
3914 req->flags |= REQ_F_NEED_CLEANUP;
3918 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
3920 struct io_symlink *sl = &req->symlink;
3923 if (issue_flags & IO_URING_F_NONBLOCK)
3926 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
3928 req->flags &= ~REQ_F_NEED_CLEANUP;
3931 io_req_complete(req, ret);
3935 static int io_linkat_prep(struct io_kiocb *req,
3936 const struct io_uring_sqe *sqe)
3938 struct io_hardlink *lnk = &req->hardlink;
3939 const char __user *oldf, *newf;
3941 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3943 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
3945 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3948 lnk->old_dfd = READ_ONCE(sqe->fd);
3949 lnk->new_dfd = READ_ONCE(sqe->len);
3950 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3951 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3952 lnk->flags = READ_ONCE(sqe->hardlink_flags);
3954 lnk->oldpath = getname(oldf);
3955 if (IS_ERR(lnk->oldpath))
3956 return PTR_ERR(lnk->oldpath);
3958 lnk->newpath = getname(newf);
3959 if (IS_ERR(lnk->newpath)) {
3960 putname(lnk->oldpath);
3961 return PTR_ERR(lnk->newpath);
3964 req->flags |= REQ_F_NEED_CLEANUP;
3968 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
3970 struct io_hardlink *lnk = &req->hardlink;
3973 if (issue_flags & IO_URING_F_NONBLOCK)
3976 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
3977 lnk->newpath, lnk->flags);
3979 req->flags &= ~REQ_F_NEED_CLEANUP;
3982 io_req_complete(req, ret);
3986 static int io_shutdown_prep(struct io_kiocb *req,
3987 const struct io_uring_sqe *sqe)
3989 #if defined(CONFIG_NET)
3990 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3992 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3993 sqe->buf_index || sqe->splice_fd_in))
3996 req->shutdown.how = READ_ONCE(sqe->len);
4003 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4005 #if defined(CONFIG_NET)
4006 struct socket *sock;
4009 if (issue_flags & IO_URING_F_NONBLOCK)
4012 sock = sock_from_file(req->file);
4013 if (unlikely(!sock))
4016 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4019 io_req_complete(req, ret);
4026 static int __io_splice_prep(struct io_kiocb *req,
4027 const struct io_uring_sqe *sqe)
4029 struct io_splice *sp = &req->splice;
4030 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4032 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4036 sp->len = READ_ONCE(sqe->len);
4037 sp->flags = READ_ONCE(sqe->splice_flags);
4039 if (unlikely(sp->flags & ~valid_flags))
4042 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4043 (sp->flags & SPLICE_F_FD_IN_FIXED));
4046 req->flags |= REQ_F_NEED_CLEANUP;
4050 static int io_tee_prep(struct io_kiocb *req,
4051 const struct io_uring_sqe *sqe)
4053 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4055 return __io_splice_prep(req, sqe);
4058 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4060 struct io_splice *sp = &req->splice;
4061 struct file *in = sp->file_in;
4062 struct file *out = sp->file_out;
4063 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4066 if (issue_flags & IO_URING_F_NONBLOCK)
4069 ret = do_tee(in, out, sp->len, flags);
4071 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4073 req->flags &= ~REQ_F_NEED_CLEANUP;
4077 io_req_complete(req, ret);
4081 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4083 struct io_splice *sp = &req->splice;
4085 sp->off_in = READ_ONCE(sqe->splice_off_in);
4086 sp->off_out = READ_ONCE(sqe->off);
4087 return __io_splice_prep(req, sqe);
4090 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4092 struct io_splice *sp = &req->splice;
4093 struct file *in = sp->file_in;
4094 struct file *out = sp->file_out;
4095 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4096 loff_t *poff_in, *poff_out;
4099 if (issue_flags & IO_URING_F_NONBLOCK)
4102 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4103 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4106 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4108 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4110 req->flags &= ~REQ_F_NEED_CLEANUP;
4114 io_req_complete(req, ret);
4119 * IORING_OP_NOP just posts a completion event, nothing else.
4121 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4123 struct io_ring_ctx *ctx = req->ctx;
4125 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4128 __io_req_complete(req, issue_flags, 0, 0);
4132 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4134 struct io_ring_ctx *ctx = req->ctx;
4139 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4141 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4145 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4146 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4149 req->sync.off = READ_ONCE(sqe->off);
4150 req->sync.len = READ_ONCE(sqe->len);
4154 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4156 loff_t end = req->sync.off + req->sync.len;
4159 /* fsync always requires a blocking context */
4160 if (issue_flags & IO_URING_F_NONBLOCK)
4163 ret = vfs_fsync_range(req->file, req->sync.off,
4164 end > 0 ? end : LLONG_MAX,
4165 req->sync.flags & IORING_FSYNC_DATASYNC);
4168 io_req_complete(req, ret);
4172 static int io_fallocate_prep(struct io_kiocb *req,
4173 const struct io_uring_sqe *sqe)
4175 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4178 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4181 req->sync.off = READ_ONCE(sqe->off);
4182 req->sync.len = READ_ONCE(sqe->addr);
4183 req->sync.mode = READ_ONCE(sqe->len);
4187 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4191 /* fallocate always requiring blocking context */
4192 if (issue_flags & IO_URING_F_NONBLOCK)
4194 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4198 io_req_complete(req, ret);
4202 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4204 const char __user *fname;
4207 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4209 if (unlikely(sqe->ioprio || sqe->buf_index))
4211 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4214 /* open.how should be already initialised */
4215 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4216 req->open.how.flags |= O_LARGEFILE;
4218 req->open.dfd = READ_ONCE(sqe->fd);
4219 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4220 req->open.filename = getname(fname);
4221 if (IS_ERR(req->open.filename)) {
4222 ret = PTR_ERR(req->open.filename);
4223 req->open.filename = NULL;
4227 req->open.file_slot = READ_ONCE(sqe->file_index);
4228 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4231 req->open.nofile = rlimit(RLIMIT_NOFILE);
4232 req->flags |= REQ_F_NEED_CLEANUP;
4236 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4238 u64 mode = READ_ONCE(sqe->len);
4239 u64 flags = READ_ONCE(sqe->open_flags);
4241 req->open.how = build_open_how(flags, mode);
4242 return __io_openat_prep(req, sqe);
4245 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4247 struct open_how __user *how;
4251 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4252 len = READ_ONCE(sqe->len);
4253 if (len < OPEN_HOW_SIZE_VER0)
4256 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4261 return __io_openat_prep(req, sqe);
4264 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4266 struct open_flags op;
4268 bool resolve_nonblock, nonblock_set;
4269 bool fixed = !!req->open.file_slot;
4272 ret = build_open_flags(&req->open.how, &op);
4275 nonblock_set = op.open_flag & O_NONBLOCK;
4276 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4277 if (issue_flags & IO_URING_F_NONBLOCK) {
4279 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4280 * it'll always -EAGAIN
4282 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4284 op.lookup_flags |= LOOKUP_CACHED;
4285 op.open_flag |= O_NONBLOCK;
4289 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4294 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4297 * We could hang on to this 'fd' on retrying, but seems like
4298 * marginal gain for something that is now known to be a slower
4299 * path. So just put it, and we'll get a new one when we retry.
4304 ret = PTR_ERR(file);
4305 /* only retry if RESOLVE_CACHED wasn't already set by application */
4306 if (ret == -EAGAIN &&
4307 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4312 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4313 file->f_flags &= ~O_NONBLOCK;
4314 fsnotify_open(file);
4317 fd_install(ret, file);
4319 ret = io_install_fixed_file(req, file, issue_flags,
4320 req->open.file_slot - 1);
4322 putname(req->open.filename);
4323 req->flags &= ~REQ_F_NEED_CLEANUP;
4326 __io_req_complete(req, issue_flags, ret, 0);
4330 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4332 return io_openat2(req, issue_flags);
4335 static int io_remove_buffers_prep(struct io_kiocb *req,
4336 const struct io_uring_sqe *sqe)
4338 struct io_provide_buf *p = &req->pbuf;
4341 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4345 tmp = READ_ONCE(sqe->fd);
4346 if (!tmp || tmp > USHRT_MAX)
4349 memset(p, 0, sizeof(*p));
4351 p->bgid = READ_ONCE(sqe->buf_group);
4355 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4356 int bgid, unsigned nbufs)
4360 /* shouldn't happen */
4364 /* the head kbuf is the list itself */
4365 while (!list_empty(&buf->list)) {
4366 struct io_buffer *nxt;
4368 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4369 list_del(&nxt->list);
4377 xa_erase(&ctx->io_buffers, bgid);
4382 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4384 struct io_provide_buf *p = &req->pbuf;
4385 struct io_ring_ctx *ctx = req->ctx;
4386 struct io_buffer *head;
4388 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4390 io_ring_submit_lock(ctx, needs_lock);
4392 lockdep_assert_held(&ctx->uring_lock);
4395 head = xa_load(&ctx->io_buffers, p->bgid);
4397 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4401 /* complete before unlock, IOPOLL may need the lock */
4402 __io_req_complete(req, issue_flags, ret, 0);
4403 io_ring_submit_unlock(ctx, needs_lock);
4407 static int io_provide_buffers_prep(struct io_kiocb *req,
4408 const struct io_uring_sqe *sqe)
4410 unsigned long size, tmp_check;
4411 struct io_provide_buf *p = &req->pbuf;
4414 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4417 tmp = READ_ONCE(sqe->fd);
4418 if (!tmp || tmp > USHRT_MAX)
4421 p->addr = READ_ONCE(sqe->addr);
4422 p->len = READ_ONCE(sqe->len);
4424 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4427 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4430 size = (unsigned long)p->len * p->nbufs;
4431 if (!access_ok(u64_to_user_ptr(p->addr), size))
4434 p->bgid = READ_ONCE(sqe->buf_group);
4435 tmp = READ_ONCE(sqe->off);
4436 if (tmp > USHRT_MAX)
4442 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4444 struct io_buffer *buf;
4445 u64 addr = pbuf->addr;
4446 int i, bid = pbuf->bid;
4448 for (i = 0; i < pbuf->nbufs; i++) {
4449 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4454 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4459 INIT_LIST_HEAD(&buf->list);
4462 list_add_tail(&buf->list, &(*head)->list);
4466 return i ? i : -ENOMEM;
4469 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4471 struct io_provide_buf *p = &req->pbuf;
4472 struct io_ring_ctx *ctx = req->ctx;
4473 struct io_buffer *head, *list;
4475 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4477 io_ring_submit_lock(ctx, needs_lock);
4479 lockdep_assert_held(&ctx->uring_lock);
4481 list = head = xa_load(&ctx->io_buffers, p->bgid);
4483 ret = io_add_buffers(p, &head);
4484 if (ret >= 0 && !list) {
4485 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4487 __io_remove_buffers(ctx, head, p->bgid, -1U);
4491 /* complete before unlock, IOPOLL may need the lock */
4492 __io_req_complete(req, issue_flags, ret, 0);
4493 io_ring_submit_unlock(ctx, needs_lock);
4497 static int io_epoll_ctl_prep(struct io_kiocb *req,
4498 const struct io_uring_sqe *sqe)
4500 #if defined(CONFIG_EPOLL)
4501 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4503 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4506 req->epoll.epfd = READ_ONCE(sqe->fd);
4507 req->epoll.op = READ_ONCE(sqe->len);
4508 req->epoll.fd = READ_ONCE(sqe->off);
4510 if (ep_op_has_event(req->epoll.op)) {
4511 struct epoll_event __user *ev;
4513 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4514 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4524 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4526 #if defined(CONFIG_EPOLL)
4527 struct io_epoll *ie = &req->epoll;
4529 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4531 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4532 if (force_nonblock && ret == -EAGAIN)
4537 __io_req_complete(req, issue_flags, ret, 0);
4544 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4546 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4547 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4549 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4552 req->madvise.addr = READ_ONCE(sqe->addr);
4553 req->madvise.len = READ_ONCE(sqe->len);
4554 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4561 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4563 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4564 struct io_madvise *ma = &req->madvise;
4567 if (issue_flags & IO_URING_F_NONBLOCK)
4570 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4573 io_req_complete(req, ret);
4580 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4582 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4584 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4587 req->fadvise.offset = READ_ONCE(sqe->off);
4588 req->fadvise.len = READ_ONCE(sqe->len);
4589 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4593 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4595 struct io_fadvise *fa = &req->fadvise;
4598 if (issue_flags & IO_URING_F_NONBLOCK) {
4599 switch (fa->advice) {
4600 case POSIX_FADV_NORMAL:
4601 case POSIX_FADV_RANDOM:
4602 case POSIX_FADV_SEQUENTIAL:
4609 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4612 __io_req_complete(req, issue_flags, ret, 0);
4616 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4618 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4620 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4622 if (req->flags & REQ_F_FIXED_FILE)
4625 req->statx.dfd = READ_ONCE(sqe->fd);
4626 req->statx.mask = READ_ONCE(sqe->len);
4627 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4628 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4629 req->statx.flags = READ_ONCE(sqe->statx_flags);
4634 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4636 struct io_statx *ctx = &req->statx;
4639 if (issue_flags & IO_URING_F_NONBLOCK)
4642 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4647 io_req_complete(req, ret);
4651 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4653 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4655 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4656 sqe->rw_flags || sqe->buf_index)
4658 if (req->flags & REQ_F_FIXED_FILE)
4661 req->close.fd = READ_ONCE(sqe->fd);
4662 req->close.file_slot = READ_ONCE(sqe->file_index);
4663 if (req->close.file_slot && req->close.fd)
4669 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4671 struct files_struct *files = current->files;
4672 struct io_close *close = &req->close;
4673 struct fdtable *fdt;
4674 struct file *file = NULL;
4677 if (req->close.file_slot) {
4678 ret = io_close_fixed(req, issue_flags);
4682 spin_lock(&files->file_lock);
4683 fdt = files_fdtable(files);
4684 if (close->fd >= fdt->max_fds) {
4685 spin_unlock(&files->file_lock);
4688 file = fdt->fd[close->fd];
4689 if (!file || file->f_op == &io_uring_fops) {
4690 spin_unlock(&files->file_lock);
4695 /* if the file has a flush method, be safe and punt to async */
4696 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4697 spin_unlock(&files->file_lock);
4701 ret = __close_fd_get_file(close->fd, &file);
4702 spin_unlock(&files->file_lock);
4709 /* No ->flush() or already async, safely close from here */
4710 ret = filp_close(file, current->files);
4716 __io_req_complete(req, issue_flags, ret, 0);
4720 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4722 struct io_ring_ctx *ctx = req->ctx;
4724 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4726 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4730 req->sync.off = READ_ONCE(sqe->off);
4731 req->sync.len = READ_ONCE(sqe->len);
4732 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4736 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4740 /* sync_file_range always requires a blocking context */
4741 if (issue_flags & IO_URING_F_NONBLOCK)
4744 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4748 io_req_complete(req, ret);
4752 #if defined(CONFIG_NET)
4753 static int io_setup_async_msg(struct io_kiocb *req,
4754 struct io_async_msghdr *kmsg)
4756 struct io_async_msghdr *async_msg = req->async_data;
4760 if (io_alloc_async_data(req)) {
4761 kfree(kmsg->free_iov);
4764 async_msg = req->async_data;
4765 req->flags |= REQ_F_NEED_CLEANUP;
4766 memcpy(async_msg, kmsg, sizeof(*kmsg));
4767 async_msg->msg.msg_name = &async_msg->addr;
4768 /* if were using fast_iov, set it to the new one */
4769 if (!async_msg->free_iov)
4770 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4775 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4776 struct io_async_msghdr *iomsg)
4778 iomsg->msg.msg_name = &iomsg->addr;
4779 iomsg->free_iov = iomsg->fast_iov;
4780 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4781 req->sr_msg.msg_flags, &iomsg->free_iov);
4784 static int io_sendmsg_prep_async(struct io_kiocb *req)
4788 ret = io_sendmsg_copy_hdr(req, req->async_data);
4790 req->flags |= REQ_F_NEED_CLEANUP;
4794 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4796 struct io_sr_msg *sr = &req->sr_msg;
4798 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4801 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4802 sr->len = READ_ONCE(sqe->len);
4803 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4804 if (sr->msg_flags & MSG_DONTWAIT)
4805 req->flags |= REQ_F_NOWAIT;
4807 #ifdef CONFIG_COMPAT
4808 if (req->ctx->compat)
4809 sr->msg_flags |= MSG_CMSG_COMPAT;
4814 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4816 struct io_async_msghdr iomsg, *kmsg;
4817 struct socket *sock;
4822 sock = sock_from_file(req->file);
4823 if (unlikely(!sock))
4826 if (req_has_async_data(req)) {
4827 kmsg = req->async_data;
4829 ret = io_sendmsg_copy_hdr(req, &iomsg);
4835 flags = req->sr_msg.msg_flags;
4836 if (issue_flags & IO_URING_F_NONBLOCK)
4837 flags |= MSG_DONTWAIT;
4838 if (flags & MSG_WAITALL)
4839 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4841 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4842 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4843 return io_setup_async_msg(req, kmsg);
4844 if (ret == -ERESTARTSYS)
4847 /* fast path, check for non-NULL to avoid function call */
4849 kfree(kmsg->free_iov);
4850 req->flags &= ~REQ_F_NEED_CLEANUP;
4853 __io_req_complete(req, issue_flags, ret, 0);
4857 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4859 struct io_sr_msg *sr = &req->sr_msg;
4862 struct socket *sock;
4867 sock = sock_from_file(req->file);
4868 if (unlikely(!sock))
4871 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4875 msg.msg_name = NULL;
4876 msg.msg_control = NULL;
4877 msg.msg_controllen = 0;
4878 msg.msg_namelen = 0;
4880 flags = req->sr_msg.msg_flags;
4881 if (issue_flags & IO_URING_F_NONBLOCK)
4882 flags |= MSG_DONTWAIT;
4883 if (flags & MSG_WAITALL)
4884 min_ret = iov_iter_count(&msg.msg_iter);
4886 msg.msg_flags = flags;
4887 ret = sock_sendmsg(sock, &msg);
4888 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4890 if (ret == -ERESTARTSYS)
4895 __io_req_complete(req, issue_flags, ret, 0);
4899 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4900 struct io_async_msghdr *iomsg)
4902 struct io_sr_msg *sr = &req->sr_msg;
4903 struct iovec __user *uiov;
4907 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4908 &iomsg->uaddr, &uiov, &iov_len);
4912 if (req->flags & REQ_F_BUFFER_SELECT) {
4915 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4917 sr->len = iomsg->fast_iov[0].iov_len;
4918 iomsg->free_iov = NULL;
4920 iomsg->free_iov = iomsg->fast_iov;
4921 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4922 &iomsg->free_iov, &iomsg->msg.msg_iter,
4931 #ifdef CONFIG_COMPAT
4932 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4933 struct io_async_msghdr *iomsg)
4935 struct io_sr_msg *sr = &req->sr_msg;
4936 struct compat_iovec __user *uiov;
4941 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4946 uiov = compat_ptr(ptr);
4947 if (req->flags & REQ_F_BUFFER_SELECT) {
4948 compat_ssize_t clen;
4952 if (!access_ok(uiov, sizeof(*uiov)))
4954 if (__get_user(clen, &uiov->iov_len))
4959 iomsg->free_iov = NULL;
4961 iomsg->free_iov = iomsg->fast_iov;
4962 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4963 UIO_FASTIOV, &iomsg->free_iov,
4964 &iomsg->msg.msg_iter, true);
4973 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4974 struct io_async_msghdr *iomsg)
4976 iomsg->msg.msg_name = &iomsg->addr;
4978 #ifdef CONFIG_COMPAT
4979 if (req->ctx->compat)
4980 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4983 return __io_recvmsg_copy_hdr(req, iomsg);
4986 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4987 unsigned int issue_flags)
4989 struct io_sr_msg *sr = &req->sr_msg;
4991 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
4994 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4996 return io_put_kbuf(req, req->kbuf);
4999 static int io_recvmsg_prep_async(struct io_kiocb *req)
5003 ret = io_recvmsg_copy_hdr(req, req->async_data);
5005 req->flags |= REQ_F_NEED_CLEANUP;
5009 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5011 struct io_sr_msg *sr = &req->sr_msg;
5013 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5016 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5017 sr->len = READ_ONCE(sqe->len);
5018 sr->bgid = READ_ONCE(sqe->buf_group);
5019 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5020 if (sr->msg_flags & MSG_DONTWAIT)
5021 req->flags |= REQ_F_NOWAIT;
5023 #ifdef CONFIG_COMPAT
5024 if (req->ctx->compat)
5025 sr->msg_flags |= MSG_CMSG_COMPAT;
5030 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5032 struct io_async_msghdr iomsg, *kmsg;
5033 struct socket *sock;
5034 struct io_buffer *kbuf;
5037 int ret, cflags = 0;
5038 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5040 sock = sock_from_file(req->file);
5041 if (unlikely(!sock))
5044 if (req_has_async_data(req)) {
5045 kmsg = req->async_data;
5047 ret = io_recvmsg_copy_hdr(req, &iomsg);
5053 if (req->flags & REQ_F_BUFFER_SELECT) {
5054 kbuf = io_recv_buffer_select(req, issue_flags);
5056 return PTR_ERR(kbuf);
5057 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5058 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5059 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5060 1, req->sr_msg.len);
5063 flags = req->sr_msg.msg_flags;
5065 flags |= MSG_DONTWAIT;
5066 if (flags & MSG_WAITALL)
5067 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5069 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5070 kmsg->uaddr, flags);
5071 if (force_nonblock && ret == -EAGAIN)
5072 return io_setup_async_msg(req, kmsg);
5073 if (ret == -ERESTARTSYS)
5076 if (req->flags & REQ_F_BUFFER_SELECTED)
5077 cflags = io_put_recv_kbuf(req);
5078 /* fast path, check for non-NULL to avoid function call */
5080 kfree(kmsg->free_iov);
5081 req->flags &= ~REQ_F_NEED_CLEANUP;
5082 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5084 __io_req_complete(req, issue_flags, ret, cflags);
5088 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5090 struct io_buffer *kbuf;
5091 struct io_sr_msg *sr = &req->sr_msg;
5093 void __user *buf = sr->buf;
5094 struct socket *sock;
5098 int ret, cflags = 0;
5099 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5101 sock = sock_from_file(req->file);
5102 if (unlikely(!sock))
5105 if (req->flags & REQ_F_BUFFER_SELECT) {
5106 kbuf = io_recv_buffer_select(req, issue_flags);
5108 return PTR_ERR(kbuf);
5109 buf = u64_to_user_ptr(kbuf->addr);
5112 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5116 msg.msg_name = NULL;
5117 msg.msg_control = NULL;
5118 msg.msg_controllen = 0;
5119 msg.msg_namelen = 0;
5120 msg.msg_iocb = NULL;
5123 flags = req->sr_msg.msg_flags;
5125 flags |= MSG_DONTWAIT;
5126 if (flags & MSG_WAITALL)
5127 min_ret = iov_iter_count(&msg.msg_iter);
5129 ret = sock_recvmsg(sock, &msg, flags);
5130 if (force_nonblock && ret == -EAGAIN)
5132 if (ret == -ERESTARTSYS)
5135 if (req->flags & REQ_F_BUFFER_SELECTED)
5136 cflags = io_put_recv_kbuf(req);
5137 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5139 __io_req_complete(req, issue_flags, ret, cflags);
5143 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5145 struct io_accept *accept = &req->accept;
5147 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5149 if (sqe->ioprio || sqe->len || sqe->buf_index)
5152 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5153 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5154 accept->flags = READ_ONCE(sqe->accept_flags);
5155 accept->nofile = rlimit(RLIMIT_NOFILE);
5157 accept->file_slot = READ_ONCE(sqe->file_index);
5158 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
5159 (accept->flags & SOCK_CLOEXEC)))
5161 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5163 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5164 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5168 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5170 struct io_accept *accept = &req->accept;
5171 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5172 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5173 bool fixed = !!accept->file_slot;
5177 if (req->file->f_flags & O_NONBLOCK)
5178 req->flags |= REQ_F_NOWAIT;
5181 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5182 if (unlikely(fd < 0))
5185 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5190 ret = PTR_ERR(file);
5191 if (ret == -EAGAIN && force_nonblock)
5193 if (ret == -ERESTARTSYS)
5196 } else if (!fixed) {
5197 fd_install(fd, file);
5200 ret = io_install_fixed_file(req, file, issue_flags,
5201 accept->file_slot - 1);
5203 __io_req_complete(req, issue_flags, ret, 0);
5207 static int io_connect_prep_async(struct io_kiocb *req)
5209 struct io_async_connect *io = req->async_data;
5210 struct io_connect *conn = &req->connect;
5212 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5215 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5217 struct io_connect *conn = &req->connect;
5219 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5221 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5225 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5226 conn->addr_len = READ_ONCE(sqe->addr2);
5230 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5232 struct io_async_connect __io, *io;
5233 unsigned file_flags;
5235 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5237 if (req_has_async_data(req)) {
5238 io = req->async_data;
5240 ret = move_addr_to_kernel(req->connect.addr,
5241 req->connect.addr_len,
5248 file_flags = force_nonblock ? O_NONBLOCK : 0;
5250 ret = __sys_connect_file(req->file, &io->address,
5251 req->connect.addr_len, file_flags);
5252 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5253 if (req_has_async_data(req))
5255 if (io_alloc_async_data(req)) {
5259 memcpy(req->async_data, &__io, sizeof(__io));
5262 if (ret == -ERESTARTSYS)
5267 __io_req_complete(req, issue_flags, ret, 0);
5270 #else /* !CONFIG_NET */
5271 #define IO_NETOP_FN(op) \
5272 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5274 return -EOPNOTSUPP; \
5277 #define IO_NETOP_PREP(op) \
5279 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5281 return -EOPNOTSUPP; \
5284 #define IO_NETOP_PREP_ASYNC(op) \
5286 static int io_##op##_prep_async(struct io_kiocb *req) \
5288 return -EOPNOTSUPP; \
5291 IO_NETOP_PREP_ASYNC(sendmsg);
5292 IO_NETOP_PREP_ASYNC(recvmsg);
5293 IO_NETOP_PREP_ASYNC(connect);
5294 IO_NETOP_PREP(accept);
5297 #endif /* CONFIG_NET */
5299 struct io_poll_table {
5300 struct poll_table_struct pt;
5301 struct io_kiocb *req;
5306 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5307 __poll_t mask, io_req_tw_func_t func)
5309 /* for instances that support it check for an event match first: */
5310 if (mask && !(mask & poll->events))
5313 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5315 list_del_init(&poll->wait.entry);
5318 req->io_task_work.func = func;
5321 * If this fails, then the task is exiting. When a task exits, the
5322 * work gets canceled, so just cancel this request as well instead
5323 * of executing it. We can't safely execute it anyway, as we may not
5324 * have the needed state needed for it anyway.
5326 io_req_task_work_add(req);
5330 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5331 __acquires(&req->ctx->completion_lock)
5333 struct io_ring_ctx *ctx = req->ctx;
5335 /* req->task == current here, checking PF_EXITING is safe */
5336 if (unlikely(req->task->flags & PF_EXITING))
5337 WRITE_ONCE(poll->canceled, true);
5339 if (!req->result && !READ_ONCE(poll->canceled)) {
5340 struct poll_table_struct pt = { ._key = poll->events };
5342 req->result = vfs_poll(req->file, &pt) & poll->events;
5345 spin_lock(&ctx->completion_lock);
5346 if (!req->result && !READ_ONCE(poll->canceled)) {
5347 add_wait_queue(poll->head, &poll->wait);
5354 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5356 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5357 if (req->opcode == IORING_OP_POLL_ADD)
5358 return req->async_data;
5359 return req->apoll->double_poll;
5362 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5364 if (req->opcode == IORING_OP_POLL_ADD)
5366 return &req->apoll->poll;
5369 static void io_poll_remove_double(struct io_kiocb *req)
5370 __must_hold(&req->ctx->completion_lock)
5372 struct io_poll_iocb *poll = io_poll_get_double(req);
5374 lockdep_assert_held(&req->ctx->completion_lock);
5376 if (poll && poll->head) {
5377 struct wait_queue_head *head = poll->head;
5379 spin_lock_irq(&head->lock);
5380 list_del_init(&poll->wait.entry);
5381 if (poll->wait.private)
5384 spin_unlock_irq(&head->lock);
5388 static bool __io_poll_complete(struct io_kiocb *req, __poll_t mask)
5389 __must_hold(&req->ctx->completion_lock)
5391 struct io_ring_ctx *ctx = req->ctx;
5392 unsigned flags = IORING_CQE_F_MORE;
5395 if (READ_ONCE(req->poll.canceled)) {
5397 req->poll.events |= EPOLLONESHOT;
5399 error = mangle_poll(mask);
5401 if (req->poll.events & EPOLLONESHOT)
5403 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5404 req->poll.events |= EPOLLONESHOT;
5407 if (flags & IORING_CQE_F_MORE)
5410 return !(flags & IORING_CQE_F_MORE);
5413 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5415 struct io_ring_ctx *ctx = req->ctx;
5416 struct io_kiocb *nxt;
5418 if (io_poll_rewait(req, &req->poll)) {
5419 spin_unlock(&ctx->completion_lock);
5423 if (req->poll.done) {
5424 spin_unlock(&ctx->completion_lock);
5427 done = __io_poll_complete(req, req->result);
5429 io_poll_remove_double(req);
5430 hash_del(&req->hash_node);
5431 req->poll.done = true;
5434 add_wait_queue(req->poll.head, &req->poll.wait);
5436 io_commit_cqring(ctx);
5437 spin_unlock(&ctx->completion_lock);
5438 io_cqring_ev_posted(ctx);
5441 nxt = io_put_req_find_next(req);
5443 io_req_task_submit(nxt, locked);
5448 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5449 int sync, void *key)
5451 struct io_kiocb *req = wait->private;
5452 struct io_poll_iocb *poll = io_poll_get_single(req);
5453 __poll_t mask = key_to_poll(key);
5454 unsigned long flags;
5456 /* for instances that support it check for an event match first: */
5457 if (mask && !(mask & poll->events))
5459 if (!(poll->events & EPOLLONESHOT))
5460 return poll->wait.func(&poll->wait, mode, sync, key);
5462 list_del_init(&wait->entry);
5467 spin_lock_irqsave(&poll->head->lock, flags);
5468 done = list_empty(&poll->wait.entry);
5470 list_del_init(&poll->wait.entry);
5471 /* make sure double remove sees this as being gone */
5472 wait->private = NULL;
5473 spin_unlock_irqrestore(&poll->head->lock, flags);
5475 /* use wait func handler, so it matches the rq type */
5476 poll->wait.func(&poll->wait, mode, sync, key);
5483 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5484 wait_queue_func_t wake_func)
5488 poll->canceled = false;
5489 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5490 /* mask in events that we always want/need */
5491 poll->events = events | IO_POLL_UNMASK;
5492 INIT_LIST_HEAD(&poll->wait.entry);
5493 init_waitqueue_func_entry(&poll->wait, wake_func);
5496 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5497 struct wait_queue_head *head,
5498 struct io_poll_iocb **poll_ptr)
5500 struct io_kiocb *req = pt->req;
5503 * The file being polled uses multiple waitqueues for poll handling
5504 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5507 if (unlikely(pt->nr_entries)) {
5508 struct io_poll_iocb *poll_one = poll;
5510 /* double add on the same waitqueue head, ignore */
5511 if (poll_one->head == head)
5513 /* already have a 2nd entry, fail a third attempt */
5515 if ((*poll_ptr)->head == head)
5517 pt->error = -EINVAL;
5521 * Can't handle multishot for double wait for now, turn it
5522 * into one-shot mode.
5524 if (!(poll_one->events & EPOLLONESHOT))
5525 poll_one->events |= EPOLLONESHOT;
5526 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5528 pt->error = -ENOMEM;
5531 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5533 poll->wait.private = req;
5536 if (req->opcode == IORING_OP_POLL_ADD)
5537 req->flags |= REQ_F_ASYNC_DATA;
5543 if (poll->events & EPOLLEXCLUSIVE)
5544 add_wait_queue_exclusive(head, &poll->wait);
5546 add_wait_queue(head, &poll->wait);
5549 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5550 struct poll_table_struct *p)
5552 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5553 struct async_poll *apoll = pt->req->apoll;
5555 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5558 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5560 struct async_poll *apoll = req->apoll;
5561 struct io_ring_ctx *ctx = req->ctx;
5563 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5565 if (io_poll_rewait(req, &apoll->poll)) {
5566 spin_unlock(&ctx->completion_lock);
5570 hash_del(&req->hash_node);
5571 io_poll_remove_double(req);
5572 apoll->poll.done = true;
5573 spin_unlock(&ctx->completion_lock);
5575 if (!READ_ONCE(apoll->poll.canceled))
5576 io_req_task_submit(req, locked);
5578 io_req_complete_failed(req, -ECANCELED);
5581 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5584 struct io_kiocb *req = wait->private;
5585 struct io_poll_iocb *poll = &req->apoll->poll;
5587 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5590 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5593 static void io_poll_req_insert(struct io_kiocb *req)
5595 struct io_ring_ctx *ctx = req->ctx;
5596 struct hlist_head *list;
5598 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5599 hlist_add_head(&req->hash_node, list);
5602 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5603 struct io_poll_iocb *poll,
5604 struct io_poll_table *ipt, __poll_t mask,
5605 wait_queue_func_t wake_func)
5606 __acquires(&ctx->completion_lock)
5608 struct io_ring_ctx *ctx = req->ctx;
5609 bool cancel = false;
5611 INIT_HLIST_NODE(&req->hash_node);
5612 io_init_poll_iocb(poll, mask, wake_func);
5613 poll->file = req->file;
5614 poll->wait.private = req;
5616 ipt->pt._key = mask;
5619 ipt->nr_entries = 0;
5621 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5622 if (unlikely(!ipt->nr_entries) && !ipt->error)
5623 ipt->error = -EINVAL;
5625 spin_lock(&ctx->completion_lock);
5626 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5627 io_poll_remove_double(req);
5628 if (likely(poll->head)) {
5629 spin_lock_irq(&poll->head->lock);
5630 if (unlikely(list_empty(&poll->wait.entry))) {
5636 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5637 list_del_init(&poll->wait.entry);
5639 WRITE_ONCE(poll->canceled, true);
5640 else if (!poll->done) /* actually waiting for an event */
5641 io_poll_req_insert(req);
5642 spin_unlock_irq(&poll->head->lock);
5654 static int io_arm_poll_handler(struct io_kiocb *req)
5656 const struct io_op_def *def = &io_op_defs[req->opcode];
5657 struct io_ring_ctx *ctx = req->ctx;
5658 struct async_poll *apoll;
5659 struct io_poll_table ipt;
5660 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5662 if (!def->pollin && !def->pollout)
5663 return IO_APOLL_ABORTED;
5664 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
5665 return IO_APOLL_ABORTED;
5668 mask |= POLLIN | POLLRDNORM;
5670 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5671 if ((req->opcode == IORING_OP_RECVMSG) &&
5672 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5675 mask |= POLLOUT | POLLWRNORM;
5678 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5679 if (unlikely(!apoll))
5680 return IO_APOLL_ABORTED;
5681 apoll->double_poll = NULL;
5683 req->flags |= REQ_F_POLLED;
5684 ipt.pt._qproc = io_async_queue_proc;
5685 io_req_set_refcount(req);
5687 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5689 spin_unlock(&ctx->completion_lock);
5690 if (ret || ipt.error)
5691 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5693 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5694 mask, apoll->poll.events);
5698 static bool __io_poll_remove_one(struct io_kiocb *req,
5699 struct io_poll_iocb *poll, bool do_cancel)
5700 __must_hold(&req->ctx->completion_lock)
5702 bool do_complete = false;
5706 spin_lock_irq(&poll->head->lock);
5708 WRITE_ONCE(poll->canceled, true);
5709 if (!list_empty(&poll->wait.entry)) {
5710 list_del_init(&poll->wait.entry);
5713 spin_unlock_irq(&poll->head->lock);
5714 hash_del(&req->hash_node);
5718 static bool io_poll_remove_one(struct io_kiocb *req)
5719 __must_hold(&req->ctx->completion_lock)
5723 io_poll_remove_double(req);
5724 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5727 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5728 io_commit_cqring(req->ctx);
5730 io_put_req_deferred(req);
5736 * Returns true if we found and killed one or more poll requests
5738 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5739 struct task_struct *tsk, bool cancel_all)
5741 struct hlist_node *tmp;
5742 struct io_kiocb *req;
5745 spin_lock(&ctx->completion_lock);
5746 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5747 struct hlist_head *list;
5749 list = &ctx->cancel_hash[i];
5750 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5751 if (io_match_task_safe(req, tsk, cancel_all))
5752 posted += io_poll_remove_one(req);
5755 spin_unlock(&ctx->completion_lock);
5758 io_cqring_ev_posted(ctx);
5763 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5765 __must_hold(&ctx->completion_lock)
5767 struct hlist_head *list;
5768 struct io_kiocb *req;
5770 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5771 hlist_for_each_entry(req, list, hash_node) {
5772 if (sqe_addr != req->user_data)
5774 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5781 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5783 __must_hold(&ctx->completion_lock)
5785 struct io_kiocb *req;
5787 req = io_poll_find(ctx, sqe_addr, poll_only);
5790 if (io_poll_remove_one(req))
5796 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5801 events = READ_ONCE(sqe->poll32_events);
5803 events = swahw32(events);
5805 if (!(flags & IORING_POLL_ADD_MULTI))
5806 events |= EPOLLONESHOT;
5807 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5810 static int io_poll_update_prep(struct io_kiocb *req,
5811 const struct io_uring_sqe *sqe)
5813 struct io_poll_update *upd = &req->poll_update;
5816 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5818 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5820 flags = READ_ONCE(sqe->len);
5821 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5822 IORING_POLL_ADD_MULTI))
5824 /* meaningless without update */
5825 if (flags == IORING_POLL_ADD_MULTI)
5828 upd->old_user_data = READ_ONCE(sqe->addr);
5829 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5830 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5832 upd->new_user_data = READ_ONCE(sqe->off);
5833 if (!upd->update_user_data && upd->new_user_data)
5835 if (upd->update_events)
5836 upd->events = io_poll_parse_events(sqe, flags);
5837 else if (sqe->poll32_events)
5843 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5846 struct io_kiocb *req = wait->private;
5847 struct io_poll_iocb *poll = &req->poll;
5849 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5852 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5853 struct poll_table_struct *p)
5855 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5857 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5860 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5862 struct io_poll_iocb *poll = &req->poll;
5865 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5867 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5869 flags = READ_ONCE(sqe->len);
5870 if (flags & ~IORING_POLL_ADD_MULTI)
5873 io_req_set_refcount(req);
5874 poll->events = io_poll_parse_events(sqe, flags);
5878 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5880 struct io_poll_iocb *poll = &req->poll;
5881 struct io_ring_ctx *ctx = req->ctx;
5882 struct io_poll_table ipt;
5886 ipt.pt._qproc = io_poll_queue_proc;
5888 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5891 if (mask) { /* no async, we'd stolen it */
5893 done = __io_poll_complete(req, mask);
5894 io_commit_cqring(req->ctx);
5896 spin_unlock(&ctx->completion_lock);
5899 io_cqring_ev_posted(ctx);
5906 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5908 struct io_ring_ctx *ctx = req->ctx;
5909 struct io_kiocb *preq;
5913 spin_lock(&ctx->completion_lock);
5914 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5920 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5922 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5927 * Don't allow racy completion with singleshot, as we cannot safely
5928 * update those. For multishot, if we're racing with completion, just
5929 * let completion re-add it.
5931 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5932 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5936 /* we now have a detached poll request. reissue. */
5940 spin_unlock(&ctx->completion_lock);
5942 io_req_complete(req, ret);
5945 /* only mask one event flags, keep behavior flags */
5946 if (req->poll_update.update_events) {
5947 preq->poll.events &= ~0xffff;
5948 preq->poll.events |= req->poll_update.events & 0xffff;
5949 preq->poll.events |= IO_POLL_UNMASK;
5951 if (req->poll_update.update_user_data)
5952 preq->user_data = req->poll_update.new_user_data;
5953 spin_unlock(&ctx->completion_lock);
5955 /* complete update request, we're done with it */
5956 io_req_complete(req, ret);
5959 ret = io_poll_add(preq, issue_flags);
5962 io_req_complete(preq, ret);
5968 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5970 struct io_timeout_data *data = req->async_data;
5972 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
5974 io_req_complete_post(req, -ETIME, 0);
5977 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5979 struct io_timeout_data *data = container_of(timer,
5980 struct io_timeout_data, timer);
5981 struct io_kiocb *req = data->req;
5982 struct io_ring_ctx *ctx = req->ctx;
5983 unsigned long flags;
5985 spin_lock_irqsave(&ctx->timeout_lock, flags);
5986 list_del_init(&req->timeout.list);
5987 atomic_set(&req->ctx->cq_timeouts,
5988 atomic_read(&req->ctx->cq_timeouts) + 1);
5989 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5991 req->io_task_work.func = io_req_task_timeout;
5992 io_req_task_work_add(req);
5993 return HRTIMER_NORESTART;
5996 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5998 __must_hold(&ctx->timeout_lock)
6000 struct io_timeout_data *io;
6001 struct io_kiocb *req;
6004 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6005 found = user_data == req->user_data;
6010 return ERR_PTR(-ENOENT);
6012 io = req->async_data;
6013 if (hrtimer_try_to_cancel(&io->timer) == -1)
6014 return ERR_PTR(-EALREADY);
6015 list_del_init(&req->timeout.list);
6019 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6020 __must_hold(&ctx->completion_lock)
6021 __must_hold(&ctx->timeout_lock)
6023 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6026 return PTR_ERR(req);
6029 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
6030 io_put_req_deferred(req);
6034 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6036 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6037 case IORING_TIMEOUT_BOOTTIME:
6038 return CLOCK_BOOTTIME;
6039 case IORING_TIMEOUT_REALTIME:
6040 return CLOCK_REALTIME;
6042 /* can't happen, vetted at prep time */
6046 return CLOCK_MONOTONIC;
6050 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6051 struct timespec64 *ts, enum hrtimer_mode mode)
6052 __must_hold(&ctx->timeout_lock)
6054 struct io_timeout_data *io;
6055 struct io_kiocb *req;
6058 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6059 found = user_data == req->user_data;
6066 io = req->async_data;
6067 if (hrtimer_try_to_cancel(&io->timer) == -1)
6069 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6070 io->timer.function = io_link_timeout_fn;
6071 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6075 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6076 struct timespec64 *ts, enum hrtimer_mode mode)
6077 __must_hold(&ctx->timeout_lock)
6079 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6080 struct io_timeout_data *data;
6083 return PTR_ERR(req);
6085 req->timeout.off = 0; /* noseq */
6086 data = req->async_data;
6087 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6088 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6089 data->timer.function = io_timeout_fn;
6090 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6094 static int io_timeout_remove_prep(struct io_kiocb *req,
6095 const struct io_uring_sqe *sqe)
6097 struct io_timeout_rem *tr = &req->timeout_rem;
6099 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6101 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6103 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6106 tr->ltimeout = false;
6107 tr->addr = READ_ONCE(sqe->addr);
6108 tr->flags = READ_ONCE(sqe->timeout_flags);
6109 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6110 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6112 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6113 tr->ltimeout = true;
6114 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6116 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6118 } else if (tr->flags) {
6119 /* timeout removal doesn't support flags */
6126 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6128 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6133 * Remove or update an existing timeout command
6135 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6137 struct io_timeout_rem *tr = &req->timeout_rem;
6138 struct io_ring_ctx *ctx = req->ctx;
6141 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6142 spin_lock(&ctx->completion_lock);
6143 spin_lock_irq(&ctx->timeout_lock);
6144 ret = io_timeout_cancel(ctx, tr->addr);
6145 spin_unlock_irq(&ctx->timeout_lock);
6146 spin_unlock(&ctx->completion_lock);
6148 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6150 spin_lock_irq(&ctx->timeout_lock);
6152 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6154 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6155 spin_unlock_irq(&ctx->timeout_lock);
6160 io_req_complete_post(req, ret, 0);
6164 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6165 bool is_timeout_link)
6167 struct io_timeout_data *data;
6169 u32 off = READ_ONCE(sqe->off);
6171 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6173 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6176 if (off && is_timeout_link)
6178 flags = READ_ONCE(sqe->timeout_flags);
6179 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6180 IORING_TIMEOUT_ETIME_SUCCESS))
6182 /* more than one clock specified is invalid, obviously */
6183 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6186 INIT_LIST_HEAD(&req->timeout.list);
6187 req->timeout.off = off;
6188 if (unlikely(off && !req->ctx->off_timeout_used))
6189 req->ctx->off_timeout_used = true;
6191 if (WARN_ON_ONCE(req_has_async_data(req)))
6193 if (io_alloc_async_data(req))
6196 data = req->async_data;
6198 data->flags = flags;
6200 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6203 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6206 data->mode = io_translate_timeout_mode(flags);
6207 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6209 if (is_timeout_link) {
6210 struct io_submit_link *link = &req->ctx->submit_state.link;
6214 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6216 req->timeout.head = link->last;
6217 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6222 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6224 struct io_ring_ctx *ctx = req->ctx;
6225 struct io_timeout_data *data = req->async_data;
6226 struct list_head *entry;
6227 u32 tail, off = req->timeout.off;
6229 spin_lock_irq(&ctx->timeout_lock);
6232 * sqe->off holds how many events that need to occur for this
6233 * timeout event to be satisfied. If it isn't set, then this is
6234 * a pure timeout request, sequence isn't used.
6236 if (io_is_timeout_noseq(req)) {
6237 entry = ctx->timeout_list.prev;
6241 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6242 req->timeout.target_seq = tail + off;
6244 /* Update the last seq here in case io_flush_timeouts() hasn't.
6245 * This is safe because ->completion_lock is held, and submissions
6246 * and completions are never mixed in the same ->completion_lock section.
6248 ctx->cq_last_tm_flush = tail;
6251 * Insertion sort, ensuring the first entry in the list is always
6252 * the one we need first.
6254 list_for_each_prev(entry, &ctx->timeout_list) {
6255 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6258 if (io_is_timeout_noseq(nxt))
6260 /* nxt.seq is behind @tail, otherwise would've been completed */
6261 if (off >= nxt->timeout.target_seq - tail)
6265 list_add(&req->timeout.list, entry);
6266 data->timer.function = io_timeout_fn;
6267 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6268 spin_unlock_irq(&ctx->timeout_lock);
6272 struct io_cancel_data {
6273 struct io_ring_ctx *ctx;
6277 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6279 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6280 struct io_cancel_data *cd = data;
6282 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6285 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6286 struct io_ring_ctx *ctx)
6288 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6289 enum io_wq_cancel cancel_ret;
6292 if (!tctx || !tctx->io_wq)
6295 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6296 switch (cancel_ret) {
6297 case IO_WQ_CANCEL_OK:
6300 case IO_WQ_CANCEL_RUNNING:
6303 case IO_WQ_CANCEL_NOTFOUND:
6311 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6313 struct io_ring_ctx *ctx = req->ctx;
6316 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6318 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6322 spin_lock(&ctx->completion_lock);
6323 spin_lock_irq(&ctx->timeout_lock);
6324 ret = io_timeout_cancel(ctx, sqe_addr);
6325 spin_unlock_irq(&ctx->timeout_lock);
6328 ret = io_poll_cancel(ctx, sqe_addr, false);
6330 spin_unlock(&ctx->completion_lock);
6334 static int io_async_cancel_prep(struct io_kiocb *req,
6335 const struct io_uring_sqe *sqe)
6337 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6339 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6341 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6345 req->cancel.addr = READ_ONCE(sqe->addr);
6349 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6351 struct io_ring_ctx *ctx = req->ctx;
6352 u64 sqe_addr = req->cancel.addr;
6353 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6354 struct io_tctx_node *node;
6357 ret = io_try_cancel_userdata(req, sqe_addr);
6361 /* slow path, try all io-wq's */
6362 io_ring_submit_lock(ctx, needs_lock);
6364 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6365 struct io_uring_task *tctx = node->task->io_uring;
6367 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6371 io_ring_submit_unlock(ctx, needs_lock);
6375 io_req_complete_post(req, ret, 0);
6379 static int io_rsrc_update_prep(struct io_kiocb *req,
6380 const struct io_uring_sqe *sqe)
6382 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6384 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6387 req->rsrc_update.offset = READ_ONCE(sqe->off);
6388 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6389 if (!req->rsrc_update.nr_args)
6391 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6395 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6397 struct io_ring_ctx *ctx = req->ctx;
6398 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6399 struct io_uring_rsrc_update2 up;
6402 up.offset = req->rsrc_update.offset;
6403 up.data = req->rsrc_update.arg;
6408 io_ring_submit_lock(ctx, needs_lock);
6409 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6410 &up, req->rsrc_update.nr_args);
6411 io_ring_submit_unlock(ctx, needs_lock);
6415 __io_req_complete(req, issue_flags, ret, 0);
6419 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6421 switch (req->opcode) {
6424 case IORING_OP_READV:
6425 case IORING_OP_READ_FIXED:
6426 case IORING_OP_READ:
6427 return io_read_prep(req, sqe);
6428 case IORING_OP_WRITEV:
6429 case IORING_OP_WRITE_FIXED:
6430 case IORING_OP_WRITE:
6431 return io_write_prep(req, sqe);
6432 case IORING_OP_POLL_ADD:
6433 return io_poll_add_prep(req, sqe);
6434 case IORING_OP_POLL_REMOVE:
6435 return io_poll_update_prep(req, sqe);
6436 case IORING_OP_FSYNC:
6437 return io_fsync_prep(req, sqe);
6438 case IORING_OP_SYNC_FILE_RANGE:
6439 return io_sfr_prep(req, sqe);
6440 case IORING_OP_SENDMSG:
6441 case IORING_OP_SEND:
6442 return io_sendmsg_prep(req, sqe);
6443 case IORING_OP_RECVMSG:
6444 case IORING_OP_RECV:
6445 return io_recvmsg_prep(req, sqe);
6446 case IORING_OP_CONNECT:
6447 return io_connect_prep(req, sqe);
6448 case IORING_OP_TIMEOUT:
6449 return io_timeout_prep(req, sqe, false);
6450 case IORING_OP_TIMEOUT_REMOVE:
6451 return io_timeout_remove_prep(req, sqe);
6452 case IORING_OP_ASYNC_CANCEL:
6453 return io_async_cancel_prep(req, sqe);
6454 case IORING_OP_LINK_TIMEOUT:
6455 return io_timeout_prep(req, sqe, true);
6456 case IORING_OP_ACCEPT:
6457 return io_accept_prep(req, sqe);
6458 case IORING_OP_FALLOCATE:
6459 return io_fallocate_prep(req, sqe);
6460 case IORING_OP_OPENAT:
6461 return io_openat_prep(req, sqe);
6462 case IORING_OP_CLOSE:
6463 return io_close_prep(req, sqe);
6464 case IORING_OP_FILES_UPDATE:
6465 return io_rsrc_update_prep(req, sqe);
6466 case IORING_OP_STATX:
6467 return io_statx_prep(req, sqe);
6468 case IORING_OP_FADVISE:
6469 return io_fadvise_prep(req, sqe);
6470 case IORING_OP_MADVISE:
6471 return io_madvise_prep(req, sqe);
6472 case IORING_OP_OPENAT2:
6473 return io_openat2_prep(req, sqe);
6474 case IORING_OP_EPOLL_CTL:
6475 return io_epoll_ctl_prep(req, sqe);
6476 case IORING_OP_SPLICE:
6477 return io_splice_prep(req, sqe);
6478 case IORING_OP_PROVIDE_BUFFERS:
6479 return io_provide_buffers_prep(req, sqe);
6480 case IORING_OP_REMOVE_BUFFERS:
6481 return io_remove_buffers_prep(req, sqe);
6483 return io_tee_prep(req, sqe);
6484 case IORING_OP_SHUTDOWN:
6485 return io_shutdown_prep(req, sqe);
6486 case IORING_OP_RENAMEAT:
6487 return io_renameat_prep(req, sqe);
6488 case IORING_OP_UNLINKAT:
6489 return io_unlinkat_prep(req, sqe);
6490 case IORING_OP_MKDIRAT:
6491 return io_mkdirat_prep(req, sqe);
6492 case IORING_OP_SYMLINKAT:
6493 return io_symlinkat_prep(req, sqe);
6494 case IORING_OP_LINKAT:
6495 return io_linkat_prep(req, sqe);
6498 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6503 static int io_req_prep_async(struct io_kiocb *req)
6505 if (!io_op_defs[req->opcode].needs_async_setup)
6507 if (WARN_ON_ONCE(req_has_async_data(req)))
6509 if (io_alloc_async_data(req))
6512 switch (req->opcode) {
6513 case IORING_OP_READV:
6514 return io_rw_prep_async(req, READ);
6515 case IORING_OP_WRITEV:
6516 return io_rw_prep_async(req, WRITE);
6517 case IORING_OP_SENDMSG:
6518 return io_sendmsg_prep_async(req);
6519 case IORING_OP_RECVMSG:
6520 return io_recvmsg_prep_async(req);
6521 case IORING_OP_CONNECT:
6522 return io_connect_prep_async(req);
6524 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6529 static u32 io_get_sequence(struct io_kiocb *req)
6531 u32 seq = req->ctx->cached_sq_head;
6533 /* need original cached_sq_head, but it was increased for each req */
6534 io_for_each_link(req, req)
6539 static __cold void io_drain_req(struct io_kiocb *req)
6541 struct io_ring_ctx *ctx = req->ctx;
6542 struct io_defer_entry *de;
6544 u32 seq = io_get_sequence(req);
6546 /* Still need defer if there is pending req in defer list. */
6547 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6549 ctx->drain_active = false;
6550 io_req_task_queue(req);
6554 ret = io_req_prep_async(req);
6557 io_req_complete_failed(req, ret);
6560 io_prep_async_link(req);
6561 de = kmalloc(sizeof(*de), GFP_KERNEL);
6567 spin_lock(&ctx->completion_lock);
6568 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6569 spin_unlock(&ctx->completion_lock);
6574 trace_io_uring_defer(ctx, req, req->user_data);
6577 list_add_tail(&de->list, &ctx->defer_list);
6578 spin_unlock(&ctx->completion_lock);
6581 static void io_clean_op(struct io_kiocb *req)
6583 if (req->flags & REQ_F_BUFFER_SELECTED) {
6588 if (req->flags & REQ_F_NEED_CLEANUP) {
6589 switch (req->opcode) {
6590 case IORING_OP_READV:
6591 case IORING_OP_READ_FIXED:
6592 case IORING_OP_READ:
6593 case IORING_OP_WRITEV:
6594 case IORING_OP_WRITE_FIXED:
6595 case IORING_OP_WRITE: {
6596 struct io_async_rw *io = req->async_data;
6598 kfree(io->free_iovec);
6601 case IORING_OP_RECVMSG:
6602 case IORING_OP_SENDMSG: {
6603 struct io_async_msghdr *io = req->async_data;
6605 kfree(io->free_iov);
6608 case IORING_OP_SPLICE:
6610 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6611 io_put_file(req->splice.file_in);
6613 case IORING_OP_OPENAT:
6614 case IORING_OP_OPENAT2:
6615 if (req->open.filename)
6616 putname(req->open.filename);
6618 case IORING_OP_RENAMEAT:
6619 putname(req->rename.oldpath);
6620 putname(req->rename.newpath);
6622 case IORING_OP_UNLINKAT:
6623 putname(req->unlink.filename);
6625 case IORING_OP_MKDIRAT:
6626 putname(req->mkdir.filename);
6628 case IORING_OP_SYMLINKAT:
6629 putname(req->symlink.oldpath);
6630 putname(req->symlink.newpath);
6632 case IORING_OP_LINKAT:
6633 putname(req->hardlink.oldpath);
6634 putname(req->hardlink.newpath);
6638 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6639 kfree(req->apoll->double_poll);
6643 if (req->flags & REQ_F_INFLIGHT) {
6644 struct io_uring_task *tctx = req->task->io_uring;
6646 atomic_dec(&tctx->inflight_tracked);
6648 if (req->flags & REQ_F_CREDS)
6649 put_cred(req->creds);
6650 if (req->flags & REQ_F_ASYNC_DATA) {
6651 kfree(req->async_data);
6652 req->async_data = NULL;
6654 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6657 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6659 const struct cred *creds = NULL;
6662 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6663 creds = override_creds(req->creds);
6665 if (!io_op_defs[req->opcode].audit_skip)
6666 audit_uring_entry(req->opcode);
6668 switch (req->opcode) {
6670 ret = io_nop(req, issue_flags);
6672 case IORING_OP_READV:
6673 case IORING_OP_READ_FIXED:
6674 case IORING_OP_READ:
6675 ret = io_read(req, issue_flags);
6677 case IORING_OP_WRITEV:
6678 case IORING_OP_WRITE_FIXED:
6679 case IORING_OP_WRITE:
6680 ret = io_write(req, issue_flags);
6682 case IORING_OP_FSYNC:
6683 ret = io_fsync(req, issue_flags);
6685 case IORING_OP_POLL_ADD:
6686 ret = io_poll_add(req, issue_flags);
6688 case IORING_OP_POLL_REMOVE:
6689 ret = io_poll_update(req, issue_flags);
6691 case IORING_OP_SYNC_FILE_RANGE:
6692 ret = io_sync_file_range(req, issue_flags);
6694 case IORING_OP_SENDMSG:
6695 ret = io_sendmsg(req, issue_flags);
6697 case IORING_OP_SEND:
6698 ret = io_send(req, issue_flags);
6700 case IORING_OP_RECVMSG:
6701 ret = io_recvmsg(req, issue_flags);
6703 case IORING_OP_RECV:
6704 ret = io_recv(req, issue_flags);
6706 case IORING_OP_TIMEOUT:
6707 ret = io_timeout(req, issue_flags);
6709 case IORING_OP_TIMEOUT_REMOVE:
6710 ret = io_timeout_remove(req, issue_flags);
6712 case IORING_OP_ACCEPT:
6713 ret = io_accept(req, issue_flags);
6715 case IORING_OP_CONNECT:
6716 ret = io_connect(req, issue_flags);
6718 case IORING_OP_ASYNC_CANCEL:
6719 ret = io_async_cancel(req, issue_flags);
6721 case IORING_OP_FALLOCATE:
6722 ret = io_fallocate(req, issue_flags);
6724 case IORING_OP_OPENAT:
6725 ret = io_openat(req, issue_flags);
6727 case IORING_OP_CLOSE:
6728 ret = io_close(req, issue_flags);
6730 case IORING_OP_FILES_UPDATE:
6731 ret = io_files_update(req, issue_flags);
6733 case IORING_OP_STATX:
6734 ret = io_statx(req, issue_flags);
6736 case IORING_OP_FADVISE:
6737 ret = io_fadvise(req, issue_flags);
6739 case IORING_OP_MADVISE:
6740 ret = io_madvise(req, issue_flags);
6742 case IORING_OP_OPENAT2:
6743 ret = io_openat2(req, issue_flags);
6745 case IORING_OP_EPOLL_CTL:
6746 ret = io_epoll_ctl(req, issue_flags);
6748 case IORING_OP_SPLICE:
6749 ret = io_splice(req, issue_flags);
6751 case IORING_OP_PROVIDE_BUFFERS:
6752 ret = io_provide_buffers(req, issue_flags);
6754 case IORING_OP_REMOVE_BUFFERS:
6755 ret = io_remove_buffers(req, issue_flags);
6758 ret = io_tee(req, issue_flags);
6760 case IORING_OP_SHUTDOWN:
6761 ret = io_shutdown(req, issue_flags);
6763 case IORING_OP_RENAMEAT:
6764 ret = io_renameat(req, issue_flags);
6766 case IORING_OP_UNLINKAT:
6767 ret = io_unlinkat(req, issue_flags);
6769 case IORING_OP_MKDIRAT:
6770 ret = io_mkdirat(req, issue_flags);
6772 case IORING_OP_SYMLINKAT:
6773 ret = io_symlinkat(req, issue_flags);
6775 case IORING_OP_LINKAT:
6776 ret = io_linkat(req, issue_flags);
6783 if (!io_op_defs[req->opcode].audit_skip)
6784 audit_uring_exit(!ret, ret);
6787 revert_creds(creds);
6790 /* If the op doesn't have a file, we're not polling for it */
6791 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6792 io_iopoll_req_issued(req, issue_flags);
6797 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6799 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6801 req = io_put_req_find_next(req);
6802 return req ? &req->work : NULL;
6805 static void io_wq_submit_work(struct io_wq_work *work)
6807 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6808 unsigned int issue_flags = IO_URING_F_UNLOCKED;
6809 bool needs_poll = false;
6810 struct io_kiocb *timeout;
6813 /* one will be dropped by ->io_free_work() after returning to io-wq */
6814 if (!(req->flags & REQ_F_REFCOUNT))
6815 __io_req_set_refcount(req, 2);
6819 timeout = io_prep_linked_timeout(req);
6821 io_queue_linked_timeout(timeout);
6823 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6824 if (work->flags & IO_WQ_WORK_CANCEL) {
6825 io_req_task_queue_fail(req, -ECANCELED);
6829 if (req->flags & REQ_F_FORCE_ASYNC) {
6830 const struct io_op_def *def = &io_op_defs[req->opcode];
6831 bool opcode_poll = def->pollin || def->pollout;
6833 if (opcode_poll && file_can_poll(req->file)) {
6835 issue_flags |= IO_URING_F_NONBLOCK;
6840 ret = io_issue_sqe(req, issue_flags);
6844 * We can get EAGAIN for iopolled IO even though we're
6845 * forcing a sync submission from here, since we can't
6846 * wait for request slots on the block side.
6853 if (io_arm_poll_handler(req) == IO_APOLL_OK)
6855 /* aborted or ready, in either case retry blocking */
6857 issue_flags &= ~IO_URING_F_NONBLOCK;
6860 /* avoid locking problems by failing it from a clean context */
6862 io_req_task_queue_fail(req, ret);
6865 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6868 return &table->files[i];
6871 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6874 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6876 return (struct file *) (slot->file_ptr & FFS_MASK);
6879 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6881 unsigned long file_ptr = (unsigned long) file;
6883 file_ptr |= io_file_get_flags(file);
6884 file_slot->file_ptr = file_ptr;
6887 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6888 struct io_kiocb *req, int fd)
6891 unsigned long file_ptr;
6893 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6895 fd = array_index_nospec(fd, ctx->nr_user_files);
6896 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6897 file = (struct file *) (file_ptr & FFS_MASK);
6898 file_ptr &= ~FFS_MASK;
6899 /* mask in overlapping REQ_F and FFS bits */
6900 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6901 io_req_set_rsrc_node(req, ctx);
6905 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6906 struct io_kiocb *req, int fd)
6908 struct file *file = fget(fd);
6910 trace_io_uring_file_get(ctx, fd);
6912 /* we don't allow fixed io_uring files */
6913 if (file && unlikely(file->f_op == &io_uring_fops))
6914 io_req_track_inflight(req);
6918 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6919 struct io_kiocb *req, int fd, bool fixed)
6922 return io_file_get_fixed(ctx, req, fd);
6924 return io_file_get_normal(ctx, req, fd);
6927 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6929 struct io_kiocb *prev = req->timeout.prev;
6933 if (!(req->task->flags & PF_EXITING))
6934 ret = io_try_cancel_userdata(req, prev->user_data);
6935 io_req_complete_post(req, ret ?: -ETIME, 0);
6938 io_req_complete_post(req, -ETIME, 0);
6942 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6944 struct io_timeout_data *data = container_of(timer,
6945 struct io_timeout_data, timer);
6946 struct io_kiocb *prev, *req = data->req;
6947 struct io_ring_ctx *ctx = req->ctx;
6948 unsigned long flags;
6950 spin_lock_irqsave(&ctx->timeout_lock, flags);
6951 prev = req->timeout.head;
6952 req->timeout.head = NULL;
6955 * We don't expect the list to be empty, that will only happen if we
6956 * race with the completion of the linked work.
6959 io_remove_next_linked(prev);
6960 if (!req_ref_inc_not_zero(prev))
6963 list_del(&req->timeout.list);
6964 req->timeout.prev = prev;
6965 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6967 req->io_task_work.func = io_req_task_link_timeout;
6968 io_req_task_work_add(req);
6969 return HRTIMER_NORESTART;
6972 static void io_queue_linked_timeout(struct io_kiocb *req)
6974 struct io_ring_ctx *ctx = req->ctx;
6976 spin_lock_irq(&ctx->timeout_lock);
6978 * If the back reference is NULL, then our linked request finished
6979 * before we got a chance to setup the timer
6981 if (req->timeout.head) {
6982 struct io_timeout_data *data = req->async_data;
6984 data->timer.function = io_link_timeout_fn;
6985 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6987 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6989 spin_unlock_irq(&ctx->timeout_lock);
6990 /* drop submission reference */
6994 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
6995 __must_hold(&req->ctx->uring_lock)
6997 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6999 switch (io_arm_poll_handler(req)) {
7000 case IO_APOLL_READY:
7001 io_req_task_queue(req);
7003 case IO_APOLL_ABORTED:
7005 * Queued up for async execution, worker will release
7006 * submit reference when the iocb is actually submitted.
7008 io_queue_async_work(req, NULL);
7013 io_queue_linked_timeout(linked_timeout);
7016 static inline void __io_queue_sqe(struct io_kiocb *req)
7017 __must_hold(&req->ctx->uring_lock)
7019 struct io_kiocb *linked_timeout;
7022 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7024 if (req->flags & REQ_F_COMPLETE_INLINE) {
7025 io_req_add_compl_list(req);
7029 * We async punt it if the file wasn't marked NOWAIT, or if the file
7030 * doesn't support non-blocking read/write attempts
7033 linked_timeout = io_prep_linked_timeout(req);
7035 io_queue_linked_timeout(linked_timeout);
7036 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7037 io_queue_sqe_arm_apoll(req);
7039 io_req_complete_failed(req, ret);
7043 static void io_queue_sqe_fallback(struct io_kiocb *req)
7044 __must_hold(&req->ctx->uring_lock)
7046 if (req->flags & REQ_F_FAIL) {
7047 io_req_complete_fail_submit(req);
7048 } else if (unlikely(req->ctx->drain_active)) {
7051 int ret = io_req_prep_async(req);
7054 io_req_complete_failed(req, ret);
7056 io_queue_async_work(req, NULL);
7060 static inline void io_queue_sqe(struct io_kiocb *req)
7061 __must_hold(&req->ctx->uring_lock)
7063 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7064 __io_queue_sqe(req);
7066 io_queue_sqe_fallback(req);
7070 * Check SQE restrictions (opcode and flags).
7072 * Returns 'true' if SQE is allowed, 'false' otherwise.
7074 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7075 struct io_kiocb *req,
7076 unsigned int sqe_flags)
7078 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7081 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7082 ctx->restrictions.sqe_flags_required)
7085 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7086 ctx->restrictions.sqe_flags_required))
7092 static void io_init_req_drain(struct io_kiocb *req)
7094 struct io_ring_ctx *ctx = req->ctx;
7095 struct io_kiocb *head = ctx->submit_state.link.head;
7097 ctx->drain_active = true;
7100 * If we need to drain a request in the middle of a link, drain
7101 * the head request and the next request/link after the current
7102 * link. Considering sequential execution of links,
7103 * IOSQE_IO_DRAIN will be maintained for every request of our
7106 head->flags |= IOSQE_IO_DRAIN | REQ_F_FORCE_ASYNC;
7107 ctx->drain_next = true;
7111 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7112 const struct io_uring_sqe *sqe)
7113 __must_hold(&ctx->uring_lock)
7115 unsigned int sqe_flags;
7119 /* req is partially pre-initialised, see io_preinit_req() */
7120 req->opcode = opcode = READ_ONCE(sqe->opcode);
7121 /* same numerical values with corresponding REQ_F_*, safe to copy */
7122 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7123 req->user_data = READ_ONCE(sqe->user_data);
7125 req->fixed_rsrc_refs = NULL;
7126 req->task = current;
7128 if (unlikely(opcode >= IORING_OP_LAST)) {
7132 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7133 /* enforce forwards compatibility on users */
7134 if (sqe_flags & ~SQE_VALID_FLAGS)
7136 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7137 !io_op_defs[opcode].buffer_select)
7139 if (sqe_flags & IOSQE_IO_DRAIN)
7140 io_init_req_drain(req);
7142 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7143 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7145 /* knock it to the slow queue path, will be drained there */
7146 if (ctx->drain_active)
7147 req->flags |= REQ_F_FORCE_ASYNC;
7148 /* if there is no link, we're at "next" request and need to drain */
7149 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7150 ctx->drain_next = false;
7151 ctx->drain_active = true;
7152 req->flags |= IOSQE_IO_DRAIN | REQ_F_FORCE_ASYNC;
7156 if (io_op_defs[opcode].needs_file) {
7157 struct io_submit_state *state = &ctx->submit_state;
7160 * Plug now if we have more than 2 IO left after this, and the
7161 * target is potentially a read/write to block based storage.
7163 if (state->need_plug && io_op_defs[opcode].plug) {
7164 state->plug_started = true;
7165 state->need_plug = false;
7166 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7169 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7170 (sqe_flags & IOSQE_FIXED_FILE));
7171 if (unlikely(!req->file))
7175 personality = READ_ONCE(sqe->personality);
7179 req->creds = xa_load(&ctx->personalities, personality);
7182 get_cred(req->creds);
7183 ret = security_uring_override_creds(req->creds);
7185 put_cred(req->creds);
7188 req->flags |= REQ_F_CREDS;
7191 return io_req_prep(req, sqe);
7194 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7195 const struct io_uring_sqe *sqe)
7196 __must_hold(&ctx->uring_lock)
7198 struct io_submit_link *link = &ctx->submit_state.link;
7201 ret = io_init_req(ctx, req, sqe);
7202 if (unlikely(ret)) {
7203 trace_io_uring_req_failed(sqe, ret);
7205 /* fail even hard links since we don't submit */
7208 * we can judge a link req is failed or cancelled by if
7209 * REQ_F_FAIL is set, but the head is an exception since
7210 * it may be set REQ_F_FAIL because of other req's failure
7211 * so let's leverage req->result to distinguish if a head
7212 * is set REQ_F_FAIL because of its failure or other req's
7213 * failure so that we can set the correct ret code for it.
7214 * init result here to avoid affecting the normal path.
7216 if (!(link->head->flags & REQ_F_FAIL))
7217 req_fail_link_node(link->head, -ECANCELED);
7218 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7220 * the current req is a normal req, we should return
7221 * error and thus break the submittion loop.
7223 io_req_complete_failed(req, ret);
7226 req_fail_link_node(req, ret);
7229 /* don't need @sqe from now on */
7230 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7232 ctx->flags & IORING_SETUP_SQPOLL);
7235 * If we already have a head request, queue this one for async
7236 * submittal once the head completes. If we don't have a head but
7237 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7238 * submitted sync once the chain is complete. If none of those
7239 * conditions are true (normal request), then just queue it.
7242 struct io_kiocb *head = link->head;
7244 if (!(req->flags & REQ_F_FAIL)) {
7245 ret = io_req_prep_async(req);
7246 if (unlikely(ret)) {
7247 req_fail_link_node(req, ret);
7248 if (!(head->flags & REQ_F_FAIL))
7249 req_fail_link_node(head, -ECANCELED);
7252 trace_io_uring_link(ctx, req, head);
7253 link->last->link = req;
7256 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7258 /* last request of a link, enqueue the link */
7261 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7272 * Batched submission is done, ensure local IO is flushed out.
7274 static void io_submit_state_end(struct io_ring_ctx *ctx)
7276 struct io_submit_state *state = &ctx->submit_state;
7278 if (state->link.head)
7279 io_queue_sqe(state->link.head);
7280 /* flush only after queuing links as they can generate completions */
7281 io_submit_flush_completions(ctx);
7282 if (state->plug_started)
7283 blk_finish_plug(&state->plug);
7287 * Start submission side cache.
7289 static void io_submit_state_start(struct io_submit_state *state,
7290 unsigned int max_ios)
7292 state->plug_started = false;
7293 state->need_plug = max_ios > 2;
7294 state->submit_nr = max_ios;
7295 /* set only head, no need to init link_last in advance */
7296 state->link.head = NULL;
7299 static void io_commit_sqring(struct io_ring_ctx *ctx)
7301 struct io_rings *rings = ctx->rings;
7304 * Ensure any loads from the SQEs are done at this point,
7305 * since once we write the new head, the application could
7306 * write new data to them.
7308 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7312 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7313 * that is mapped by userspace. This means that care needs to be taken to
7314 * ensure that reads are stable, as we cannot rely on userspace always
7315 * being a good citizen. If members of the sqe are validated and then later
7316 * used, it's important that those reads are done through READ_ONCE() to
7317 * prevent a re-load down the line.
7319 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7321 unsigned head, mask = ctx->sq_entries - 1;
7322 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7325 * The cached sq head (or cq tail) serves two purposes:
7327 * 1) allows us to batch the cost of updating the user visible
7329 * 2) allows the kernel side to track the head on its own, even
7330 * though the application is the one updating it.
7332 head = READ_ONCE(ctx->sq_array[sq_idx]);
7333 if (likely(head < ctx->sq_entries))
7334 return &ctx->sq_sqes[head];
7336 /* drop invalid entries */
7338 WRITE_ONCE(ctx->rings->sq_dropped,
7339 READ_ONCE(ctx->rings->sq_dropped) + 1);
7343 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7344 __must_hold(&ctx->uring_lock)
7346 unsigned int entries = io_sqring_entries(ctx);
7349 if (unlikely(!entries))
7351 /* make sure SQ entry isn't read before tail */
7352 nr = min3(nr, ctx->sq_entries, entries);
7353 io_get_task_refs(nr);
7355 io_submit_state_start(&ctx->submit_state, nr);
7357 const struct io_uring_sqe *sqe;
7358 struct io_kiocb *req;
7360 if (unlikely(!io_alloc_req_refill(ctx))) {
7362 submitted = -EAGAIN;
7365 req = io_alloc_req(ctx);
7366 sqe = io_get_sqe(ctx);
7367 if (unlikely(!sqe)) {
7368 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7371 /* will complete beyond this point, count as submitted */
7373 if (io_submit_sqe(ctx, req, sqe))
7375 } while (submitted < nr);
7377 if (unlikely(submitted != nr)) {
7378 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7379 int unused = nr - ref_used;
7381 current->io_uring->cached_refs += unused;
7384 io_submit_state_end(ctx);
7385 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7386 io_commit_sqring(ctx);
7391 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7393 return READ_ONCE(sqd->state);
7396 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7398 /* Tell userspace we may need a wakeup call */
7399 spin_lock(&ctx->completion_lock);
7400 WRITE_ONCE(ctx->rings->sq_flags,
7401 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7402 spin_unlock(&ctx->completion_lock);
7405 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7407 spin_lock(&ctx->completion_lock);
7408 WRITE_ONCE(ctx->rings->sq_flags,
7409 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7410 spin_unlock(&ctx->completion_lock);
7413 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7415 unsigned int to_submit;
7418 to_submit = io_sqring_entries(ctx);
7419 /* if we're handling multiple rings, cap submit size for fairness */
7420 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7421 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7423 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7424 const struct cred *creds = NULL;
7426 if (ctx->sq_creds != current_cred())
7427 creds = override_creds(ctx->sq_creds);
7429 mutex_lock(&ctx->uring_lock);
7430 if (!wq_list_empty(&ctx->iopoll_list))
7431 io_do_iopoll(ctx, true);
7434 * Don't submit if refs are dying, good for io_uring_register(),
7435 * but also it is relied upon by io_ring_exit_work()
7437 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7438 !(ctx->flags & IORING_SETUP_R_DISABLED))
7439 ret = io_submit_sqes(ctx, to_submit);
7440 mutex_unlock(&ctx->uring_lock);
7442 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7443 wake_up(&ctx->sqo_sq_wait);
7445 revert_creds(creds);
7451 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7453 struct io_ring_ctx *ctx;
7454 unsigned sq_thread_idle = 0;
7456 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7457 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7458 sqd->sq_thread_idle = sq_thread_idle;
7461 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7463 bool did_sig = false;
7464 struct ksignal ksig;
7466 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7467 signal_pending(current)) {
7468 mutex_unlock(&sqd->lock);
7469 if (signal_pending(current))
7470 did_sig = get_signal(&ksig);
7472 mutex_lock(&sqd->lock);
7474 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7477 static int io_sq_thread(void *data)
7479 struct io_sq_data *sqd = data;
7480 struct io_ring_ctx *ctx;
7481 unsigned long timeout = 0;
7482 char buf[TASK_COMM_LEN];
7485 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7486 set_task_comm(current, buf);
7488 if (sqd->sq_cpu != -1)
7489 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7491 set_cpus_allowed_ptr(current, cpu_online_mask);
7492 current->flags |= PF_NO_SETAFFINITY;
7494 audit_alloc_kernel(current);
7496 mutex_lock(&sqd->lock);
7498 bool cap_entries, sqt_spin = false;
7500 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7501 if (io_sqd_handle_event(sqd))
7503 timeout = jiffies + sqd->sq_thread_idle;
7506 cap_entries = !list_is_singular(&sqd->ctx_list);
7507 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7508 int ret = __io_sq_thread(ctx, cap_entries);
7510 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7513 if (io_run_task_work())
7516 if (sqt_spin || !time_after(jiffies, timeout)) {
7519 timeout = jiffies + sqd->sq_thread_idle;
7523 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7524 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7525 bool needs_sched = true;
7527 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7528 io_ring_set_wakeup_flag(ctx);
7530 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7531 !wq_list_empty(&ctx->iopoll_list)) {
7532 needs_sched = false;
7535 if (io_sqring_entries(ctx)) {
7536 needs_sched = false;
7542 mutex_unlock(&sqd->lock);
7544 mutex_lock(&sqd->lock);
7546 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7547 io_ring_clear_wakeup_flag(ctx);
7550 finish_wait(&sqd->wait, &wait);
7551 timeout = jiffies + sqd->sq_thread_idle;
7554 io_uring_cancel_generic(true, sqd);
7556 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7557 io_ring_set_wakeup_flag(ctx);
7559 mutex_unlock(&sqd->lock);
7561 audit_free(current);
7563 complete(&sqd->exited);
7567 struct io_wait_queue {
7568 struct wait_queue_entry wq;
7569 struct io_ring_ctx *ctx;
7571 unsigned nr_timeouts;
7574 static inline bool io_should_wake(struct io_wait_queue *iowq)
7576 struct io_ring_ctx *ctx = iowq->ctx;
7577 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7580 * Wake up if we have enough events, or if a timeout occurred since we
7581 * started waiting. For timeouts, we always want to return to userspace,
7582 * regardless of event count.
7584 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7587 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7588 int wake_flags, void *key)
7590 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7594 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7595 * the task, and the next invocation will do it.
7597 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7598 return autoremove_wake_function(curr, mode, wake_flags, key);
7602 static int io_run_task_work_sig(void)
7604 if (io_run_task_work())
7606 if (!signal_pending(current))
7608 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7609 return -ERESTARTSYS;
7613 /* when returns >0, the caller should retry */
7614 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7615 struct io_wait_queue *iowq,
7616 signed long *timeout)
7620 /* make sure we run task_work before checking for signals */
7621 ret = io_run_task_work_sig();
7622 if (ret || io_should_wake(iowq))
7624 /* let the caller flush overflows, retry */
7625 if (test_bit(0, &ctx->check_cq_overflow))
7628 *timeout = schedule_timeout(*timeout);
7629 return !*timeout ? -ETIME : 1;
7633 * Wait until events become available, if we don't already have some. The
7634 * application must reap them itself, as they reside on the shared cq ring.
7636 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7637 const sigset_t __user *sig, size_t sigsz,
7638 struct __kernel_timespec __user *uts)
7640 struct io_wait_queue iowq;
7641 struct io_rings *rings = ctx->rings;
7642 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7646 io_cqring_overflow_flush(ctx);
7647 if (io_cqring_events(ctx) >= min_events)
7649 if (!io_run_task_work())
7654 struct timespec64 ts;
7656 if (get_timespec64(&ts, uts))
7658 timeout = timespec64_to_jiffies(&ts);
7662 #ifdef CONFIG_COMPAT
7663 if (in_compat_syscall())
7664 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7668 ret = set_user_sigmask(sig, sigsz);
7674 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7675 iowq.wq.private = current;
7676 INIT_LIST_HEAD(&iowq.wq.entry);
7678 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7679 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7681 trace_io_uring_cqring_wait(ctx, min_events);
7683 /* if we can't even flush overflow, don't wait for more */
7684 if (!io_cqring_overflow_flush(ctx)) {
7688 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7689 TASK_INTERRUPTIBLE);
7690 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7691 finish_wait(&ctx->cq_wait, &iowq.wq);
7695 restore_saved_sigmask_unless(ret == -EINTR);
7697 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7700 static void io_free_page_table(void **table, size_t size)
7702 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7704 for (i = 0; i < nr_tables; i++)
7709 static __cold void **io_alloc_page_table(size_t size)
7711 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7712 size_t init_size = size;
7715 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7719 for (i = 0; i < nr_tables; i++) {
7720 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7722 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7724 io_free_page_table(table, init_size);
7732 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7734 percpu_ref_exit(&ref_node->refs);
7738 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7740 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7741 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7742 unsigned long flags;
7743 bool first_add = false;
7745 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7748 while (!list_empty(&ctx->rsrc_ref_list)) {
7749 node = list_first_entry(&ctx->rsrc_ref_list,
7750 struct io_rsrc_node, node);
7751 /* recycle ref nodes in order */
7754 list_del(&node->node);
7755 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7757 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7760 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7763 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7765 struct io_rsrc_node *ref_node;
7767 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7771 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7776 INIT_LIST_HEAD(&ref_node->node);
7777 INIT_LIST_HEAD(&ref_node->rsrc_list);
7778 ref_node->done = false;
7782 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7783 struct io_rsrc_data *data_to_kill)
7784 __must_hold(&ctx->uring_lock)
7786 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7787 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7789 io_rsrc_refs_drop(ctx);
7792 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7794 rsrc_node->rsrc_data = data_to_kill;
7795 spin_lock_irq(&ctx->rsrc_ref_lock);
7796 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7797 spin_unlock_irq(&ctx->rsrc_ref_lock);
7799 atomic_inc(&data_to_kill->refs);
7800 percpu_ref_kill(&rsrc_node->refs);
7801 ctx->rsrc_node = NULL;
7804 if (!ctx->rsrc_node) {
7805 ctx->rsrc_node = ctx->rsrc_backup_node;
7806 ctx->rsrc_backup_node = NULL;
7810 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7812 if (ctx->rsrc_backup_node)
7814 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7815 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7818 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7819 struct io_ring_ctx *ctx)
7823 /* As we may drop ->uring_lock, other task may have started quiesce */
7827 data->quiesce = true;
7829 ret = io_rsrc_node_switch_start(ctx);
7832 io_rsrc_node_switch(ctx, data);
7834 /* kill initial ref, already quiesced if zero */
7835 if (atomic_dec_and_test(&data->refs))
7837 mutex_unlock(&ctx->uring_lock);
7838 flush_delayed_work(&ctx->rsrc_put_work);
7839 ret = wait_for_completion_interruptible(&data->done);
7841 mutex_lock(&ctx->uring_lock);
7845 atomic_inc(&data->refs);
7846 /* wait for all works potentially completing data->done */
7847 flush_delayed_work(&ctx->rsrc_put_work);
7848 reinit_completion(&data->done);
7850 ret = io_run_task_work_sig();
7851 mutex_lock(&ctx->uring_lock);
7853 data->quiesce = false;
7858 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7860 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7861 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7863 return &data->tags[table_idx][off];
7866 static void io_rsrc_data_free(struct io_rsrc_data *data)
7868 size_t size = data->nr * sizeof(data->tags[0][0]);
7871 io_free_page_table((void **)data->tags, size);
7875 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7876 u64 __user *utags, unsigned nr,
7877 struct io_rsrc_data **pdata)
7879 struct io_rsrc_data *data;
7883 data = kzalloc(sizeof(*data), GFP_KERNEL);
7886 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7894 data->do_put = do_put;
7897 for (i = 0; i < nr; i++) {
7898 u64 *tag_slot = io_get_tag_slot(data, i);
7900 if (copy_from_user(tag_slot, &utags[i],
7906 atomic_set(&data->refs, 1);
7907 init_completion(&data->done);
7911 io_rsrc_data_free(data);
7915 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7917 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7918 GFP_KERNEL_ACCOUNT);
7919 return !!table->files;
7922 static void io_free_file_tables(struct io_file_table *table)
7924 kvfree(table->files);
7925 table->files = NULL;
7928 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7930 #if defined(CONFIG_UNIX)
7931 if (ctx->ring_sock) {
7932 struct sock *sock = ctx->ring_sock->sk;
7933 struct sk_buff *skb;
7935 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7941 for (i = 0; i < ctx->nr_user_files; i++) {
7944 file = io_file_from_index(ctx, i);
7949 io_free_file_tables(&ctx->file_table);
7950 io_rsrc_data_free(ctx->file_data);
7951 ctx->file_data = NULL;
7952 ctx->nr_user_files = 0;
7955 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7959 if (!ctx->file_data)
7961 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7963 __io_sqe_files_unregister(ctx);
7967 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7968 __releases(&sqd->lock)
7970 WARN_ON_ONCE(sqd->thread == current);
7973 * Do the dance but not conditional clear_bit() because it'd race with
7974 * other threads incrementing park_pending and setting the bit.
7976 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7977 if (atomic_dec_return(&sqd->park_pending))
7978 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7979 mutex_unlock(&sqd->lock);
7982 static void io_sq_thread_park(struct io_sq_data *sqd)
7983 __acquires(&sqd->lock)
7985 WARN_ON_ONCE(sqd->thread == current);
7987 atomic_inc(&sqd->park_pending);
7988 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7989 mutex_lock(&sqd->lock);
7991 wake_up_process(sqd->thread);
7994 static void io_sq_thread_stop(struct io_sq_data *sqd)
7996 WARN_ON_ONCE(sqd->thread == current);
7997 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7999 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8000 mutex_lock(&sqd->lock);
8002 wake_up_process(sqd->thread);
8003 mutex_unlock(&sqd->lock);
8004 wait_for_completion(&sqd->exited);
8007 static void io_put_sq_data(struct io_sq_data *sqd)
8009 if (refcount_dec_and_test(&sqd->refs)) {
8010 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8012 io_sq_thread_stop(sqd);
8017 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8019 struct io_sq_data *sqd = ctx->sq_data;
8022 io_sq_thread_park(sqd);
8023 list_del_init(&ctx->sqd_list);
8024 io_sqd_update_thread_idle(sqd);
8025 io_sq_thread_unpark(sqd);
8027 io_put_sq_data(sqd);
8028 ctx->sq_data = NULL;
8032 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8034 struct io_ring_ctx *ctx_attach;
8035 struct io_sq_data *sqd;
8038 f = fdget(p->wq_fd);
8040 return ERR_PTR(-ENXIO);
8041 if (f.file->f_op != &io_uring_fops) {
8043 return ERR_PTR(-EINVAL);
8046 ctx_attach = f.file->private_data;
8047 sqd = ctx_attach->sq_data;
8050 return ERR_PTR(-EINVAL);
8052 if (sqd->task_tgid != current->tgid) {
8054 return ERR_PTR(-EPERM);
8057 refcount_inc(&sqd->refs);
8062 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8065 struct io_sq_data *sqd;
8068 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8069 sqd = io_attach_sq_data(p);
8074 /* fall through for EPERM case, setup new sqd/task */
8075 if (PTR_ERR(sqd) != -EPERM)
8079 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8081 return ERR_PTR(-ENOMEM);
8083 atomic_set(&sqd->park_pending, 0);
8084 refcount_set(&sqd->refs, 1);
8085 INIT_LIST_HEAD(&sqd->ctx_list);
8086 mutex_init(&sqd->lock);
8087 init_waitqueue_head(&sqd->wait);
8088 init_completion(&sqd->exited);
8092 #if defined(CONFIG_UNIX)
8094 * Ensure the UNIX gc is aware of our file set, so we are certain that
8095 * the io_uring can be safely unregistered on process exit, even if we have
8096 * loops in the file referencing.
8098 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8100 struct sock *sk = ctx->ring_sock->sk;
8101 struct scm_fp_list *fpl;
8102 struct sk_buff *skb;
8105 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8109 skb = alloc_skb(0, GFP_KERNEL);
8118 fpl->user = get_uid(current_user());
8119 for (i = 0; i < nr; i++) {
8120 struct file *file = io_file_from_index(ctx, i + offset);
8124 fpl->fp[nr_files] = get_file(file);
8125 unix_inflight(fpl->user, fpl->fp[nr_files]);
8130 fpl->max = SCM_MAX_FD;
8131 fpl->count = nr_files;
8132 UNIXCB(skb).fp = fpl;
8133 skb->destructor = unix_destruct_scm;
8134 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8135 skb_queue_head(&sk->sk_receive_queue, skb);
8137 for (i = 0; i < nr_files; i++)
8148 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8149 * causes regular reference counting to break down. We rely on the UNIX
8150 * garbage collection to take care of this problem for us.
8152 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8154 unsigned left, total;
8158 left = ctx->nr_user_files;
8160 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8162 ret = __io_sqe_files_scm(ctx, this_files, total);
8166 total += this_files;
8172 while (total < ctx->nr_user_files) {
8173 struct file *file = io_file_from_index(ctx, total);
8183 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8189 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8191 struct file *file = prsrc->file;
8192 #if defined(CONFIG_UNIX)
8193 struct sock *sock = ctx->ring_sock->sk;
8194 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8195 struct sk_buff *skb;
8198 __skb_queue_head_init(&list);
8201 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8202 * remove this entry and rearrange the file array.
8204 skb = skb_dequeue(head);
8206 struct scm_fp_list *fp;
8208 fp = UNIXCB(skb).fp;
8209 for (i = 0; i < fp->count; i++) {
8212 if (fp->fp[i] != file)
8215 unix_notinflight(fp->user, fp->fp[i]);
8216 left = fp->count - 1 - i;
8218 memmove(&fp->fp[i], &fp->fp[i + 1],
8219 left * sizeof(struct file *));
8226 __skb_queue_tail(&list, skb);
8236 __skb_queue_tail(&list, skb);
8238 skb = skb_dequeue(head);
8241 if (skb_peek(&list)) {
8242 spin_lock_irq(&head->lock);
8243 while ((skb = __skb_dequeue(&list)) != NULL)
8244 __skb_queue_tail(head, skb);
8245 spin_unlock_irq(&head->lock);
8252 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8254 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8255 struct io_ring_ctx *ctx = rsrc_data->ctx;
8256 struct io_rsrc_put *prsrc, *tmp;
8258 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8259 list_del(&prsrc->list);
8262 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8264 io_ring_submit_lock(ctx, lock_ring);
8265 spin_lock(&ctx->completion_lock);
8266 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
8268 io_commit_cqring(ctx);
8269 spin_unlock(&ctx->completion_lock);
8270 io_cqring_ev_posted(ctx);
8271 io_ring_submit_unlock(ctx, lock_ring);
8274 rsrc_data->do_put(ctx, prsrc);
8278 io_rsrc_node_destroy(ref_node);
8279 if (atomic_dec_and_test(&rsrc_data->refs))
8280 complete(&rsrc_data->done);
8283 static void io_rsrc_put_work(struct work_struct *work)
8285 struct io_ring_ctx *ctx;
8286 struct llist_node *node;
8288 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8289 node = llist_del_all(&ctx->rsrc_put_llist);
8292 struct io_rsrc_node *ref_node;
8293 struct llist_node *next = node->next;
8295 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8296 __io_rsrc_put_work(ref_node);
8301 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8302 unsigned nr_args, u64 __user *tags)
8304 __s32 __user *fds = (__s32 __user *) arg;
8313 if (nr_args > IORING_MAX_FIXED_FILES)
8315 if (nr_args > rlimit(RLIMIT_NOFILE))
8317 ret = io_rsrc_node_switch_start(ctx);
8320 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8326 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8329 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8330 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8334 /* allow sparse sets */
8337 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8344 if (unlikely(!file))
8348 * Don't allow io_uring instances to be registered. If UNIX
8349 * isn't enabled, then this causes a reference cycle and this
8350 * instance can never get freed. If UNIX is enabled we'll
8351 * handle it just fine, but there's still no point in allowing
8352 * a ring fd as it doesn't support regular read/write anyway.
8354 if (file->f_op == &io_uring_fops) {
8358 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8361 ret = io_sqe_files_scm(ctx);
8363 __io_sqe_files_unregister(ctx);
8367 io_rsrc_node_switch(ctx, NULL);
8370 for (i = 0; i < ctx->nr_user_files; i++) {
8371 file = io_file_from_index(ctx, i);
8375 io_free_file_tables(&ctx->file_table);
8376 ctx->nr_user_files = 0;
8378 io_rsrc_data_free(ctx->file_data);
8379 ctx->file_data = NULL;
8383 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8386 #if defined(CONFIG_UNIX)
8387 struct sock *sock = ctx->ring_sock->sk;
8388 struct sk_buff_head *head = &sock->sk_receive_queue;
8389 struct sk_buff *skb;
8392 * See if we can merge this file into an existing skb SCM_RIGHTS
8393 * file set. If there's no room, fall back to allocating a new skb
8394 * and filling it in.
8396 spin_lock_irq(&head->lock);
8397 skb = skb_peek(head);
8399 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8401 if (fpl->count < SCM_MAX_FD) {
8402 __skb_unlink(skb, head);
8403 spin_unlock_irq(&head->lock);
8404 fpl->fp[fpl->count] = get_file(file);
8405 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8407 spin_lock_irq(&head->lock);
8408 __skb_queue_head(head, skb);
8413 spin_unlock_irq(&head->lock);
8420 return __io_sqe_files_scm(ctx, 1, index);
8426 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8427 struct io_rsrc_node *node, void *rsrc)
8429 struct io_rsrc_put *prsrc;
8431 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8435 prsrc->tag = *io_get_tag_slot(data, idx);
8437 list_add(&prsrc->list, &node->rsrc_list);
8441 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8442 unsigned int issue_flags, u32 slot_index)
8444 struct io_ring_ctx *ctx = req->ctx;
8445 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8446 bool needs_switch = false;
8447 struct io_fixed_file *file_slot;
8450 io_ring_submit_lock(ctx, needs_lock);
8451 if (file->f_op == &io_uring_fops)
8454 if (!ctx->file_data)
8457 if (slot_index >= ctx->nr_user_files)
8460 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8461 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8463 if (file_slot->file_ptr) {
8464 struct file *old_file;
8466 ret = io_rsrc_node_switch_start(ctx);
8470 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8471 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8472 ctx->rsrc_node, old_file);
8475 file_slot->file_ptr = 0;
8476 needs_switch = true;
8479 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8480 io_fixed_file_set(file_slot, file);
8481 ret = io_sqe_file_register(ctx, file, slot_index);
8483 file_slot->file_ptr = 0;
8490 io_rsrc_node_switch(ctx, ctx->file_data);
8491 io_ring_submit_unlock(ctx, needs_lock);
8497 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8499 unsigned int offset = req->close.file_slot - 1;
8500 struct io_ring_ctx *ctx = req->ctx;
8501 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8502 struct io_fixed_file *file_slot;
8506 io_ring_submit_lock(ctx, needs_lock);
8508 if (unlikely(!ctx->file_data))
8511 if (offset >= ctx->nr_user_files)
8513 ret = io_rsrc_node_switch_start(ctx);
8517 i = array_index_nospec(offset, ctx->nr_user_files);
8518 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8520 if (!file_slot->file_ptr)
8523 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8524 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8528 file_slot->file_ptr = 0;
8529 io_rsrc_node_switch(ctx, ctx->file_data);
8532 io_ring_submit_unlock(ctx, needs_lock);
8536 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8537 struct io_uring_rsrc_update2 *up,
8540 u64 __user *tags = u64_to_user_ptr(up->tags);
8541 __s32 __user *fds = u64_to_user_ptr(up->data);
8542 struct io_rsrc_data *data = ctx->file_data;
8543 struct io_fixed_file *file_slot;
8547 bool needs_switch = false;
8549 if (!ctx->file_data)
8551 if (up->offset + nr_args > ctx->nr_user_files)
8554 for (done = 0; done < nr_args; done++) {
8557 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8558 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8562 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8566 if (fd == IORING_REGISTER_FILES_SKIP)
8569 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8570 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8572 if (file_slot->file_ptr) {
8573 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8574 err = io_queue_rsrc_removal(data, up->offset + done,
8575 ctx->rsrc_node, file);
8578 file_slot->file_ptr = 0;
8579 needs_switch = true;
8588 * Don't allow io_uring instances to be registered. If
8589 * UNIX isn't enabled, then this causes a reference
8590 * cycle and this instance can never get freed. If UNIX
8591 * is enabled we'll handle it just fine, but there's
8592 * still no point in allowing a ring fd as it doesn't
8593 * support regular read/write anyway.
8595 if (file->f_op == &io_uring_fops) {
8600 *io_get_tag_slot(data, up->offset + done) = tag;
8601 io_fixed_file_set(file_slot, file);
8602 err = io_sqe_file_register(ctx, file, i);
8604 file_slot->file_ptr = 0;
8612 io_rsrc_node_switch(ctx, data);
8613 return done ? done : err;
8616 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8617 struct task_struct *task)
8619 struct io_wq_hash *hash;
8620 struct io_wq_data data;
8621 unsigned int concurrency;
8623 mutex_lock(&ctx->uring_lock);
8624 hash = ctx->hash_map;
8626 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8628 mutex_unlock(&ctx->uring_lock);
8629 return ERR_PTR(-ENOMEM);
8631 refcount_set(&hash->refs, 1);
8632 init_waitqueue_head(&hash->wait);
8633 ctx->hash_map = hash;
8635 mutex_unlock(&ctx->uring_lock);
8639 data.free_work = io_wq_free_work;
8640 data.do_work = io_wq_submit_work;
8642 /* Do QD, or 4 * CPUS, whatever is smallest */
8643 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8645 return io_wq_create(concurrency, &data);
8648 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8649 struct io_ring_ctx *ctx)
8651 struct io_uring_task *tctx;
8654 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8655 if (unlikely(!tctx))
8658 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8659 if (unlikely(ret)) {
8664 tctx->io_wq = io_init_wq_offload(ctx, task);
8665 if (IS_ERR(tctx->io_wq)) {
8666 ret = PTR_ERR(tctx->io_wq);
8667 percpu_counter_destroy(&tctx->inflight);
8673 init_waitqueue_head(&tctx->wait);
8674 atomic_set(&tctx->in_idle, 0);
8675 atomic_set(&tctx->inflight_tracked, 0);
8676 task->io_uring = tctx;
8677 spin_lock_init(&tctx->task_lock);
8678 INIT_WQ_LIST(&tctx->task_list);
8679 init_task_work(&tctx->task_work, tctx_task_work);
8683 void __io_uring_free(struct task_struct *tsk)
8685 struct io_uring_task *tctx = tsk->io_uring;
8687 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8688 WARN_ON_ONCE(tctx->io_wq);
8689 WARN_ON_ONCE(tctx->cached_refs);
8691 percpu_counter_destroy(&tctx->inflight);
8693 tsk->io_uring = NULL;
8696 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8697 struct io_uring_params *p)
8701 /* Retain compatibility with failing for an invalid attach attempt */
8702 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8703 IORING_SETUP_ATTACH_WQ) {
8706 f = fdget(p->wq_fd);
8709 if (f.file->f_op != &io_uring_fops) {
8715 if (ctx->flags & IORING_SETUP_SQPOLL) {
8716 struct task_struct *tsk;
8717 struct io_sq_data *sqd;
8720 ret = security_uring_sqpoll();
8724 sqd = io_get_sq_data(p, &attached);
8730 ctx->sq_creds = get_current_cred();
8732 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8733 if (!ctx->sq_thread_idle)
8734 ctx->sq_thread_idle = HZ;
8736 io_sq_thread_park(sqd);
8737 list_add(&ctx->sqd_list, &sqd->ctx_list);
8738 io_sqd_update_thread_idle(sqd);
8739 /* don't attach to a dying SQPOLL thread, would be racy */
8740 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8741 io_sq_thread_unpark(sqd);
8748 if (p->flags & IORING_SETUP_SQ_AFF) {
8749 int cpu = p->sq_thread_cpu;
8752 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8759 sqd->task_pid = current->pid;
8760 sqd->task_tgid = current->tgid;
8761 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8768 ret = io_uring_alloc_task_context(tsk, ctx);
8769 wake_up_new_task(tsk);
8772 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8773 /* Can't have SQ_AFF without SQPOLL */
8780 complete(&ctx->sq_data->exited);
8782 io_sq_thread_finish(ctx);
8786 static inline void __io_unaccount_mem(struct user_struct *user,
8787 unsigned long nr_pages)
8789 atomic_long_sub(nr_pages, &user->locked_vm);
8792 static inline int __io_account_mem(struct user_struct *user,
8793 unsigned long nr_pages)
8795 unsigned long page_limit, cur_pages, new_pages;
8797 /* Don't allow more pages than we can safely lock */
8798 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8801 cur_pages = atomic_long_read(&user->locked_vm);
8802 new_pages = cur_pages + nr_pages;
8803 if (new_pages > page_limit)
8805 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8806 new_pages) != cur_pages);
8811 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8814 __io_unaccount_mem(ctx->user, nr_pages);
8816 if (ctx->mm_account)
8817 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8820 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8825 ret = __io_account_mem(ctx->user, nr_pages);
8830 if (ctx->mm_account)
8831 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8836 static void io_mem_free(void *ptr)
8843 page = virt_to_head_page(ptr);
8844 if (put_page_testzero(page))
8845 free_compound_page(page);
8848 static void *io_mem_alloc(size_t size)
8850 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8851 __GFP_NORETRY | __GFP_ACCOUNT;
8853 return (void *) __get_free_pages(gfp_flags, get_order(size));
8856 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8859 struct io_rings *rings;
8860 size_t off, sq_array_size;
8862 off = struct_size(rings, cqes, cq_entries);
8863 if (off == SIZE_MAX)
8867 off = ALIGN(off, SMP_CACHE_BYTES);
8875 sq_array_size = array_size(sizeof(u32), sq_entries);
8876 if (sq_array_size == SIZE_MAX)
8879 if (check_add_overflow(off, sq_array_size, &off))
8885 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8887 struct io_mapped_ubuf *imu = *slot;
8890 if (imu != ctx->dummy_ubuf) {
8891 for (i = 0; i < imu->nr_bvecs; i++)
8892 unpin_user_page(imu->bvec[i].bv_page);
8893 if (imu->acct_pages)
8894 io_unaccount_mem(ctx, imu->acct_pages);
8900 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8902 io_buffer_unmap(ctx, &prsrc->buf);
8906 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8910 for (i = 0; i < ctx->nr_user_bufs; i++)
8911 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8912 kfree(ctx->user_bufs);
8913 io_rsrc_data_free(ctx->buf_data);
8914 ctx->user_bufs = NULL;
8915 ctx->buf_data = NULL;
8916 ctx->nr_user_bufs = 0;
8919 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8926 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8928 __io_sqe_buffers_unregister(ctx);
8932 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8933 void __user *arg, unsigned index)
8935 struct iovec __user *src;
8937 #ifdef CONFIG_COMPAT
8939 struct compat_iovec __user *ciovs;
8940 struct compat_iovec ciov;
8942 ciovs = (struct compat_iovec __user *) arg;
8943 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8946 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8947 dst->iov_len = ciov.iov_len;
8951 src = (struct iovec __user *) arg;
8952 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8958 * Not super efficient, but this is just a registration time. And we do cache
8959 * the last compound head, so generally we'll only do a full search if we don't
8962 * We check if the given compound head page has already been accounted, to
8963 * avoid double accounting it. This allows us to account the full size of the
8964 * page, not just the constituent pages of a huge page.
8966 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8967 int nr_pages, struct page *hpage)
8971 /* check current page array */
8972 for (i = 0; i < nr_pages; i++) {
8973 if (!PageCompound(pages[i]))
8975 if (compound_head(pages[i]) == hpage)
8979 /* check previously registered pages */
8980 for (i = 0; i < ctx->nr_user_bufs; i++) {
8981 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8983 for (j = 0; j < imu->nr_bvecs; j++) {
8984 if (!PageCompound(imu->bvec[j].bv_page))
8986 if (compound_head(imu->bvec[j].bv_page) == hpage)
8994 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8995 int nr_pages, struct io_mapped_ubuf *imu,
8996 struct page **last_hpage)
9000 imu->acct_pages = 0;
9001 for (i = 0; i < nr_pages; i++) {
9002 if (!PageCompound(pages[i])) {
9007 hpage = compound_head(pages[i]);
9008 if (hpage == *last_hpage)
9010 *last_hpage = hpage;
9011 if (headpage_already_acct(ctx, pages, i, hpage))
9013 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9017 if (!imu->acct_pages)
9020 ret = io_account_mem(ctx, imu->acct_pages);
9022 imu->acct_pages = 0;
9026 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9027 struct io_mapped_ubuf **pimu,
9028 struct page **last_hpage)
9030 struct io_mapped_ubuf *imu = NULL;
9031 struct vm_area_struct **vmas = NULL;
9032 struct page **pages = NULL;
9033 unsigned long off, start, end, ubuf;
9035 int ret, pret, nr_pages, i;
9037 if (!iov->iov_base) {
9038 *pimu = ctx->dummy_ubuf;
9042 ubuf = (unsigned long) iov->iov_base;
9043 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9044 start = ubuf >> PAGE_SHIFT;
9045 nr_pages = end - start;
9050 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9054 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9059 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9064 mmap_read_lock(current->mm);
9065 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9067 if (pret == nr_pages) {
9068 /* don't support file backed memory */
9069 for (i = 0; i < nr_pages; i++) {
9070 struct vm_area_struct *vma = vmas[i];
9072 if (vma_is_shmem(vma))
9075 !is_file_hugepages(vma->vm_file)) {
9081 ret = pret < 0 ? pret : -EFAULT;
9083 mmap_read_unlock(current->mm);
9086 * if we did partial map, or found file backed vmas,
9087 * release any pages we did get
9090 unpin_user_pages(pages, pret);
9094 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9096 unpin_user_pages(pages, pret);
9100 off = ubuf & ~PAGE_MASK;
9101 size = iov->iov_len;
9102 for (i = 0; i < nr_pages; i++) {
9105 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9106 imu->bvec[i].bv_page = pages[i];
9107 imu->bvec[i].bv_len = vec_len;
9108 imu->bvec[i].bv_offset = off;
9112 /* store original address for later verification */
9114 imu->ubuf_end = ubuf + iov->iov_len;
9115 imu->nr_bvecs = nr_pages;
9126 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9128 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9129 return ctx->user_bufs ? 0 : -ENOMEM;
9132 static int io_buffer_validate(struct iovec *iov)
9134 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9137 * Don't impose further limits on the size and buffer
9138 * constraints here, we'll -EINVAL later when IO is
9139 * submitted if they are wrong.
9142 return iov->iov_len ? -EFAULT : 0;
9146 /* arbitrary limit, but we need something */
9147 if (iov->iov_len > SZ_1G)
9150 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9156 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9157 unsigned int nr_args, u64 __user *tags)
9159 struct page *last_hpage = NULL;
9160 struct io_rsrc_data *data;
9166 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9168 ret = io_rsrc_node_switch_start(ctx);
9171 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9174 ret = io_buffers_map_alloc(ctx, nr_args);
9176 io_rsrc_data_free(data);
9180 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9181 ret = io_copy_iov(ctx, &iov, arg, i);
9184 ret = io_buffer_validate(&iov);
9187 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9192 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9198 WARN_ON_ONCE(ctx->buf_data);
9200 ctx->buf_data = data;
9202 __io_sqe_buffers_unregister(ctx);
9204 io_rsrc_node_switch(ctx, NULL);
9208 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9209 struct io_uring_rsrc_update2 *up,
9210 unsigned int nr_args)
9212 u64 __user *tags = u64_to_user_ptr(up->tags);
9213 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9214 struct page *last_hpage = NULL;
9215 bool needs_switch = false;
9221 if (up->offset + nr_args > ctx->nr_user_bufs)
9224 for (done = 0; done < nr_args; done++) {
9225 struct io_mapped_ubuf *imu;
9226 int offset = up->offset + done;
9229 err = io_copy_iov(ctx, &iov, iovs, done);
9232 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9236 err = io_buffer_validate(&iov);
9239 if (!iov.iov_base && tag) {
9243 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9247 i = array_index_nospec(offset, ctx->nr_user_bufs);
9248 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9249 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9250 ctx->rsrc_node, ctx->user_bufs[i]);
9251 if (unlikely(err)) {
9252 io_buffer_unmap(ctx, &imu);
9255 ctx->user_bufs[i] = NULL;
9256 needs_switch = true;
9259 ctx->user_bufs[i] = imu;
9260 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9264 io_rsrc_node_switch(ctx, ctx->buf_data);
9265 return done ? done : err;
9268 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9270 __s32 __user *fds = arg;
9276 if (copy_from_user(&fd, fds, sizeof(*fds)))
9279 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9280 if (IS_ERR(ctx->cq_ev_fd)) {
9281 int ret = PTR_ERR(ctx->cq_ev_fd);
9283 ctx->cq_ev_fd = NULL;
9290 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9292 if (ctx->cq_ev_fd) {
9293 eventfd_ctx_put(ctx->cq_ev_fd);
9294 ctx->cq_ev_fd = NULL;
9301 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9303 struct io_buffer *buf;
9304 unsigned long index;
9306 xa_for_each(&ctx->io_buffers, index, buf)
9307 __io_remove_buffers(ctx, buf, index, -1U);
9310 static void io_req_caches_free(struct io_ring_ctx *ctx)
9312 struct io_submit_state *state = &ctx->submit_state;
9315 mutex_lock(&ctx->uring_lock);
9316 io_flush_cached_locked_reqs(ctx, state);
9318 while (state->free_list.next) {
9319 struct io_wq_work_node *node;
9320 struct io_kiocb *req;
9322 node = wq_stack_extract(&state->free_list);
9323 req = container_of(node, struct io_kiocb, comp_list);
9324 kmem_cache_free(req_cachep, req);
9328 percpu_ref_put_many(&ctx->refs, nr);
9329 mutex_unlock(&ctx->uring_lock);
9332 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9334 if (data && !atomic_dec_and_test(&data->refs))
9335 wait_for_completion(&data->done);
9338 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9340 io_sq_thread_finish(ctx);
9342 if (ctx->mm_account) {
9343 mmdrop(ctx->mm_account);
9344 ctx->mm_account = NULL;
9347 io_rsrc_refs_drop(ctx);
9348 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9349 io_wait_rsrc_data(ctx->buf_data);
9350 io_wait_rsrc_data(ctx->file_data);
9352 mutex_lock(&ctx->uring_lock);
9354 __io_sqe_buffers_unregister(ctx);
9356 __io_sqe_files_unregister(ctx);
9358 __io_cqring_overflow_flush(ctx, true);
9359 mutex_unlock(&ctx->uring_lock);
9360 io_eventfd_unregister(ctx);
9361 io_destroy_buffers(ctx);
9363 put_cred(ctx->sq_creds);
9365 /* there are no registered resources left, nobody uses it */
9367 io_rsrc_node_destroy(ctx->rsrc_node);
9368 if (ctx->rsrc_backup_node)
9369 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9370 flush_delayed_work(&ctx->rsrc_put_work);
9371 flush_delayed_work(&ctx->fallback_work);
9373 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9374 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9376 #if defined(CONFIG_UNIX)
9377 if (ctx->ring_sock) {
9378 ctx->ring_sock->file = NULL; /* so that iput() is called */
9379 sock_release(ctx->ring_sock);
9382 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9384 io_mem_free(ctx->rings);
9385 io_mem_free(ctx->sq_sqes);
9387 percpu_ref_exit(&ctx->refs);
9388 free_uid(ctx->user);
9389 io_req_caches_free(ctx);
9391 io_wq_put_hash(ctx->hash_map);
9392 kfree(ctx->cancel_hash);
9393 kfree(ctx->dummy_ubuf);
9397 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9399 struct io_ring_ctx *ctx = file->private_data;
9402 poll_wait(file, &ctx->cq_wait, wait);
9404 * synchronizes with barrier from wq_has_sleeper call in
9408 if (!io_sqring_full(ctx))
9409 mask |= EPOLLOUT | EPOLLWRNORM;
9412 * Don't flush cqring overflow list here, just do a simple check.
9413 * Otherwise there could possible be ABBA deadlock:
9416 * lock(&ctx->uring_lock);
9418 * lock(&ctx->uring_lock);
9421 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9422 * pushs them to do the flush.
9424 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9425 mask |= EPOLLIN | EPOLLRDNORM;
9430 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9432 const struct cred *creds;
9434 creds = xa_erase(&ctx->personalities, id);
9443 struct io_tctx_exit {
9444 struct callback_head task_work;
9445 struct completion completion;
9446 struct io_ring_ctx *ctx;
9449 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9451 struct io_uring_task *tctx = current->io_uring;
9452 struct io_tctx_exit *work;
9454 work = container_of(cb, struct io_tctx_exit, task_work);
9456 * When @in_idle, we're in cancellation and it's racy to remove the
9457 * node. It'll be removed by the end of cancellation, just ignore it.
9459 if (!atomic_read(&tctx->in_idle))
9460 io_uring_del_tctx_node((unsigned long)work->ctx);
9461 complete(&work->completion);
9464 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9466 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9468 return req->ctx == data;
9471 static __cold void io_ring_exit_work(struct work_struct *work)
9473 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9474 unsigned long timeout = jiffies + HZ * 60 * 5;
9475 unsigned long interval = HZ / 20;
9476 struct io_tctx_exit exit;
9477 struct io_tctx_node *node;
9481 * If we're doing polled IO and end up having requests being
9482 * submitted async (out-of-line), then completions can come in while
9483 * we're waiting for refs to drop. We need to reap these manually,
9484 * as nobody else will be looking for them.
9487 io_uring_try_cancel_requests(ctx, NULL, true);
9489 struct io_sq_data *sqd = ctx->sq_data;
9490 struct task_struct *tsk;
9492 io_sq_thread_park(sqd);
9494 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9495 io_wq_cancel_cb(tsk->io_uring->io_wq,
9496 io_cancel_ctx_cb, ctx, true);
9497 io_sq_thread_unpark(sqd);
9500 io_req_caches_free(ctx);
9502 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9503 /* there is little hope left, don't run it too often */
9506 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9508 init_completion(&exit.completion);
9509 init_task_work(&exit.task_work, io_tctx_exit_cb);
9512 * Some may use context even when all refs and requests have been put,
9513 * and they are free to do so while still holding uring_lock or
9514 * completion_lock, see io_req_task_submit(). Apart from other work,
9515 * this lock/unlock section also waits them to finish.
9517 mutex_lock(&ctx->uring_lock);
9518 while (!list_empty(&ctx->tctx_list)) {
9519 WARN_ON_ONCE(time_after(jiffies, timeout));
9521 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9523 /* don't spin on a single task if cancellation failed */
9524 list_rotate_left(&ctx->tctx_list);
9525 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9526 if (WARN_ON_ONCE(ret))
9529 mutex_unlock(&ctx->uring_lock);
9530 wait_for_completion(&exit.completion);
9531 mutex_lock(&ctx->uring_lock);
9533 mutex_unlock(&ctx->uring_lock);
9534 spin_lock(&ctx->completion_lock);
9535 spin_unlock(&ctx->completion_lock);
9537 io_ring_ctx_free(ctx);
9540 /* Returns true if we found and killed one or more timeouts */
9541 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9542 struct task_struct *tsk, bool cancel_all)
9544 struct io_kiocb *req, *tmp;
9547 spin_lock(&ctx->completion_lock);
9548 spin_lock_irq(&ctx->timeout_lock);
9549 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9550 if (io_match_task(req, tsk, cancel_all)) {
9551 io_kill_timeout(req, -ECANCELED);
9555 spin_unlock_irq(&ctx->timeout_lock);
9557 io_commit_cqring(ctx);
9558 spin_unlock(&ctx->completion_lock);
9560 io_cqring_ev_posted(ctx);
9561 return canceled != 0;
9564 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9566 unsigned long index;
9567 struct creds *creds;
9569 mutex_lock(&ctx->uring_lock);
9570 percpu_ref_kill(&ctx->refs);
9572 __io_cqring_overflow_flush(ctx, true);
9573 xa_for_each(&ctx->personalities, index, creds)
9574 io_unregister_personality(ctx, index);
9575 mutex_unlock(&ctx->uring_lock);
9577 io_kill_timeouts(ctx, NULL, true);
9578 io_poll_remove_all(ctx, NULL, true);
9580 /* if we failed setting up the ctx, we might not have any rings */
9581 io_iopoll_try_reap_events(ctx);
9583 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9585 * Use system_unbound_wq to avoid spawning tons of event kworkers
9586 * if we're exiting a ton of rings at the same time. It just adds
9587 * noise and overhead, there's no discernable change in runtime
9588 * over using system_wq.
9590 queue_work(system_unbound_wq, &ctx->exit_work);
9593 static int io_uring_release(struct inode *inode, struct file *file)
9595 struct io_ring_ctx *ctx = file->private_data;
9597 file->private_data = NULL;
9598 io_ring_ctx_wait_and_kill(ctx);
9602 struct io_task_cancel {
9603 struct task_struct *task;
9607 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9609 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9610 struct io_task_cancel *cancel = data;
9612 return io_match_task_safe(req, cancel->task, cancel->all);
9615 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9616 struct task_struct *task,
9619 struct io_defer_entry *de;
9622 spin_lock(&ctx->completion_lock);
9623 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9624 if (io_match_task_safe(de->req, task, cancel_all)) {
9625 list_cut_position(&list, &ctx->defer_list, &de->list);
9629 spin_unlock(&ctx->completion_lock);
9630 if (list_empty(&list))
9633 while (!list_empty(&list)) {
9634 de = list_first_entry(&list, struct io_defer_entry, list);
9635 list_del_init(&de->list);
9636 io_req_complete_failed(de->req, -ECANCELED);
9642 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9644 struct io_tctx_node *node;
9645 enum io_wq_cancel cret;
9648 mutex_lock(&ctx->uring_lock);
9649 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9650 struct io_uring_task *tctx = node->task->io_uring;
9653 * io_wq will stay alive while we hold uring_lock, because it's
9654 * killed after ctx nodes, which requires to take the lock.
9656 if (!tctx || !tctx->io_wq)
9658 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9659 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9661 mutex_unlock(&ctx->uring_lock);
9666 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9667 struct task_struct *task,
9670 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9671 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9674 enum io_wq_cancel cret;
9678 ret |= io_uring_try_cancel_iowq(ctx);
9679 } else if (tctx && tctx->io_wq) {
9681 * Cancels requests of all rings, not only @ctx, but
9682 * it's fine as the task is in exit/exec.
9684 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9686 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9689 /* SQPOLL thread does its own polling */
9690 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9691 (ctx->sq_data && ctx->sq_data->thread == current)) {
9692 while (!wq_list_empty(&ctx->iopoll_list)) {
9693 io_iopoll_try_reap_events(ctx);
9698 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9699 ret |= io_poll_remove_all(ctx, task, cancel_all);
9700 ret |= io_kill_timeouts(ctx, task, cancel_all);
9702 ret |= io_run_task_work();
9709 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9711 struct io_uring_task *tctx = current->io_uring;
9712 struct io_tctx_node *node;
9715 if (unlikely(!tctx)) {
9716 ret = io_uring_alloc_task_context(current, ctx);
9720 tctx = current->io_uring;
9721 if (ctx->iowq_limits_set) {
9722 unsigned int limits[2] = { ctx->iowq_limits[0],
9723 ctx->iowq_limits[1], };
9725 ret = io_wq_max_workers(tctx->io_wq, limits);
9730 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9731 node = kmalloc(sizeof(*node), GFP_KERNEL);
9735 node->task = current;
9737 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9744 mutex_lock(&ctx->uring_lock);
9745 list_add(&node->ctx_node, &ctx->tctx_list);
9746 mutex_unlock(&ctx->uring_lock);
9753 * Note that this task has used io_uring. We use it for cancelation purposes.
9755 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9757 struct io_uring_task *tctx = current->io_uring;
9759 if (likely(tctx && tctx->last == ctx))
9761 return __io_uring_add_tctx_node(ctx);
9765 * Remove this io_uring_file -> task mapping.
9767 static __cold void io_uring_del_tctx_node(unsigned long index)
9769 struct io_uring_task *tctx = current->io_uring;
9770 struct io_tctx_node *node;
9774 node = xa_erase(&tctx->xa, index);
9778 WARN_ON_ONCE(current != node->task);
9779 WARN_ON_ONCE(list_empty(&node->ctx_node));
9781 mutex_lock(&node->ctx->uring_lock);
9782 list_del(&node->ctx_node);
9783 mutex_unlock(&node->ctx->uring_lock);
9785 if (tctx->last == node->ctx)
9790 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9792 struct io_wq *wq = tctx->io_wq;
9793 struct io_tctx_node *node;
9794 unsigned long index;
9796 xa_for_each(&tctx->xa, index, node) {
9797 io_uring_del_tctx_node(index);
9802 * Must be after io_uring_del_tctx_node() (removes nodes under
9803 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9805 io_wq_put_and_exit(wq);
9810 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9813 return atomic_read(&tctx->inflight_tracked);
9814 return percpu_counter_sum(&tctx->inflight);
9817 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
9819 struct io_uring_task *tctx = task->io_uring;
9820 unsigned int refs = tctx->cached_refs;
9823 tctx->cached_refs = 0;
9824 percpu_counter_sub(&tctx->inflight, refs);
9825 put_task_struct_many(task, refs);
9830 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9831 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9833 static __cold void io_uring_cancel_generic(bool cancel_all,
9834 struct io_sq_data *sqd)
9836 struct io_uring_task *tctx = current->io_uring;
9837 struct io_ring_ctx *ctx;
9841 WARN_ON_ONCE(sqd && sqd->thread != current);
9843 if (!current->io_uring)
9846 io_wq_exit_start(tctx->io_wq);
9848 atomic_inc(&tctx->in_idle);
9850 io_uring_drop_tctx_refs(current);
9851 /* read completions before cancelations */
9852 inflight = tctx_inflight(tctx, !cancel_all);
9857 struct io_tctx_node *node;
9858 unsigned long index;
9860 xa_for_each(&tctx->xa, index, node) {
9861 /* sqpoll task will cancel all its requests */
9862 if (node->ctx->sq_data)
9864 io_uring_try_cancel_requests(node->ctx, current,
9868 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9869 io_uring_try_cancel_requests(ctx, current,
9873 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9875 io_uring_drop_tctx_refs(current);
9878 * If we've seen completions, retry without waiting. This
9879 * avoids a race where a completion comes in before we did
9880 * prepare_to_wait().
9882 if (inflight == tctx_inflight(tctx, !cancel_all))
9884 finish_wait(&tctx->wait, &wait);
9886 atomic_dec(&tctx->in_idle);
9888 io_uring_clean_tctx(tctx);
9890 /* for exec all current's requests should be gone, kill tctx */
9891 __io_uring_free(current);
9895 void __io_uring_cancel(bool cancel_all)
9897 io_uring_cancel_generic(cancel_all, NULL);
9900 static void *io_uring_validate_mmap_request(struct file *file,
9901 loff_t pgoff, size_t sz)
9903 struct io_ring_ctx *ctx = file->private_data;
9904 loff_t offset = pgoff << PAGE_SHIFT;
9909 case IORING_OFF_SQ_RING:
9910 case IORING_OFF_CQ_RING:
9913 case IORING_OFF_SQES:
9917 return ERR_PTR(-EINVAL);
9920 page = virt_to_head_page(ptr);
9921 if (sz > page_size(page))
9922 return ERR_PTR(-EINVAL);
9929 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9931 size_t sz = vma->vm_end - vma->vm_start;
9935 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9937 return PTR_ERR(ptr);
9939 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9940 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9943 #else /* !CONFIG_MMU */
9945 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9947 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9950 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9952 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9955 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9956 unsigned long addr, unsigned long len,
9957 unsigned long pgoff, unsigned long flags)
9961 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9963 return PTR_ERR(ptr);
9965 return (unsigned long) ptr;
9968 #endif /* !CONFIG_MMU */
9970 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9975 if (!io_sqring_full(ctx))
9977 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9979 if (!io_sqring_full(ctx))
9982 } while (!signal_pending(current));
9984 finish_wait(&ctx->sqo_sq_wait, &wait);
9988 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9989 struct __kernel_timespec __user **ts,
9990 const sigset_t __user **sig)
9992 struct io_uring_getevents_arg arg;
9995 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9996 * is just a pointer to the sigset_t.
9998 if (!(flags & IORING_ENTER_EXT_ARG)) {
9999 *sig = (const sigset_t __user *) argp;
10005 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10006 * timespec and sigset_t pointers if good.
10008 if (*argsz != sizeof(arg))
10010 if (copy_from_user(&arg, argp, sizeof(arg)))
10012 *sig = u64_to_user_ptr(arg.sigmask);
10013 *argsz = arg.sigmask_sz;
10014 *ts = u64_to_user_ptr(arg.ts);
10018 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10019 u32, min_complete, u32, flags, const void __user *, argp,
10022 struct io_ring_ctx *ctx;
10027 io_run_task_work();
10029 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10030 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10034 if (unlikely(!f.file))
10038 if (unlikely(f.file->f_op != &io_uring_fops))
10042 ctx = f.file->private_data;
10043 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10047 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10051 * For SQ polling, the thread will do all submissions and completions.
10052 * Just return the requested submit count, and wake the thread if
10053 * we were asked to.
10056 if (ctx->flags & IORING_SETUP_SQPOLL) {
10057 io_cqring_overflow_flush(ctx);
10059 if (unlikely(ctx->sq_data->thread == NULL)) {
10063 if (flags & IORING_ENTER_SQ_WAKEUP)
10064 wake_up(&ctx->sq_data->wait);
10065 if (flags & IORING_ENTER_SQ_WAIT) {
10066 ret = io_sqpoll_wait_sq(ctx);
10070 submitted = to_submit;
10071 } else if (to_submit) {
10072 ret = io_uring_add_tctx_node(ctx);
10075 mutex_lock(&ctx->uring_lock);
10076 submitted = io_submit_sqes(ctx, to_submit);
10077 mutex_unlock(&ctx->uring_lock);
10079 if (submitted != to_submit)
10082 if (flags & IORING_ENTER_GETEVENTS) {
10083 const sigset_t __user *sig;
10084 struct __kernel_timespec __user *ts;
10086 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10090 min_complete = min(min_complete, ctx->cq_entries);
10093 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10094 * space applications don't need to do io completion events
10095 * polling again, they can rely on io_sq_thread to do polling
10096 * work, which can reduce cpu usage and uring_lock contention.
10098 if (ctx->flags & IORING_SETUP_IOPOLL &&
10099 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10100 ret = io_iopoll_check(ctx, min_complete);
10102 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10107 percpu_ref_put(&ctx->refs);
10110 return submitted ? submitted : ret;
10113 #ifdef CONFIG_PROC_FS
10114 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10115 const struct cred *cred)
10117 struct user_namespace *uns = seq_user_ns(m);
10118 struct group_info *gi;
10123 seq_printf(m, "%5d\n", id);
10124 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10125 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10126 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10127 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10128 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10129 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10130 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10131 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10132 seq_puts(m, "\n\tGroups:\t");
10133 gi = cred->group_info;
10134 for (g = 0; g < gi->ngroups; g++) {
10135 seq_put_decimal_ull(m, g ? " " : "",
10136 from_kgid_munged(uns, gi->gid[g]));
10138 seq_puts(m, "\n\tCapEff:\t");
10139 cap = cred->cap_effective;
10140 CAP_FOR_EACH_U32(__capi)
10141 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10146 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10147 struct seq_file *m)
10149 struct io_sq_data *sq = NULL;
10150 struct io_overflow_cqe *ocqe;
10151 struct io_rings *r = ctx->rings;
10152 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10153 unsigned int sq_head = READ_ONCE(r->sq.head);
10154 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10155 unsigned int cq_head = READ_ONCE(r->cq.head);
10156 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10157 unsigned int sq_entries, cq_entries;
10162 * we may get imprecise sqe and cqe info if uring is actively running
10163 * since we get cached_sq_head and cached_cq_tail without uring_lock
10164 * and sq_tail and cq_head are changed by userspace. But it's ok since
10165 * we usually use these info when it is stuck.
10167 seq_printf(m, "SqMask:\t\t0x%x\n", sq_mask);
10168 seq_printf(m, "SqHead:\t%u\n", sq_head);
10169 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10170 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10171 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10172 seq_printf(m, "CqHead:\t%u\n", cq_head);
10173 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10174 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10175 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10176 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10177 for (i = 0; i < sq_entries; i++) {
10178 unsigned int entry = i + sq_head;
10179 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10180 struct io_uring_sqe *sqe;
10182 if (sq_idx > sq_mask)
10184 sqe = &ctx->sq_sqes[sq_idx];
10185 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10186 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10189 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10190 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10191 for (i = 0; i < cq_entries; i++) {
10192 unsigned int entry = i + cq_head;
10193 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10195 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10196 entry & cq_mask, cqe->user_data, cqe->res,
10201 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10202 * since fdinfo case grabs it in the opposite direction of normal use
10203 * cases. If we fail to get the lock, we just don't iterate any
10204 * structures that could be going away outside the io_uring mutex.
10206 has_lock = mutex_trylock(&ctx->uring_lock);
10208 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10214 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10215 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10216 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10217 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10218 struct file *f = io_file_from_index(ctx, i);
10221 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10223 seq_printf(m, "%5u: <none>\n", i);
10225 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10226 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10227 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10228 unsigned int len = buf->ubuf_end - buf->ubuf;
10230 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10232 if (has_lock && !xa_empty(&ctx->personalities)) {
10233 unsigned long index;
10234 const struct cred *cred;
10236 seq_printf(m, "Personalities:\n");
10237 xa_for_each(&ctx->personalities, index, cred)
10238 io_uring_show_cred(m, index, cred);
10241 mutex_unlock(&ctx->uring_lock);
10243 seq_puts(m, "PollList:\n");
10244 spin_lock(&ctx->completion_lock);
10245 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10246 struct hlist_head *list = &ctx->cancel_hash[i];
10247 struct io_kiocb *req;
10249 hlist_for_each_entry(req, list, hash_node)
10250 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10251 req->task->task_works != NULL);
10254 seq_puts(m, "CqOverflowList:\n");
10255 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10256 struct io_uring_cqe *cqe = &ocqe->cqe;
10258 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10259 cqe->user_data, cqe->res, cqe->flags);
10263 spin_unlock(&ctx->completion_lock);
10266 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10268 struct io_ring_ctx *ctx = f->private_data;
10270 if (percpu_ref_tryget(&ctx->refs)) {
10271 __io_uring_show_fdinfo(ctx, m);
10272 percpu_ref_put(&ctx->refs);
10277 static const struct file_operations io_uring_fops = {
10278 .release = io_uring_release,
10279 .mmap = io_uring_mmap,
10281 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10282 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10284 .poll = io_uring_poll,
10285 #ifdef CONFIG_PROC_FS
10286 .show_fdinfo = io_uring_show_fdinfo,
10290 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10291 struct io_uring_params *p)
10293 struct io_rings *rings;
10294 size_t size, sq_array_offset;
10296 /* make sure these are sane, as we already accounted them */
10297 ctx->sq_entries = p->sq_entries;
10298 ctx->cq_entries = p->cq_entries;
10300 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10301 if (size == SIZE_MAX)
10304 rings = io_mem_alloc(size);
10308 ctx->rings = rings;
10309 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10310 rings->sq_ring_mask = p->sq_entries - 1;
10311 rings->cq_ring_mask = p->cq_entries - 1;
10312 rings->sq_ring_entries = p->sq_entries;
10313 rings->cq_ring_entries = p->cq_entries;
10315 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10316 if (size == SIZE_MAX) {
10317 io_mem_free(ctx->rings);
10322 ctx->sq_sqes = io_mem_alloc(size);
10323 if (!ctx->sq_sqes) {
10324 io_mem_free(ctx->rings);
10332 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10336 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10340 ret = io_uring_add_tctx_node(ctx);
10345 fd_install(fd, file);
10350 * Allocate an anonymous fd, this is what constitutes the application
10351 * visible backing of an io_uring instance. The application mmaps this
10352 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10353 * we have to tie this fd to a socket for file garbage collection purposes.
10355 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10358 #if defined(CONFIG_UNIX)
10361 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10364 return ERR_PTR(ret);
10367 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10368 O_RDWR | O_CLOEXEC, NULL);
10369 #if defined(CONFIG_UNIX)
10370 if (IS_ERR(file)) {
10371 sock_release(ctx->ring_sock);
10372 ctx->ring_sock = NULL;
10374 ctx->ring_sock->file = file;
10380 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10381 struct io_uring_params __user *params)
10383 struct io_ring_ctx *ctx;
10389 if (entries > IORING_MAX_ENTRIES) {
10390 if (!(p->flags & IORING_SETUP_CLAMP))
10392 entries = IORING_MAX_ENTRIES;
10396 * Use twice as many entries for the CQ ring. It's possible for the
10397 * application to drive a higher depth than the size of the SQ ring,
10398 * since the sqes are only used at submission time. This allows for
10399 * some flexibility in overcommitting a bit. If the application has
10400 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10401 * of CQ ring entries manually.
10403 p->sq_entries = roundup_pow_of_two(entries);
10404 if (p->flags & IORING_SETUP_CQSIZE) {
10406 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10407 * to a power-of-two, if it isn't already. We do NOT impose
10408 * any cq vs sq ring sizing.
10410 if (!p->cq_entries)
10412 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10413 if (!(p->flags & IORING_SETUP_CLAMP))
10415 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10417 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10418 if (p->cq_entries < p->sq_entries)
10421 p->cq_entries = 2 * p->sq_entries;
10424 ctx = io_ring_ctx_alloc(p);
10427 ctx->compat = in_compat_syscall();
10428 if (!capable(CAP_IPC_LOCK))
10429 ctx->user = get_uid(current_user());
10432 * This is just grabbed for accounting purposes. When a process exits,
10433 * the mm is exited and dropped before the files, hence we need to hang
10434 * on to this mm purely for the purposes of being able to unaccount
10435 * memory (locked/pinned vm). It's not used for anything else.
10437 mmgrab(current->mm);
10438 ctx->mm_account = current->mm;
10440 ret = io_allocate_scq_urings(ctx, p);
10444 ret = io_sq_offload_create(ctx, p);
10447 /* always set a rsrc node */
10448 ret = io_rsrc_node_switch_start(ctx);
10451 io_rsrc_node_switch(ctx, NULL);
10453 memset(&p->sq_off, 0, sizeof(p->sq_off));
10454 p->sq_off.head = offsetof(struct io_rings, sq.head);
10455 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10456 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10457 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10458 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10459 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10460 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10462 memset(&p->cq_off, 0, sizeof(p->cq_off));
10463 p->cq_off.head = offsetof(struct io_rings, cq.head);
10464 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10465 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10466 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10467 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10468 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10469 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10471 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10472 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10473 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10474 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10475 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10476 IORING_FEAT_RSRC_TAGS;
10478 if (copy_to_user(params, p, sizeof(*p))) {
10483 file = io_uring_get_file(ctx);
10484 if (IS_ERR(file)) {
10485 ret = PTR_ERR(file);
10490 * Install ring fd as the very last thing, so we don't risk someone
10491 * having closed it before we finish setup
10493 ret = io_uring_install_fd(ctx, file);
10495 /* fput will clean it up */
10500 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10503 io_ring_ctx_wait_and_kill(ctx);
10508 * Sets up an aio uring context, and returns the fd. Applications asks for a
10509 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10510 * params structure passed in.
10512 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10514 struct io_uring_params p;
10517 if (copy_from_user(&p, params, sizeof(p)))
10519 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10524 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10525 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10526 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10527 IORING_SETUP_R_DISABLED))
10530 return io_uring_create(entries, &p, params);
10533 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10534 struct io_uring_params __user *, params)
10536 return io_uring_setup(entries, params);
10539 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10542 struct io_uring_probe *p;
10546 size = struct_size(p, ops, nr_args);
10547 if (size == SIZE_MAX)
10549 p = kzalloc(size, GFP_KERNEL);
10554 if (copy_from_user(p, arg, size))
10557 if (memchr_inv(p, 0, size))
10560 p->last_op = IORING_OP_LAST - 1;
10561 if (nr_args > IORING_OP_LAST)
10562 nr_args = IORING_OP_LAST;
10564 for (i = 0; i < nr_args; i++) {
10566 if (!io_op_defs[i].not_supported)
10567 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10572 if (copy_to_user(arg, p, size))
10579 static int io_register_personality(struct io_ring_ctx *ctx)
10581 const struct cred *creds;
10585 creds = get_current_cred();
10587 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10588 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10596 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10597 void __user *arg, unsigned int nr_args)
10599 struct io_uring_restriction *res;
10603 /* Restrictions allowed only if rings started disabled */
10604 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10607 /* We allow only a single restrictions registration */
10608 if (ctx->restrictions.registered)
10611 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10614 size = array_size(nr_args, sizeof(*res));
10615 if (size == SIZE_MAX)
10618 res = memdup_user(arg, size);
10620 return PTR_ERR(res);
10624 for (i = 0; i < nr_args; i++) {
10625 switch (res[i].opcode) {
10626 case IORING_RESTRICTION_REGISTER_OP:
10627 if (res[i].register_op >= IORING_REGISTER_LAST) {
10632 __set_bit(res[i].register_op,
10633 ctx->restrictions.register_op);
10635 case IORING_RESTRICTION_SQE_OP:
10636 if (res[i].sqe_op >= IORING_OP_LAST) {
10641 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10643 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10644 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10646 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10647 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10656 /* Reset all restrictions if an error happened */
10658 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10660 ctx->restrictions.registered = true;
10666 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10668 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10671 if (ctx->restrictions.registered)
10672 ctx->restricted = 1;
10674 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10675 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10676 wake_up(&ctx->sq_data->wait);
10680 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10681 struct io_uring_rsrc_update2 *up,
10689 if (check_add_overflow(up->offset, nr_args, &tmp))
10691 err = io_rsrc_node_switch_start(ctx);
10696 case IORING_RSRC_FILE:
10697 return __io_sqe_files_update(ctx, up, nr_args);
10698 case IORING_RSRC_BUFFER:
10699 return __io_sqe_buffers_update(ctx, up, nr_args);
10704 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10707 struct io_uring_rsrc_update2 up;
10711 memset(&up, 0, sizeof(up));
10712 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10714 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10717 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10718 unsigned size, unsigned type)
10720 struct io_uring_rsrc_update2 up;
10722 if (size != sizeof(up))
10724 if (copy_from_user(&up, arg, sizeof(up)))
10726 if (!up.nr || up.resv)
10728 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10731 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10732 unsigned int size, unsigned int type)
10734 struct io_uring_rsrc_register rr;
10736 /* keep it extendible */
10737 if (size != sizeof(rr))
10740 memset(&rr, 0, sizeof(rr));
10741 if (copy_from_user(&rr, arg, size))
10743 if (!rr.nr || rr.resv || rr.resv2)
10747 case IORING_RSRC_FILE:
10748 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10749 rr.nr, u64_to_user_ptr(rr.tags));
10750 case IORING_RSRC_BUFFER:
10751 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10752 rr.nr, u64_to_user_ptr(rr.tags));
10757 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
10758 void __user *arg, unsigned len)
10760 struct io_uring_task *tctx = current->io_uring;
10761 cpumask_var_t new_mask;
10764 if (!tctx || !tctx->io_wq)
10767 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10770 cpumask_clear(new_mask);
10771 if (len > cpumask_size())
10772 len = cpumask_size();
10774 if (copy_from_user(new_mask, arg, len)) {
10775 free_cpumask_var(new_mask);
10779 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10780 free_cpumask_var(new_mask);
10784 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10786 struct io_uring_task *tctx = current->io_uring;
10788 if (!tctx || !tctx->io_wq)
10791 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10794 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10796 __must_hold(&ctx->uring_lock)
10798 struct io_tctx_node *node;
10799 struct io_uring_task *tctx = NULL;
10800 struct io_sq_data *sqd = NULL;
10801 __u32 new_count[2];
10804 if (copy_from_user(new_count, arg, sizeof(new_count)))
10806 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10807 if (new_count[i] > INT_MAX)
10810 if (ctx->flags & IORING_SETUP_SQPOLL) {
10811 sqd = ctx->sq_data;
10814 * Observe the correct sqd->lock -> ctx->uring_lock
10815 * ordering. Fine to drop uring_lock here, we hold
10816 * a ref to the ctx.
10818 refcount_inc(&sqd->refs);
10819 mutex_unlock(&ctx->uring_lock);
10820 mutex_lock(&sqd->lock);
10821 mutex_lock(&ctx->uring_lock);
10823 tctx = sqd->thread->io_uring;
10826 tctx = current->io_uring;
10829 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10831 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10833 ctx->iowq_limits[i] = new_count[i];
10834 ctx->iowq_limits_set = true;
10836 if (tctx && tctx->io_wq) {
10837 ret = io_wq_max_workers(tctx->io_wq, new_count);
10841 memset(new_count, 0, sizeof(new_count));
10845 mutex_unlock(&sqd->lock);
10846 io_put_sq_data(sqd);
10849 if (copy_to_user(arg, new_count, sizeof(new_count)))
10852 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10856 /* now propagate the restriction to all registered users */
10857 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10858 struct io_uring_task *tctx = node->task->io_uring;
10860 if (WARN_ON_ONCE(!tctx->io_wq))
10863 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10864 new_count[i] = ctx->iowq_limits[i];
10865 /* ignore errors, it always returns zero anyway */
10866 (void)io_wq_max_workers(tctx->io_wq, new_count);
10871 mutex_unlock(&sqd->lock);
10872 io_put_sq_data(sqd);
10877 static bool io_register_op_must_quiesce(int op)
10880 case IORING_REGISTER_BUFFERS:
10881 case IORING_UNREGISTER_BUFFERS:
10882 case IORING_REGISTER_FILES:
10883 case IORING_UNREGISTER_FILES:
10884 case IORING_REGISTER_FILES_UPDATE:
10885 case IORING_REGISTER_PROBE:
10886 case IORING_REGISTER_PERSONALITY:
10887 case IORING_UNREGISTER_PERSONALITY:
10888 case IORING_REGISTER_FILES2:
10889 case IORING_REGISTER_FILES_UPDATE2:
10890 case IORING_REGISTER_BUFFERS2:
10891 case IORING_REGISTER_BUFFERS_UPDATE:
10892 case IORING_REGISTER_IOWQ_AFF:
10893 case IORING_UNREGISTER_IOWQ_AFF:
10894 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10901 static __cold int io_ctx_quiesce(struct io_ring_ctx *ctx)
10905 percpu_ref_kill(&ctx->refs);
10908 * Drop uring mutex before waiting for references to exit. If another
10909 * thread is currently inside io_uring_enter() it might need to grab the
10910 * uring_lock to make progress. If we hold it here across the drain
10911 * wait, then we can deadlock. It's safe to drop the mutex here, since
10912 * no new references will come in after we've killed the percpu ref.
10914 mutex_unlock(&ctx->uring_lock);
10916 ret = wait_for_completion_interruptible_timeout(&ctx->ref_comp, HZ);
10918 ret = min(0L, ret);
10922 ret = io_run_task_work_sig();
10923 io_req_caches_free(ctx);
10924 } while (ret >= 0);
10925 mutex_lock(&ctx->uring_lock);
10928 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10932 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10933 void __user *arg, unsigned nr_args)
10934 __releases(ctx->uring_lock)
10935 __acquires(ctx->uring_lock)
10940 * We're inside the ring mutex, if the ref is already dying, then
10941 * someone else killed the ctx or is already going through
10942 * io_uring_register().
10944 if (percpu_ref_is_dying(&ctx->refs))
10947 if (ctx->restricted) {
10948 if (opcode >= IORING_REGISTER_LAST)
10950 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10951 if (!test_bit(opcode, ctx->restrictions.register_op))
10955 if (io_register_op_must_quiesce(opcode)) {
10956 ret = io_ctx_quiesce(ctx);
10962 case IORING_REGISTER_BUFFERS:
10963 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10965 case IORING_UNREGISTER_BUFFERS:
10967 if (arg || nr_args)
10969 ret = io_sqe_buffers_unregister(ctx);
10971 case IORING_REGISTER_FILES:
10972 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10974 case IORING_UNREGISTER_FILES:
10976 if (arg || nr_args)
10978 ret = io_sqe_files_unregister(ctx);
10980 case IORING_REGISTER_FILES_UPDATE:
10981 ret = io_register_files_update(ctx, arg, nr_args);
10983 case IORING_REGISTER_EVENTFD:
10984 case IORING_REGISTER_EVENTFD_ASYNC:
10988 ret = io_eventfd_register(ctx, arg);
10991 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10992 ctx->eventfd_async = 1;
10994 ctx->eventfd_async = 0;
10996 case IORING_UNREGISTER_EVENTFD:
10998 if (arg || nr_args)
11000 ret = io_eventfd_unregister(ctx);
11002 case IORING_REGISTER_PROBE:
11004 if (!arg || nr_args > 256)
11006 ret = io_probe(ctx, arg, nr_args);
11008 case IORING_REGISTER_PERSONALITY:
11010 if (arg || nr_args)
11012 ret = io_register_personality(ctx);
11014 case IORING_UNREGISTER_PERSONALITY:
11018 ret = io_unregister_personality(ctx, nr_args);
11020 case IORING_REGISTER_ENABLE_RINGS:
11022 if (arg || nr_args)
11024 ret = io_register_enable_rings(ctx);
11026 case IORING_REGISTER_RESTRICTIONS:
11027 ret = io_register_restrictions(ctx, arg, nr_args);
11029 case IORING_REGISTER_FILES2:
11030 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11032 case IORING_REGISTER_FILES_UPDATE2:
11033 ret = io_register_rsrc_update(ctx, arg, nr_args,
11036 case IORING_REGISTER_BUFFERS2:
11037 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11039 case IORING_REGISTER_BUFFERS_UPDATE:
11040 ret = io_register_rsrc_update(ctx, arg, nr_args,
11041 IORING_RSRC_BUFFER);
11043 case IORING_REGISTER_IOWQ_AFF:
11045 if (!arg || !nr_args)
11047 ret = io_register_iowq_aff(ctx, arg, nr_args);
11049 case IORING_UNREGISTER_IOWQ_AFF:
11051 if (arg || nr_args)
11053 ret = io_unregister_iowq_aff(ctx);
11055 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11057 if (!arg || nr_args != 2)
11059 ret = io_register_iowq_max_workers(ctx, arg);
11066 if (io_register_op_must_quiesce(opcode)) {
11067 /* bring the ctx back to life */
11068 percpu_ref_reinit(&ctx->refs);
11069 reinit_completion(&ctx->ref_comp);
11074 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11075 void __user *, arg, unsigned int, nr_args)
11077 struct io_ring_ctx *ctx;
11086 if (f.file->f_op != &io_uring_fops)
11089 ctx = f.file->private_data;
11091 io_run_task_work();
11093 mutex_lock(&ctx->uring_lock);
11094 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11095 mutex_unlock(&ctx->uring_lock);
11096 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11097 ctx->cq_ev_fd != NULL, ret);
11103 static int __init io_uring_init(void)
11105 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11106 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11107 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11110 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11111 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11112 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11113 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11114 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11115 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11116 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11117 BUILD_BUG_SQE_ELEM(8, __u64, off);
11118 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11119 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11120 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11121 BUILD_BUG_SQE_ELEM(24, __u32, len);
11122 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11123 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11124 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11125 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11126 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11127 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11128 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11129 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11130 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11131 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11132 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11133 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11134 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11135 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11136 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11137 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11138 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11139 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11140 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11141 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11142 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11144 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11145 sizeof(struct io_uring_rsrc_update));
11146 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11147 sizeof(struct io_uring_rsrc_update2));
11149 /* ->buf_index is u16 */
11150 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11152 /* should fit into one byte */
11153 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11154 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11155 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11157 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11158 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11160 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11164 __initcall(io_uring_init);