1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/tracehook.h>
82 #include <linux/audit.h>
83 #include <linux/security.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
98 #define IORING_MAX_FIXED_FILES (1U << 15)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
102 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
103 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
104 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
106 #define IORING_MAX_REG_BUFFERS (1U << 14)
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
118 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
121 u32 head ____cacheline_aligned_in_smp;
122 u32 tail ____cacheline_aligned_in_smp;
126 * This data is shared with the application through the mmap at offsets
127 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
129 * The offsets to the member fields are published through struct
130 * io_sqring_offsets when calling io_uring_setup.
134 * Head and tail offsets into the ring; the offsets need to be
135 * masked to get valid indices.
137 * The kernel controls head of the sq ring and the tail of the cq ring,
138 * and the application controls tail of the sq ring and the head of the
141 struct io_uring sq, cq;
143 * Bitmasks to apply to head and tail offsets (constant, equals
146 u32 sq_ring_mask, cq_ring_mask;
147 /* Ring sizes (constant, power of 2) */
148 u32 sq_ring_entries, cq_ring_entries;
150 * Number of invalid entries dropped by the kernel due to
151 * invalid index stored in array
153 * Written by the kernel, shouldn't be modified by the
154 * application (i.e. get number of "new events" by comparing to
157 * After a new SQ head value was read by the application this
158 * counter includes all submissions that were dropped reaching
159 * the new SQ head (and possibly more).
165 * Written by the kernel, shouldn't be modified by the
168 * The application needs a full memory barrier before checking
169 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
175 * Written by the application, shouldn't be modified by the
180 * Number of completion events lost because the queue was full;
181 * this should be avoided by the application by making sure
182 * there are not more requests pending than there is space in
183 * the completion queue.
185 * Written by the kernel, shouldn't be modified by the
186 * application (i.e. get number of "new events" by comparing to
189 * As completion events come in out of order this counter is not
190 * ordered with any other data.
194 * Ring buffer of completion events.
196 * The kernel writes completion events fresh every time they are
197 * produced, so the application is allowed to modify pending
200 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
203 enum io_uring_cmd_flags {
204 IO_URING_F_COMPLETE_DEFER = 1,
205 IO_URING_F_UNLOCKED = 2,
206 /* int's last bit, sign checks are usually faster than a bit test */
207 IO_URING_F_NONBLOCK = INT_MIN,
210 struct io_mapped_ubuf {
213 unsigned int nr_bvecs;
214 unsigned long acct_pages;
215 struct bio_vec bvec[];
220 struct io_overflow_cqe {
221 struct io_uring_cqe cqe;
222 struct list_head list;
225 struct io_fixed_file {
226 /* file * with additional FFS_* flags */
227 unsigned long file_ptr;
231 struct list_head list;
236 struct io_mapped_ubuf *buf;
240 struct io_file_table {
241 struct io_fixed_file *files;
244 struct io_rsrc_node {
245 struct percpu_ref refs;
246 struct list_head node;
247 struct list_head rsrc_list;
248 struct io_rsrc_data *rsrc_data;
249 struct llist_node llist;
253 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
255 struct io_rsrc_data {
256 struct io_ring_ctx *ctx;
262 struct completion done;
267 struct list_head list;
273 struct io_restriction {
274 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
275 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
276 u8 sqe_flags_allowed;
277 u8 sqe_flags_required;
282 IO_SQ_THREAD_SHOULD_STOP = 0,
283 IO_SQ_THREAD_SHOULD_PARK,
288 atomic_t park_pending;
291 /* ctx's that are using this sqd */
292 struct list_head ctx_list;
294 struct task_struct *thread;
295 struct wait_queue_head wait;
297 unsigned sq_thread_idle;
303 struct completion exited;
306 #define IO_COMPL_BATCH 32
307 #define IO_REQ_CACHE_SIZE 32
308 #define IO_REQ_ALLOC_BATCH 8
310 struct io_submit_link {
311 struct io_kiocb *head;
312 struct io_kiocb *last;
315 struct io_submit_state {
316 /* inline/task_work completion list, under ->uring_lock */
317 struct io_wq_work_node free_list;
318 /* batch completion logic */
319 struct io_wq_work_list compl_reqs;
320 struct io_submit_link link;
325 unsigned short submit_nr;
326 struct blk_plug plug;
330 /* const or read-mostly hot data */
332 struct percpu_ref refs;
334 struct io_rings *rings;
336 unsigned int compat: 1;
337 unsigned int drain_next: 1;
338 unsigned int eventfd_async: 1;
339 unsigned int restricted: 1;
340 unsigned int off_timeout_used: 1;
341 unsigned int drain_active: 1;
342 unsigned int drain_disabled: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 int rsrc_cached_refs;
372 struct io_file_table file_table;
373 unsigned nr_user_files;
374 unsigned nr_user_bufs;
375 struct io_mapped_ubuf **user_bufs;
377 struct io_submit_state submit_state;
378 struct list_head timeout_list;
379 struct list_head ltimeout_list;
380 struct list_head cq_overflow_list;
381 struct xarray io_buffers;
382 struct xarray personalities;
384 unsigned sq_thread_idle;
385 } ____cacheline_aligned_in_smp;
387 /* IRQ completion list, under ->completion_lock */
388 struct io_wq_work_list locked_free_list;
389 unsigned int locked_free_nr;
391 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
392 struct io_sq_data *sq_data; /* if using sq thread polling */
394 struct wait_queue_head sqo_sq_wait;
395 struct list_head sqd_list;
397 unsigned long check_cq_overflow;
400 unsigned cached_cq_tail;
402 struct eventfd_ctx *cq_ev_fd;
403 struct wait_queue_head cq_wait;
405 atomic_t cq_timeouts;
406 unsigned cq_last_tm_flush;
407 } ____cacheline_aligned_in_smp;
410 spinlock_t completion_lock;
412 spinlock_t timeout_lock;
415 * ->iopoll_list is protected by the ctx->uring_lock for
416 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417 * For SQPOLL, only the single threaded io_sq_thread() will
418 * manipulate the list, hence no extra locking is needed there.
420 struct io_wq_work_list iopoll_list;
421 struct hlist_head *cancel_hash;
422 unsigned cancel_hash_bits;
423 bool poll_multi_queue;
424 } ____cacheline_aligned_in_smp;
426 struct io_restriction restrictions;
428 /* slow path rsrc auxilary data, used by update/register */
430 struct io_rsrc_node *rsrc_backup_node;
431 struct io_mapped_ubuf *dummy_ubuf;
432 struct io_rsrc_data *file_data;
433 struct io_rsrc_data *buf_data;
435 struct delayed_work rsrc_put_work;
436 struct llist_head rsrc_put_llist;
437 struct list_head rsrc_ref_list;
438 spinlock_t rsrc_ref_lock;
441 /* Keep this last, we don't need it for the fast path */
443 #if defined(CONFIG_UNIX)
444 struct socket *ring_sock;
446 /* hashed buffered write serialization */
447 struct io_wq_hash *hash_map;
449 /* Only used for accounting purposes */
450 struct user_struct *user;
451 struct mm_struct *mm_account;
453 /* ctx exit and cancelation */
454 struct llist_head fallback_llist;
455 struct delayed_work fallback_work;
456 struct work_struct exit_work;
457 struct list_head tctx_list;
458 struct completion ref_comp;
460 bool iowq_limits_set;
464 struct io_uring_task {
465 /* submission side */
468 struct wait_queue_head wait;
469 const struct io_ring_ctx *last;
471 struct percpu_counter inflight;
472 atomic_t inflight_tracked;
475 spinlock_t task_lock;
476 struct io_wq_work_list task_list;
477 struct io_wq_work_list prior_task_list;
478 struct callback_head task_work;
483 * First field must be the file pointer in all the
484 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
486 struct io_poll_iocb {
488 struct wait_queue_head *head;
490 struct wait_queue_entry wait;
493 struct io_poll_update {
499 bool update_user_data;
508 struct io_timeout_data {
509 struct io_kiocb *req;
510 struct hrtimer timer;
511 struct timespec64 ts;
512 enum hrtimer_mode mode;
518 struct sockaddr __user *addr;
519 int __user *addr_len;
522 unsigned long nofile;
542 struct list_head list;
543 /* head of the link, used by linked timeouts only */
544 struct io_kiocb *head;
545 /* for linked completions */
546 struct io_kiocb *prev;
549 struct io_timeout_rem {
554 struct timespec64 ts;
560 /* NOTE: kiocb has the file as the first member, so don't do it here */
568 struct sockaddr __user *addr;
575 struct compat_msghdr __user *umsg_compat;
576 struct user_msghdr __user *umsg;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
624 struct file *file_in;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
674 struct filename *filename;
680 struct filename *oldpath;
681 struct filename *newpath;
688 struct filename *oldpath;
689 struct filename *newpath;
693 struct io_async_connect {
694 struct sockaddr_storage address;
697 struct io_async_msghdr {
698 struct iovec fast_iov[UIO_FASTIOV];
699 /* points to an allocated iov, if NULL we use fast_iov instead */
700 struct iovec *free_iov;
701 struct sockaddr __user *uaddr;
703 struct sockaddr_storage addr;
707 struct iov_iter iter;
708 struct iov_iter_state iter_state;
709 struct iovec fast_iov[UIO_FASTIOV];
713 struct io_rw_state s;
714 const struct iovec *free_iovec;
716 struct wait_page_queue wpq;
720 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
721 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
722 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
723 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
724 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
725 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
726 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
728 /* first byte is taken by user flags, shift it to not overlap */
733 REQ_F_LINK_TIMEOUT_BIT,
734 REQ_F_NEED_CLEANUP_BIT,
736 REQ_F_BUFFER_SELECTED_BIT,
737 REQ_F_COMPLETE_INLINE_BIT,
741 REQ_F_ARM_LTIMEOUT_BIT,
742 REQ_F_ASYNC_DATA_BIT,
743 REQ_F_SKIP_LINK_CQES_BIT,
744 /* keep async read/write and isreg together and in order */
745 REQ_F_SUPPORT_NOWAIT_BIT,
748 /* not a real bit, just to check we're not overflowing the space */
754 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
755 /* drain existing IO first */
756 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
758 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
759 /* doesn't sever on completion < 0 */
760 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
762 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
763 /* IOSQE_BUFFER_SELECT */
764 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
765 /* IOSQE_CQE_SKIP_SUCCESS */
766 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
768 /* fail rest of links */
769 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
770 /* on inflight list, should be cancelled and waited on exit reliably */
771 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
772 /* read/write uses file position */
773 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
774 /* must not punt to workers */
775 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
776 /* has or had linked timeout */
777 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
779 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
780 /* already went through poll handler */
781 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
782 /* buffer already selected */
783 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
784 /* completion is deferred through io_comp_state */
785 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
786 /* caller should reissue async */
787 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
788 /* supports async reads/writes */
789 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
791 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
792 /* has creds assigned */
793 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
794 /* skip refcounting if not set */
795 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
796 /* there is a linked timeout that has to be armed */
797 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
798 /* ->async_data allocated */
799 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
800 /* don't post CQEs while failing linked requests */
801 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
805 struct io_poll_iocb poll;
806 struct io_poll_iocb *double_poll;
809 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
811 struct io_task_work {
813 struct io_wq_work_node node;
814 struct llist_node fallback_node;
816 io_req_tw_func_t func;
820 IORING_RSRC_FILE = 0,
821 IORING_RSRC_BUFFER = 1,
825 * NOTE! Each of the iocb union members has the file pointer
826 * as the first entry in their struct definition. So you can
827 * access the file pointer through any of the sub-structs,
828 * or directly as just 'ki_filp' in this struct.
834 struct io_poll_iocb poll;
835 struct io_poll_update poll_update;
836 struct io_accept accept;
838 struct io_cancel cancel;
839 struct io_timeout timeout;
840 struct io_timeout_rem timeout_rem;
841 struct io_connect connect;
842 struct io_sr_msg sr_msg;
844 struct io_close close;
845 struct io_rsrc_update rsrc_update;
846 struct io_fadvise fadvise;
847 struct io_madvise madvise;
848 struct io_epoll epoll;
849 struct io_splice splice;
850 struct io_provide_buf pbuf;
851 struct io_statx statx;
852 struct io_shutdown shutdown;
853 struct io_rename rename;
854 struct io_unlink unlink;
855 struct io_mkdir mkdir;
856 struct io_symlink symlink;
857 struct io_hardlink hardlink;
861 /* polled IO has completed */
870 struct io_ring_ctx *ctx;
871 struct task_struct *task;
873 struct percpu_ref *fixed_rsrc_refs;
874 /* store used ubuf, so we can prevent reloading */
875 struct io_mapped_ubuf *imu;
877 /* used by request caches, completion batching and iopoll */
878 struct io_wq_work_node comp_list;
880 struct io_kiocb *link;
881 struct io_task_work io_task_work;
882 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
883 struct hlist_node hash_node;
884 /* internal polling, see IORING_FEAT_FAST_POLL */
885 struct async_poll *apoll;
886 /* opcode allocated if it needs to store data for async defer */
888 struct io_wq_work work;
889 /* custom credentials, valid IFF REQ_F_CREDS is set */
890 const struct cred *creds;
891 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
892 struct io_buffer *kbuf;
896 struct io_tctx_node {
897 struct list_head ctx_node;
898 struct task_struct *task;
899 struct io_ring_ctx *ctx;
902 struct io_defer_entry {
903 struct list_head list;
904 struct io_kiocb *req;
909 /* needs req->file assigned */
910 unsigned needs_file : 1;
911 /* should block plug */
913 /* hash wq insertion if file is a regular file */
914 unsigned hash_reg_file : 1;
915 /* unbound wq insertion if file is a non-regular file */
916 unsigned unbound_nonreg_file : 1;
917 /* set if opcode supports polled "wait" */
919 unsigned pollout : 1;
920 /* op supports buffer selection */
921 unsigned buffer_select : 1;
922 /* do prep async if is going to be punted */
923 unsigned needs_async_setup : 1;
924 /* opcode is not supported by this kernel */
925 unsigned not_supported : 1;
927 unsigned audit_skip : 1;
928 /* size of async data needed, if any */
929 unsigned short async_size;
932 static const struct io_op_def io_op_defs[] = {
933 [IORING_OP_NOP] = {},
934 [IORING_OP_READV] = {
936 .unbound_nonreg_file = 1,
939 .needs_async_setup = 1,
942 .async_size = sizeof(struct io_async_rw),
944 [IORING_OP_WRITEV] = {
947 .unbound_nonreg_file = 1,
949 .needs_async_setup = 1,
952 .async_size = sizeof(struct io_async_rw),
954 [IORING_OP_FSYNC] = {
958 [IORING_OP_READ_FIXED] = {
960 .unbound_nonreg_file = 1,
964 .async_size = sizeof(struct io_async_rw),
966 [IORING_OP_WRITE_FIXED] = {
969 .unbound_nonreg_file = 1,
973 .async_size = sizeof(struct io_async_rw),
975 [IORING_OP_POLL_ADD] = {
977 .unbound_nonreg_file = 1,
980 [IORING_OP_POLL_REMOVE] = {
983 [IORING_OP_SYNC_FILE_RANGE] = {
987 [IORING_OP_SENDMSG] = {
989 .unbound_nonreg_file = 1,
991 .needs_async_setup = 1,
992 .async_size = sizeof(struct io_async_msghdr),
994 [IORING_OP_RECVMSG] = {
996 .unbound_nonreg_file = 1,
999 .needs_async_setup = 1,
1000 .async_size = sizeof(struct io_async_msghdr),
1002 [IORING_OP_TIMEOUT] = {
1004 .async_size = sizeof(struct io_timeout_data),
1006 [IORING_OP_TIMEOUT_REMOVE] = {
1007 /* used by timeout updates' prep() */
1010 [IORING_OP_ACCEPT] = {
1012 .unbound_nonreg_file = 1,
1015 [IORING_OP_ASYNC_CANCEL] = {
1018 [IORING_OP_LINK_TIMEOUT] = {
1020 .async_size = sizeof(struct io_timeout_data),
1022 [IORING_OP_CONNECT] = {
1024 .unbound_nonreg_file = 1,
1026 .needs_async_setup = 1,
1027 .async_size = sizeof(struct io_async_connect),
1029 [IORING_OP_FALLOCATE] = {
1032 [IORING_OP_OPENAT] = {},
1033 [IORING_OP_CLOSE] = {},
1034 [IORING_OP_FILES_UPDATE] = {
1037 [IORING_OP_STATX] = {
1040 [IORING_OP_READ] = {
1042 .unbound_nonreg_file = 1,
1047 .async_size = sizeof(struct io_async_rw),
1049 [IORING_OP_WRITE] = {
1052 .unbound_nonreg_file = 1,
1056 .async_size = sizeof(struct io_async_rw),
1058 [IORING_OP_FADVISE] = {
1062 [IORING_OP_MADVISE] = {},
1063 [IORING_OP_SEND] = {
1065 .unbound_nonreg_file = 1,
1069 [IORING_OP_RECV] = {
1071 .unbound_nonreg_file = 1,
1076 [IORING_OP_OPENAT2] = {
1078 [IORING_OP_EPOLL_CTL] = {
1079 .unbound_nonreg_file = 1,
1082 [IORING_OP_SPLICE] = {
1085 .unbound_nonreg_file = 1,
1088 [IORING_OP_PROVIDE_BUFFERS] = {
1091 [IORING_OP_REMOVE_BUFFERS] = {
1097 .unbound_nonreg_file = 1,
1100 [IORING_OP_SHUTDOWN] = {
1103 [IORING_OP_RENAMEAT] = {},
1104 [IORING_OP_UNLINKAT] = {},
1105 [IORING_OP_MKDIRAT] = {},
1106 [IORING_OP_SYMLINKAT] = {},
1107 [IORING_OP_LINKAT] = {},
1110 /* requests with any of those set should undergo io_disarm_next() */
1111 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1113 static bool io_disarm_next(struct io_kiocb *req);
1114 static void io_uring_del_tctx_node(unsigned long index);
1115 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1116 struct task_struct *task,
1118 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1120 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1122 static void io_put_req(struct io_kiocb *req);
1123 static void io_put_req_deferred(struct io_kiocb *req);
1124 static void io_dismantle_req(struct io_kiocb *req);
1125 static void io_queue_linked_timeout(struct io_kiocb *req);
1126 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1127 struct io_uring_rsrc_update2 *up,
1129 static void io_clean_op(struct io_kiocb *req);
1130 static struct file *io_file_get(struct io_ring_ctx *ctx,
1131 struct io_kiocb *req, int fd, bool fixed);
1132 static void __io_queue_sqe(struct io_kiocb *req);
1133 static void io_rsrc_put_work(struct work_struct *work);
1135 static void io_req_task_queue(struct io_kiocb *req);
1136 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1137 static int io_req_prep_async(struct io_kiocb *req);
1139 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1140 unsigned int issue_flags, u32 slot_index);
1141 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1143 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1145 static struct kmem_cache *req_cachep;
1147 static const struct file_operations io_uring_fops;
1149 struct sock *io_uring_get_socket(struct file *file)
1151 #if defined(CONFIG_UNIX)
1152 if (file->f_op == &io_uring_fops) {
1153 struct io_ring_ctx *ctx = file->private_data;
1155 return ctx->ring_sock->sk;
1160 EXPORT_SYMBOL(io_uring_get_socket);
1162 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1165 mutex_lock(&ctx->uring_lock);
1170 #define io_for_each_link(pos, head) \
1171 for (pos = (head); pos; pos = pos->link)
1174 * Shamelessly stolen from the mm implementation of page reference checking,
1175 * see commit f958d7b528b1 for details.
1177 #define req_ref_zero_or_close_to_overflow(req) \
1178 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1180 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1182 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1183 return atomic_inc_not_zero(&req->refs);
1186 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1188 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1191 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1192 return atomic_dec_and_test(&req->refs);
1195 static inline void req_ref_put(struct io_kiocb *req)
1197 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1198 WARN_ON_ONCE(req_ref_put_and_test(req));
1201 static inline void req_ref_get(struct io_kiocb *req)
1203 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1204 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1205 atomic_inc(&req->refs);
1208 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1210 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1211 __io_submit_flush_completions(ctx);
1214 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1216 if (!(req->flags & REQ_F_REFCOUNT)) {
1217 req->flags |= REQ_F_REFCOUNT;
1218 atomic_set(&req->refs, nr);
1222 static inline void io_req_set_refcount(struct io_kiocb *req)
1224 __io_req_set_refcount(req, 1);
1227 #define IO_RSRC_REF_BATCH 100
1229 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1230 struct io_ring_ctx *ctx)
1231 __must_hold(&ctx->uring_lock)
1233 struct percpu_ref *ref = req->fixed_rsrc_refs;
1236 if (ref == &ctx->rsrc_node->refs)
1237 ctx->rsrc_cached_refs++;
1239 percpu_ref_put(ref);
1243 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1245 if (req->fixed_rsrc_refs)
1246 percpu_ref_put(req->fixed_rsrc_refs);
1249 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1250 __must_hold(&ctx->uring_lock)
1252 if (ctx->rsrc_cached_refs) {
1253 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1254 ctx->rsrc_cached_refs = 0;
1258 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1259 __must_hold(&ctx->uring_lock)
1261 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1262 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1265 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1266 struct io_ring_ctx *ctx)
1268 if (!req->fixed_rsrc_refs) {
1269 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1270 ctx->rsrc_cached_refs--;
1271 if (unlikely(ctx->rsrc_cached_refs < 0))
1272 io_rsrc_refs_refill(ctx);
1276 static unsigned int __io_put_kbuf(struct io_kiocb *req)
1278 struct io_buffer *kbuf = req->kbuf;
1279 unsigned int cflags;
1281 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1282 cflags |= IORING_CQE_F_BUFFER;
1283 req->flags &= ~REQ_F_BUFFER_SELECTED;
1289 static inline unsigned int io_put_kbuf(struct io_kiocb *req)
1291 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1293 return __io_put_kbuf(req);
1296 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1298 bool got = percpu_ref_tryget(ref);
1300 /* already at zero, wait for ->release() */
1302 wait_for_completion(compl);
1303 percpu_ref_resurrect(ref);
1305 percpu_ref_put(ref);
1308 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1310 __must_hold(&req->ctx->timeout_lock)
1312 struct io_kiocb *req;
1314 if (task && head->task != task)
1319 io_for_each_link(req, head) {
1320 if (req->flags & REQ_F_INFLIGHT)
1326 static bool io_match_linked(struct io_kiocb *head)
1328 struct io_kiocb *req;
1330 io_for_each_link(req, head) {
1331 if (req->flags & REQ_F_INFLIGHT)
1338 * As io_match_task() but protected against racing with linked timeouts.
1339 * User must not hold timeout_lock.
1341 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1346 if (task && head->task != task)
1351 if (head->flags & REQ_F_LINK_TIMEOUT) {
1352 struct io_ring_ctx *ctx = head->ctx;
1354 /* protect against races with linked timeouts */
1355 spin_lock_irq(&ctx->timeout_lock);
1356 matched = io_match_linked(head);
1357 spin_unlock_irq(&ctx->timeout_lock);
1359 matched = io_match_linked(head);
1364 static inline bool req_has_async_data(struct io_kiocb *req)
1366 return req->flags & REQ_F_ASYNC_DATA;
1369 static inline void req_set_fail(struct io_kiocb *req)
1371 req->flags |= REQ_F_FAIL;
1372 if (req->flags & REQ_F_CQE_SKIP) {
1373 req->flags &= ~REQ_F_CQE_SKIP;
1374 req->flags |= REQ_F_SKIP_LINK_CQES;
1378 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1384 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1386 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1388 complete(&ctx->ref_comp);
1391 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1393 return !req->timeout.off;
1396 static __cold void io_fallback_req_func(struct work_struct *work)
1398 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1399 fallback_work.work);
1400 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1401 struct io_kiocb *req, *tmp;
1402 bool locked = false;
1404 percpu_ref_get(&ctx->refs);
1405 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1406 req->io_task_work.func(req, &locked);
1409 io_submit_flush_completions(ctx);
1410 mutex_unlock(&ctx->uring_lock);
1412 percpu_ref_put(&ctx->refs);
1415 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1417 struct io_ring_ctx *ctx;
1420 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1425 * Use 5 bits less than the max cq entries, that should give us around
1426 * 32 entries per hash list if totally full and uniformly spread.
1428 hash_bits = ilog2(p->cq_entries);
1432 ctx->cancel_hash_bits = hash_bits;
1433 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1435 if (!ctx->cancel_hash)
1437 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1439 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1440 if (!ctx->dummy_ubuf)
1442 /* set invalid range, so io_import_fixed() fails meeting it */
1443 ctx->dummy_ubuf->ubuf = -1UL;
1445 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1446 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1449 ctx->flags = p->flags;
1450 init_waitqueue_head(&ctx->sqo_sq_wait);
1451 INIT_LIST_HEAD(&ctx->sqd_list);
1452 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1453 init_completion(&ctx->ref_comp);
1454 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1455 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1456 mutex_init(&ctx->uring_lock);
1457 init_waitqueue_head(&ctx->cq_wait);
1458 spin_lock_init(&ctx->completion_lock);
1459 spin_lock_init(&ctx->timeout_lock);
1460 INIT_WQ_LIST(&ctx->iopoll_list);
1461 INIT_LIST_HEAD(&ctx->defer_list);
1462 INIT_LIST_HEAD(&ctx->timeout_list);
1463 INIT_LIST_HEAD(&ctx->ltimeout_list);
1464 spin_lock_init(&ctx->rsrc_ref_lock);
1465 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1466 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1467 init_llist_head(&ctx->rsrc_put_llist);
1468 INIT_LIST_HEAD(&ctx->tctx_list);
1469 ctx->submit_state.free_list.next = NULL;
1470 INIT_WQ_LIST(&ctx->locked_free_list);
1471 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1472 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1475 kfree(ctx->dummy_ubuf);
1476 kfree(ctx->cancel_hash);
1481 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1483 struct io_rings *r = ctx->rings;
1485 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1489 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1491 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1492 struct io_ring_ctx *ctx = req->ctx;
1494 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1500 #define FFS_NOWAIT 0x1UL
1501 #define FFS_ISREG 0x2UL
1502 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1504 static inline bool io_req_ffs_set(struct io_kiocb *req)
1506 return req->flags & REQ_F_FIXED_FILE;
1509 static inline void io_req_track_inflight(struct io_kiocb *req)
1511 if (!(req->flags & REQ_F_INFLIGHT)) {
1512 req->flags |= REQ_F_INFLIGHT;
1513 atomic_inc(¤t->io_uring->inflight_tracked);
1517 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1519 if (WARN_ON_ONCE(!req->link))
1522 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1523 req->flags |= REQ_F_LINK_TIMEOUT;
1525 /* linked timeouts should have two refs once prep'ed */
1526 io_req_set_refcount(req);
1527 __io_req_set_refcount(req->link, 2);
1531 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1533 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1535 return __io_prep_linked_timeout(req);
1538 static void io_prep_async_work(struct io_kiocb *req)
1540 const struct io_op_def *def = &io_op_defs[req->opcode];
1541 struct io_ring_ctx *ctx = req->ctx;
1543 if (!(req->flags & REQ_F_CREDS)) {
1544 req->flags |= REQ_F_CREDS;
1545 req->creds = get_current_cred();
1548 req->work.list.next = NULL;
1549 req->work.flags = 0;
1550 if (req->flags & REQ_F_FORCE_ASYNC)
1551 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1553 if (req->flags & REQ_F_ISREG) {
1554 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1555 io_wq_hash_work(&req->work, file_inode(req->file));
1556 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1557 if (def->unbound_nonreg_file)
1558 req->work.flags |= IO_WQ_WORK_UNBOUND;
1561 switch (req->opcode) {
1562 case IORING_OP_SPLICE:
1564 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1565 req->work.flags |= IO_WQ_WORK_UNBOUND;
1570 static void io_prep_async_link(struct io_kiocb *req)
1572 struct io_kiocb *cur;
1574 if (req->flags & REQ_F_LINK_TIMEOUT) {
1575 struct io_ring_ctx *ctx = req->ctx;
1577 spin_lock_irq(&ctx->timeout_lock);
1578 io_for_each_link(cur, req)
1579 io_prep_async_work(cur);
1580 spin_unlock_irq(&ctx->timeout_lock);
1582 io_for_each_link(cur, req)
1583 io_prep_async_work(cur);
1587 static inline void io_req_add_compl_list(struct io_kiocb *req)
1589 struct io_ring_ctx *ctx = req->ctx;
1590 struct io_submit_state *state = &ctx->submit_state;
1592 if (!(req->flags & REQ_F_CQE_SKIP))
1593 ctx->submit_state.flush_cqes = true;
1594 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1597 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1599 struct io_ring_ctx *ctx = req->ctx;
1600 struct io_kiocb *link = io_prep_linked_timeout(req);
1601 struct io_uring_task *tctx = req->task->io_uring;
1604 BUG_ON(!tctx->io_wq);
1606 /* init ->work of the whole link before punting */
1607 io_prep_async_link(req);
1610 * Not expected to happen, but if we do have a bug where this _can_
1611 * happen, catch it here and ensure the request is marked as
1612 * canceled. That will make io-wq go through the usual work cancel
1613 * procedure rather than attempt to run this request (or create a new
1616 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1617 req->work.flags |= IO_WQ_WORK_CANCEL;
1619 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1620 &req->work, req->flags);
1621 io_wq_enqueue(tctx->io_wq, &req->work);
1623 io_queue_linked_timeout(link);
1626 static void io_kill_timeout(struct io_kiocb *req, int status)
1627 __must_hold(&req->ctx->completion_lock)
1628 __must_hold(&req->ctx->timeout_lock)
1630 struct io_timeout_data *io = req->async_data;
1632 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1635 atomic_set(&req->ctx->cq_timeouts,
1636 atomic_read(&req->ctx->cq_timeouts) + 1);
1637 list_del_init(&req->timeout.list);
1638 io_fill_cqe_req(req, status, 0);
1639 io_put_req_deferred(req);
1643 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1645 while (!list_empty(&ctx->defer_list)) {
1646 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1647 struct io_defer_entry, list);
1649 if (req_need_defer(de->req, de->seq))
1651 list_del_init(&de->list);
1652 io_req_task_queue(de->req);
1657 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1658 __must_hold(&ctx->completion_lock)
1660 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1662 spin_lock_irq(&ctx->timeout_lock);
1663 while (!list_empty(&ctx->timeout_list)) {
1664 u32 events_needed, events_got;
1665 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1666 struct io_kiocb, timeout.list);
1668 if (io_is_timeout_noseq(req))
1672 * Since seq can easily wrap around over time, subtract
1673 * the last seq at which timeouts were flushed before comparing.
1674 * Assuming not more than 2^31-1 events have happened since,
1675 * these subtractions won't have wrapped, so we can check if
1676 * target is in [last_seq, current_seq] by comparing the two.
1678 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1679 events_got = seq - ctx->cq_last_tm_flush;
1680 if (events_got < events_needed)
1683 list_del_init(&req->timeout.list);
1684 io_kill_timeout(req, 0);
1686 ctx->cq_last_tm_flush = seq;
1687 spin_unlock_irq(&ctx->timeout_lock);
1690 static __cold void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1692 if (ctx->off_timeout_used)
1693 io_flush_timeouts(ctx);
1694 if (ctx->drain_active)
1695 io_queue_deferred(ctx);
1698 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1700 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1701 __io_commit_cqring_flush(ctx);
1702 /* order cqe stores with ring update */
1703 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1706 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1708 struct io_rings *r = ctx->rings;
1710 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1713 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1715 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1718 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1720 struct io_rings *rings = ctx->rings;
1721 unsigned tail, mask = ctx->cq_entries - 1;
1724 * writes to the cq entry need to come after reading head; the
1725 * control dependency is enough as we're using WRITE_ONCE to
1728 if (__io_cqring_events(ctx) == ctx->cq_entries)
1731 tail = ctx->cached_cq_tail++;
1732 return &rings->cqes[tail & mask];
1735 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1737 if (likely(!ctx->cq_ev_fd))
1739 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1741 return !ctx->eventfd_async || io_wq_current_is_worker();
1745 * This should only get called when at least one event has been posted.
1746 * Some applications rely on the eventfd notification count only changing
1747 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1748 * 1:1 relationship between how many times this function is called (and
1749 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1751 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1754 * wake_up_all() may seem excessive, but io_wake_function() and
1755 * io_should_wake() handle the termination of the loop and only
1756 * wake as many waiters as we need to.
1758 if (wq_has_sleeper(&ctx->cq_wait))
1759 wake_up_all(&ctx->cq_wait);
1760 if (io_should_trigger_evfd(ctx))
1761 eventfd_signal(ctx->cq_ev_fd, 1);
1764 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1766 /* see waitqueue_active() comment */
1769 if (ctx->flags & IORING_SETUP_SQPOLL) {
1770 if (waitqueue_active(&ctx->cq_wait))
1771 wake_up_all(&ctx->cq_wait);
1773 if (io_should_trigger_evfd(ctx))
1774 eventfd_signal(ctx->cq_ev_fd, 1);
1777 /* Returns true if there are no backlogged entries after the flush */
1778 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1780 bool all_flushed, posted;
1782 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1786 spin_lock(&ctx->completion_lock);
1787 while (!list_empty(&ctx->cq_overflow_list)) {
1788 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1789 struct io_overflow_cqe *ocqe;
1793 ocqe = list_first_entry(&ctx->cq_overflow_list,
1794 struct io_overflow_cqe, list);
1796 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1798 io_account_cq_overflow(ctx);
1801 list_del(&ocqe->list);
1805 all_flushed = list_empty(&ctx->cq_overflow_list);
1807 clear_bit(0, &ctx->check_cq_overflow);
1808 WRITE_ONCE(ctx->rings->sq_flags,
1809 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1813 io_commit_cqring(ctx);
1814 spin_unlock(&ctx->completion_lock);
1816 io_cqring_ev_posted(ctx);
1820 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1824 if (test_bit(0, &ctx->check_cq_overflow)) {
1825 /* iopoll syncs against uring_lock, not completion_lock */
1826 if (ctx->flags & IORING_SETUP_IOPOLL)
1827 mutex_lock(&ctx->uring_lock);
1828 ret = __io_cqring_overflow_flush(ctx, false);
1829 if (ctx->flags & IORING_SETUP_IOPOLL)
1830 mutex_unlock(&ctx->uring_lock);
1836 /* must to be called somewhat shortly after putting a request */
1837 static inline void io_put_task(struct task_struct *task, int nr)
1839 struct io_uring_task *tctx = task->io_uring;
1841 if (likely(task == current)) {
1842 tctx->cached_refs += nr;
1844 percpu_counter_sub(&tctx->inflight, nr);
1845 if (unlikely(atomic_read(&tctx->in_idle)))
1846 wake_up(&tctx->wait);
1847 put_task_struct_many(task, nr);
1851 static void io_task_refs_refill(struct io_uring_task *tctx)
1853 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1855 percpu_counter_add(&tctx->inflight, refill);
1856 refcount_add(refill, ¤t->usage);
1857 tctx->cached_refs += refill;
1860 static inline void io_get_task_refs(int nr)
1862 struct io_uring_task *tctx = current->io_uring;
1864 tctx->cached_refs -= nr;
1865 if (unlikely(tctx->cached_refs < 0))
1866 io_task_refs_refill(tctx);
1869 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1871 struct io_uring_task *tctx = task->io_uring;
1872 unsigned int refs = tctx->cached_refs;
1875 tctx->cached_refs = 0;
1876 percpu_counter_sub(&tctx->inflight, refs);
1877 put_task_struct_many(task, refs);
1881 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1882 s32 res, u32 cflags)
1884 struct io_overflow_cqe *ocqe;
1886 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1889 * If we're in ring overflow flush mode, or in task cancel mode,
1890 * or cannot allocate an overflow entry, then we need to drop it
1893 io_account_cq_overflow(ctx);
1896 if (list_empty(&ctx->cq_overflow_list)) {
1897 set_bit(0, &ctx->check_cq_overflow);
1898 WRITE_ONCE(ctx->rings->sq_flags,
1899 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1902 ocqe->cqe.user_data = user_data;
1903 ocqe->cqe.res = res;
1904 ocqe->cqe.flags = cflags;
1905 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1909 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
1910 s32 res, u32 cflags)
1912 struct io_uring_cqe *cqe;
1914 trace_io_uring_complete(ctx, user_data, res, cflags);
1917 * If we can't get a cq entry, userspace overflowed the
1918 * submission (by quite a lot). Increment the overflow count in
1921 cqe = io_get_cqe(ctx);
1923 WRITE_ONCE(cqe->user_data, user_data);
1924 WRITE_ONCE(cqe->res, res);
1925 WRITE_ONCE(cqe->flags, cflags);
1928 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1931 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
1933 if (!(req->flags & REQ_F_CQE_SKIP))
1934 __io_fill_cqe(req->ctx, req->user_data, res, cflags);
1937 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1938 s32 res, u32 cflags)
1941 return __io_fill_cqe(ctx, user_data, res, cflags);
1944 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
1947 struct io_ring_ctx *ctx = req->ctx;
1949 if (!(req->flags & REQ_F_CQE_SKIP))
1950 __io_fill_cqe(ctx, req->user_data, res, cflags);
1952 * If we're the last reference to this request, add to our locked
1955 if (req_ref_put_and_test(req)) {
1956 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1957 if (req->flags & IO_DISARM_MASK)
1958 io_disarm_next(req);
1960 io_req_task_queue(req->link);
1964 io_req_put_rsrc(req, ctx);
1965 io_dismantle_req(req);
1966 io_put_task(req->task, 1);
1967 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
1968 ctx->locked_free_nr++;
1972 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1975 struct io_ring_ctx *ctx = req->ctx;
1977 spin_lock(&ctx->completion_lock);
1978 __io_req_complete_post(req, res, cflags);
1979 io_commit_cqring(ctx);
1980 spin_unlock(&ctx->completion_lock);
1981 io_cqring_ev_posted(ctx);
1984 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1988 req->cflags = cflags;
1989 req->flags |= REQ_F_COMPLETE_INLINE;
1992 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1993 s32 res, u32 cflags)
1995 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1996 io_req_complete_state(req, res, cflags);
1998 io_req_complete_post(req, res, cflags);
2001 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2003 __io_req_complete(req, 0, res, 0);
2006 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2009 io_req_complete_post(req, res, 0);
2012 static void io_req_complete_fail_submit(struct io_kiocb *req)
2015 * We don't submit, fail them all, for that replace hardlinks with
2016 * normal links. Extra REQ_F_LINK is tolerated.
2018 req->flags &= ~REQ_F_HARDLINK;
2019 req->flags |= REQ_F_LINK;
2020 io_req_complete_failed(req, req->result);
2024 * Don't initialise the fields below on every allocation, but do that in
2025 * advance and keep them valid across allocations.
2027 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2031 req->async_data = NULL;
2032 /* not necessary, but safer to zero */
2036 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2037 struct io_submit_state *state)
2039 spin_lock(&ctx->completion_lock);
2040 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2041 ctx->locked_free_nr = 0;
2042 spin_unlock(&ctx->completion_lock);
2045 /* Returns true IFF there are requests in the cache */
2046 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2048 struct io_submit_state *state = &ctx->submit_state;
2051 * If we have more than a batch's worth of requests in our IRQ side
2052 * locked cache, grab the lock and move them over to our submission
2055 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2056 io_flush_cached_locked_reqs(ctx, state);
2057 return !!state->free_list.next;
2061 * A request might get retired back into the request caches even before opcode
2062 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2063 * Because of that, io_alloc_req() should be called only under ->uring_lock
2064 * and with extra caution to not get a request that is still worked on.
2066 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2067 __must_hold(&ctx->uring_lock)
2069 struct io_submit_state *state = &ctx->submit_state;
2070 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2071 void *reqs[IO_REQ_ALLOC_BATCH];
2072 struct io_kiocb *req;
2075 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2078 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2081 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2082 * retry single alloc to be on the safe side.
2084 if (unlikely(ret <= 0)) {
2085 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2091 percpu_ref_get_many(&ctx->refs, ret);
2092 for (i = 0; i < ret; i++) {
2095 io_preinit_req(req, ctx);
2096 wq_stack_add_head(&req->comp_list, &state->free_list);
2101 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2103 if (unlikely(!ctx->submit_state.free_list.next))
2104 return __io_alloc_req_refill(ctx);
2108 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2110 struct io_wq_work_node *node;
2112 node = wq_stack_extract(&ctx->submit_state.free_list);
2113 return container_of(node, struct io_kiocb, comp_list);
2116 static inline void io_put_file(struct file *file)
2122 static inline void io_dismantle_req(struct io_kiocb *req)
2124 unsigned int flags = req->flags;
2126 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2128 if (!(flags & REQ_F_FIXED_FILE))
2129 io_put_file(req->file);
2132 static __cold void __io_free_req(struct io_kiocb *req)
2134 struct io_ring_ctx *ctx = req->ctx;
2136 io_req_put_rsrc(req, ctx);
2137 io_dismantle_req(req);
2138 io_put_task(req->task, 1);
2140 spin_lock(&ctx->completion_lock);
2141 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2142 ctx->locked_free_nr++;
2143 spin_unlock(&ctx->completion_lock);
2146 static inline void io_remove_next_linked(struct io_kiocb *req)
2148 struct io_kiocb *nxt = req->link;
2150 req->link = nxt->link;
2154 static bool io_kill_linked_timeout(struct io_kiocb *req)
2155 __must_hold(&req->ctx->completion_lock)
2156 __must_hold(&req->ctx->timeout_lock)
2158 struct io_kiocb *link = req->link;
2160 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2161 struct io_timeout_data *io = link->async_data;
2163 io_remove_next_linked(req);
2164 link->timeout.head = NULL;
2165 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2166 list_del(&link->timeout.list);
2167 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2168 io_fill_cqe_req(link, -ECANCELED, 0);
2169 io_put_req_deferred(link);
2176 static void io_fail_links(struct io_kiocb *req)
2177 __must_hold(&req->ctx->completion_lock)
2179 struct io_kiocb *nxt, *link = req->link;
2180 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2184 long res = -ECANCELED;
2186 if (link->flags & REQ_F_FAIL)
2192 trace_io_uring_fail_link(req, link);
2194 link->flags &= ~REQ_F_CQE_SKIP;
2195 io_fill_cqe_req(link, res, 0);
2197 io_put_req_deferred(link);
2202 static bool io_disarm_next(struct io_kiocb *req)
2203 __must_hold(&req->ctx->completion_lock)
2205 bool posted = false;
2207 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2208 struct io_kiocb *link = req->link;
2210 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2211 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2212 io_remove_next_linked(req);
2213 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2214 io_fill_cqe_req(link, -ECANCELED, 0);
2215 io_put_req_deferred(link);
2218 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2219 struct io_ring_ctx *ctx = req->ctx;
2221 spin_lock_irq(&ctx->timeout_lock);
2222 posted = io_kill_linked_timeout(req);
2223 spin_unlock_irq(&ctx->timeout_lock);
2225 if (unlikely((req->flags & REQ_F_FAIL) &&
2226 !(req->flags & REQ_F_HARDLINK))) {
2227 posted |= (req->link != NULL);
2233 static void __io_req_find_next_prep(struct io_kiocb *req)
2235 struct io_ring_ctx *ctx = req->ctx;
2238 spin_lock(&ctx->completion_lock);
2239 posted = io_disarm_next(req);
2241 io_commit_cqring(ctx);
2242 spin_unlock(&ctx->completion_lock);
2244 io_cqring_ev_posted(ctx);
2247 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2249 struct io_kiocb *nxt;
2251 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2254 * If LINK is set, we have dependent requests in this chain. If we
2255 * didn't fail this request, queue the first one up, moving any other
2256 * dependencies to the next request. In case of failure, fail the rest
2259 if (unlikely(req->flags & IO_DISARM_MASK))
2260 __io_req_find_next_prep(req);
2266 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2271 io_submit_flush_completions(ctx);
2272 mutex_unlock(&ctx->uring_lock);
2275 percpu_ref_put(&ctx->refs);
2278 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2280 io_commit_cqring(ctx);
2281 spin_unlock(&ctx->completion_lock);
2282 io_cqring_ev_posted(ctx);
2285 static void handle_prev_tw_list(struct io_wq_work_node *node,
2286 struct io_ring_ctx **ctx, bool *uring_locked)
2288 if (*ctx && !*uring_locked)
2289 spin_lock(&(*ctx)->completion_lock);
2292 struct io_wq_work_node *next = node->next;
2293 struct io_kiocb *req = container_of(node, struct io_kiocb,
2296 if (req->ctx != *ctx) {
2297 if (unlikely(!*uring_locked && *ctx))
2298 ctx_commit_and_unlock(*ctx);
2300 ctx_flush_and_put(*ctx, uring_locked);
2302 /* if not contended, grab and improve batching */
2303 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2304 percpu_ref_get(&(*ctx)->refs);
2305 if (unlikely(!*uring_locked))
2306 spin_lock(&(*ctx)->completion_lock);
2308 if (likely(*uring_locked))
2309 req->io_task_work.func(req, uring_locked);
2311 __io_req_complete_post(req, req->result, io_put_kbuf(req));
2315 if (unlikely(!*uring_locked))
2316 ctx_commit_and_unlock(*ctx);
2319 static void handle_tw_list(struct io_wq_work_node *node,
2320 struct io_ring_ctx **ctx, bool *locked)
2323 struct io_wq_work_node *next = node->next;
2324 struct io_kiocb *req = container_of(node, struct io_kiocb,
2327 if (req->ctx != *ctx) {
2328 ctx_flush_and_put(*ctx, locked);
2330 /* if not contended, grab and improve batching */
2331 *locked = mutex_trylock(&(*ctx)->uring_lock);
2332 percpu_ref_get(&(*ctx)->refs);
2334 req->io_task_work.func(req, locked);
2339 static void tctx_task_work(struct callback_head *cb)
2341 bool uring_locked = false;
2342 struct io_ring_ctx *ctx = NULL;
2343 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2347 struct io_wq_work_node *node1, *node2;
2349 if (!tctx->task_list.first &&
2350 !tctx->prior_task_list.first && uring_locked)
2351 io_submit_flush_completions(ctx);
2353 spin_lock_irq(&tctx->task_lock);
2354 node1 = tctx->prior_task_list.first;
2355 node2 = tctx->task_list.first;
2356 INIT_WQ_LIST(&tctx->task_list);
2357 INIT_WQ_LIST(&tctx->prior_task_list);
2358 if (!node2 && !node1)
2359 tctx->task_running = false;
2360 spin_unlock_irq(&tctx->task_lock);
2361 if (!node2 && !node1)
2365 handle_prev_tw_list(node1, &ctx, &uring_locked);
2368 handle_tw_list(node2, &ctx, &uring_locked);
2372 ctx_flush_and_put(ctx, &uring_locked);
2374 /* relaxed read is enough as only the task itself sets ->in_idle */
2375 if (unlikely(atomic_read(&tctx->in_idle)))
2376 io_uring_drop_tctx_refs(current);
2379 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2381 struct task_struct *tsk = req->task;
2382 struct io_uring_task *tctx = tsk->io_uring;
2383 enum task_work_notify_mode notify;
2384 struct io_wq_work_node *node;
2385 unsigned long flags;
2388 WARN_ON_ONCE(!tctx);
2390 spin_lock_irqsave(&tctx->task_lock, flags);
2392 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2394 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2395 running = tctx->task_running;
2397 tctx->task_running = true;
2398 spin_unlock_irqrestore(&tctx->task_lock, flags);
2400 /* task_work already pending, we're done */
2405 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2406 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2407 * processing task_work. There's no reliable way to tell if TWA_RESUME
2410 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2411 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2412 if (notify == TWA_NONE)
2413 wake_up_process(tsk);
2417 spin_lock_irqsave(&tctx->task_lock, flags);
2418 tctx->task_running = false;
2419 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2420 spin_unlock_irqrestore(&tctx->task_lock, flags);
2423 req = container_of(node, struct io_kiocb, io_task_work.node);
2425 if (llist_add(&req->io_task_work.fallback_node,
2426 &req->ctx->fallback_llist))
2427 schedule_delayed_work(&req->ctx->fallback_work, 1);
2431 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2433 struct io_ring_ctx *ctx = req->ctx;
2435 /* not needed for normal modes, but SQPOLL depends on it */
2436 io_tw_lock(ctx, locked);
2437 io_req_complete_failed(req, req->result);
2440 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2442 struct io_ring_ctx *ctx = req->ctx;
2444 io_tw_lock(ctx, locked);
2445 /* req->task == current here, checking PF_EXITING is safe */
2446 if (likely(!(req->task->flags & PF_EXITING)))
2447 __io_queue_sqe(req);
2449 io_req_complete_failed(req, -EFAULT);
2452 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2455 req->io_task_work.func = io_req_task_cancel;
2456 io_req_task_work_add(req, false);
2459 static void io_req_task_queue(struct io_kiocb *req)
2461 req->io_task_work.func = io_req_task_submit;
2462 io_req_task_work_add(req, false);
2465 static void io_req_task_queue_reissue(struct io_kiocb *req)
2467 req->io_task_work.func = io_queue_async_work;
2468 io_req_task_work_add(req, false);
2471 static inline void io_queue_next(struct io_kiocb *req)
2473 struct io_kiocb *nxt = io_req_find_next(req);
2476 io_req_task_queue(nxt);
2479 static void io_free_req(struct io_kiocb *req)
2485 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2490 static void io_free_batch_list(struct io_ring_ctx *ctx,
2491 struct io_wq_work_node *node)
2492 __must_hold(&ctx->uring_lock)
2494 struct task_struct *task = NULL;
2498 struct io_kiocb *req = container_of(node, struct io_kiocb,
2501 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2502 node = req->comp_list.next;
2503 if (!req_ref_put_and_test(req))
2507 io_req_put_rsrc_locked(req, ctx);
2509 io_dismantle_req(req);
2511 if (req->task != task) {
2513 io_put_task(task, task_refs);
2518 node = req->comp_list.next;
2519 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2523 io_put_task(task, task_refs);
2526 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2527 __must_hold(&ctx->uring_lock)
2529 struct io_wq_work_node *node, *prev;
2530 struct io_submit_state *state = &ctx->submit_state;
2532 if (state->flush_cqes) {
2533 spin_lock(&ctx->completion_lock);
2534 wq_list_for_each(node, prev, &state->compl_reqs) {
2535 struct io_kiocb *req = container_of(node, struct io_kiocb,
2538 if (!(req->flags & REQ_F_CQE_SKIP))
2539 __io_fill_cqe(ctx, req->user_data, req->result,
2543 io_commit_cqring(ctx);
2544 spin_unlock(&ctx->completion_lock);
2545 io_cqring_ev_posted(ctx);
2546 state->flush_cqes = false;
2549 io_free_batch_list(ctx, state->compl_reqs.first);
2550 INIT_WQ_LIST(&state->compl_reqs);
2554 * Drop reference to request, return next in chain (if there is one) if this
2555 * was the last reference to this request.
2557 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2559 struct io_kiocb *nxt = NULL;
2561 if (req_ref_put_and_test(req)) {
2562 nxt = io_req_find_next(req);
2568 static inline void io_put_req(struct io_kiocb *req)
2570 if (req_ref_put_and_test(req))
2574 static inline void io_put_req_deferred(struct io_kiocb *req)
2576 if (req_ref_put_and_test(req)) {
2577 req->io_task_work.func = io_free_req_work;
2578 io_req_task_work_add(req, false);
2582 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2584 /* See comment at the top of this file */
2586 return __io_cqring_events(ctx);
2589 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2591 struct io_rings *rings = ctx->rings;
2593 /* make sure SQ entry isn't read before tail */
2594 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2597 static inline bool io_run_task_work(void)
2599 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2600 __set_current_state(TASK_RUNNING);
2601 tracehook_notify_signal();
2608 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2610 struct io_wq_work_node *pos, *start, *prev;
2611 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2612 DEFINE_IO_COMP_BATCH(iob);
2616 * Only spin for completions if we don't have multiple devices hanging
2617 * off our complete list.
2619 if (ctx->poll_multi_queue || force_nonspin)
2620 poll_flags |= BLK_POLL_ONESHOT;
2622 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2623 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2624 struct kiocb *kiocb = &req->rw.kiocb;
2628 * Move completed and retryable entries to our local lists.
2629 * If we find a request that requires polling, break out
2630 * and complete those lists first, if we have entries there.
2632 if (READ_ONCE(req->iopoll_completed))
2635 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2636 if (unlikely(ret < 0))
2639 poll_flags |= BLK_POLL_ONESHOT;
2641 /* iopoll may have completed current req */
2642 if (!rq_list_empty(iob.req_list) ||
2643 READ_ONCE(req->iopoll_completed))
2647 if (!rq_list_empty(iob.req_list))
2653 wq_list_for_each_resume(pos, prev) {
2654 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2656 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2657 if (!smp_load_acquire(&req->iopoll_completed))
2659 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2662 __io_fill_cqe(ctx, req->user_data, req->result, io_put_kbuf(req));
2666 if (unlikely(!nr_events))
2669 io_commit_cqring(ctx);
2670 io_cqring_ev_posted_iopoll(ctx);
2671 pos = start ? start->next : ctx->iopoll_list.first;
2672 wq_list_cut(&ctx->iopoll_list, prev, start);
2673 io_free_batch_list(ctx, pos);
2678 * We can't just wait for polled events to come to us, we have to actively
2679 * find and complete them.
2681 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2683 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2686 mutex_lock(&ctx->uring_lock);
2687 while (!wq_list_empty(&ctx->iopoll_list)) {
2688 /* let it sleep and repeat later if can't complete a request */
2689 if (io_do_iopoll(ctx, true) == 0)
2692 * Ensure we allow local-to-the-cpu processing to take place,
2693 * in this case we need to ensure that we reap all events.
2694 * Also let task_work, etc. to progress by releasing the mutex
2696 if (need_resched()) {
2697 mutex_unlock(&ctx->uring_lock);
2699 mutex_lock(&ctx->uring_lock);
2702 mutex_unlock(&ctx->uring_lock);
2705 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2707 unsigned int nr_events = 0;
2711 * We disallow the app entering submit/complete with polling, but we
2712 * still need to lock the ring to prevent racing with polled issue
2713 * that got punted to a workqueue.
2715 mutex_lock(&ctx->uring_lock);
2717 * Don't enter poll loop if we already have events pending.
2718 * If we do, we can potentially be spinning for commands that
2719 * already triggered a CQE (eg in error).
2721 if (test_bit(0, &ctx->check_cq_overflow))
2722 __io_cqring_overflow_flush(ctx, false);
2723 if (io_cqring_events(ctx))
2727 * If a submit got punted to a workqueue, we can have the
2728 * application entering polling for a command before it gets
2729 * issued. That app will hold the uring_lock for the duration
2730 * of the poll right here, so we need to take a breather every
2731 * now and then to ensure that the issue has a chance to add
2732 * the poll to the issued list. Otherwise we can spin here
2733 * forever, while the workqueue is stuck trying to acquire the
2736 if (wq_list_empty(&ctx->iopoll_list)) {
2737 u32 tail = ctx->cached_cq_tail;
2739 mutex_unlock(&ctx->uring_lock);
2741 mutex_lock(&ctx->uring_lock);
2743 /* some requests don't go through iopoll_list */
2744 if (tail != ctx->cached_cq_tail ||
2745 wq_list_empty(&ctx->iopoll_list))
2748 ret = io_do_iopoll(ctx, !min);
2753 } while (nr_events < min && !need_resched());
2755 mutex_unlock(&ctx->uring_lock);
2759 static void kiocb_end_write(struct io_kiocb *req)
2762 * Tell lockdep we inherited freeze protection from submission
2765 if (req->flags & REQ_F_ISREG) {
2766 struct super_block *sb = file_inode(req->file)->i_sb;
2768 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2774 static bool io_resubmit_prep(struct io_kiocb *req)
2776 struct io_async_rw *rw = req->async_data;
2778 if (!req_has_async_data(req))
2779 return !io_req_prep_async(req);
2780 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2784 static bool io_rw_should_reissue(struct io_kiocb *req)
2786 umode_t mode = file_inode(req->file)->i_mode;
2787 struct io_ring_ctx *ctx = req->ctx;
2789 if (!S_ISBLK(mode) && !S_ISREG(mode))
2791 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2792 !(ctx->flags & IORING_SETUP_IOPOLL)))
2795 * If ref is dying, we might be running poll reap from the exit work.
2796 * Don't attempt to reissue from that path, just let it fail with
2799 if (percpu_ref_is_dying(&ctx->refs))
2802 * Play it safe and assume not safe to re-import and reissue if we're
2803 * not in the original thread group (or in task context).
2805 if (!same_thread_group(req->task, current) || !in_task())
2810 static bool io_resubmit_prep(struct io_kiocb *req)
2814 static bool io_rw_should_reissue(struct io_kiocb *req)
2820 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2822 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2823 kiocb_end_write(req);
2824 if (unlikely(res != req->result)) {
2825 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2826 io_rw_should_reissue(req)) {
2827 req->flags |= REQ_F_REISSUE;
2836 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2838 unsigned int cflags = io_put_kbuf(req);
2839 int res = req->result;
2842 io_req_complete_state(req, res, cflags);
2843 io_req_add_compl_list(req);
2845 io_req_complete_post(req, res, cflags);
2849 static void __io_complete_rw(struct io_kiocb *req, long res,
2850 unsigned int issue_flags)
2852 if (__io_complete_rw_common(req, res))
2854 __io_req_complete(req, issue_flags, req->result, io_put_kbuf(req));
2857 static void io_complete_rw(struct kiocb *kiocb, long res)
2859 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2861 if (__io_complete_rw_common(req, res))
2864 req->io_task_work.func = io_req_task_complete;
2865 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
2868 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
2870 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2872 if (kiocb->ki_flags & IOCB_WRITE)
2873 kiocb_end_write(req);
2874 if (unlikely(res != req->result)) {
2875 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2876 req->flags |= REQ_F_REISSUE;
2882 /* order with io_iopoll_complete() checking ->iopoll_completed */
2883 smp_store_release(&req->iopoll_completed, 1);
2887 * After the iocb has been issued, it's safe to be found on the poll list.
2888 * Adding the kiocb to the list AFTER submission ensures that we don't
2889 * find it from a io_do_iopoll() thread before the issuer is done
2890 * accessing the kiocb cookie.
2892 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
2894 struct io_ring_ctx *ctx = req->ctx;
2895 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
2897 /* workqueue context doesn't hold uring_lock, grab it now */
2898 if (unlikely(needs_lock))
2899 mutex_lock(&ctx->uring_lock);
2902 * Track whether we have multiple files in our lists. This will impact
2903 * how we do polling eventually, not spinning if we're on potentially
2904 * different devices.
2906 if (wq_list_empty(&ctx->iopoll_list)) {
2907 ctx->poll_multi_queue = false;
2908 } else if (!ctx->poll_multi_queue) {
2909 struct io_kiocb *list_req;
2911 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
2913 if (list_req->file != req->file)
2914 ctx->poll_multi_queue = true;
2918 * For fast devices, IO may have already completed. If it has, add
2919 * it to the front so we find it first.
2921 if (READ_ONCE(req->iopoll_completed))
2922 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
2924 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
2926 if (unlikely(needs_lock)) {
2928 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2929 * in sq thread task context or in io worker task context. If
2930 * current task context is sq thread, we don't need to check
2931 * whether should wake up sq thread.
2933 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2934 wq_has_sleeper(&ctx->sq_data->wait))
2935 wake_up(&ctx->sq_data->wait);
2937 mutex_unlock(&ctx->uring_lock);
2941 static bool io_bdev_nowait(struct block_device *bdev)
2943 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2947 * If we tracked the file through the SCM inflight mechanism, we could support
2948 * any file. For now, just ensure that anything potentially problematic is done
2951 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2953 if (S_ISBLK(mode)) {
2954 if (IS_ENABLED(CONFIG_BLOCK) &&
2955 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2961 if (S_ISREG(mode)) {
2962 if (IS_ENABLED(CONFIG_BLOCK) &&
2963 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2964 file->f_op != &io_uring_fops)
2969 /* any ->read/write should understand O_NONBLOCK */
2970 if (file->f_flags & O_NONBLOCK)
2972 return file->f_mode & FMODE_NOWAIT;
2976 * If we tracked the file through the SCM inflight mechanism, we could support
2977 * any file. For now, just ensure that anything potentially problematic is done
2980 static unsigned int io_file_get_flags(struct file *file)
2982 umode_t mode = file_inode(file)->i_mode;
2983 unsigned int res = 0;
2987 if (__io_file_supports_nowait(file, mode))
2992 static inline bool io_file_supports_nowait(struct io_kiocb *req)
2994 return req->flags & REQ_F_SUPPORT_NOWAIT;
2997 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2999 struct io_ring_ctx *ctx = req->ctx;
3000 struct kiocb *kiocb = &req->rw.kiocb;
3001 struct file *file = req->file;
3005 if (!io_req_ffs_set(req))
3006 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3008 kiocb->ki_pos = READ_ONCE(sqe->off);
3009 if (kiocb->ki_pos == -1) {
3010 if (!(file->f_mode & FMODE_STREAM)) {
3011 req->flags |= REQ_F_CUR_POS;
3012 kiocb->ki_pos = file->f_pos;
3017 kiocb->ki_flags = iocb_flags(file);
3018 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3023 * If the file is marked O_NONBLOCK, still allow retry for it if it
3024 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3025 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3027 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3028 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3029 req->flags |= REQ_F_NOWAIT;
3031 if (ctx->flags & IORING_SETUP_IOPOLL) {
3032 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3035 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3036 kiocb->ki_complete = io_complete_rw_iopoll;
3037 req->iopoll_completed = 0;
3039 if (kiocb->ki_flags & IOCB_HIPRI)
3041 kiocb->ki_complete = io_complete_rw;
3044 ioprio = READ_ONCE(sqe->ioprio);
3046 ret = ioprio_check_cap(ioprio);
3050 kiocb->ki_ioprio = ioprio;
3052 kiocb->ki_ioprio = get_current_ioprio();
3056 req->rw.addr = READ_ONCE(sqe->addr);
3057 req->rw.len = READ_ONCE(sqe->len);
3058 req->buf_index = READ_ONCE(sqe->buf_index);
3062 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3068 case -ERESTARTNOINTR:
3069 case -ERESTARTNOHAND:
3070 case -ERESTART_RESTARTBLOCK:
3072 * We can't just restart the syscall, since previously
3073 * submitted sqes may already be in progress. Just fail this
3079 kiocb->ki_complete(kiocb, ret);
3083 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3084 unsigned int issue_flags)
3086 struct io_async_rw *io = req->async_data;
3088 /* add previously done IO, if any */
3089 if (req_has_async_data(req) && io->bytes_done > 0) {
3091 ret = io->bytes_done;
3093 ret += io->bytes_done;
3096 if (req->flags & REQ_F_CUR_POS)
3097 req->file->f_pos = req->rw.kiocb.ki_pos;
3098 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3099 __io_complete_rw(req, ret, issue_flags);
3101 io_rw_done(&req->rw.kiocb, ret);
3103 if (req->flags & REQ_F_REISSUE) {
3104 req->flags &= ~REQ_F_REISSUE;
3105 if (io_resubmit_prep(req)) {
3106 io_req_task_queue_reissue(req);
3110 req->io_task_work.func = io_req_task_complete;
3111 io_req_task_work_add(req, false);
3116 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3117 struct io_mapped_ubuf *imu)
3119 size_t len = req->rw.len;
3120 u64 buf_end, buf_addr = req->rw.addr;
3123 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3125 /* not inside the mapped region */
3126 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3130 * May not be a start of buffer, set size appropriately
3131 * and advance us to the beginning.
3133 offset = buf_addr - imu->ubuf;
3134 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3138 * Don't use iov_iter_advance() here, as it's really slow for
3139 * using the latter parts of a big fixed buffer - it iterates
3140 * over each segment manually. We can cheat a bit here, because
3143 * 1) it's a BVEC iter, we set it up
3144 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3145 * first and last bvec
3147 * So just find our index, and adjust the iterator afterwards.
3148 * If the offset is within the first bvec (or the whole first
3149 * bvec, just use iov_iter_advance(). This makes it easier
3150 * since we can just skip the first segment, which may not
3151 * be PAGE_SIZE aligned.
3153 const struct bio_vec *bvec = imu->bvec;
3155 if (offset <= bvec->bv_len) {
3156 iov_iter_advance(iter, offset);
3158 unsigned long seg_skip;
3160 /* skip first vec */
3161 offset -= bvec->bv_len;
3162 seg_skip = 1 + (offset >> PAGE_SHIFT);
3164 iter->bvec = bvec + seg_skip;
3165 iter->nr_segs -= seg_skip;
3166 iter->count -= bvec->bv_len + offset;
3167 iter->iov_offset = offset & ~PAGE_MASK;
3174 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3176 struct io_mapped_ubuf *imu = req->imu;
3177 u16 index, buf_index = req->buf_index;
3180 struct io_ring_ctx *ctx = req->ctx;
3182 if (unlikely(buf_index >= ctx->nr_user_bufs))
3184 io_req_set_rsrc_node(req, ctx);
3185 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3186 imu = READ_ONCE(ctx->user_bufs[index]);
3189 return __io_import_fixed(req, rw, iter, imu);
3192 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3195 mutex_unlock(&ctx->uring_lock);
3198 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3201 * "Normal" inline submissions always hold the uring_lock, since we
3202 * grab it from the system call. Same is true for the SQPOLL offload.
3203 * The only exception is when we've detached the request and issue it
3204 * from an async worker thread, grab the lock for that case.
3207 mutex_lock(&ctx->uring_lock);
3210 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3211 int bgid, unsigned int issue_flags)
3213 struct io_buffer *kbuf = req->kbuf;
3214 struct io_buffer *head;
3215 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3217 if (req->flags & REQ_F_BUFFER_SELECTED)
3220 io_ring_submit_lock(req->ctx, needs_lock);
3222 lockdep_assert_held(&req->ctx->uring_lock);
3224 head = xa_load(&req->ctx->io_buffers, bgid);
3226 if (!list_empty(&head->list)) {
3227 kbuf = list_last_entry(&head->list, struct io_buffer,
3229 list_del(&kbuf->list);
3232 xa_erase(&req->ctx->io_buffers, bgid);
3234 if (*len > kbuf->len)
3236 req->flags |= REQ_F_BUFFER_SELECTED;
3239 kbuf = ERR_PTR(-ENOBUFS);
3242 io_ring_submit_unlock(req->ctx, needs_lock);
3246 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3247 unsigned int issue_flags)
3249 struct io_buffer *kbuf;
3252 bgid = req->buf_index;
3253 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3256 return u64_to_user_ptr(kbuf->addr);
3259 #ifdef CONFIG_COMPAT
3260 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3261 unsigned int issue_flags)
3263 struct compat_iovec __user *uiov;
3264 compat_ssize_t clen;
3268 uiov = u64_to_user_ptr(req->rw.addr);
3269 if (!access_ok(uiov, sizeof(*uiov)))
3271 if (__get_user(clen, &uiov->iov_len))
3277 buf = io_rw_buffer_select(req, &len, issue_flags);
3279 return PTR_ERR(buf);
3280 iov[0].iov_base = buf;
3281 iov[0].iov_len = (compat_size_t) len;
3286 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3287 unsigned int issue_flags)
3289 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3293 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3296 len = iov[0].iov_len;
3299 buf = io_rw_buffer_select(req, &len, issue_flags);
3301 return PTR_ERR(buf);
3302 iov[0].iov_base = buf;
3303 iov[0].iov_len = len;
3307 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3308 unsigned int issue_flags)
3310 if (req->flags & REQ_F_BUFFER_SELECTED) {
3311 struct io_buffer *kbuf = req->kbuf;
3313 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3314 iov[0].iov_len = kbuf->len;
3317 if (req->rw.len != 1)
3320 #ifdef CONFIG_COMPAT
3321 if (req->ctx->compat)
3322 return io_compat_import(req, iov, issue_flags);
3325 return __io_iov_buffer_select(req, iov, issue_flags);
3328 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3329 struct io_rw_state *s,
3330 unsigned int issue_flags)
3332 struct iov_iter *iter = &s->iter;
3333 u8 opcode = req->opcode;
3334 struct iovec *iovec;
3339 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3340 ret = io_import_fixed(req, rw, iter);
3342 return ERR_PTR(ret);
3346 /* buffer index only valid with fixed read/write, or buffer select */
3347 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3348 return ERR_PTR(-EINVAL);
3350 buf = u64_to_user_ptr(req->rw.addr);
3351 sqe_len = req->rw.len;
3353 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3354 if (req->flags & REQ_F_BUFFER_SELECT) {
3355 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3357 return ERR_CAST(buf);
3358 req->rw.len = sqe_len;
3361 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3363 return ERR_PTR(ret);
3367 iovec = s->fast_iov;
3368 if (req->flags & REQ_F_BUFFER_SELECT) {
3369 ret = io_iov_buffer_select(req, iovec, issue_flags);
3371 return ERR_PTR(ret);
3372 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3376 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3378 if (unlikely(ret < 0))
3379 return ERR_PTR(ret);
3383 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3384 struct iovec **iovec, struct io_rw_state *s,
3385 unsigned int issue_flags)
3387 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3388 if (unlikely(IS_ERR(*iovec)))
3389 return PTR_ERR(*iovec);
3391 iov_iter_save_state(&s->iter, &s->iter_state);
3395 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3397 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3401 * For files that don't have ->read_iter() and ->write_iter(), handle them
3402 * by looping over ->read() or ->write() manually.
3404 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3406 struct kiocb *kiocb = &req->rw.kiocb;
3407 struct file *file = req->file;
3411 * Don't support polled IO through this interface, and we can't
3412 * support non-blocking either. For the latter, this just causes
3413 * the kiocb to be handled from an async context.
3415 if (kiocb->ki_flags & IOCB_HIPRI)
3417 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3418 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3421 while (iov_iter_count(iter)) {
3425 if (!iov_iter_is_bvec(iter)) {
3426 iovec = iov_iter_iovec(iter);
3428 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3429 iovec.iov_len = req->rw.len;
3433 nr = file->f_op->read(file, iovec.iov_base,
3434 iovec.iov_len, io_kiocb_ppos(kiocb));
3436 nr = file->f_op->write(file, iovec.iov_base,
3437 iovec.iov_len, io_kiocb_ppos(kiocb));
3445 if (!iov_iter_is_bvec(iter)) {
3446 iov_iter_advance(iter, nr);
3452 if (nr != iovec.iov_len)
3459 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3460 const struct iovec *fast_iov, struct iov_iter *iter)
3462 struct io_async_rw *rw = req->async_data;
3464 memcpy(&rw->s.iter, iter, sizeof(*iter));
3465 rw->free_iovec = iovec;
3467 /* can only be fixed buffers, no need to do anything */
3468 if (iov_iter_is_bvec(iter))
3471 unsigned iov_off = 0;
3473 rw->s.iter.iov = rw->s.fast_iov;
3474 if (iter->iov != fast_iov) {
3475 iov_off = iter->iov - fast_iov;
3476 rw->s.iter.iov += iov_off;
3478 if (rw->s.fast_iov != fast_iov)
3479 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3480 sizeof(struct iovec) * iter->nr_segs);
3482 req->flags |= REQ_F_NEED_CLEANUP;
3486 static inline bool io_alloc_async_data(struct io_kiocb *req)
3488 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3489 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3490 if (req->async_data) {
3491 req->flags |= REQ_F_ASYNC_DATA;
3497 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3498 struct io_rw_state *s, bool force)
3500 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3502 if (!req_has_async_data(req)) {
3503 struct io_async_rw *iorw;
3505 if (io_alloc_async_data(req)) {
3510 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3511 iorw = req->async_data;
3512 /* we've copied and mapped the iter, ensure state is saved */
3513 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3518 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3520 struct io_async_rw *iorw = req->async_data;
3524 /* submission path, ->uring_lock should already be taken */
3525 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3526 if (unlikely(ret < 0))
3529 iorw->bytes_done = 0;
3530 iorw->free_iovec = iov;
3532 req->flags |= REQ_F_NEED_CLEANUP;
3536 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3538 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3540 return io_prep_rw(req, sqe);
3544 * This is our waitqueue callback handler, registered through __folio_lock_async()
3545 * when we initially tried to do the IO with the iocb armed our waitqueue.
3546 * This gets called when the page is unlocked, and we generally expect that to
3547 * happen when the page IO is completed and the page is now uptodate. This will
3548 * queue a task_work based retry of the operation, attempting to copy the data
3549 * again. If the latter fails because the page was NOT uptodate, then we will
3550 * do a thread based blocking retry of the operation. That's the unexpected
3553 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3554 int sync, void *arg)
3556 struct wait_page_queue *wpq;
3557 struct io_kiocb *req = wait->private;
3558 struct wait_page_key *key = arg;
3560 wpq = container_of(wait, struct wait_page_queue, wait);
3562 if (!wake_page_match(wpq, key))
3565 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3566 list_del_init(&wait->entry);
3567 io_req_task_queue(req);
3572 * This controls whether a given IO request should be armed for async page
3573 * based retry. If we return false here, the request is handed to the async
3574 * worker threads for retry. If we're doing buffered reads on a regular file,
3575 * we prepare a private wait_page_queue entry and retry the operation. This
3576 * will either succeed because the page is now uptodate and unlocked, or it
3577 * will register a callback when the page is unlocked at IO completion. Through
3578 * that callback, io_uring uses task_work to setup a retry of the operation.
3579 * That retry will attempt the buffered read again. The retry will generally
3580 * succeed, or in rare cases where it fails, we then fall back to using the
3581 * async worker threads for a blocking retry.
3583 static bool io_rw_should_retry(struct io_kiocb *req)
3585 struct io_async_rw *rw = req->async_data;
3586 struct wait_page_queue *wait = &rw->wpq;
3587 struct kiocb *kiocb = &req->rw.kiocb;
3589 /* never retry for NOWAIT, we just complete with -EAGAIN */
3590 if (req->flags & REQ_F_NOWAIT)
3593 /* Only for buffered IO */
3594 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3598 * just use poll if we can, and don't attempt if the fs doesn't
3599 * support callback based unlocks
3601 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3604 wait->wait.func = io_async_buf_func;
3605 wait->wait.private = req;
3606 wait->wait.flags = 0;
3607 INIT_LIST_HEAD(&wait->wait.entry);
3608 kiocb->ki_flags |= IOCB_WAITQ;
3609 kiocb->ki_flags &= ~IOCB_NOWAIT;
3610 kiocb->ki_waitq = wait;
3614 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3616 if (likely(req->file->f_op->read_iter))
3617 return call_read_iter(req->file, &req->rw.kiocb, iter);
3618 else if (req->file->f_op->read)
3619 return loop_rw_iter(READ, req, iter);
3624 static bool need_read_all(struct io_kiocb *req)
3626 return req->flags & REQ_F_ISREG ||
3627 S_ISBLK(file_inode(req->file)->i_mode);
3630 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3632 struct io_rw_state __s, *s = &__s;
3633 struct iovec *iovec;
3634 struct kiocb *kiocb = &req->rw.kiocb;
3635 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3636 struct io_async_rw *rw;
3639 if (!req_has_async_data(req)) {
3640 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3641 if (unlikely(ret < 0))
3644 rw = req->async_data;
3647 * We come here from an earlier attempt, restore our state to
3648 * match in case it doesn't. It's cheap enough that we don't
3649 * need to make this conditional.
3651 iov_iter_restore(&s->iter, &s->iter_state);
3654 req->result = iov_iter_count(&s->iter);
3656 if (force_nonblock) {
3657 /* If the file doesn't support async, just async punt */
3658 if (unlikely(!io_file_supports_nowait(req))) {
3659 ret = io_setup_async_rw(req, iovec, s, true);
3660 return ret ?: -EAGAIN;
3662 kiocb->ki_flags |= IOCB_NOWAIT;
3664 /* Ensure we clear previously set non-block flag */
3665 kiocb->ki_flags &= ~IOCB_NOWAIT;
3668 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), req->result);
3669 if (unlikely(ret)) {
3674 ret = io_iter_do_read(req, &s->iter);
3676 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3677 req->flags &= ~REQ_F_REISSUE;
3678 /* IOPOLL retry should happen for io-wq threads */
3679 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3681 /* no retry on NONBLOCK nor RWF_NOWAIT */
3682 if (req->flags & REQ_F_NOWAIT)
3685 } else if (ret == -EIOCBQUEUED) {
3687 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3688 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3689 /* read all, failed, already did sync or don't want to retry */
3694 * Don't depend on the iter state matching what was consumed, or being
3695 * untouched in case of error. Restore it and we'll advance it
3696 * manually if we need to.
3698 iov_iter_restore(&s->iter, &s->iter_state);
3700 ret2 = io_setup_async_rw(req, iovec, s, true);
3705 rw = req->async_data;
3708 * Now use our persistent iterator and state, if we aren't already.
3709 * We've restored and mapped the iter to match.
3714 * We end up here because of a partial read, either from
3715 * above or inside this loop. Advance the iter by the bytes
3716 * that were consumed.
3718 iov_iter_advance(&s->iter, ret);
3719 if (!iov_iter_count(&s->iter))
3721 rw->bytes_done += ret;
3722 iov_iter_save_state(&s->iter, &s->iter_state);
3724 /* if we can retry, do so with the callbacks armed */
3725 if (!io_rw_should_retry(req)) {
3726 kiocb->ki_flags &= ~IOCB_WAITQ;
3731 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3732 * we get -EIOCBQUEUED, then we'll get a notification when the
3733 * desired page gets unlocked. We can also get a partial read
3734 * here, and if we do, then just retry at the new offset.
3736 ret = io_iter_do_read(req, &s->iter);
3737 if (ret == -EIOCBQUEUED)
3739 /* we got some bytes, but not all. retry. */
3740 kiocb->ki_flags &= ~IOCB_WAITQ;
3741 iov_iter_restore(&s->iter, &s->iter_state);
3744 kiocb_done(req, ret, issue_flags);
3746 /* it's faster to check here then delegate to kfree */
3752 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3754 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3756 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
3757 return io_prep_rw(req, sqe);
3760 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3762 struct io_rw_state __s, *s = &__s;
3763 struct iovec *iovec;
3764 struct kiocb *kiocb = &req->rw.kiocb;
3765 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3768 if (!req_has_async_data(req)) {
3769 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3770 if (unlikely(ret < 0))
3773 struct io_async_rw *rw = req->async_data;
3776 iov_iter_restore(&s->iter, &s->iter_state);
3779 req->result = iov_iter_count(&s->iter);
3781 if (force_nonblock) {
3782 /* If the file doesn't support async, just async punt */
3783 if (unlikely(!io_file_supports_nowait(req)))
3786 /* file path doesn't support NOWAIT for non-direct_IO */
3787 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3788 (req->flags & REQ_F_ISREG))
3791 kiocb->ki_flags |= IOCB_NOWAIT;
3793 /* Ensure we clear previously set non-block flag */
3794 kiocb->ki_flags &= ~IOCB_NOWAIT;
3797 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), req->result);
3802 * Open-code file_start_write here to grab freeze protection,
3803 * which will be released by another thread in
3804 * io_complete_rw(). Fool lockdep by telling it the lock got
3805 * released so that it doesn't complain about the held lock when
3806 * we return to userspace.
3808 if (req->flags & REQ_F_ISREG) {
3809 sb_start_write(file_inode(req->file)->i_sb);
3810 __sb_writers_release(file_inode(req->file)->i_sb,
3813 kiocb->ki_flags |= IOCB_WRITE;
3815 if (likely(req->file->f_op->write_iter))
3816 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3817 else if (req->file->f_op->write)
3818 ret2 = loop_rw_iter(WRITE, req, &s->iter);
3822 if (req->flags & REQ_F_REISSUE) {
3823 req->flags &= ~REQ_F_REISSUE;
3828 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3829 * retry them without IOCB_NOWAIT.
3831 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3833 /* no retry on NONBLOCK nor RWF_NOWAIT */
3834 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3836 if (!force_nonblock || ret2 != -EAGAIN) {
3837 /* IOPOLL retry should happen for io-wq threads */
3838 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
3841 kiocb_done(req, ret2, issue_flags);
3844 iov_iter_restore(&s->iter, &s->iter_state);
3845 ret = io_setup_async_rw(req, iovec, s, false);
3846 return ret ?: -EAGAIN;
3849 /* it's reportedly faster than delegating the null check to kfree() */
3855 static int io_renameat_prep(struct io_kiocb *req,
3856 const struct io_uring_sqe *sqe)
3858 struct io_rename *ren = &req->rename;
3859 const char __user *oldf, *newf;
3861 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3863 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3865 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3868 ren->old_dfd = READ_ONCE(sqe->fd);
3869 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3870 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3871 ren->new_dfd = READ_ONCE(sqe->len);
3872 ren->flags = READ_ONCE(sqe->rename_flags);
3874 ren->oldpath = getname(oldf);
3875 if (IS_ERR(ren->oldpath))
3876 return PTR_ERR(ren->oldpath);
3878 ren->newpath = getname(newf);
3879 if (IS_ERR(ren->newpath)) {
3880 putname(ren->oldpath);
3881 return PTR_ERR(ren->newpath);
3884 req->flags |= REQ_F_NEED_CLEANUP;
3888 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3890 struct io_rename *ren = &req->rename;
3893 if (issue_flags & IO_URING_F_NONBLOCK)
3896 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3897 ren->newpath, ren->flags);
3899 req->flags &= ~REQ_F_NEED_CLEANUP;
3902 io_req_complete(req, ret);
3906 static int io_unlinkat_prep(struct io_kiocb *req,
3907 const struct io_uring_sqe *sqe)
3909 struct io_unlink *un = &req->unlink;
3910 const char __user *fname;
3912 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3914 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3917 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3920 un->dfd = READ_ONCE(sqe->fd);
3922 un->flags = READ_ONCE(sqe->unlink_flags);
3923 if (un->flags & ~AT_REMOVEDIR)
3926 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3927 un->filename = getname(fname);
3928 if (IS_ERR(un->filename))
3929 return PTR_ERR(un->filename);
3931 req->flags |= REQ_F_NEED_CLEANUP;
3935 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3937 struct io_unlink *un = &req->unlink;
3940 if (issue_flags & IO_URING_F_NONBLOCK)
3943 if (un->flags & AT_REMOVEDIR)
3944 ret = do_rmdir(un->dfd, un->filename);
3946 ret = do_unlinkat(un->dfd, un->filename);
3948 req->flags &= ~REQ_F_NEED_CLEANUP;
3951 io_req_complete(req, ret);
3955 static int io_mkdirat_prep(struct io_kiocb *req,
3956 const struct io_uring_sqe *sqe)
3958 struct io_mkdir *mkd = &req->mkdir;
3959 const char __user *fname;
3961 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3963 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3966 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3969 mkd->dfd = READ_ONCE(sqe->fd);
3970 mkd->mode = READ_ONCE(sqe->len);
3972 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3973 mkd->filename = getname(fname);
3974 if (IS_ERR(mkd->filename))
3975 return PTR_ERR(mkd->filename);
3977 req->flags |= REQ_F_NEED_CLEANUP;
3981 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
3983 struct io_mkdir *mkd = &req->mkdir;
3986 if (issue_flags & IO_URING_F_NONBLOCK)
3989 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3991 req->flags &= ~REQ_F_NEED_CLEANUP;
3994 io_req_complete(req, ret);
3998 static int io_symlinkat_prep(struct io_kiocb *req,
3999 const struct io_uring_sqe *sqe)
4001 struct io_symlink *sl = &req->symlink;
4002 const char __user *oldpath, *newpath;
4004 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4006 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4009 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4012 sl->new_dfd = READ_ONCE(sqe->fd);
4013 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4014 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4016 sl->oldpath = getname(oldpath);
4017 if (IS_ERR(sl->oldpath))
4018 return PTR_ERR(sl->oldpath);
4020 sl->newpath = getname(newpath);
4021 if (IS_ERR(sl->newpath)) {
4022 putname(sl->oldpath);
4023 return PTR_ERR(sl->newpath);
4026 req->flags |= REQ_F_NEED_CLEANUP;
4030 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4032 struct io_symlink *sl = &req->symlink;
4035 if (issue_flags & IO_URING_F_NONBLOCK)
4038 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4040 req->flags &= ~REQ_F_NEED_CLEANUP;
4043 io_req_complete(req, ret);
4047 static int io_linkat_prep(struct io_kiocb *req,
4048 const struct io_uring_sqe *sqe)
4050 struct io_hardlink *lnk = &req->hardlink;
4051 const char __user *oldf, *newf;
4053 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4055 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4057 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4060 lnk->old_dfd = READ_ONCE(sqe->fd);
4061 lnk->new_dfd = READ_ONCE(sqe->len);
4062 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4063 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4064 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4066 lnk->oldpath = getname(oldf);
4067 if (IS_ERR(lnk->oldpath))
4068 return PTR_ERR(lnk->oldpath);
4070 lnk->newpath = getname(newf);
4071 if (IS_ERR(lnk->newpath)) {
4072 putname(lnk->oldpath);
4073 return PTR_ERR(lnk->newpath);
4076 req->flags |= REQ_F_NEED_CLEANUP;
4080 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4082 struct io_hardlink *lnk = &req->hardlink;
4085 if (issue_flags & IO_URING_F_NONBLOCK)
4088 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4089 lnk->newpath, lnk->flags);
4091 req->flags &= ~REQ_F_NEED_CLEANUP;
4094 io_req_complete(req, ret);
4098 static int io_shutdown_prep(struct io_kiocb *req,
4099 const struct io_uring_sqe *sqe)
4101 #if defined(CONFIG_NET)
4102 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4104 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4105 sqe->buf_index || sqe->splice_fd_in))
4108 req->shutdown.how = READ_ONCE(sqe->len);
4115 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4117 #if defined(CONFIG_NET)
4118 struct socket *sock;
4121 if (issue_flags & IO_URING_F_NONBLOCK)
4124 sock = sock_from_file(req->file);
4125 if (unlikely(!sock))
4128 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4131 io_req_complete(req, ret);
4138 static int __io_splice_prep(struct io_kiocb *req,
4139 const struct io_uring_sqe *sqe)
4141 struct io_splice *sp = &req->splice;
4142 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4144 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4148 sp->len = READ_ONCE(sqe->len);
4149 sp->flags = READ_ONCE(sqe->splice_flags);
4151 if (unlikely(sp->flags & ~valid_flags))
4154 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4155 (sp->flags & SPLICE_F_FD_IN_FIXED));
4158 req->flags |= REQ_F_NEED_CLEANUP;
4162 static int io_tee_prep(struct io_kiocb *req,
4163 const struct io_uring_sqe *sqe)
4165 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4167 return __io_splice_prep(req, sqe);
4170 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4172 struct io_splice *sp = &req->splice;
4173 struct file *in = sp->file_in;
4174 struct file *out = sp->file_out;
4175 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4178 if (issue_flags & IO_URING_F_NONBLOCK)
4181 ret = do_tee(in, out, sp->len, flags);
4183 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4185 req->flags &= ~REQ_F_NEED_CLEANUP;
4189 io_req_complete(req, ret);
4193 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4195 struct io_splice *sp = &req->splice;
4197 sp->off_in = READ_ONCE(sqe->splice_off_in);
4198 sp->off_out = READ_ONCE(sqe->off);
4199 return __io_splice_prep(req, sqe);
4202 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4204 struct io_splice *sp = &req->splice;
4205 struct file *in = sp->file_in;
4206 struct file *out = sp->file_out;
4207 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4208 loff_t *poff_in, *poff_out;
4211 if (issue_flags & IO_URING_F_NONBLOCK)
4214 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4215 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4218 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4220 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4222 req->flags &= ~REQ_F_NEED_CLEANUP;
4226 io_req_complete(req, ret);
4231 * IORING_OP_NOP just posts a completion event, nothing else.
4233 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4235 struct io_ring_ctx *ctx = req->ctx;
4237 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4240 __io_req_complete(req, issue_flags, 0, 0);
4244 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4246 struct io_ring_ctx *ctx = req->ctx;
4251 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4253 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4257 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4258 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4261 req->sync.off = READ_ONCE(sqe->off);
4262 req->sync.len = READ_ONCE(sqe->len);
4266 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4268 loff_t end = req->sync.off + req->sync.len;
4271 /* fsync always requires a blocking context */
4272 if (issue_flags & IO_URING_F_NONBLOCK)
4275 ret = vfs_fsync_range(req->file, req->sync.off,
4276 end > 0 ? end : LLONG_MAX,
4277 req->sync.flags & IORING_FSYNC_DATASYNC);
4280 io_req_complete(req, ret);
4284 static int io_fallocate_prep(struct io_kiocb *req,
4285 const struct io_uring_sqe *sqe)
4287 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4290 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4293 req->sync.off = READ_ONCE(sqe->off);
4294 req->sync.len = READ_ONCE(sqe->addr);
4295 req->sync.mode = READ_ONCE(sqe->len);
4299 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4303 /* fallocate always requiring blocking context */
4304 if (issue_flags & IO_URING_F_NONBLOCK)
4306 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4310 io_req_complete(req, ret);
4314 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4316 const char __user *fname;
4319 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4321 if (unlikely(sqe->ioprio || sqe->buf_index))
4323 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4326 /* open.how should be already initialised */
4327 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4328 req->open.how.flags |= O_LARGEFILE;
4330 req->open.dfd = READ_ONCE(sqe->fd);
4331 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4332 req->open.filename = getname(fname);
4333 if (IS_ERR(req->open.filename)) {
4334 ret = PTR_ERR(req->open.filename);
4335 req->open.filename = NULL;
4339 req->open.file_slot = READ_ONCE(sqe->file_index);
4340 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4343 req->open.nofile = rlimit(RLIMIT_NOFILE);
4344 req->flags |= REQ_F_NEED_CLEANUP;
4348 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4350 u64 mode = READ_ONCE(sqe->len);
4351 u64 flags = READ_ONCE(sqe->open_flags);
4353 req->open.how = build_open_how(flags, mode);
4354 return __io_openat_prep(req, sqe);
4357 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4359 struct open_how __user *how;
4363 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4364 len = READ_ONCE(sqe->len);
4365 if (len < OPEN_HOW_SIZE_VER0)
4368 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4373 return __io_openat_prep(req, sqe);
4376 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4378 struct open_flags op;
4380 bool resolve_nonblock, nonblock_set;
4381 bool fixed = !!req->open.file_slot;
4384 ret = build_open_flags(&req->open.how, &op);
4387 nonblock_set = op.open_flag & O_NONBLOCK;
4388 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4389 if (issue_flags & IO_URING_F_NONBLOCK) {
4391 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4392 * it'll always -EAGAIN
4394 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4396 op.lookup_flags |= LOOKUP_CACHED;
4397 op.open_flag |= O_NONBLOCK;
4401 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4406 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4409 * We could hang on to this 'fd' on retrying, but seems like
4410 * marginal gain for something that is now known to be a slower
4411 * path. So just put it, and we'll get a new one when we retry.
4416 ret = PTR_ERR(file);
4417 /* only retry if RESOLVE_CACHED wasn't already set by application */
4418 if (ret == -EAGAIN &&
4419 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4424 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4425 file->f_flags &= ~O_NONBLOCK;
4426 fsnotify_open(file);
4429 fd_install(ret, file);
4431 ret = io_install_fixed_file(req, file, issue_flags,
4432 req->open.file_slot - 1);
4434 putname(req->open.filename);
4435 req->flags &= ~REQ_F_NEED_CLEANUP;
4438 __io_req_complete(req, issue_flags, ret, 0);
4442 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4444 return io_openat2(req, issue_flags);
4447 static int io_remove_buffers_prep(struct io_kiocb *req,
4448 const struct io_uring_sqe *sqe)
4450 struct io_provide_buf *p = &req->pbuf;
4453 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4457 tmp = READ_ONCE(sqe->fd);
4458 if (!tmp || tmp > USHRT_MAX)
4461 memset(p, 0, sizeof(*p));
4463 p->bgid = READ_ONCE(sqe->buf_group);
4467 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4468 int bgid, unsigned nbufs)
4472 /* shouldn't happen */
4476 /* the head kbuf is the list itself */
4477 while (!list_empty(&buf->list)) {
4478 struct io_buffer *nxt;
4480 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4481 list_del(&nxt->list);
4489 xa_erase(&ctx->io_buffers, bgid);
4494 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4496 struct io_provide_buf *p = &req->pbuf;
4497 struct io_ring_ctx *ctx = req->ctx;
4498 struct io_buffer *head;
4500 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4502 io_ring_submit_lock(ctx, needs_lock);
4504 lockdep_assert_held(&ctx->uring_lock);
4507 head = xa_load(&ctx->io_buffers, p->bgid);
4509 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4513 /* complete before unlock, IOPOLL may need the lock */
4514 __io_req_complete(req, issue_flags, ret, 0);
4515 io_ring_submit_unlock(ctx, needs_lock);
4519 static int io_provide_buffers_prep(struct io_kiocb *req,
4520 const struct io_uring_sqe *sqe)
4522 unsigned long size, tmp_check;
4523 struct io_provide_buf *p = &req->pbuf;
4526 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4529 tmp = READ_ONCE(sqe->fd);
4530 if (!tmp || tmp > USHRT_MAX)
4533 p->addr = READ_ONCE(sqe->addr);
4534 p->len = READ_ONCE(sqe->len);
4536 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4539 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4542 size = (unsigned long)p->len * p->nbufs;
4543 if (!access_ok(u64_to_user_ptr(p->addr), size))
4546 p->bgid = READ_ONCE(sqe->buf_group);
4547 tmp = READ_ONCE(sqe->off);
4548 if (tmp > USHRT_MAX)
4554 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4556 struct io_buffer *buf;
4557 u64 addr = pbuf->addr;
4558 int i, bid = pbuf->bid;
4560 for (i = 0; i < pbuf->nbufs; i++) {
4561 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4566 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4571 INIT_LIST_HEAD(&buf->list);
4574 list_add_tail(&buf->list, &(*head)->list);
4578 return i ? i : -ENOMEM;
4581 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4583 struct io_provide_buf *p = &req->pbuf;
4584 struct io_ring_ctx *ctx = req->ctx;
4585 struct io_buffer *head, *list;
4587 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4589 io_ring_submit_lock(ctx, needs_lock);
4591 lockdep_assert_held(&ctx->uring_lock);
4593 list = head = xa_load(&ctx->io_buffers, p->bgid);
4595 ret = io_add_buffers(p, &head);
4596 if (ret >= 0 && !list) {
4597 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4599 __io_remove_buffers(ctx, head, p->bgid, -1U);
4603 /* complete before unlock, IOPOLL may need the lock */
4604 __io_req_complete(req, issue_flags, ret, 0);
4605 io_ring_submit_unlock(ctx, needs_lock);
4609 static int io_epoll_ctl_prep(struct io_kiocb *req,
4610 const struct io_uring_sqe *sqe)
4612 #if defined(CONFIG_EPOLL)
4613 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4615 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4618 req->epoll.epfd = READ_ONCE(sqe->fd);
4619 req->epoll.op = READ_ONCE(sqe->len);
4620 req->epoll.fd = READ_ONCE(sqe->off);
4622 if (ep_op_has_event(req->epoll.op)) {
4623 struct epoll_event __user *ev;
4625 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4626 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4636 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4638 #if defined(CONFIG_EPOLL)
4639 struct io_epoll *ie = &req->epoll;
4641 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4643 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4644 if (force_nonblock && ret == -EAGAIN)
4649 __io_req_complete(req, issue_flags, ret, 0);
4656 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4658 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4659 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4661 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4664 req->madvise.addr = READ_ONCE(sqe->addr);
4665 req->madvise.len = READ_ONCE(sqe->len);
4666 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4673 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4675 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4676 struct io_madvise *ma = &req->madvise;
4679 if (issue_flags & IO_URING_F_NONBLOCK)
4682 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4685 io_req_complete(req, ret);
4692 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4694 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4696 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4699 req->fadvise.offset = READ_ONCE(sqe->off);
4700 req->fadvise.len = READ_ONCE(sqe->len);
4701 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4705 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4707 struct io_fadvise *fa = &req->fadvise;
4710 if (issue_flags & IO_URING_F_NONBLOCK) {
4711 switch (fa->advice) {
4712 case POSIX_FADV_NORMAL:
4713 case POSIX_FADV_RANDOM:
4714 case POSIX_FADV_SEQUENTIAL:
4721 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4724 __io_req_complete(req, issue_flags, ret, 0);
4728 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4730 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4732 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4734 if (req->flags & REQ_F_FIXED_FILE)
4737 req->statx.dfd = READ_ONCE(sqe->fd);
4738 req->statx.mask = READ_ONCE(sqe->len);
4739 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4740 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4741 req->statx.flags = READ_ONCE(sqe->statx_flags);
4746 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4748 struct io_statx *ctx = &req->statx;
4751 if (issue_flags & IO_URING_F_NONBLOCK)
4754 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4759 io_req_complete(req, ret);
4763 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4765 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4767 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4768 sqe->rw_flags || sqe->buf_index)
4770 if (req->flags & REQ_F_FIXED_FILE)
4773 req->close.fd = READ_ONCE(sqe->fd);
4774 req->close.file_slot = READ_ONCE(sqe->file_index);
4775 if (req->close.file_slot && req->close.fd)
4781 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4783 struct files_struct *files = current->files;
4784 struct io_close *close = &req->close;
4785 struct fdtable *fdt;
4786 struct file *file = NULL;
4789 if (req->close.file_slot) {
4790 ret = io_close_fixed(req, issue_flags);
4794 spin_lock(&files->file_lock);
4795 fdt = files_fdtable(files);
4796 if (close->fd >= fdt->max_fds) {
4797 spin_unlock(&files->file_lock);
4800 file = fdt->fd[close->fd];
4801 if (!file || file->f_op == &io_uring_fops) {
4802 spin_unlock(&files->file_lock);
4807 /* if the file has a flush method, be safe and punt to async */
4808 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4809 spin_unlock(&files->file_lock);
4813 ret = __close_fd_get_file(close->fd, &file);
4814 spin_unlock(&files->file_lock);
4821 /* No ->flush() or already async, safely close from here */
4822 ret = filp_close(file, current->files);
4828 __io_req_complete(req, issue_flags, ret, 0);
4832 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4834 struct io_ring_ctx *ctx = req->ctx;
4836 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4838 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4842 req->sync.off = READ_ONCE(sqe->off);
4843 req->sync.len = READ_ONCE(sqe->len);
4844 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4848 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4852 /* sync_file_range always requires a blocking context */
4853 if (issue_flags & IO_URING_F_NONBLOCK)
4856 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4860 io_req_complete(req, ret);
4864 #if defined(CONFIG_NET)
4865 static int io_setup_async_msg(struct io_kiocb *req,
4866 struct io_async_msghdr *kmsg)
4868 struct io_async_msghdr *async_msg = req->async_data;
4872 if (io_alloc_async_data(req)) {
4873 kfree(kmsg->free_iov);
4876 async_msg = req->async_data;
4877 req->flags |= REQ_F_NEED_CLEANUP;
4878 memcpy(async_msg, kmsg, sizeof(*kmsg));
4879 async_msg->msg.msg_name = &async_msg->addr;
4880 /* if were using fast_iov, set it to the new one */
4881 if (!async_msg->free_iov)
4882 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4887 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4888 struct io_async_msghdr *iomsg)
4890 iomsg->msg.msg_name = &iomsg->addr;
4891 iomsg->free_iov = iomsg->fast_iov;
4892 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4893 req->sr_msg.msg_flags, &iomsg->free_iov);
4896 static int io_sendmsg_prep_async(struct io_kiocb *req)
4900 ret = io_sendmsg_copy_hdr(req, req->async_data);
4902 req->flags |= REQ_F_NEED_CLEANUP;
4906 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4908 struct io_sr_msg *sr = &req->sr_msg;
4910 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4913 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4914 sr->len = READ_ONCE(sqe->len);
4915 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4916 if (sr->msg_flags & MSG_DONTWAIT)
4917 req->flags |= REQ_F_NOWAIT;
4919 #ifdef CONFIG_COMPAT
4920 if (req->ctx->compat)
4921 sr->msg_flags |= MSG_CMSG_COMPAT;
4926 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4928 struct io_async_msghdr iomsg, *kmsg;
4929 struct socket *sock;
4934 sock = sock_from_file(req->file);
4935 if (unlikely(!sock))
4938 if (req_has_async_data(req)) {
4939 kmsg = req->async_data;
4941 ret = io_sendmsg_copy_hdr(req, &iomsg);
4947 flags = req->sr_msg.msg_flags;
4948 if (issue_flags & IO_URING_F_NONBLOCK)
4949 flags |= MSG_DONTWAIT;
4950 if (flags & MSG_WAITALL)
4951 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4953 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4955 if (ret < min_ret) {
4956 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
4957 return io_setup_async_msg(req, kmsg);
4958 if (ret == -ERESTARTSYS)
4962 /* fast path, check for non-NULL to avoid function call */
4964 kfree(kmsg->free_iov);
4965 req->flags &= ~REQ_F_NEED_CLEANUP;
4966 __io_req_complete(req, issue_flags, ret, 0);
4970 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4972 struct io_sr_msg *sr = &req->sr_msg;
4975 struct socket *sock;
4980 sock = sock_from_file(req->file);
4981 if (unlikely(!sock))
4984 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4988 msg.msg_name = NULL;
4989 msg.msg_control = NULL;
4990 msg.msg_controllen = 0;
4991 msg.msg_namelen = 0;
4993 flags = req->sr_msg.msg_flags;
4994 if (issue_flags & IO_URING_F_NONBLOCK)
4995 flags |= MSG_DONTWAIT;
4996 if (flags & MSG_WAITALL)
4997 min_ret = iov_iter_count(&msg.msg_iter);
4999 msg.msg_flags = flags;
5000 ret = sock_sendmsg(sock, &msg);
5001 if (ret < min_ret) {
5002 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5004 if (ret == -ERESTARTSYS)
5008 __io_req_complete(req, issue_flags, ret, 0);
5012 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5013 struct io_async_msghdr *iomsg)
5015 struct io_sr_msg *sr = &req->sr_msg;
5016 struct iovec __user *uiov;
5020 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5021 &iomsg->uaddr, &uiov, &iov_len);
5025 if (req->flags & REQ_F_BUFFER_SELECT) {
5028 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5030 sr->len = iomsg->fast_iov[0].iov_len;
5031 iomsg->free_iov = NULL;
5033 iomsg->free_iov = iomsg->fast_iov;
5034 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5035 &iomsg->free_iov, &iomsg->msg.msg_iter,
5044 #ifdef CONFIG_COMPAT
5045 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5046 struct io_async_msghdr *iomsg)
5048 struct io_sr_msg *sr = &req->sr_msg;
5049 struct compat_iovec __user *uiov;
5054 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5059 uiov = compat_ptr(ptr);
5060 if (req->flags & REQ_F_BUFFER_SELECT) {
5061 compat_ssize_t clen;
5065 if (!access_ok(uiov, sizeof(*uiov)))
5067 if (__get_user(clen, &uiov->iov_len))
5072 iomsg->free_iov = NULL;
5074 iomsg->free_iov = iomsg->fast_iov;
5075 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5076 UIO_FASTIOV, &iomsg->free_iov,
5077 &iomsg->msg.msg_iter, true);
5086 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5087 struct io_async_msghdr *iomsg)
5089 iomsg->msg.msg_name = &iomsg->addr;
5091 #ifdef CONFIG_COMPAT
5092 if (req->ctx->compat)
5093 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5096 return __io_recvmsg_copy_hdr(req, iomsg);
5099 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5100 unsigned int issue_flags)
5102 struct io_sr_msg *sr = &req->sr_msg;
5104 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5107 static int io_recvmsg_prep_async(struct io_kiocb *req)
5111 ret = io_recvmsg_copy_hdr(req, req->async_data);
5113 req->flags |= REQ_F_NEED_CLEANUP;
5117 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5119 struct io_sr_msg *sr = &req->sr_msg;
5121 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5124 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5125 sr->len = READ_ONCE(sqe->len);
5126 sr->bgid = READ_ONCE(sqe->buf_group);
5127 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5128 if (sr->msg_flags & MSG_DONTWAIT)
5129 req->flags |= REQ_F_NOWAIT;
5131 #ifdef CONFIG_COMPAT
5132 if (req->ctx->compat)
5133 sr->msg_flags |= MSG_CMSG_COMPAT;
5138 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5140 struct io_async_msghdr iomsg, *kmsg;
5141 struct socket *sock;
5142 struct io_buffer *kbuf;
5144 int ret, min_ret = 0;
5145 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5147 sock = sock_from_file(req->file);
5148 if (unlikely(!sock))
5151 if (req_has_async_data(req)) {
5152 kmsg = req->async_data;
5154 ret = io_recvmsg_copy_hdr(req, &iomsg);
5160 if (req->flags & REQ_F_BUFFER_SELECT) {
5161 kbuf = io_recv_buffer_select(req, issue_flags);
5163 return PTR_ERR(kbuf);
5164 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5165 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5166 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5167 1, req->sr_msg.len);
5170 flags = req->sr_msg.msg_flags;
5172 flags |= MSG_DONTWAIT;
5173 if (flags & MSG_WAITALL)
5174 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5176 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5177 kmsg->uaddr, flags);
5178 if (ret < min_ret) {
5179 if (ret == -EAGAIN && force_nonblock)
5180 return io_setup_async_msg(req, kmsg);
5181 if (ret == -ERESTARTSYS)
5184 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5188 /* fast path, check for non-NULL to avoid function call */
5190 kfree(kmsg->free_iov);
5191 req->flags &= ~REQ_F_NEED_CLEANUP;
5192 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req));
5196 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5198 struct io_buffer *kbuf;
5199 struct io_sr_msg *sr = &req->sr_msg;
5201 void __user *buf = sr->buf;
5202 struct socket *sock;
5205 int ret, min_ret = 0;
5206 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5208 sock = sock_from_file(req->file);
5209 if (unlikely(!sock))
5212 if (req->flags & REQ_F_BUFFER_SELECT) {
5213 kbuf = io_recv_buffer_select(req, issue_flags);
5215 return PTR_ERR(kbuf);
5216 buf = u64_to_user_ptr(kbuf->addr);
5219 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5223 msg.msg_name = NULL;
5224 msg.msg_control = NULL;
5225 msg.msg_controllen = 0;
5226 msg.msg_namelen = 0;
5227 msg.msg_iocb = NULL;
5230 flags = req->sr_msg.msg_flags;
5232 flags |= MSG_DONTWAIT;
5233 if (flags & MSG_WAITALL)
5234 min_ret = iov_iter_count(&msg.msg_iter);
5236 ret = sock_recvmsg(sock, &msg, flags);
5238 if (ret < min_ret) {
5239 if (ret == -EAGAIN && force_nonblock)
5241 if (ret == -ERESTARTSYS)
5244 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5248 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req));
5252 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5254 struct io_accept *accept = &req->accept;
5256 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5258 if (sqe->ioprio || sqe->len || sqe->buf_index)
5261 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5262 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5263 accept->flags = READ_ONCE(sqe->accept_flags);
5264 accept->nofile = rlimit(RLIMIT_NOFILE);
5266 accept->file_slot = READ_ONCE(sqe->file_index);
5267 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
5268 (accept->flags & SOCK_CLOEXEC)))
5270 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5272 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5273 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5277 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5279 struct io_accept *accept = &req->accept;
5280 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5281 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5282 bool fixed = !!accept->file_slot;
5286 if (req->file->f_flags & O_NONBLOCK)
5287 req->flags |= REQ_F_NOWAIT;
5290 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5291 if (unlikely(fd < 0))
5294 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5299 ret = PTR_ERR(file);
5300 if (ret == -EAGAIN && force_nonblock)
5302 if (ret == -ERESTARTSYS)
5305 } else if (!fixed) {
5306 fd_install(fd, file);
5309 ret = io_install_fixed_file(req, file, issue_flags,
5310 accept->file_slot - 1);
5312 __io_req_complete(req, issue_flags, ret, 0);
5316 static int io_connect_prep_async(struct io_kiocb *req)
5318 struct io_async_connect *io = req->async_data;
5319 struct io_connect *conn = &req->connect;
5321 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5324 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5326 struct io_connect *conn = &req->connect;
5328 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5330 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5334 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5335 conn->addr_len = READ_ONCE(sqe->addr2);
5339 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5341 struct io_async_connect __io, *io;
5342 unsigned file_flags;
5344 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5346 if (req_has_async_data(req)) {
5347 io = req->async_data;
5349 ret = move_addr_to_kernel(req->connect.addr,
5350 req->connect.addr_len,
5357 file_flags = force_nonblock ? O_NONBLOCK : 0;
5359 ret = __sys_connect_file(req->file, &io->address,
5360 req->connect.addr_len, file_flags);
5361 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5362 if (req_has_async_data(req))
5364 if (io_alloc_async_data(req)) {
5368 memcpy(req->async_data, &__io, sizeof(__io));
5371 if (ret == -ERESTARTSYS)
5376 __io_req_complete(req, issue_flags, ret, 0);
5379 #else /* !CONFIG_NET */
5380 #define IO_NETOP_FN(op) \
5381 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5383 return -EOPNOTSUPP; \
5386 #define IO_NETOP_PREP(op) \
5388 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5390 return -EOPNOTSUPP; \
5393 #define IO_NETOP_PREP_ASYNC(op) \
5395 static int io_##op##_prep_async(struct io_kiocb *req) \
5397 return -EOPNOTSUPP; \
5400 IO_NETOP_PREP_ASYNC(sendmsg);
5401 IO_NETOP_PREP_ASYNC(recvmsg);
5402 IO_NETOP_PREP_ASYNC(connect);
5403 IO_NETOP_PREP(accept);
5406 #endif /* CONFIG_NET */
5408 struct io_poll_table {
5409 struct poll_table_struct pt;
5410 struct io_kiocb *req;
5415 #define IO_POLL_CANCEL_FLAG BIT(31)
5416 #define IO_POLL_REF_MASK ((1u << 20)-1)
5419 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5420 * bump it and acquire ownership. It's disallowed to modify requests while not
5421 * owning it, that prevents from races for enqueueing task_work's and b/w
5422 * arming poll and wakeups.
5424 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5426 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5429 static void io_poll_mark_cancelled(struct io_kiocb *req)
5431 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5434 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5436 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5437 if (req->opcode == IORING_OP_POLL_ADD)
5438 return req->async_data;
5439 return req->apoll->double_poll;
5442 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5444 if (req->opcode == IORING_OP_POLL_ADD)
5446 return &req->apoll->poll;
5449 static void io_poll_req_insert(struct io_kiocb *req)
5451 struct io_ring_ctx *ctx = req->ctx;
5452 struct hlist_head *list;
5454 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5455 hlist_add_head(&req->hash_node, list);
5458 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5459 wait_queue_func_t wake_func)
5462 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5463 /* mask in events that we always want/need */
5464 poll->events = events | IO_POLL_UNMASK;
5465 INIT_LIST_HEAD(&poll->wait.entry);
5466 init_waitqueue_func_entry(&poll->wait, wake_func);
5469 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5471 struct wait_queue_head *head = poll->head;
5473 spin_lock_irq(&head->lock);
5474 list_del_init(&poll->wait.entry);
5476 spin_unlock_irq(&head->lock);
5479 static void io_poll_remove_entries(struct io_kiocb *req)
5481 struct io_poll_iocb *poll = io_poll_get_single(req);
5482 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5485 io_poll_remove_entry(poll);
5486 if (poll_double && poll_double->head)
5487 io_poll_remove_entry(poll_double);
5491 * All poll tw should go through this. Checks for poll events, manages
5492 * references, does rewait, etc.
5494 * Returns a negative error on failure. >0 when no action require, which is
5495 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5496 * the request, then the mask is stored in req->result.
5498 static int io_poll_check_events(struct io_kiocb *req)
5500 struct io_ring_ctx *ctx = req->ctx;
5501 struct io_poll_iocb *poll = io_poll_get_single(req);
5504 /* req->task == current here, checking PF_EXITING is safe */
5505 if (unlikely(req->task->flags & PF_EXITING))
5506 io_poll_mark_cancelled(req);
5509 v = atomic_read(&req->poll_refs);
5511 /* tw handler should be the owner, and so have some references */
5512 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5514 if (v & IO_POLL_CANCEL_FLAG)
5518 struct poll_table_struct pt = { ._key = poll->events };
5520 req->result = vfs_poll(req->file, &pt) & poll->events;
5523 /* multishot, just fill an CQE and proceed */
5524 if (req->result && !(poll->events & EPOLLONESHOT)) {
5525 __poll_t mask = mangle_poll(req->result & poll->events);
5528 spin_lock(&ctx->completion_lock);
5529 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5531 io_commit_cqring(ctx);
5532 spin_unlock(&ctx->completion_lock);
5533 if (unlikely(!filled))
5535 io_cqring_ev_posted(ctx);
5536 } else if (req->result) {
5541 * Release all references, retry if someone tried to restart
5542 * task_work while we were executing it.
5544 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5549 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5551 struct io_ring_ctx *ctx = req->ctx;
5554 ret = io_poll_check_events(req);
5559 req->result = mangle_poll(req->result & req->poll.events);
5565 io_poll_remove_entries(req);
5566 spin_lock(&ctx->completion_lock);
5567 hash_del(&req->hash_node);
5568 __io_req_complete_post(req, req->result, 0);
5569 io_commit_cqring(ctx);
5570 spin_unlock(&ctx->completion_lock);
5571 io_cqring_ev_posted(ctx);
5574 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5576 struct io_ring_ctx *ctx = req->ctx;
5579 ret = io_poll_check_events(req);
5583 io_poll_remove_entries(req);
5584 spin_lock(&ctx->completion_lock);
5585 hash_del(&req->hash_node);
5586 spin_unlock(&ctx->completion_lock);
5589 io_req_task_submit(req, locked);
5591 io_req_complete_failed(req, ret);
5594 static void __io_poll_execute(struct io_kiocb *req, int mask)
5597 if (req->opcode == IORING_OP_POLL_ADD)
5598 req->io_task_work.func = io_poll_task_func;
5600 req->io_task_work.func = io_apoll_task_func;
5602 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5603 io_req_task_work_add(req, false);
5606 static inline void io_poll_execute(struct io_kiocb *req, int res)
5608 if (io_poll_get_ownership(req))
5609 __io_poll_execute(req, res);
5612 static void io_poll_cancel_req(struct io_kiocb *req)
5614 io_poll_mark_cancelled(req);
5615 /* kick tw, which should complete the request */
5616 io_poll_execute(req, 0);
5619 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5622 struct io_kiocb *req = wait->private;
5623 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5625 __poll_t mask = key_to_poll(key);
5627 /* for instances that support it check for an event match first */
5628 if (mask && !(mask & poll->events))
5631 if (io_poll_get_ownership(req)) {
5632 /* optional, saves extra locking for removal in tw handler */
5633 if (mask && poll->events & EPOLLONESHOT) {
5634 list_del_init(&poll->wait.entry);
5637 __io_poll_execute(req, mask);
5642 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5643 struct wait_queue_head *head,
5644 struct io_poll_iocb **poll_ptr)
5646 struct io_kiocb *req = pt->req;
5649 * The file being polled uses multiple waitqueues for poll handling
5650 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5653 if (unlikely(pt->nr_entries)) {
5654 struct io_poll_iocb *first = poll;
5656 /* double add on the same waitqueue head, ignore */
5657 if (first->head == head)
5659 /* already have a 2nd entry, fail a third attempt */
5661 if ((*poll_ptr)->head == head)
5663 pt->error = -EINVAL;
5667 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5669 pt->error = -ENOMEM;
5672 io_init_poll_iocb(poll, first->events, first->wait.func);
5674 if (req->opcode == IORING_OP_POLL_ADD)
5675 req->flags |= REQ_F_ASYNC_DATA;
5680 poll->wait.private = req;
5682 if (poll->events & EPOLLEXCLUSIVE)
5683 add_wait_queue_exclusive(head, &poll->wait);
5685 add_wait_queue(head, &poll->wait);
5688 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5689 struct poll_table_struct *p)
5691 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5693 __io_queue_proc(&pt->req->poll, pt, head,
5694 (struct io_poll_iocb **) &pt->req->async_data);
5697 static int __io_arm_poll_handler(struct io_kiocb *req,
5698 struct io_poll_iocb *poll,
5699 struct io_poll_table *ipt, __poll_t mask)
5701 struct io_ring_ctx *ctx = req->ctx;
5704 INIT_HLIST_NODE(&req->hash_node);
5705 io_init_poll_iocb(poll, mask, io_poll_wake);
5706 poll->file = req->file;
5707 poll->wait.private = req;
5709 ipt->pt._key = mask;
5712 ipt->nr_entries = 0;
5715 * Take the ownership to delay any tw execution up until we're done
5716 * with poll arming. see io_poll_get_ownership().
5718 atomic_set(&req->poll_refs, 1);
5719 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5721 if (mask && (poll->events & EPOLLONESHOT)) {
5722 io_poll_remove_entries(req);
5723 /* no one else has access to the req, forget about the ref */
5726 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5727 io_poll_remove_entries(req);
5729 ipt->error = -EINVAL;
5733 spin_lock(&ctx->completion_lock);
5734 io_poll_req_insert(req);
5735 spin_unlock(&ctx->completion_lock);
5738 /* can't multishot if failed, just queue the event we've got */
5739 if (unlikely(ipt->error || !ipt->nr_entries))
5740 poll->events |= EPOLLONESHOT;
5741 __io_poll_execute(req, mask);
5746 * Release ownership. If someone tried to queue a tw while it was
5747 * locked, kick it off for them.
5749 v = atomic_dec_return(&req->poll_refs);
5750 if (unlikely(v & IO_POLL_REF_MASK))
5751 __io_poll_execute(req, 0);
5755 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5756 struct poll_table_struct *p)
5758 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5759 struct async_poll *apoll = pt->req->apoll;
5761 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5770 static int io_arm_poll_handler(struct io_kiocb *req)
5772 const struct io_op_def *def = &io_op_defs[req->opcode];
5773 struct io_ring_ctx *ctx = req->ctx;
5774 struct async_poll *apoll;
5775 struct io_poll_table ipt;
5776 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5779 if (!def->pollin && !def->pollout)
5780 return IO_APOLL_ABORTED;
5781 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
5782 return IO_APOLL_ABORTED;
5785 mask |= POLLIN | POLLRDNORM;
5787 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5788 if ((req->opcode == IORING_OP_RECVMSG) &&
5789 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5792 mask |= POLLOUT | POLLWRNORM;
5795 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5796 if (unlikely(!apoll))
5797 return IO_APOLL_ABORTED;
5798 apoll->double_poll = NULL;
5800 req->flags |= REQ_F_POLLED;
5801 ipt.pt._qproc = io_async_queue_proc;
5803 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5804 if (ret || ipt.error)
5805 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5807 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5808 mask, apoll->poll.events);
5813 * Returns true if we found and killed one or more poll requests
5815 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
5816 struct task_struct *tsk, bool cancel_all)
5818 struct hlist_node *tmp;
5819 struct io_kiocb *req;
5823 spin_lock(&ctx->completion_lock);
5824 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5825 struct hlist_head *list;
5827 list = &ctx->cancel_hash[i];
5828 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5829 if (io_match_task_safe(req, tsk, cancel_all)) {
5830 io_poll_cancel_req(req);
5835 spin_unlock(&ctx->completion_lock);
5839 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5841 __must_hold(&ctx->completion_lock)
5843 struct hlist_head *list;
5844 struct io_kiocb *req;
5846 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5847 hlist_for_each_entry(req, list, hash_node) {
5848 if (sqe_addr != req->user_data)
5850 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5857 static bool io_poll_disarm(struct io_kiocb *req)
5858 __must_hold(&ctx->completion_lock)
5860 if (!io_poll_get_ownership(req))
5862 io_poll_remove_entries(req);
5863 hash_del(&req->hash_node);
5867 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5869 __must_hold(&ctx->completion_lock)
5871 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
5875 io_poll_cancel_req(req);
5879 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5884 events = READ_ONCE(sqe->poll32_events);
5886 events = swahw32(events);
5888 if (!(flags & IORING_POLL_ADD_MULTI))
5889 events |= EPOLLONESHOT;
5890 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5893 static int io_poll_update_prep(struct io_kiocb *req,
5894 const struct io_uring_sqe *sqe)
5896 struct io_poll_update *upd = &req->poll_update;
5899 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5901 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5903 flags = READ_ONCE(sqe->len);
5904 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5905 IORING_POLL_ADD_MULTI))
5907 /* meaningless without update */
5908 if (flags == IORING_POLL_ADD_MULTI)
5911 upd->old_user_data = READ_ONCE(sqe->addr);
5912 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5913 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5915 upd->new_user_data = READ_ONCE(sqe->off);
5916 if (!upd->update_user_data && upd->new_user_data)
5918 if (upd->update_events)
5919 upd->events = io_poll_parse_events(sqe, flags);
5920 else if (sqe->poll32_events)
5926 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5928 struct io_poll_iocb *poll = &req->poll;
5931 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5933 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5935 flags = READ_ONCE(sqe->len);
5936 if (flags & ~IORING_POLL_ADD_MULTI)
5938 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
5941 io_req_set_refcount(req);
5942 poll->events = io_poll_parse_events(sqe, flags);
5946 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5948 struct io_poll_iocb *poll = &req->poll;
5949 struct io_poll_table ipt;
5952 ipt.pt._qproc = io_poll_queue_proc;
5954 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
5955 ret = ret ?: ipt.error;
5957 __io_req_complete(req, issue_flags, ret, 0);
5961 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5963 struct io_ring_ctx *ctx = req->ctx;
5964 struct io_kiocb *preq;
5968 spin_lock(&ctx->completion_lock);
5969 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5970 if (!preq || !io_poll_disarm(preq)) {
5971 spin_unlock(&ctx->completion_lock);
5972 ret = preq ? -EALREADY : -ENOENT;
5975 spin_unlock(&ctx->completion_lock);
5977 if (req->poll_update.update_events || req->poll_update.update_user_data) {
5978 /* only mask one event flags, keep behavior flags */
5979 if (req->poll_update.update_events) {
5980 preq->poll.events &= ~0xffff;
5981 preq->poll.events |= req->poll_update.events & 0xffff;
5982 preq->poll.events |= IO_POLL_UNMASK;
5984 if (req->poll_update.update_user_data)
5985 preq->user_data = req->poll_update.new_user_data;
5987 ret2 = io_poll_add(preq, issue_flags);
5988 /* successfully updated, don't complete poll request */
5994 preq->result = -ECANCELED;
5995 locked = !(issue_flags & IO_URING_F_UNLOCKED);
5996 io_req_task_complete(preq, &locked);
6000 /* complete update request, we're done with it */
6001 __io_req_complete(req, issue_flags, ret, 0);
6005 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6007 struct io_timeout_data *data = container_of(timer,
6008 struct io_timeout_data, timer);
6009 struct io_kiocb *req = data->req;
6010 struct io_ring_ctx *ctx = req->ctx;
6011 unsigned long flags;
6013 spin_lock_irqsave(&ctx->timeout_lock, flags);
6014 list_del_init(&req->timeout.list);
6015 atomic_set(&req->ctx->cq_timeouts,
6016 atomic_read(&req->ctx->cq_timeouts) + 1);
6017 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6019 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6022 req->result = -ETIME;
6023 req->io_task_work.func = io_req_task_complete;
6024 io_req_task_work_add(req, false);
6025 return HRTIMER_NORESTART;
6028 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6030 __must_hold(&ctx->timeout_lock)
6032 struct io_timeout_data *io;
6033 struct io_kiocb *req;
6036 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6037 found = user_data == req->user_data;
6042 return ERR_PTR(-ENOENT);
6044 io = req->async_data;
6045 if (hrtimer_try_to_cancel(&io->timer) == -1)
6046 return ERR_PTR(-EALREADY);
6047 list_del_init(&req->timeout.list);
6051 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6052 __must_hold(&ctx->completion_lock)
6053 __must_hold(&ctx->timeout_lock)
6055 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6058 return PTR_ERR(req);
6061 io_fill_cqe_req(req, -ECANCELED, 0);
6062 io_put_req_deferred(req);
6066 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6068 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6069 case IORING_TIMEOUT_BOOTTIME:
6070 return CLOCK_BOOTTIME;
6071 case IORING_TIMEOUT_REALTIME:
6072 return CLOCK_REALTIME;
6074 /* can't happen, vetted at prep time */
6078 return CLOCK_MONOTONIC;
6082 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6083 struct timespec64 *ts, enum hrtimer_mode mode)
6084 __must_hold(&ctx->timeout_lock)
6086 struct io_timeout_data *io;
6087 struct io_kiocb *req;
6090 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6091 found = user_data == req->user_data;
6098 io = req->async_data;
6099 if (hrtimer_try_to_cancel(&io->timer) == -1)
6101 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6102 io->timer.function = io_link_timeout_fn;
6103 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6107 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6108 struct timespec64 *ts, enum hrtimer_mode mode)
6109 __must_hold(&ctx->timeout_lock)
6111 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6112 struct io_timeout_data *data;
6115 return PTR_ERR(req);
6117 req->timeout.off = 0; /* noseq */
6118 data = req->async_data;
6119 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6120 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6121 data->timer.function = io_timeout_fn;
6122 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6126 static int io_timeout_remove_prep(struct io_kiocb *req,
6127 const struct io_uring_sqe *sqe)
6129 struct io_timeout_rem *tr = &req->timeout_rem;
6131 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6133 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6135 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6138 tr->ltimeout = false;
6139 tr->addr = READ_ONCE(sqe->addr);
6140 tr->flags = READ_ONCE(sqe->timeout_flags);
6141 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6142 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6144 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6145 tr->ltimeout = true;
6146 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6148 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6150 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6152 } else if (tr->flags) {
6153 /* timeout removal doesn't support flags */
6160 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6162 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6167 * Remove or update an existing timeout command
6169 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6171 struct io_timeout_rem *tr = &req->timeout_rem;
6172 struct io_ring_ctx *ctx = req->ctx;
6175 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6176 spin_lock(&ctx->completion_lock);
6177 spin_lock_irq(&ctx->timeout_lock);
6178 ret = io_timeout_cancel(ctx, tr->addr);
6179 spin_unlock_irq(&ctx->timeout_lock);
6180 spin_unlock(&ctx->completion_lock);
6182 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6184 spin_lock_irq(&ctx->timeout_lock);
6186 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6188 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6189 spin_unlock_irq(&ctx->timeout_lock);
6194 io_req_complete_post(req, ret, 0);
6198 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6199 bool is_timeout_link)
6201 struct io_timeout_data *data;
6203 u32 off = READ_ONCE(sqe->off);
6205 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6207 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6210 if (off && is_timeout_link)
6212 flags = READ_ONCE(sqe->timeout_flags);
6213 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6214 IORING_TIMEOUT_ETIME_SUCCESS))
6216 /* more than one clock specified is invalid, obviously */
6217 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6220 INIT_LIST_HEAD(&req->timeout.list);
6221 req->timeout.off = off;
6222 if (unlikely(off && !req->ctx->off_timeout_used))
6223 req->ctx->off_timeout_used = true;
6225 if (WARN_ON_ONCE(req_has_async_data(req)))
6227 if (io_alloc_async_data(req))
6230 data = req->async_data;
6232 data->flags = flags;
6234 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6237 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6240 data->mode = io_translate_timeout_mode(flags);
6241 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6243 if (is_timeout_link) {
6244 struct io_submit_link *link = &req->ctx->submit_state.link;
6248 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6250 req->timeout.head = link->last;
6251 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6256 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6258 struct io_ring_ctx *ctx = req->ctx;
6259 struct io_timeout_data *data = req->async_data;
6260 struct list_head *entry;
6261 u32 tail, off = req->timeout.off;
6263 spin_lock_irq(&ctx->timeout_lock);
6266 * sqe->off holds how many events that need to occur for this
6267 * timeout event to be satisfied. If it isn't set, then this is
6268 * a pure timeout request, sequence isn't used.
6270 if (io_is_timeout_noseq(req)) {
6271 entry = ctx->timeout_list.prev;
6275 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6276 req->timeout.target_seq = tail + off;
6278 /* Update the last seq here in case io_flush_timeouts() hasn't.
6279 * This is safe because ->completion_lock is held, and submissions
6280 * and completions are never mixed in the same ->completion_lock section.
6282 ctx->cq_last_tm_flush = tail;
6285 * Insertion sort, ensuring the first entry in the list is always
6286 * the one we need first.
6288 list_for_each_prev(entry, &ctx->timeout_list) {
6289 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6292 if (io_is_timeout_noseq(nxt))
6294 /* nxt.seq is behind @tail, otherwise would've been completed */
6295 if (off >= nxt->timeout.target_seq - tail)
6299 list_add(&req->timeout.list, entry);
6300 data->timer.function = io_timeout_fn;
6301 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6302 spin_unlock_irq(&ctx->timeout_lock);
6306 struct io_cancel_data {
6307 struct io_ring_ctx *ctx;
6311 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6313 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6314 struct io_cancel_data *cd = data;
6316 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6319 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6320 struct io_ring_ctx *ctx)
6322 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6323 enum io_wq_cancel cancel_ret;
6326 if (!tctx || !tctx->io_wq)
6329 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6330 switch (cancel_ret) {
6331 case IO_WQ_CANCEL_OK:
6334 case IO_WQ_CANCEL_RUNNING:
6337 case IO_WQ_CANCEL_NOTFOUND:
6345 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6347 struct io_ring_ctx *ctx = req->ctx;
6350 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6352 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6356 spin_lock(&ctx->completion_lock);
6357 spin_lock_irq(&ctx->timeout_lock);
6358 ret = io_timeout_cancel(ctx, sqe_addr);
6359 spin_unlock_irq(&ctx->timeout_lock);
6362 ret = io_poll_cancel(ctx, sqe_addr, false);
6364 spin_unlock(&ctx->completion_lock);
6368 static int io_async_cancel_prep(struct io_kiocb *req,
6369 const struct io_uring_sqe *sqe)
6371 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6373 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6375 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6379 req->cancel.addr = READ_ONCE(sqe->addr);
6383 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6385 struct io_ring_ctx *ctx = req->ctx;
6386 u64 sqe_addr = req->cancel.addr;
6387 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6388 struct io_tctx_node *node;
6391 ret = io_try_cancel_userdata(req, sqe_addr);
6395 /* slow path, try all io-wq's */
6396 io_ring_submit_lock(ctx, needs_lock);
6398 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6399 struct io_uring_task *tctx = node->task->io_uring;
6401 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6405 io_ring_submit_unlock(ctx, needs_lock);
6409 io_req_complete_post(req, ret, 0);
6413 static int io_rsrc_update_prep(struct io_kiocb *req,
6414 const struct io_uring_sqe *sqe)
6416 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6418 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6421 req->rsrc_update.offset = READ_ONCE(sqe->off);
6422 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6423 if (!req->rsrc_update.nr_args)
6425 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6429 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6431 struct io_ring_ctx *ctx = req->ctx;
6432 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6433 struct io_uring_rsrc_update2 up;
6436 up.offset = req->rsrc_update.offset;
6437 up.data = req->rsrc_update.arg;
6442 io_ring_submit_lock(ctx, needs_lock);
6443 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6444 &up, req->rsrc_update.nr_args);
6445 io_ring_submit_unlock(ctx, needs_lock);
6449 __io_req_complete(req, issue_flags, ret, 0);
6453 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6455 switch (req->opcode) {
6458 case IORING_OP_READV:
6459 case IORING_OP_READ_FIXED:
6460 case IORING_OP_READ:
6461 return io_read_prep(req, sqe);
6462 case IORING_OP_WRITEV:
6463 case IORING_OP_WRITE_FIXED:
6464 case IORING_OP_WRITE:
6465 return io_write_prep(req, sqe);
6466 case IORING_OP_POLL_ADD:
6467 return io_poll_add_prep(req, sqe);
6468 case IORING_OP_POLL_REMOVE:
6469 return io_poll_update_prep(req, sqe);
6470 case IORING_OP_FSYNC:
6471 return io_fsync_prep(req, sqe);
6472 case IORING_OP_SYNC_FILE_RANGE:
6473 return io_sfr_prep(req, sqe);
6474 case IORING_OP_SENDMSG:
6475 case IORING_OP_SEND:
6476 return io_sendmsg_prep(req, sqe);
6477 case IORING_OP_RECVMSG:
6478 case IORING_OP_RECV:
6479 return io_recvmsg_prep(req, sqe);
6480 case IORING_OP_CONNECT:
6481 return io_connect_prep(req, sqe);
6482 case IORING_OP_TIMEOUT:
6483 return io_timeout_prep(req, sqe, false);
6484 case IORING_OP_TIMEOUT_REMOVE:
6485 return io_timeout_remove_prep(req, sqe);
6486 case IORING_OP_ASYNC_CANCEL:
6487 return io_async_cancel_prep(req, sqe);
6488 case IORING_OP_LINK_TIMEOUT:
6489 return io_timeout_prep(req, sqe, true);
6490 case IORING_OP_ACCEPT:
6491 return io_accept_prep(req, sqe);
6492 case IORING_OP_FALLOCATE:
6493 return io_fallocate_prep(req, sqe);
6494 case IORING_OP_OPENAT:
6495 return io_openat_prep(req, sqe);
6496 case IORING_OP_CLOSE:
6497 return io_close_prep(req, sqe);
6498 case IORING_OP_FILES_UPDATE:
6499 return io_rsrc_update_prep(req, sqe);
6500 case IORING_OP_STATX:
6501 return io_statx_prep(req, sqe);
6502 case IORING_OP_FADVISE:
6503 return io_fadvise_prep(req, sqe);
6504 case IORING_OP_MADVISE:
6505 return io_madvise_prep(req, sqe);
6506 case IORING_OP_OPENAT2:
6507 return io_openat2_prep(req, sqe);
6508 case IORING_OP_EPOLL_CTL:
6509 return io_epoll_ctl_prep(req, sqe);
6510 case IORING_OP_SPLICE:
6511 return io_splice_prep(req, sqe);
6512 case IORING_OP_PROVIDE_BUFFERS:
6513 return io_provide_buffers_prep(req, sqe);
6514 case IORING_OP_REMOVE_BUFFERS:
6515 return io_remove_buffers_prep(req, sqe);
6517 return io_tee_prep(req, sqe);
6518 case IORING_OP_SHUTDOWN:
6519 return io_shutdown_prep(req, sqe);
6520 case IORING_OP_RENAMEAT:
6521 return io_renameat_prep(req, sqe);
6522 case IORING_OP_UNLINKAT:
6523 return io_unlinkat_prep(req, sqe);
6524 case IORING_OP_MKDIRAT:
6525 return io_mkdirat_prep(req, sqe);
6526 case IORING_OP_SYMLINKAT:
6527 return io_symlinkat_prep(req, sqe);
6528 case IORING_OP_LINKAT:
6529 return io_linkat_prep(req, sqe);
6532 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6537 static int io_req_prep_async(struct io_kiocb *req)
6539 if (!io_op_defs[req->opcode].needs_async_setup)
6541 if (WARN_ON_ONCE(req_has_async_data(req)))
6543 if (io_alloc_async_data(req))
6546 switch (req->opcode) {
6547 case IORING_OP_READV:
6548 return io_rw_prep_async(req, READ);
6549 case IORING_OP_WRITEV:
6550 return io_rw_prep_async(req, WRITE);
6551 case IORING_OP_SENDMSG:
6552 return io_sendmsg_prep_async(req);
6553 case IORING_OP_RECVMSG:
6554 return io_recvmsg_prep_async(req);
6555 case IORING_OP_CONNECT:
6556 return io_connect_prep_async(req);
6558 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6563 static u32 io_get_sequence(struct io_kiocb *req)
6565 u32 seq = req->ctx->cached_sq_head;
6567 /* need original cached_sq_head, but it was increased for each req */
6568 io_for_each_link(req, req)
6573 static __cold void io_drain_req(struct io_kiocb *req)
6575 struct io_ring_ctx *ctx = req->ctx;
6576 struct io_defer_entry *de;
6578 u32 seq = io_get_sequence(req);
6580 /* Still need defer if there is pending req in defer list. */
6581 spin_lock(&ctx->completion_lock);
6582 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
6583 spin_unlock(&ctx->completion_lock);
6585 ctx->drain_active = false;
6586 io_req_task_queue(req);
6589 spin_unlock(&ctx->completion_lock);
6591 ret = io_req_prep_async(req);
6594 io_req_complete_failed(req, ret);
6597 io_prep_async_link(req);
6598 de = kmalloc(sizeof(*de), GFP_KERNEL);
6604 spin_lock(&ctx->completion_lock);
6605 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6606 spin_unlock(&ctx->completion_lock);
6611 trace_io_uring_defer(ctx, req, req->user_data);
6614 list_add_tail(&de->list, &ctx->defer_list);
6615 spin_unlock(&ctx->completion_lock);
6618 static void io_clean_op(struct io_kiocb *req)
6620 if (req->flags & REQ_F_BUFFER_SELECTED)
6623 if (req->flags & REQ_F_NEED_CLEANUP) {
6624 switch (req->opcode) {
6625 case IORING_OP_READV:
6626 case IORING_OP_READ_FIXED:
6627 case IORING_OP_READ:
6628 case IORING_OP_WRITEV:
6629 case IORING_OP_WRITE_FIXED:
6630 case IORING_OP_WRITE: {
6631 struct io_async_rw *io = req->async_data;
6633 kfree(io->free_iovec);
6636 case IORING_OP_RECVMSG:
6637 case IORING_OP_SENDMSG: {
6638 struct io_async_msghdr *io = req->async_data;
6640 kfree(io->free_iov);
6643 case IORING_OP_SPLICE:
6645 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6646 io_put_file(req->splice.file_in);
6648 case IORING_OP_OPENAT:
6649 case IORING_OP_OPENAT2:
6650 if (req->open.filename)
6651 putname(req->open.filename);
6653 case IORING_OP_RENAMEAT:
6654 putname(req->rename.oldpath);
6655 putname(req->rename.newpath);
6657 case IORING_OP_UNLINKAT:
6658 putname(req->unlink.filename);
6660 case IORING_OP_MKDIRAT:
6661 putname(req->mkdir.filename);
6663 case IORING_OP_SYMLINKAT:
6664 putname(req->symlink.oldpath);
6665 putname(req->symlink.newpath);
6667 case IORING_OP_LINKAT:
6668 putname(req->hardlink.oldpath);
6669 putname(req->hardlink.newpath);
6673 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6674 kfree(req->apoll->double_poll);
6678 if (req->flags & REQ_F_INFLIGHT) {
6679 struct io_uring_task *tctx = req->task->io_uring;
6681 atomic_dec(&tctx->inflight_tracked);
6683 if (req->flags & REQ_F_CREDS)
6684 put_cred(req->creds);
6685 if (req->flags & REQ_F_ASYNC_DATA) {
6686 kfree(req->async_data);
6687 req->async_data = NULL;
6689 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6692 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6694 const struct cred *creds = NULL;
6697 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
6698 creds = override_creds(req->creds);
6700 if (!io_op_defs[req->opcode].audit_skip)
6701 audit_uring_entry(req->opcode);
6703 switch (req->opcode) {
6705 ret = io_nop(req, issue_flags);
6707 case IORING_OP_READV:
6708 case IORING_OP_READ_FIXED:
6709 case IORING_OP_READ:
6710 ret = io_read(req, issue_flags);
6712 case IORING_OP_WRITEV:
6713 case IORING_OP_WRITE_FIXED:
6714 case IORING_OP_WRITE:
6715 ret = io_write(req, issue_flags);
6717 case IORING_OP_FSYNC:
6718 ret = io_fsync(req, issue_flags);
6720 case IORING_OP_POLL_ADD:
6721 ret = io_poll_add(req, issue_flags);
6723 case IORING_OP_POLL_REMOVE:
6724 ret = io_poll_update(req, issue_flags);
6726 case IORING_OP_SYNC_FILE_RANGE:
6727 ret = io_sync_file_range(req, issue_flags);
6729 case IORING_OP_SENDMSG:
6730 ret = io_sendmsg(req, issue_flags);
6732 case IORING_OP_SEND:
6733 ret = io_send(req, issue_flags);
6735 case IORING_OP_RECVMSG:
6736 ret = io_recvmsg(req, issue_flags);
6738 case IORING_OP_RECV:
6739 ret = io_recv(req, issue_flags);
6741 case IORING_OP_TIMEOUT:
6742 ret = io_timeout(req, issue_flags);
6744 case IORING_OP_TIMEOUT_REMOVE:
6745 ret = io_timeout_remove(req, issue_flags);
6747 case IORING_OP_ACCEPT:
6748 ret = io_accept(req, issue_flags);
6750 case IORING_OP_CONNECT:
6751 ret = io_connect(req, issue_flags);
6753 case IORING_OP_ASYNC_CANCEL:
6754 ret = io_async_cancel(req, issue_flags);
6756 case IORING_OP_FALLOCATE:
6757 ret = io_fallocate(req, issue_flags);
6759 case IORING_OP_OPENAT:
6760 ret = io_openat(req, issue_flags);
6762 case IORING_OP_CLOSE:
6763 ret = io_close(req, issue_flags);
6765 case IORING_OP_FILES_UPDATE:
6766 ret = io_files_update(req, issue_flags);
6768 case IORING_OP_STATX:
6769 ret = io_statx(req, issue_flags);
6771 case IORING_OP_FADVISE:
6772 ret = io_fadvise(req, issue_flags);
6774 case IORING_OP_MADVISE:
6775 ret = io_madvise(req, issue_flags);
6777 case IORING_OP_OPENAT2:
6778 ret = io_openat2(req, issue_flags);
6780 case IORING_OP_EPOLL_CTL:
6781 ret = io_epoll_ctl(req, issue_flags);
6783 case IORING_OP_SPLICE:
6784 ret = io_splice(req, issue_flags);
6786 case IORING_OP_PROVIDE_BUFFERS:
6787 ret = io_provide_buffers(req, issue_flags);
6789 case IORING_OP_REMOVE_BUFFERS:
6790 ret = io_remove_buffers(req, issue_flags);
6793 ret = io_tee(req, issue_flags);
6795 case IORING_OP_SHUTDOWN:
6796 ret = io_shutdown(req, issue_flags);
6798 case IORING_OP_RENAMEAT:
6799 ret = io_renameat(req, issue_flags);
6801 case IORING_OP_UNLINKAT:
6802 ret = io_unlinkat(req, issue_flags);
6804 case IORING_OP_MKDIRAT:
6805 ret = io_mkdirat(req, issue_flags);
6807 case IORING_OP_SYMLINKAT:
6808 ret = io_symlinkat(req, issue_flags);
6810 case IORING_OP_LINKAT:
6811 ret = io_linkat(req, issue_flags);
6818 if (!io_op_defs[req->opcode].audit_skip)
6819 audit_uring_exit(!ret, ret);
6822 revert_creds(creds);
6825 /* If the op doesn't have a file, we're not polling for it */
6826 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6827 io_iopoll_req_issued(req, issue_flags);
6832 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6834 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6836 req = io_put_req_find_next(req);
6837 return req ? &req->work : NULL;
6840 static void io_wq_submit_work(struct io_wq_work *work)
6842 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6843 unsigned int issue_flags = IO_URING_F_UNLOCKED;
6844 bool needs_poll = false;
6845 struct io_kiocb *timeout;
6848 /* one will be dropped by ->io_free_work() after returning to io-wq */
6849 if (!(req->flags & REQ_F_REFCOUNT))
6850 __io_req_set_refcount(req, 2);
6854 timeout = io_prep_linked_timeout(req);
6856 io_queue_linked_timeout(timeout);
6858 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6859 if (work->flags & IO_WQ_WORK_CANCEL) {
6860 io_req_task_queue_fail(req, -ECANCELED);
6864 if (req->flags & REQ_F_FORCE_ASYNC) {
6865 const struct io_op_def *def = &io_op_defs[req->opcode];
6866 bool opcode_poll = def->pollin || def->pollout;
6868 if (opcode_poll && file_can_poll(req->file)) {
6870 issue_flags |= IO_URING_F_NONBLOCK;
6875 ret = io_issue_sqe(req, issue_flags);
6879 * We can get EAGAIN for iopolled IO even though we're
6880 * forcing a sync submission from here, since we can't
6881 * wait for request slots on the block side.
6888 if (io_arm_poll_handler(req) == IO_APOLL_OK)
6890 /* aborted or ready, in either case retry blocking */
6892 issue_flags &= ~IO_URING_F_NONBLOCK;
6895 /* avoid locking problems by failing it from a clean context */
6897 io_req_task_queue_fail(req, ret);
6900 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6903 return &table->files[i];
6906 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6909 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6911 return (struct file *) (slot->file_ptr & FFS_MASK);
6914 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6916 unsigned long file_ptr = (unsigned long) file;
6918 file_ptr |= io_file_get_flags(file);
6919 file_slot->file_ptr = file_ptr;
6922 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6923 struct io_kiocb *req, int fd)
6926 unsigned long file_ptr;
6928 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6930 fd = array_index_nospec(fd, ctx->nr_user_files);
6931 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6932 file = (struct file *) (file_ptr & FFS_MASK);
6933 file_ptr &= ~FFS_MASK;
6934 /* mask in overlapping REQ_F and FFS bits */
6935 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
6936 io_req_set_rsrc_node(req, ctx);
6940 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6941 struct io_kiocb *req, int fd)
6943 struct file *file = fget(fd);
6945 trace_io_uring_file_get(ctx, fd);
6947 /* we don't allow fixed io_uring files */
6948 if (file && unlikely(file->f_op == &io_uring_fops))
6949 io_req_track_inflight(req);
6953 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6954 struct io_kiocb *req, int fd, bool fixed)
6957 return io_file_get_fixed(ctx, req, fd);
6959 return io_file_get_normal(ctx, req, fd);
6962 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6964 struct io_kiocb *prev = req->timeout.prev;
6968 if (!(req->task->flags & PF_EXITING))
6969 ret = io_try_cancel_userdata(req, prev->user_data);
6970 io_req_complete_post(req, ret ?: -ETIME, 0);
6973 io_req_complete_post(req, -ETIME, 0);
6977 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6979 struct io_timeout_data *data = container_of(timer,
6980 struct io_timeout_data, timer);
6981 struct io_kiocb *prev, *req = data->req;
6982 struct io_ring_ctx *ctx = req->ctx;
6983 unsigned long flags;
6985 spin_lock_irqsave(&ctx->timeout_lock, flags);
6986 prev = req->timeout.head;
6987 req->timeout.head = NULL;
6990 * We don't expect the list to be empty, that will only happen if we
6991 * race with the completion of the linked work.
6994 io_remove_next_linked(prev);
6995 if (!req_ref_inc_not_zero(prev))
6998 list_del(&req->timeout.list);
6999 req->timeout.prev = prev;
7000 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7002 req->io_task_work.func = io_req_task_link_timeout;
7003 io_req_task_work_add(req, false);
7004 return HRTIMER_NORESTART;
7007 static void io_queue_linked_timeout(struct io_kiocb *req)
7009 struct io_ring_ctx *ctx = req->ctx;
7011 spin_lock_irq(&ctx->timeout_lock);
7013 * If the back reference is NULL, then our linked request finished
7014 * before we got a chance to setup the timer
7016 if (req->timeout.head) {
7017 struct io_timeout_data *data = req->async_data;
7019 data->timer.function = io_link_timeout_fn;
7020 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7022 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7024 spin_unlock_irq(&ctx->timeout_lock);
7025 /* drop submission reference */
7029 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7030 __must_hold(&req->ctx->uring_lock)
7032 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7034 switch (io_arm_poll_handler(req)) {
7035 case IO_APOLL_READY:
7036 io_req_task_queue(req);
7038 case IO_APOLL_ABORTED:
7040 * Queued up for async execution, worker will release
7041 * submit reference when the iocb is actually submitted.
7043 io_queue_async_work(req, NULL);
7048 io_queue_linked_timeout(linked_timeout);
7051 static inline void __io_queue_sqe(struct io_kiocb *req)
7052 __must_hold(&req->ctx->uring_lock)
7054 struct io_kiocb *linked_timeout;
7057 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7059 if (req->flags & REQ_F_COMPLETE_INLINE) {
7060 io_req_add_compl_list(req);
7064 * We async punt it if the file wasn't marked NOWAIT, or if the file
7065 * doesn't support non-blocking read/write attempts
7068 linked_timeout = io_prep_linked_timeout(req);
7070 io_queue_linked_timeout(linked_timeout);
7071 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7072 io_queue_sqe_arm_apoll(req);
7074 io_req_complete_failed(req, ret);
7078 static void io_queue_sqe_fallback(struct io_kiocb *req)
7079 __must_hold(&req->ctx->uring_lock)
7081 if (req->flags & REQ_F_FAIL) {
7082 io_req_complete_fail_submit(req);
7083 } else if (unlikely(req->ctx->drain_active)) {
7086 int ret = io_req_prep_async(req);
7089 io_req_complete_failed(req, ret);
7091 io_queue_async_work(req, NULL);
7095 static inline void io_queue_sqe(struct io_kiocb *req)
7096 __must_hold(&req->ctx->uring_lock)
7098 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7099 __io_queue_sqe(req);
7101 io_queue_sqe_fallback(req);
7105 * Check SQE restrictions (opcode and flags).
7107 * Returns 'true' if SQE is allowed, 'false' otherwise.
7109 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7110 struct io_kiocb *req,
7111 unsigned int sqe_flags)
7113 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7116 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7117 ctx->restrictions.sqe_flags_required)
7120 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7121 ctx->restrictions.sqe_flags_required))
7127 static void io_init_req_drain(struct io_kiocb *req)
7129 struct io_ring_ctx *ctx = req->ctx;
7130 struct io_kiocb *head = ctx->submit_state.link.head;
7132 ctx->drain_active = true;
7135 * If we need to drain a request in the middle of a link, drain
7136 * the head request and the next request/link after the current
7137 * link. Considering sequential execution of links,
7138 * REQ_F_IO_DRAIN will be maintained for every request of our
7141 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7142 ctx->drain_next = true;
7146 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7147 const struct io_uring_sqe *sqe)
7148 __must_hold(&ctx->uring_lock)
7150 unsigned int sqe_flags;
7154 /* req is partially pre-initialised, see io_preinit_req() */
7155 req->opcode = opcode = READ_ONCE(sqe->opcode);
7156 /* same numerical values with corresponding REQ_F_*, safe to copy */
7157 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7158 req->user_data = READ_ONCE(sqe->user_data);
7160 req->fixed_rsrc_refs = NULL;
7161 req->task = current;
7163 if (unlikely(opcode >= IORING_OP_LAST)) {
7167 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7168 /* enforce forwards compatibility on users */
7169 if (sqe_flags & ~SQE_VALID_FLAGS)
7171 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7172 !io_op_defs[opcode].buffer_select)
7174 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7175 ctx->drain_disabled = true;
7176 if (sqe_flags & IOSQE_IO_DRAIN) {
7177 if (ctx->drain_disabled)
7179 io_init_req_drain(req);
7182 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7183 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7185 /* knock it to the slow queue path, will be drained there */
7186 if (ctx->drain_active)
7187 req->flags |= REQ_F_FORCE_ASYNC;
7188 /* if there is no link, we're at "next" request and need to drain */
7189 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7190 ctx->drain_next = false;
7191 ctx->drain_active = true;
7192 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7196 if (io_op_defs[opcode].needs_file) {
7197 struct io_submit_state *state = &ctx->submit_state;
7200 * Plug now if we have more than 2 IO left after this, and the
7201 * target is potentially a read/write to block based storage.
7203 if (state->need_plug && io_op_defs[opcode].plug) {
7204 state->plug_started = true;
7205 state->need_plug = false;
7206 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7209 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7210 (sqe_flags & IOSQE_FIXED_FILE));
7211 if (unlikely(!req->file))
7215 personality = READ_ONCE(sqe->personality);
7219 req->creds = xa_load(&ctx->personalities, personality);
7222 get_cred(req->creds);
7223 ret = security_uring_override_creds(req->creds);
7225 put_cred(req->creds);
7228 req->flags |= REQ_F_CREDS;
7231 return io_req_prep(req, sqe);
7234 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7235 const struct io_uring_sqe *sqe)
7236 __must_hold(&ctx->uring_lock)
7238 struct io_submit_link *link = &ctx->submit_state.link;
7241 ret = io_init_req(ctx, req, sqe);
7242 if (unlikely(ret)) {
7243 trace_io_uring_req_failed(sqe, ret);
7245 /* fail even hard links since we don't submit */
7248 * we can judge a link req is failed or cancelled by if
7249 * REQ_F_FAIL is set, but the head is an exception since
7250 * it may be set REQ_F_FAIL because of other req's failure
7251 * so let's leverage req->result to distinguish if a head
7252 * is set REQ_F_FAIL because of its failure or other req's
7253 * failure so that we can set the correct ret code for it.
7254 * init result here to avoid affecting the normal path.
7256 if (!(link->head->flags & REQ_F_FAIL))
7257 req_fail_link_node(link->head, -ECANCELED);
7258 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7260 * the current req is a normal req, we should return
7261 * error and thus break the submittion loop.
7263 io_req_complete_failed(req, ret);
7266 req_fail_link_node(req, ret);
7269 /* don't need @sqe from now on */
7270 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7272 ctx->flags & IORING_SETUP_SQPOLL);
7275 * If we already have a head request, queue this one for async
7276 * submittal once the head completes. If we don't have a head but
7277 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7278 * submitted sync once the chain is complete. If none of those
7279 * conditions are true (normal request), then just queue it.
7282 struct io_kiocb *head = link->head;
7284 if (!(req->flags & REQ_F_FAIL)) {
7285 ret = io_req_prep_async(req);
7286 if (unlikely(ret)) {
7287 req_fail_link_node(req, ret);
7288 if (!(head->flags & REQ_F_FAIL))
7289 req_fail_link_node(head, -ECANCELED);
7292 trace_io_uring_link(ctx, req, head);
7293 link->last->link = req;
7296 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7298 /* last request of a link, enqueue the link */
7301 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7312 * Batched submission is done, ensure local IO is flushed out.
7314 static void io_submit_state_end(struct io_ring_ctx *ctx)
7316 struct io_submit_state *state = &ctx->submit_state;
7318 if (state->link.head)
7319 io_queue_sqe(state->link.head);
7320 /* flush only after queuing links as they can generate completions */
7321 io_submit_flush_completions(ctx);
7322 if (state->plug_started)
7323 blk_finish_plug(&state->plug);
7327 * Start submission side cache.
7329 static void io_submit_state_start(struct io_submit_state *state,
7330 unsigned int max_ios)
7332 state->plug_started = false;
7333 state->need_plug = max_ios > 2;
7334 state->submit_nr = max_ios;
7335 /* set only head, no need to init link_last in advance */
7336 state->link.head = NULL;
7339 static void io_commit_sqring(struct io_ring_ctx *ctx)
7341 struct io_rings *rings = ctx->rings;
7344 * Ensure any loads from the SQEs are done at this point,
7345 * since once we write the new head, the application could
7346 * write new data to them.
7348 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7352 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7353 * that is mapped by userspace. This means that care needs to be taken to
7354 * ensure that reads are stable, as we cannot rely on userspace always
7355 * being a good citizen. If members of the sqe are validated and then later
7356 * used, it's important that those reads are done through READ_ONCE() to
7357 * prevent a re-load down the line.
7359 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7361 unsigned head, mask = ctx->sq_entries - 1;
7362 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7365 * The cached sq head (or cq tail) serves two purposes:
7367 * 1) allows us to batch the cost of updating the user visible
7369 * 2) allows the kernel side to track the head on its own, even
7370 * though the application is the one updating it.
7372 head = READ_ONCE(ctx->sq_array[sq_idx]);
7373 if (likely(head < ctx->sq_entries))
7374 return &ctx->sq_sqes[head];
7376 /* drop invalid entries */
7378 WRITE_ONCE(ctx->rings->sq_dropped,
7379 READ_ONCE(ctx->rings->sq_dropped) + 1);
7383 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7384 __must_hold(&ctx->uring_lock)
7386 unsigned int entries = io_sqring_entries(ctx);
7389 if (unlikely(!entries))
7391 /* make sure SQ entry isn't read before tail */
7392 nr = min3(nr, ctx->sq_entries, entries);
7393 io_get_task_refs(nr);
7395 io_submit_state_start(&ctx->submit_state, nr);
7397 const struct io_uring_sqe *sqe;
7398 struct io_kiocb *req;
7400 if (unlikely(!io_alloc_req_refill(ctx))) {
7402 submitted = -EAGAIN;
7405 req = io_alloc_req(ctx);
7406 sqe = io_get_sqe(ctx);
7407 if (unlikely(!sqe)) {
7408 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7411 /* will complete beyond this point, count as submitted */
7413 if (io_submit_sqe(ctx, req, sqe))
7415 } while (submitted < nr);
7417 if (unlikely(submitted != nr)) {
7418 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7419 int unused = nr - ref_used;
7421 current->io_uring->cached_refs += unused;
7424 io_submit_state_end(ctx);
7425 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7426 io_commit_sqring(ctx);
7431 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7433 return READ_ONCE(sqd->state);
7436 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7438 /* Tell userspace we may need a wakeup call */
7439 spin_lock(&ctx->completion_lock);
7440 WRITE_ONCE(ctx->rings->sq_flags,
7441 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7442 spin_unlock(&ctx->completion_lock);
7445 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7447 spin_lock(&ctx->completion_lock);
7448 WRITE_ONCE(ctx->rings->sq_flags,
7449 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7450 spin_unlock(&ctx->completion_lock);
7453 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7455 unsigned int to_submit;
7458 to_submit = io_sqring_entries(ctx);
7459 /* if we're handling multiple rings, cap submit size for fairness */
7460 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7461 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7463 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7464 const struct cred *creds = NULL;
7466 if (ctx->sq_creds != current_cred())
7467 creds = override_creds(ctx->sq_creds);
7469 mutex_lock(&ctx->uring_lock);
7470 if (!wq_list_empty(&ctx->iopoll_list))
7471 io_do_iopoll(ctx, true);
7474 * Don't submit if refs are dying, good for io_uring_register(),
7475 * but also it is relied upon by io_ring_exit_work()
7477 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7478 !(ctx->flags & IORING_SETUP_R_DISABLED))
7479 ret = io_submit_sqes(ctx, to_submit);
7480 mutex_unlock(&ctx->uring_lock);
7482 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7483 wake_up(&ctx->sqo_sq_wait);
7485 revert_creds(creds);
7491 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7493 struct io_ring_ctx *ctx;
7494 unsigned sq_thread_idle = 0;
7496 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7497 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7498 sqd->sq_thread_idle = sq_thread_idle;
7501 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7503 bool did_sig = false;
7504 struct ksignal ksig;
7506 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7507 signal_pending(current)) {
7508 mutex_unlock(&sqd->lock);
7509 if (signal_pending(current))
7510 did_sig = get_signal(&ksig);
7512 mutex_lock(&sqd->lock);
7514 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7517 static int io_sq_thread(void *data)
7519 struct io_sq_data *sqd = data;
7520 struct io_ring_ctx *ctx;
7521 unsigned long timeout = 0;
7522 char buf[TASK_COMM_LEN];
7525 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7526 set_task_comm(current, buf);
7528 if (sqd->sq_cpu != -1)
7529 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7531 set_cpus_allowed_ptr(current, cpu_online_mask);
7532 current->flags |= PF_NO_SETAFFINITY;
7534 audit_alloc_kernel(current);
7536 mutex_lock(&sqd->lock);
7538 bool cap_entries, sqt_spin = false;
7540 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7541 if (io_sqd_handle_event(sqd))
7543 timeout = jiffies + sqd->sq_thread_idle;
7546 cap_entries = !list_is_singular(&sqd->ctx_list);
7547 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7548 int ret = __io_sq_thread(ctx, cap_entries);
7550 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7553 if (io_run_task_work())
7556 if (sqt_spin || !time_after(jiffies, timeout)) {
7559 timeout = jiffies + sqd->sq_thread_idle;
7563 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7564 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7565 bool needs_sched = true;
7567 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7568 io_ring_set_wakeup_flag(ctx);
7570 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7571 !wq_list_empty(&ctx->iopoll_list)) {
7572 needs_sched = false;
7575 if (io_sqring_entries(ctx)) {
7576 needs_sched = false;
7582 mutex_unlock(&sqd->lock);
7584 mutex_lock(&sqd->lock);
7586 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7587 io_ring_clear_wakeup_flag(ctx);
7590 finish_wait(&sqd->wait, &wait);
7591 timeout = jiffies + sqd->sq_thread_idle;
7594 io_uring_cancel_generic(true, sqd);
7596 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7597 io_ring_set_wakeup_flag(ctx);
7599 mutex_unlock(&sqd->lock);
7601 audit_free(current);
7603 complete(&sqd->exited);
7607 struct io_wait_queue {
7608 struct wait_queue_entry wq;
7609 struct io_ring_ctx *ctx;
7611 unsigned nr_timeouts;
7614 static inline bool io_should_wake(struct io_wait_queue *iowq)
7616 struct io_ring_ctx *ctx = iowq->ctx;
7617 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7620 * Wake up if we have enough events, or if a timeout occurred since we
7621 * started waiting. For timeouts, we always want to return to userspace,
7622 * regardless of event count.
7624 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7627 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7628 int wake_flags, void *key)
7630 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7634 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7635 * the task, and the next invocation will do it.
7637 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7638 return autoremove_wake_function(curr, mode, wake_flags, key);
7642 static int io_run_task_work_sig(void)
7644 if (io_run_task_work())
7646 if (!signal_pending(current))
7648 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7649 return -ERESTARTSYS;
7653 /* when returns >0, the caller should retry */
7654 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7655 struct io_wait_queue *iowq,
7656 signed long *timeout)
7660 /* make sure we run task_work before checking for signals */
7661 ret = io_run_task_work_sig();
7662 if (ret || io_should_wake(iowq))
7664 /* let the caller flush overflows, retry */
7665 if (test_bit(0, &ctx->check_cq_overflow))
7668 *timeout = schedule_timeout(*timeout);
7669 return !*timeout ? -ETIME : 1;
7673 * Wait until events become available, if we don't already have some. The
7674 * application must reap them itself, as they reside on the shared cq ring.
7676 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7677 const sigset_t __user *sig, size_t sigsz,
7678 struct __kernel_timespec __user *uts)
7680 struct io_wait_queue iowq;
7681 struct io_rings *rings = ctx->rings;
7682 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7686 io_cqring_overflow_flush(ctx);
7687 if (io_cqring_events(ctx) >= min_events)
7689 if (!io_run_task_work())
7694 struct timespec64 ts;
7696 if (get_timespec64(&ts, uts))
7698 timeout = timespec64_to_jiffies(&ts);
7702 #ifdef CONFIG_COMPAT
7703 if (in_compat_syscall())
7704 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7708 ret = set_user_sigmask(sig, sigsz);
7714 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7715 iowq.wq.private = current;
7716 INIT_LIST_HEAD(&iowq.wq.entry);
7718 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7719 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7721 trace_io_uring_cqring_wait(ctx, min_events);
7723 /* if we can't even flush overflow, don't wait for more */
7724 if (!io_cqring_overflow_flush(ctx)) {
7728 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7729 TASK_INTERRUPTIBLE);
7730 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7731 finish_wait(&ctx->cq_wait, &iowq.wq);
7735 restore_saved_sigmask_unless(ret == -EINTR);
7737 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7740 static void io_free_page_table(void **table, size_t size)
7742 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7744 for (i = 0; i < nr_tables; i++)
7749 static __cold void **io_alloc_page_table(size_t size)
7751 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7752 size_t init_size = size;
7755 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7759 for (i = 0; i < nr_tables; i++) {
7760 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7762 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7764 io_free_page_table(table, init_size);
7772 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7774 percpu_ref_exit(&ref_node->refs);
7778 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7780 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7781 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7782 unsigned long flags;
7783 bool first_add = false;
7785 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7788 while (!list_empty(&ctx->rsrc_ref_list)) {
7789 node = list_first_entry(&ctx->rsrc_ref_list,
7790 struct io_rsrc_node, node);
7791 /* recycle ref nodes in order */
7794 list_del(&node->node);
7795 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7797 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7800 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7803 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7805 struct io_rsrc_node *ref_node;
7807 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7811 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7816 INIT_LIST_HEAD(&ref_node->node);
7817 INIT_LIST_HEAD(&ref_node->rsrc_list);
7818 ref_node->done = false;
7822 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7823 struct io_rsrc_data *data_to_kill)
7824 __must_hold(&ctx->uring_lock)
7826 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7827 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7829 io_rsrc_refs_drop(ctx);
7832 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7834 rsrc_node->rsrc_data = data_to_kill;
7835 spin_lock_irq(&ctx->rsrc_ref_lock);
7836 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7837 spin_unlock_irq(&ctx->rsrc_ref_lock);
7839 atomic_inc(&data_to_kill->refs);
7840 percpu_ref_kill(&rsrc_node->refs);
7841 ctx->rsrc_node = NULL;
7844 if (!ctx->rsrc_node) {
7845 ctx->rsrc_node = ctx->rsrc_backup_node;
7846 ctx->rsrc_backup_node = NULL;
7850 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7852 if (ctx->rsrc_backup_node)
7854 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7855 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7858 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
7859 struct io_ring_ctx *ctx)
7863 /* As we may drop ->uring_lock, other task may have started quiesce */
7867 data->quiesce = true;
7869 ret = io_rsrc_node_switch_start(ctx);
7872 io_rsrc_node_switch(ctx, data);
7874 /* kill initial ref, already quiesced if zero */
7875 if (atomic_dec_and_test(&data->refs))
7877 mutex_unlock(&ctx->uring_lock);
7878 flush_delayed_work(&ctx->rsrc_put_work);
7879 ret = wait_for_completion_interruptible(&data->done);
7881 mutex_lock(&ctx->uring_lock);
7885 atomic_inc(&data->refs);
7886 /* wait for all works potentially completing data->done */
7887 flush_delayed_work(&ctx->rsrc_put_work);
7888 reinit_completion(&data->done);
7890 ret = io_run_task_work_sig();
7891 mutex_lock(&ctx->uring_lock);
7893 data->quiesce = false;
7898 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7900 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7901 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7903 return &data->tags[table_idx][off];
7906 static void io_rsrc_data_free(struct io_rsrc_data *data)
7908 size_t size = data->nr * sizeof(data->tags[0][0]);
7911 io_free_page_table((void **)data->tags, size);
7915 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7916 u64 __user *utags, unsigned nr,
7917 struct io_rsrc_data **pdata)
7919 struct io_rsrc_data *data;
7923 data = kzalloc(sizeof(*data), GFP_KERNEL);
7926 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7934 data->do_put = do_put;
7937 for (i = 0; i < nr; i++) {
7938 u64 *tag_slot = io_get_tag_slot(data, i);
7940 if (copy_from_user(tag_slot, &utags[i],
7946 atomic_set(&data->refs, 1);
7947 init_completion(&data->done);
7951 io_rsrc_data_free(data);
7955 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7957 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7958 GFP_KERNEL_ACCOUNT);
7959 return !!table->files;
7962 static void io_free_file_tables(struct io_file_table *table)
7964 kvfree(table->files);
7965 table->files = NULL;
7968 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7970 #if defined(CONFIG_UNIX)
7971 if (ctx->ring_sock) {
7972 struct sock *sock = ctx->ring_sock->sk;
7973 struct sk_buff *skb;
7975 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7981 for (i = 0; i < ctx->nr_user_files; i++) {
7984 file = io_file_from_index(ctx, i);
7989 io_free_file_tables(&ctx->file_table);
7990 io_rsrc_data_free(ctx->file_data);
7991 ctx->file_data = NULL;
7992 ctx->nr_user_files = 0;
7995 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7999 if (!ctx->file_data)
8001 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8003 __io_sqe_files_unregister(ctx);
8007 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8008 __releases(&sqd->lock)
8010 WARN_ON_ONCE(sqd->thread == current);
8013 * Do the dance but not conditional clear_bit() because it'd race with
8014 * other threads incrementing park_pending and setting the bit.
8016 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8017 if (atomic_dec_return(&sqd->park_pending))
8018 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8019 mutex_unlock(&sqd->lock);
8022 static void io_sq_thread_park(struct io_sq_data *sqd)
8023 __acquires(&sqd->lock)
8025 WARN_ON_ONCE(sqd->thread == current);
8027 atomic_inc(&sqd->park_pending);
8028 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8029 mutex_lock(&sqd->lock);
8031 wake_up_process(sqd->thread);
8034 static void io_sq_thread_stop(struct io_sq_data *sqd)
8036 WARN_ON_ONCE(sqd->thread == current);
8037 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8039 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8040 mutex_lock(&sqd->lock);
8042 wake_up_process(sqd->thread);
8043 mutex_unlock(&sqd->lock);
8044 wait_for_completion(&sqd->exited);
8047 static void io_put_sq_data(struct io_sq_data *sqd)
8049 if (refcount_dec_and_test(&sqd->refs)) {
8050 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8052 io_sq_thread_stop(sqd);
8057 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8059 struct io_sq_data *sqd = ctx->sq_data;
8062 io_sq_thread_park(sqd);
8063 list_del_init(&ctx->sqd_list);
8064 io_sqd_update_thread_idle(sqd);
8065 io_sq_thread_unpark(sqd);
8067 io_put_sq_data(sqd);
8068 ctx->sq_data = NULL;
8072 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8074 struct io_ring_ctx *ctx_attach;
8075 struct io_sq_data *sqd;
8078 f = fdget(p->wq_fd);
8080 return ERR_PTR(-ENXIO);
8081 if (f.file->f_op != &io_uring_fops) {
8083 return ERR_PTR(-EINVAL);
8086 ctx_attach = f.file->private_data;
8087 sqd = ctx_attach->sq_data;
8090 return ERR_PTR(-EINVAL);
8092 if (sqd->task_tgid != current->tgid) {
8094 return ERR_PTR(-EPERM);
8097 refcount_inc(&sqd->refs);
8102 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8105 struct io_sq_data *sqd;
8108 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8109 sqd = io_attach_sq_data(p);
8114 /* fall through for EPERM case, setup new sqd/task */
8115 if (PTR_ERR(sqd) != -EPERM)
8119 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8121 return ERR_PTR(-ENOMEM);
8123 atomic_set(&sqd->park_pending, 0);
8124 refcount_set(&sqd->refs, 1);
8125 INIT_LIST_HEAD(&sqd->ctx_list);
8126 mutex_init(&sqd->lock);
8127 init_waitqueue_head(&sqd->wait);
8128 init_completion(&sqd->exited);
8132 #if defined(CONFIG_UNIX)
8134 * Ensure the UNIX gc is aware of our file set, so we are certain that
8135 * the io_uring can be safely unregistered on process exit, even if we have
8136 * loops in the file referencing.
8138 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8140 struct sock *sk = ctx->ring_sock->sk;
8141 struct scm_fp_list *fpl;
8142 struct sk_buff *skb;
8145 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8149 skb = alloc_skb(0, GFP_KERNEL);
8158 fpl->user = get_uid(current_user());
8159 for (i = 0; i < nr; i++) {
8160 struct file *file = io_file_from_index(ctx, i + offset);
8164 fpl->fp[nr_files] = get_file(file);
8165 unix_inflight(fpl->user, fpl->fp[nr_files]);
8170 fpl->max = SCM_MAX_FD;
8171 fpl->count = nr_files;
8172 UNIXCB(skb).fp = fpl;
8173 skb->destructor = unix_destruct_scm;
8174 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8175 skb_queue_head(&sk->sk_receive_queue, skb);
8177 for (i = 0; i < nr_files; i++)
8188 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8189 * causes regular reference counting to break down. We rely on the UNIX
8190 * garbage collection to take care of this problem for us.
8192 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8194 unsigned left, total;
8198 left = ctx->nr_user_files;
8200 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8202 ret = __io_sqe_files_scm(ctx, this_files, total);
8206 total += this_files;
8212 while (total < ctx->nr_user_files) {
8213 struct file *file = io_file_from_index(ctx, total);
8223 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8229 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8231 struct file *file = prsrc->file;
8232 #if defined(CONFIG_UNIX)
8233 struct sock *sock = ctx->ring_sock->sk;
8234 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8235 struct sk_buff *skb;
8238 __skb_queue_head_init(&list);
8241 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8242 * remove this entry and rearrange the file array.
8244 skb = skb_dequeue(head);
8246 struct scm_fp_list *fp;
8248 fp = UNIXCB(skb).fp;
8249 for (i = 0; i < fp->count; i++) {
8252 if (fp->fp[i] != file)
8255 unix_notinflight(fp->user, fp->fp[i]);
8256 left = fp->count - 1 - i;
8258 memmove(&fp->fp[i], &fp->fp[i + 1],
8259 left * sizeof(struct file *));
8266 __skb_queue_tail(&list, skb);
8276 __skb_queue_tail(&list, skb);
8278 skb = skb_dequeue(head);
8281 if (skb_peek(&list)) {
8282 spin_lock_irq(&head->lock);
8283 while ((skb = __skb_dequeue(&list)) != NULL)
8284 __skb_queue_tail(head, skb);
8285 spin_unlock_irq(&head->lock);
8292 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8294 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8295 struct io_ring_ctx *ctx = rsrc_data->ctx;
8296 struct io_rsrc_put *prsrc, *tmp;
8298 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8299 list_del(&prsrc->list);
8302 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8304 io_ring_submit_lock(ctx, lock_ring);
8305 spin_lock(&ctx->completion_lock);
8306 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8307 io_commit_cqring(ctx);
8308 spin_unlock(&ctx->completion_lock);
8309 io_cqring_ev_posted(ctx);
8310 io_ring_submit_unlock(ctx, lock_ring);
8313 rsrc_data->do_put(ctx, prsrc);
8317 io_rsrc_node_destroy(ref_node);
8318 if (atomic_dec_and_test(&rsrc_data->refs))
8319 complete(&rsrc_data->done);
8322 static void io_rsrc_put_work(struct work_struct *work)
8324 struct io_ring_ctx *ctx;
8325 struct llist_node *node;
8327 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8328 node = llist_del_all(&ctx->rsrc_put_llist);
8331 struct io_rsrc_node *ref_node;
8332 struct llist_node *next = node->next;
8334 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8335 __io_rsrc_put_work(ref_node);
8340 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8341 unsigned nr_args, u64 __user *tags)
8343 __s32 __user *fds = (__s32 __user *) arg;
8352 if (nr_args > IORING_MAX_FIXED_FILES)
8354 if (nr_args > rlimit(RLIMIT_NOFILE))
8356 ret = io_rsrc_node_switch_start(ctx);
8359 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8365 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8368 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8369 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8373 /* allow sparse sets */
8376 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8383 if (unlikely(!file))
8387 * Don't allow io_uring instances to be registered. If UNIX
8388 * isn't enabled, then this causes a reference cycle and this
8389 * instance can never get freed. If UNIX is enabled we'll
8390 * handle it just fine, but there's still no point in allowing
8391 * a ring fd as it doesn't support regular read/write anyway.
8393 if (file->f_op == &io_uring_fops) {
8397 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8400 ret = io_sqe_files_scm(ctx);
8402 __io_sqe_files_unregister(ctx);
8406 io_rsrc_node_switch(ctx, NULL);
8409 for (i = 0; i < ctx->nr_user_files; i++) {
8410 file = io_file_from_index(ctx, i);
8414 io_free_file_tables(&ctx->file_table);
8415 ctx->nr_user_files = 0;
8417 io_rsrc_data_free(ctx->file_data);
8418 ctx->file_data = NULL;
8422 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8425 #if defined(CONFIG_UNIX)
8426 struct sock *sock = ctx->ring_sock->sk;
8427 struct sk_buff_head *head = &sock->sk_receive_queue;
8428 struct sk_buff *skb;
8431 * See if we can merge this file into an existing skb SCM_RIGHTS
8432 * file set. If there's no room, fall back to allocating a new skb
8433 * and filling it in.
8435 spin_lock_irq(&head->lock);
8436 skb = skb_peek(head);
8438 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8440 if (fpl->count < SCM_MAX_FD) {
8441 __skb_unlink(skb, head);
8442 spin_unlock_irq(&head->lock);
8443 fpl->fp[fpl->count] = get_file(file);
8444 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8446 spin_lock_irq(&head->lock);
8447 __skb_queue_head(head, skb);
8452 spin_unlock_irq(&head->lock);
8459 return __io_sqe_files_scm(ctx, 1, index);
8465 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8466 struct io_rsrc_node *node, void *rsrc)
8468 struct io_rsrc_put *prsrc;
8470 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8474 prsrc->tag = *io_get_tag_slot(data, idx);
8476 list_add(&prsrc->list, &node->rsrc_list);
8480 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8481 unsigned int issue_flags, u32 slot_index)
8483 struct io_ring_ctx *ctx = req->ctx;
8484 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8485 bool needs_switch = false;
8486 struct io_fixed_file *file_slot;
8489 io_ring_submit_lock(ctx, needs_lock);
8490 if (file->f_op == &io_uring_fops)
8493 if (!ctx->file_data)
8496 if (slot_index >= ctx->nr_user_files)
8499 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8500 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8502 if (file_slot->file_ptr) {
8503 struct file *old_file;
8505 ret = io_rsrc_node_switch_start(ctx);
8509 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8510 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8511 ctx->rsrc_node, old_file);
8514 file_slot->file_ptr = 0;
8515 needs_switch = true;
8518 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8519 io_fixed_file_set(file_slot, file);
8520 ret = io_sqe_file_register(ctx, file, slot_index);
8522 file_slot->file_ptr = 0;
8529 io_rsrc_node_switch(ctx, ctx->file_data);
8530 io_ring_submit_unlock(ctx, needs_lock);
8536 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8538 unsigned int offset = req->close.file_slot - 1;
8539 struct io_ring_ctx *ctx = req->ctx;
8540 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
8541 struct io_fixed_file *file_slot;
8545 io_ring_submit_lock(ctx, needs_lock);
8547 if (unlikely(!ctx->file_data))
8550 if (offset >= ctx->nr_user_files)
8552 ret = io_rsrc_node_switch_start(ctx);
8556 i = array_index_nospec(offset, ctx->nr_user_files);
8557 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8559 if (!file_slot->file_ptr)
8562 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8563 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8567 file_slot->file_ptr = 0;
8568 io_rsrc_node_switch(ctx, ctx->file_data);
8571 io_ring_submit_unlock(ctx, needs_lock);
8575 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8576 struct io_uring_rsrc_update2 *up,
8579 u64 __user *tags = u64_to_user_ptr(up->tags);
8580 __s32 __user *fds = u64_to_user_ptr(up->data);
8581 struct io_rsrc_data *data = ctx->file_data;
8582 struct io_fixed_file *file_slot;
8586 bool needs_switch = false;
8588 if (!ctx->file_data)
8590 if (up->offset + nr_args > ctx->nr_user_files)
8593 for (done = 0; done < nr_args; done++) {
8596 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8597 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8601 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8605 if (fd == IORING_REGISTER_FILES_SKIP)
8608 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8609 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8611 if (file_slot->file_ptr) {
8612 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8613 err = io_queue_rsrc_removal(data, up->offset + done,
8614 ctx->rsrc_node, file);
8617 file_slot->file_ptr = 0;
8618 needs_switch = true;
8627 * Don't allow io_uring instances to be registered. If
8628 * UNIX isn't enabled, then this causes a reference
8629 * cycle and this instance can never get freed. If UNIX
8630 * is enabled we'll handle it just fine, but there's
8631 * still no point in allowing a ring fd as it doesn't
8632 * support regular read/write anyway.
8634 if (file->f_op == &io_uring_fops) {
8639 *io_get_tag_slot(data, up->offset + done) = tag;
8640 io_fixed_file_set(file_slot, file);
8641 err = io_sqe_file_register(ctx, file, i);
8643 file_slot->file_ptr = 0;
8651 io_rsrc_node_switch(ctx, data);
8652 return done ? done : err;
8655 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8656 struct task_struct *task)
8658 struct io_wq_hash *hash;
8659 struct io_wq_data data;
8660 unsigned int concurrency;
8662 mutex_lock(&ctx->uring_lock);
8663 hash = ctx->hash_map;
8665 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8667 mutex_unlock(&ctx->uring_lock);
8668 return ERR_PTR(-ENOMEM);
8670 refcount_set(&hash->refs, 1);
8671 init_waitqueue_head(&hash->wait);
8672 ctx->hash_map = hash;
8674 mutex_unlock(&ctx->uring_lock);
8678 data.free_work = io_wq_free_work;
8679 data.do_work = io_wq_submit_work;
8681 /* Do QD, or 4 * CPUS, whatever is smallest */
8682 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8684 return io_wq_create(concurrency, &data);
8687 static __cold int io_uring_alloc_task_context(struct task_struct *task,
8688 struct io_ring_ctx *ctx)
8690 struct io_uring_task *tctx;
8693 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8694 if (unlikely(!tctx))
8697 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8698 if (unlikely(ret)) {
8703 tctx->io_wq = io_init_wq_offload(ctx, task);
8704 if (IS_ERR(tctx->io_wq)) {
8705 ret = PTR_ERR(tctx->io_wq);
8706 percpu_counter_destroy(&tctx->inflight);
8712 init_waitqueue_head(&tctx->wait);
8713 atomic_set(&tctx->in_idle, 0);
8714 atomic_set(&tctx->inflight_tracked, 0);
8715 task->io_uring = tctx;
8716 spin_lock_init(&tctx->task_lock);
8717 INIT_WQ_LIST(&tctx->task_list);
8718 INIT_WQ_LIST(&tctx->prior_task_list);
8719 init_task_work(&tctx->task_work, tctx_task_work);
8723 void __io_uring_free(struct task_struct *tsk)
8725 struct io_uring_task *tctx = tsk->io_uring;
8727 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8728 WARN_ON_ONCE(tctx->io_wq);
8729 WARN_ON_ONCE(tctx->cached_refs);
8731 percpu_counter_destroy(&tctx->inflight);
8733 tsk->io_uring = NULL;
8736 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
8737 struct io_uring_params *p)
8741 /* Retain compatibility with failing for an invalid attach attempt */
8742 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8743 IORING_SETUP_ATTACH_WQ) {
8746 f = fdget(p->wq_fd);
8749 if (f.file->f_op != &io_uring_fops) {
8755 if (ctx->flags & IORING_SETUP_SQPOLL) {
8756 struct task_struct *tsk;
8757 struct io_sq_data *sqd;
8760 ret = security_uring_sqpoll();
8764 sqd = io_get_sq_data(p, &attached);
8770 ctx->sq_creds = get_current_cred();
8772 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8773 if (!ctx->sq_thread_idle)
8774 ctx->sq_thread_idle = HZ;
8776 io_sq_thread_park(sqd);
8777 list_add(&ctx->sqd_list, &sqd->ctx_list);
8778 io_sqd_update_thread_idle(sqd);
8779 /* don't attach to a dying SQPOLL thread, would be racy */
8780 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8781 io_sq_thread_unpark(sqd);
8788 if (p->flags & IORING_SETUP_SQ_AFF) {
8789 int cpu = p->sq_thread_cpu;
8792 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8799 sqd->task_pid = current->pid;
8800 sqd->task_tgid = current->tgid;
8801 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8808 ret = io_uring_alloc_task_context(tsk, ctx);
8809 wake_up_new_task(tsk);
8812 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8813 /* Can't have SQ_AFF without SQPOLL */
8820 complete(&ctx->sq_data->exited);
8822 io_sq_thread_finish(ctx);
8826 static inline void __io_unaccount_mem(struct user_struct *user,
8827 unsigned long nr_pages)
8829 atomic_long_sub(nr_pages, &user->locked_vm);
8832 static inline int __io_account_mem(struct user_struct *user,
8833 unsigned long nr_pages)
8835 unsigned long page_limit, cur_pages, new_pages;
8837 /* Don't allow more pages than we can safely lock */
8838 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8841 cur_pages = atomic_long_read(&user->locked_vm);
8842 new_pages = cur_pages + nr_pages;
8843 if (new_pages > page_limit)
8845 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8846 new_pages) != cur_pages);
8851 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8854 __io_unaccount_mem(ctx->user, nr_pages);
8856 if (ctx->mm_account)
8857 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8860 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8865 ret = __io_account_mem(ctx->user, nr_pages);
8870 if (ctx->mm_account)
8871 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8876 static void io_mem_free(void *ptr)
8883 page = virt_to_head_page(ptr);
8884 if (put_page_testzero(page))
8885 free_compound_page(page);
8888 static void *io_mem_alloc(size_t size)
8890 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8891 __GFP_NORETRY | __GFP_ACCOUNT;
8893 return (void *) __get_free_pages(gfp_flags, get_order(size));
8896 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8899 struct io_rings *rings;
8900 size_t off, sq_array_size;
8902 off = struct_size(rings, cqes, cq_entries);
8903 if (off == SIZE_MAX)
8907 off = ALIGN(off, SMP_CACHE_BYTES);
8915 sq_array_size = array_size(sizeof(u32), sq_entries);
8916 if (sq_array_size == SIZE_MAX)
8919 if (check_add_overflow(off, sq_array_size, &off))
8925 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8927 struct io_mapped_ubuf *imu = *slot;
8930 if (imu != ctx->dummy_ubuf) {
8931 for (i = 0; i < imu->nr_bvecs; i++)
8932 unpin_user_page(imu->bvec[i].bv_page);
8933 if (imu->acct_pages)
8934 io_unaccount_mem(ctx, imu->acct_pages);
8940 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8942 io_buffer_unmap(ctx, &prsrc->buf);
8946 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8950 for (i = 0; i < ctx->nr_user_bufs; i++)
8951 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8952 kfree(ctx->user_bufs);
8953 io_rsrc_data_free(ctx->buf_data);
8954 ctx->user_bufs = NULL;
8955 ctx->buf_data = NULL;
8956 ctx->nr_user_bufs = 0;
8959 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8966 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8968 __io_sqe_buffers_unregister(ctx);
8972 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8973 void __user *arg, unsigned index)
8975 struct iovec __user *src;
8977 #ifdef CONFIG_COMPAT
8979 struct compat_iovec __user *ciovs;
8980 struct compat_iovec ciov;
8982 ciovs = (struct compat_iovec __user *) arg;
8983 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8986 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8987 dst->iov_len = ciov.iov_len;
8991 src = (struct iovec __user *) arg;
8992 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8998 * Not super efficient, but this is just a registration time. And we do cache
8999 * the last compound head, so generally we'll only do a full search if we don't
9002 * We check if the given compound head page has already been accounted, to
9003 * avoid double accounting it. This allows us to account the full size of the
9004 * page, not just the constituent pages of a huge page.
9006 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9007 int nr_pages, struct page *hpage)
9011 /* check current page array */
9012 for (i = 0; i < nr_pages; i++) {
9013 if (!PageCompound(pages[i]))
9015 if (compound_head(pages[i]) == hpage)
9019 /* check previously registered pages */
9020 for (i = 0; i < ctx->nr_user_bufs; i++) {
9021 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9023 for (j = 0; j < imu->nr_bvecs; j++) {
9024 if (!PageCompound(imu->bvec[j].bv_page))
9026 if (compound_head(imu->bvec[j].bv_page) == hpage)
9034 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9035 int nr_pages, struct io_mapped_ubuf *imu,
9036 struct page **last_hpage)
9040 imu->acct_pages = 0;
9041 for (i = 0; i < nr_pages; i++) {
9042 if (!PageCompound(pages[i])) {
9047 hpage = compound_head(pages[i]);
9048 if (hpage == *last_hpage)
9050 *last_hpage = hpage;
9051 if (headpage_already_acct(ctx, pages, i, hpage))
9053 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9057 if (!imu->acct_pages)
9060 ret = io_account_mem(ctx, imu->acct_pages);
9062 imu->acct_pages = 0;
9066 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9067 struct io_mapped_ubuf **pimu,
9068 struct page **last_hpage)
9070 struct io_mapped_ubuf *imu = NULL;
9071 struct vm_area_struct **vmas = NULL;
9072 struct page **pages = NULL;
9073 unsigned long off, start, end, ubuf;
9075 int ret, pret, nr_pages, i;
9077 if (!iov->iov_base) {
9078 *pimu = ctx->dummy_ubuf;
9082 ubuf = (unsigned long) iov->iov_base;
9083 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9084 start = ubuf >> PAGE_SHIFT;
9085 nr_pages = end - start;
9090 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9094 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9099 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9104 mmap_read_lock(current->mm);
9105 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9107 if (pret == nr_pages) {
9108 /* don't support file backed memory */
9109 for (i = 0; i < nr_pages; i++) {
9110 struct vm_area_struct *vma = vmas[i];
9112 if (vma_is_shmem(vma))
9115 !is_file_hugepages(vma->vm_file)) {
9121 ret = pret < 0 ? pret : -EFAULT;
9123 mmap_read_unlock(current->mm);
9126 * if we did partial map, or found file backed vmas,
9127 * release any pages we did get
9130 unpin_user_pages(pages, pret);
9134 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9136 unpin_user_pages(pages, pret);
9140 off = ubuf & ~PAGE_MASK;
9141 size = iov->iov_len;
9142 for (i = 0; i < nr_pages; i++) {
9145 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9146 imu->bvec[i].bv_page = pages[i];
9147 imu->bvec[i].bv_len = vec_len;
9148 imu->bvec[i].bv_offset = off;
9152 /* store original address for later verification */
9154 imu->ubuf_end = ubuf + iov->iov_len;
9155 imu->nr_bvecs = nr_pages;
9166 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9168 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9169 return ctx->user_bufs ? 0 : -ENOMEM;
9172 static int io_buffer_validate(struct iovec *iov)
9174 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9177 * Don't impose further limits on the size and buffer
9178 * constraints here, we'll -EINVAL later when IO is
9179 * submitted if they are wrong.
9182 return iov->iov_len ? -EFAULT : 0;
9186 /* arbitrary limit, but we need something */
9187 if (iov->iov_len > SZ_1G)
9190 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9196 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9197 unsigned int nr_args, u64 __user *tags)
9199 struct page *last_hpage = NULL;
9200 struct io_rsrc_data *data;
9206 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9208 ret = io_rsrc_node_switch_start(ctx);
9211 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9214 ret = io_buffers_map_alloc(ctx, nr_args);
9216 io_rsrc_data_free(data);
9220 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9221 ret = io_copy_iov(ctx, &iov, arg, i);
9224 ret = io_buffer_validate(&iov);
9227 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9232 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9238 WARN_ON_ONCE(ctx->buf_data);
9240 ctx->buf_data = data;
9242 __io_sqe_buffers_unregister(ctx);
9244 io_rsrc_node_switch(ctx, NULL);
9248 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9249 struct io_uring_rsrc_update2 *up,
9250 unsigned int nr_args)
9252 u64 __user *tags = u64_to_user_ptr(up->tags);
9253 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9254 struct page *last_hpage = NULL;
9255 bool needs_switch = false;
9261 if (up->offset + nr_args > ctx->nr_user_bufs)
9264 for (done = 0; done < nr_args; done++) {
9265 struct io_mapped_ubuf *imu;
9266 int offset = up->offset + done;
9269 err = io_copy_iov(ctx, &iov, iovs, done);
9272 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9276 err = io_buffer_validate(&iov);
9279 if (!iov.iov_base && tag) {
9283 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9287 i = array_index_nospec(offset, ctx->nr_user_bufs);
9288 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9289 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9290 ctx->rsrc_node, ctx->user_bufs[i]);
9291 if (unlikely(err)) {
9292 io_buffer_unmap(ctx, &imu);
9295 ctx->user_bufs[i] = NULL;
9296 needs_switch = true;
9299 ctx->user_bufs[i] = imu;
9300 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9304 io_rsrc_node_switch(ctx, ctx->buf_data);
9305 return done ? done : err;
9308 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9310 __s32 __user *fds = arg;
9316 if (copy_from_user(&fd, fds, sizeof(*fds)))
9319 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9320 if (IS_ERR(ctx->cq_ev_fd)) {
9321 int ret = PTR_ERR(ctx->cq_ev_fd);
9323 ctx->cq_ev_fd = NULL;
9330 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9332 if (ctx->cq_ev_fd) {
9333 eventfd_ctx_put(ctx->cq_ev_fd);
9334 ctx->cq_ev_fd = NULL;
9341 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9343 struct io_buffer *buf;
9344 unsigned long index;
9346 xa_for_each(&ctx->io_buffers, index, buf)
9347 __io_remove_buffers(ctx, buf, index, -1U);
9350 static void io_req_caches_free(struct io_ring_ctx *ctx)
9352 struct io_submit_state *state = &ctx->submit_state;
9355 mutex_lock(&ctx->uring_lock);
9356 io_flush_cached_locked_reqs(ctx, state);
9358 while (state->free_list.next) {
9359 struct io_wq_work_node *node;
9360 struct io_kiocb *req;
9362 node = wq_stack_extract(&state->free_list);
9363 req = container_of(node, struct io_kiocb, comp_list);
9364 kmem_cache_free(req_cachep, req);
9368 percpu_ref_put_many(&ctx->refs, nr);
9369 mutex_unlock(&ctx->uring_lock);
9372 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9374 if (data && !atomic_dec_and_test(&data->refs))
9375 wait_for_completion(&data->done);
9378 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9380 io_sq_thread_finish(ctx);
9382 if (ctx->mm_account) {
9383 mmdrop(ctx->mm_account);
9384 ctx->mm_account = NULL;
9387 io_rsrc_refs_drop(ctx);
9388 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9389 io_wait_rsrc_data(ctx->buf_data);
9390 io_wait_rsrc_data(ctx->file_data);
9392 mutex_lock(&ctx->uring_lock);
9394 __io_sqe_buffers_unregister(ctx);
9396 __io_sqe_files_unregister(ctx);
9398 __io_cqring_overflow_flush(ctx, true);
9399 mutex_unlock(&ctx->uring_lock);
9400 io_eventfd_unregister(ctx);
9401 io_destroy_buffers(ctx);
9403 put_cred(ctx->sq_creds);
9405 /* there are no registered resources left, nobody uses it */
9407 io_rsrc_node_destroy(ctx->rsrc_node);
9408 if (ctx->rsrc_backup_node)
9409 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9410 flush_delayed_work(&ctx->rsrc_put_work);
9411 flush_delayed_work(&ctx->fallback_work);
9413 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9414 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9416 #if defined(CONFIG_UNIX)
9417 if (ctx->ring_sock) {
9418 ctx->ring_sock->file = NULL; /* so that iput() is called */
9419 sock_release(ctx->ring_sock);
9422 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9424 io_mem_free(ctx->rings);
9425 io_mem_free(ctx->sq_sqes);
9427 percpu_ref_exit(&ctx->refs);
9428 free_uid(ctx->user);
9429 io_req_caches_free(ctx);
9431 io_wq_put_hash(ctx->hash_map);
9432 kfree(ctx->cancel_hash);
9433 kfree(ctx->dummy_ubuf);
9437 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9439 struct io_ring_ctx *ctx = file->private_data;
9442 poll_wait(file, &ctx->cq_wait, wait);
9444 * synchronizes with barrier from wq_has_sleeper call in
9448 if (!io_sqring_full(ctx))
9449 mask |= EPOLLOUT | EPOLLWRNORM;
9452 * Don't flush cqring overflow list here, just do a simple check.
9453 * Otherwise there could possible be ABBA deadlock:
9456 * lock(&ctx->uring_lock);
9458 * lock(&ctx->uring_lock);
9461 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9462 * pushs them to do the flush.
9464 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9465 mask |= EPOLLIN | EPOLLRDNORM;
9470 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9472 const struct cred *creds;
9474 creds = xa_erase(&ctx->personalities, id);
9483 struct io_tctx_exit {
9484 struct callback_head task_work;
9485 struct completion completion;
9486 struct io_ring_ctx *ctx;
9489 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9491 struct io_uring_task *tctx = current->io_uring;
9492 struct io_tctx_exit *work;
9494 work = container_of(cb, struct io_tctx_exit, task_work);
9496 * When @in_idle, we're in cancellation and it's racy to remove the
9497 * node. It'll be removed by the end of cancellation, just ignore it.
9499 if (!atomic_read(&tctx->in_idle))
9500 io_uring_del_tctx_node((unsigned long)work->ctx);
9501 complete(&work->completion);
9504 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9506 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9508 return req->ctx == data;
9511 static __cold void io_ring_exit_work(struct work_struct *work)
9513 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9514 unsigned long timeout = jiffies + HZ * 60 * 5;
9515 unsigned long interval = HZ / 20;
9516 struct io_tctx_exit exit;
9517 struct io_tctx_node *node;
9521 * If we're doing polled IO and end up having requests being
9522 * submitted async (out-of-line), then completions can come in while
9523 * we're waiting for refs to drop. We need to reap these manually,
9524 * as nobody else will be looking for them.
9527 io_uring_try_cancel_requests(ctx, NULL, true);
9529 struct io_sq_data *sqd = ctx->sq_data;
9530 struct task_struct *tsk;
9532 io_sq_thread_park(sqd);
9534 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9535 io_wq_cancel_cb(tsk->io_uring->io_wq,
9536 io_cancel_ctx_cb, ctx, true);
9537 io_sq_thread_unpark(sqd);
9540 io_req_caches_free(ctx);
9542 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9543 /* there is little hope left, don't run it too often */
9546 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9548 init_completion(&exit.completion);
9549 init_task_work(&exit.task_work, io_tctx_exit_cb);
9552 * Some may use context even when all refs and requests have been put,
9553 * and they are free to do so while still holding uring_lock or
9554 * completion_lock, see io_req_task_submit(). Apart from other work,
9555 * this lock/unlock section also waits them to finish.
9557 mutex_lock(&ctx->uring_lock);
9558 while (!list_empty(&ctx->tctx_list)) {
9559 WARN_ON_ONCE(time_after(jiffies, timeout));
9561 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9563 /* don't spin on a single task if cancellation failed */
9564 list_rotate_left(&ctx->tctx_list);
9565 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9566 if (WARN_ON_ONCE(ret))
9569 mutex_unlock(&ctx->uring_lock);
9570 wait_for_completion(&exit.completion);
9571 mutex_lock(&ctx->uring_lock);
9573 mutex_unlock(&ctx->uring_lock);
9574 spin_lock(&ctx->completion_lock);
9575 spin_unlock(&ctx->completion_lock);
9577 io_ring_ctx_free(ctx);
9580 /* Returns true if we found and killed one or more timeouts */
9581 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
9582 struct task_struct *tsk, bool cancel_all)
9584 struct io_kiocb *req, *tmp;
9587 spin_lock(&ctx->completion_lock);
9588 spin_lock_irq(&ctx->timeout_lock);
9589 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9590 if (io_match_task(req, tsk, cancel_all)) {
9591 io_kill_timeout(req, -ECANCELED);
9595 spin_unlock_irq(&ctx->timeout_lock);
9597 io_commit_cqring(ctx);
9598 spin_unlock(&ctx->completion_lock);
9600 io_cqring_ev_posted(ctx);
9601 return canceled != 0;
9604 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9606 unsigned long index;
9607 struct creds *creds;
9609 mutex_lock(&ctx->uring_lock);
9610 percpu_ref_kill(&ctx->refs);
9612 __io_cqring_overflow_flush(ctx, true);
9613 xa_for_each(&ctx->personalities, index, creds)
9614 io_unregister_personality(ctx, index);
9615 mutex_unlock(&ctx->uring_lock);
9617 io_kill_timeouts(ctx, NULL, true);
9618 io_poll_remove_all(ctx, NULL, true);
9620 /* if we failed setting up the ctx, we might not have any rings */
9621 io_iopoll_try_reap_events(ctx);
9623 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9625 * Use system_unbound_wq to avoid spawning tons of event kworkers
9626 * if we're exiting a ton of rings at the same time. It just adds
9627 * noise and overhead, there's no discernable change in runtime
9628 * over using system_wq.
9630 queue_work(system_unbound_wq, &ctx->exit_work);
9633 static int io_uring_release(struct inode *inode, struct file *file)
9635 struct io_ring_ctx *ctx = file->private_data;
9637 file->private_data = NULL;
9638 io_ring_ctx_wait_and_kill(ctx);
9642 struct io_task_cancel {
9643 struct task_struct *task;
9647 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9649 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9650 struct io_task_cancel *cancel = data;
9652 return io_match_task_safe(req, cancel->task, cancel->all);
9655 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9656 struct task_struct *task,
9659 struct io_defer_entry *de;
9662 spin_lock(&ctx->completion_lock);
9663 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9664 if (io_match_task_safe(de->req, task, cancel_all)) {
9665 list_cut_position(&list, &ctx->defer_list, &de->list);
9669 spin_unlock(&ctx->completion_lock);
9670 if (list_empty(&list))
9673 while (!list_empty(&list)) {
9674 de = list_first_entry(&list, struct io_defer_entry, list);
9675 list_del_init(&de->list);
9676 io_req_complete_failed(de->req, -ECANCELED);
9682 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9684 struct io_tctx_node *node;
9685 enum io_wq_cancel cret;
9688 mutex_lock(&ctx->uring_lock);
9689 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9690 struct io_uring_task *tctx = node->task->io_uring;
9693 * io_wq will stay alive while we hold uring_lock, because it's
9694 * killed after ctx nodes, which requires to take the lock.
9696 if (!tctx || !tctx->io_wq)
9698 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9699 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9701 mutex_unlock(&ctx->uring_lock);
9706 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9707 struct task_struct *task,
9710 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9711 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9714 enum io_wq_cancel cret;
9718 ret |= io_uring_try_cancel_iowq(ctx);
9719 } else if (tctx && tctx->io_wq) {
9721 * Cancels requests of all rings, not only @ctx, but
9722 * it's fine as the task is in exit/exec.
9724 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9726 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9729 /* SQPOLL thread does its own polling */
9730 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9731 (ctx->sq_data && ctx->sq_data->thread == current)) {
9732 while (!wq_list_empty(&ctx->iopoll_list)) {
9733 io_iopoll_try_reap_events(ctx);
9738 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9739 ret |= io_poll_remove_all(ctx, task, cancel_all);
9740 ret |= io_kill_timeouts(ctx, task, cancel_all);
9742 ret |= io_run_task_work();
9749 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9751 struct io_uring_task *tctx = current->io_uring;
9752 struct io_tctx_node *node;
9755 if (unlikely(!tctx)) {
9756 ret = io_uring_alloc_task_context(current, ctx);
9760 tctx = current->io_uring;
9761 if (ctx->iowq_limits_set) {
9762 unsigned int limits[2] = { ctx->iowq_limits[0],
9763 ctx->iowq_limits[1], };
9765 ret = io_wq_max_workers(tctx->io_wq, limits);
9770 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9771 node = kmalloc(sizeof(*node), GFP_KERNEL);
9775 node->task = current;
9777 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9784 mutex_lock(&ctx->uring_lock);
9785 list_add(&node->ctx_node, &ctx->tctx_list);
9786 mutex_unlock(&ctx->uring_lock);
9793 * Note that this task has used io_uring. We use it for cancelation purposes.
9795 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9797 struct io_uring_task *tctx = current->io_uring;
9799 if (likely(tctx && tctx->last == ctx))
9801 return __io_uring_add_tctx_node(ctx);
9805 * Remove this io_uring_file -> task mapping.
9807 static __cold void io_uring_del_tctx_node(unsigned long index)
9809 struct io_uring_task *tctx = current->io_uring;
9810 struct io_tctx_node *node;
9814 node = xa_erase(&tctx->xa, index);
9818 WARN_ON_ONCE(current != node->task);
9819 WARN_ON_ONCE(list_empty(&node->ctx_node));
9821 mutex_lock(&node->ctx->uring_lock);
9822 list_del(&node->ctx_node);
9823 mutex_unlock(&node->ctx->uring_lock);
9825 if (tctx->last == node->ctx)
9830 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
9832 struct io_wq *wq = tctx->io_wq;
9833 struct io_tctx_node *node;
9834 unsigned long index;
9836 xa_for_each(&tctx->xa, index, node) {
9837 io_uring_del_tctx_node(index);
9842 * Must be after io_uring_del_tctx_node() (removes nodes under
9843 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9845 io_wq_put_and_exit(wq);
9850 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9853 return atomic_read(&tctx->inflight_tracked);
9854 return percpu_counter_sum(&tctx->inflight);
9858 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9859 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9861 static __cold void io_uring_cancel_generic(bool cancel_all,
9862 struct io_sq_data *sqd)
9864 struct io_uring_task *tctx = current->io_uring;
9865 struct io_ring_ctx *ctx;
9869 WARN_ON_ONCE(sqd && sqd->thread != current);
9871 if (!current->io_uring)
9874 io_wq_exit_start(tctx->io_wq);
9876 atomic_inc(&tctx->in_idle);
9878 io_uring_drop_tctx_refs(current);
9879 /* read completions before cancelations */
9880 inflight = tctx_inflight(tctx, !cancel_all);
9885 struct io_tctx_node *node;
9886 unsigned long index;
9888 xa_for_each(&tctx->xa, index, node) {
9889 /* sqpoll task will cancel all its requests */
9890 if (node->ctx->sq_data)
9892 io_uring_try_cancel_requests(node->ctx, current,
9896 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9897 io_uring_try_cancel_requests(ctx, current,
9901 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9903 io_uring_drop_tctx_refs(current);
9906 * If we've seen completions, retry without waiting. This
9907 * avoids a race where a completion comes in before we did
9908 * prepare_to_wait().
9910 if (inflight == tctx_inflight(tctx, !cancel_all))
9912 finish_wait(&tctx->wait, &wait);
9915 io_uring_clean_tctx(tctx);
9918 * We shouldn't run task_works after cancel, so just leave
9919 * ->in_idle set for normal exit.
9921 atomic_dec(&tctx->in_idle);
9922 /* for exec all current's requests should be gone, kill tctx */
9923 __io_uring_free(current);
9927 void __io_uring_cancel(bool cancel_all)
9929 io_uring_cancel_generic(cancel_all, NULL);
9932 static void *io_uring_validate_mmap_request(struct file *file,
9933 loff_t pgoff, size_t sz)
9935 struct io_ring_ctx *ctx = file->private_data;
9936 loff_t offset = pgoff << PAGE_SHIFT;
9941 case IORING_OFF_SQ_RING:
9942 case IORING_OFF_CQ_RING:
9945 case IORING_OFF_SQES:
9949 return ERR_PTR(-EINVAL);
9952 page = virt_to_head_page(ptr);
9953 if (sz > page_size(page))
9954 return ERR_PTR(-EINVAL);
9961 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9963 size_t sz = vma->vm_end - vma->vm_start;
9967 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9969 return PTR_ERR(ptr);
9971 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9972 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9975 #else /* !CONFIG_MMU */
9977 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9979 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9982 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9984 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9987 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9988 unsigned long addr, unsigned long len,
9989 unsigned long pgoff, unsigned long flags)
9993 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9995 return PTR_ERR(ptr);
9997 return (unsigned long) ptr;
10000 #endif /* !CONFIG_MMU */
10002 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10007 if (!io_sqring_full(ctx))
10009 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10011 if (!io_sqring_full(ctx))
10014 } while (!signal_pending(current));
10016 finish_wait(&ctx->sqo_sq_wait, &wait);
10020 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10021 struct __kernel_timespec __user **ts,
10022 const sigset_t __user **sig)
10024 struct io_uring_getevents_arg arg;
10027 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10028 * is just a pointer to the sigset_t.
10030 if (!(flags & IORING_ENTER_EXT_ARG)) {
10031 *sig = (const sigset_t __user *) argp;
10037 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10038 * timespec and sigset_t pointers if good.
10040 if (*argsz != sizeof(arg))
10042 if (copy_from_user(&arg, argp, sizeof(arg)))
10044 *sig = u64_to_user_ptr(arg.sigmask);
10045 *argsz = arg.sigmask_sz;
10046 *ts = u64_to_user_ptr(arg.ts);
10050 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10051 u32, min_complete, u32, flags, const void __user *, argp,
10054 struct io_ring_ctx *ctx;
10059 io_run_task_work();
10061 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10062 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
10066 if (unlikely(!f.file))
10070 if (unlikely(f.file->f_op != &io_uring_fops))
10074 ctx = f.file->private_data;
10075 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10079 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10083 * For SQ polling, the thread will do all submissions and completions.
10084 * Just return the requested submit count, and wake the thread if
10085 * we were asked to.
10088 if (ctx->flags & IORING_SETUP_SQPOLL) {
10089 io_cqring_overflow_flush(ctx);
10091 if (unlikely(ctx->sq_data->thread == NULL)) {
10095 if (flags & IORING_ENTER_SQ_WAKEUP)
10096 wake_up(&ctx->sq_data->wait);
10097 if (flags & IORING_ENTER_SQ_WAIT) {
10098 ret = io_sqpoll_wait_sq(ctx);
10102 submitted = to_submit;
10103 } else if (to_submit) {
10104 ret = io_uring_add_tctx_node(ctx);
10107 mutex_lock(&ctx->uring_lock);
10108 submitted = io_submit_sqes(ctx, to_submit);
10109 mutex_unlock(&ctx->uring_lock);
10111 if (submitted != to_submit)
10114 if (flags & IORING_ENTER_GETEVENTS) {
10115 const sigset_t __user *sig;
10116 struct __kernel_timespec __user *ts;
10118 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10122 min_complete = min(min_complete, ctx->cq_entries);
10125 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10126 * space applications don't need to do io completion events
10127 * polling again, they can rely on io_sq_thread to do polling
10128 * work, which can reduce cpu usage and uring_lock contention.
10130 if (ctx->flags & IORING_SETUP_IOPOLL &&
10131 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10132 ret = io_iopoll_check(ctx, min_complete);
10134 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10139 percpu_ref_put(&ctx->refs);
10142 return submitted ? submitted : ret;
10145 #ifdef CONFIG_PROC_FS
10146 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10147 const struct cred *cred)
10149 struct user_namespace *uns = seq_user_ns(m);
10150 struct group_info *gi;
10155 seq_printf(m, "%5d\n", id);
10156 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10157 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10158 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10159 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10160 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10161 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10162 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10163 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10164 seq_puts(m, "\n\tGroups:\t");
10165 gi = cred->group_info;
10166 for (g = 0; g < gi->ngroups; g++) {
10167 seq_put_decimal_ull(m, g ? " " : "",
10168 from_kgid_munged(uns, gi->gid[g]));
10170 seq_puts(m, "\n\tCapEff:\t");
10171 cap = cred->cap_effective;
10172 CAP_FOR_EACH_U32(__capi)
10173 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10178 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10179 struct seq_file *m)
10181 struct io_sq_data *sq = NULL;
10182 struct io_overflow_cqe *ocqe;
10183 struct io_rings *r = ctx->rings;
10184 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10185 unsigned int sq_head = READ_ONCE(r->sq.head);
10186 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10187 unsigned int cq_head = READ_ONCE(r->cq.head);
10188 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10189 unsigned int sq_entries, cq_entries;
10194 * we may get imprecise sqe and cqe info if uring is actively running
10195 * since we get cached_sq_head and cached_cq_tail without uring_lock
10196 * and sq_tail and cq_head are changed by userspace. But it's ok since
10197 * we usually use these info when it is stuck.
10199 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10200 seq_printf(m, "SqHead:\t%u\n", sq_head);
10201 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10202 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10203 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10204 seq_printf(m, "CqHead:\t%u\n", cq_head);
10205 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10206 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10207 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10208 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10209 for (i = 0; i < sq_entries; i++) {
10210 unsigned int entry = i + sq_head;
10211 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10212 struct io_uring_sqe *sqe;
10214 if (sq_idx > sq_mask)
10216 sqe = &ctx->sq_sqes[sq_idx];
10217 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10218 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10221 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10222 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10223 for (i = 0; i < cq_entries; i++) {
10224 unsigned int entry = i + cq_head;
10225 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10227 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10228 entry & cq_mask, cqe->user_data, cqe->res,
10233 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10234 * since fdinfo case grabs it in the opposite direction of normal use
10235 * cases. If we fail to get the lock, we just don't iterate any
10236 * structures that could be going away outside the io_uring mutex.
10238 has_lock = mutex_trylock(&ctx->uring_lock);
10240 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10246 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10247 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10248 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10249 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10250 struct file *f = io_file_from_index(ctx, i);
10253 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10255 seq_printf(m, "%5u: <none>\n", i);
10257 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10258 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10259 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10260 unsigned int len = buf->ubuf_end - buf->ubuf;
10262 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10264 if (has_lock && !xa_empty(&ctx->personalities)) {
10265 unsigned long index;
10266 const struct cred *cred;
10268 seq_printf(m, "Personalities:\n");
10269 xa_for_each(&ctx->personalities, index, cred)
10270 io_uring_show_cred(m, index, cred);
10273 mutex_unlock(&ctx->uring_lock);
10275 seq_puts(m, "PollList:\n");
10276 spin_lock(&ctx->completion_lock);
10277 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10278 struct hlist_head *list = &ctx->cancel_hash[i];
10279 struct io_kiocb *req;
10281 hlist_for_each_entry(req, list, hash_node)
10282 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10283 req->task->task_works != NULL);
10286 seq_puts(m, "CqOverflowList:\n");
10287 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10288 struct io_uring_cqe *cqe = &ocqe->cqe;
10290 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10291 cqe->user_data, cqe->res, cqe->flags);
10295 spin_unlock(&ctx->completion_lock);
10298 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10300 struct io_ring_ctx *ctx = f->private_data;
10302 if (percpu_ref_tryget(&ctx->refs)) {
10303 __io_uring_show_fdinfo(ctx, m);
10304 percpu_ref_put(&ctx->refs);
10309 static const struct file_operations io_uring_fops = {
10310 .release = io_uring_release,
10311 .mmap = io_uring_mmap,
10313 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10314 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10316 .poll = io_uring_poll,
10317 #ifdef CONFIG_PROC_FS
10318 .show_fdinfo = io_uring_show_fdinfo,
10322 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10323 struct io_uring_params *p)
10325 struct io_rings *rings;
10326 size_t size, sq_array_offset;
10328 /* make sure these are sane, as we already accounted them */
10329 ctx->sq_entries = p->sq_entries;
10330 ctx->cq_entries = p->cq_entries;
10332 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10333 if (size == SIZE_MAX)
10336 rings = io_mem_alloc(size);
10340 ctx->rings = rings;
10341 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10342 rings->sq_ring_mask = p->sq_entries - 1;
10343 rings->cq_ring_mask = p->cq_entries - 1;
10344 rings->sq_ring_entries = p->sq_entries;
10345 rings->cq_ring_entries = p->cq_entries;
10347 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10348 if (size == SIZE_MAX) {
10349 io_mem_free(ctx->rings);
10354 ctx->sq_sqes = io_mem_alloc(size);
10355 if (!ctx->sq_sqes) {
10356 io_mem_free(ctx->rings);
10364 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10368 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10372 ret = io_uring_add_tctx_node(ctx);
10377 fd_install(fd, file);
10382 * Allocate an anonymous fd, this is what constitutes the application
10383 * visible backing of an io_uring instance. The application mmaps this
10384 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10385 * we have to tie this fd to a socket for file garbage collection purposes.
10387 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10390 #if defined(CONFIG_UNIX)
10393 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10396 return ERR_PTR(ret);
10399 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
10400 O_RDWR | O_CLOEXEC, NULL);
10401 #if defined(CONFIG_UNIX)
10402 if (IS_ERR(file)) {
10403 sock_release(ctx->ring_sock);
10404 ctx->ring_sock = NULL;
10406 ctx->ring_sock->file = file;
10412 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
10413 struct io_uring_params __user *params)
10415 struct io_ring_ctx *ctx;
10421 if (entries > IORING_MAX_ENTRIES) {
10422 if (!(p->flags & IORING_SETUP_CLAMP))
10424 entries = IORING_MAX_ENTRIES;
10428 * Use twice as many entries for the CQ ring. It's possible for the
10429 * application to drive a higher depth than the size of the SQ ring,
10430 * since the sqes are only used at submission time. This allows for
10431 * some flexibility in overcommitting a bit. If the application has
10432 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10433 * of CQ ring entries manually.
10435 p->sq_entries = roundup_pow_of_two(entries);
10436 if (p->flags & IORING_SETUP_CQSIZE) {
10438 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10439 * to a power-of-two, if it isn't already. We do NOT impose
10440 * any cq vs sq ring sizing.
10442 if (!p->cq_entries)
10444 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10445 if (!(p->flags & IORING_SETUP_CLAMP))
10447 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10449 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10450 if (p->cq_entries < p->sq_entries)
10453 p->cq_entries = 2 * p->sq_entries;
10456 ctx = io_ring_ctx_alloc(p);
10459 ctx->compat = in_compat_syscall();
10460 if (!capable(CAP_IPC_LOCK))
10461 ctx->user = get_uid(current_user());
10464 * This is just grabbed for accounting purposes. When a process exits,
10465 * the mm is exited and dropped before the files, hence we need to hang
10466 * on to this mm purely for the purposes of being able to unaccount
10467 * memory (locked/pinned vm). It's not used for anything else.
10469 mmgrab(current->mm);
10470 ctx->mm_account = current->mm;
10472 ret = io_allocate_scq_urings(ctx, p);
10476 ret = io_sq_offload_create(ctx, p);
10479 /* always set a rsrc node */
10480 ret = io_rsrc_node_switch_start(ctx);
10483 io_rsrc_node_switch(ctx, NULL);
10485 memset(&p->sq_off, 0, sizeof(p->sq_off));
10486 p->sq_off.head = offsetof(struct io_rings, sq.head);
10487 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10488 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10489 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10490 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10491 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10492 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10494 memset(&p->cq_off, 0, sizeof(p->cq_off));
10495 p->cq_off.head = offsetof(struct io_rings, cq.head);
10496 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10497 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10498 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10499 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10500 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10501 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10503 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10504 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10505 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10506 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10507 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10508 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
10510 if (copy_to_user(params, p, sizeof(*p))) {
10515 file = io_uring_get_file(ctx);
10516 if (IS_ERR(file)) {
10517 ret = PTR_ERR(file);
10522 * Install ring fd as the very last thing, so we don't risk someone
10523 * having closed it before we finish setup
10525 ret = io_uring_install_fd(ctx, file);
10527 /* fput will clean it up */
10532 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10535 io_ring_ctx_wait_and_kill(ctx);
10540 * Sets up an aio uring context, and returns the fd. Applications asks for a
10541 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10542 * params structure passed in.
10544 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10546 struct io_uring_params p;
10549 if (copy_from_user(&p, params, sizeof(p)))
10551 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10556 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10557 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10558 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10559 IORING_SETUP_R_DISABLED))
10562 return io_uring_create(entries, &p, params);
10565 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10566 struct io_uring_params __user *, params)
10568 return io_uring_setup(entries, params);
10571 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
10574 struct io_uring_probe *p;
10578 size = struct_size(p, ops, nr_args);
10579 if (size == SIZE_MAX)
10581 p = kzalloc(size, GFP_KERNEL);
10586 if (copy_from_user(p, arg, size))
10589 if (memchr_inv(p, 0, size))
10592 p->last_op = IORING_OP_LAST - 1;
10593 if (nr_args > IORING_OP_LAST)
10594 nr_args = IORING_OP_LAST;
10596 for (i = 0; i < nr_args; i++) {
10598 if (!io_op_defs[i].not_supported)
10599 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10604 if (copy_to_user(arg, p, size))
10611 static int io_register_personality(struct io_ring_ctx *ctx)
10613 const struct cred *creds;
10617 creds = get_current_cred();
10619 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10620 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10628 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
10629 void __user *arg, unsigned int nr_args)
10631 struct io_uring_restriction *res;
10635 /* Restrictions allowed only if rings started disabled */
10636 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10639 /* We allow only a single restrictions registration */
10640 if (ctx->restrictions.registered)
10643 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10646 size = array_size(nr_args, sizeof(*res));
10647 if (size == SIZE_MAX)
10650 res = memdup_user(arg, size);
10652 return PTR_ERR(res);
10656 for (i = 0; i < nr_args; i++) {
10657 switch (res[i].opcode) {
10658 case IORING_RESTRICTION_REGISTER_OP:
10659 if (res[i].register_op >= IORING_REGISTER_LAST) {
10664 __set_bit(res[i].register_op,
10665 ctx->restrictions.register_op);
10667 case IORING_RESTRICTION_SQE_OP:
10668 if (res[i].sqe_op >= IORING_OP_LAST) {
10673 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10675 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10676 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10678 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10679 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10688 /* Reset all restrictions if an error happened */
10690 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10692 ctx->restrictions.registered = true;
10698 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10700 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10703 if (ctx->restrictions.registered)
10704 ctx->restricted = 1;
10706 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10707 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10708 wake_up(&ctx->sq_data->wait);
10712 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10713 struct io_uring_rsrc_update2 *up,
10721 if (check_add_overflow(up->offset, nr_args, &tmp))
10723 err = io_rsrc_node_switch_start(ctx);
10728 case IORING_RSRC_FILE:
10729 return __io_sqe_files_update(ctx, up, nr_args);
10730 case IORING_RSRC_BUFFER:
10731 return __io_sqe_buffers_update(ctx, up, nr_args);
10736 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10739 struct io_uring_rsrc_update2 up;
10743 memset(&up, 0, sizeof(up));
10744 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10746 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10749 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10750 unsigned size, unsigned type)
10752 struct io_uring_rsrc_update2 up;
10754 if (size != sizeof(up))
10756 if (copy_from_user(&up, arg, sizeof(up)))
10758 if (!up.nr || up.resv)
10760 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10763 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10764 unsigned int size, unsigned int type)
10766 struct io_uring_rsrc_register rr;
10768 /* keep it extendible */
10769 if (size != sizeof(rr))
10772 memset(&rr, 0, sizeof(rr));
10773 if (copy_from_user(&rr, arg, size))
10775 if (!rr.nr || rr.resv || rr.resv2)
10779 case IORING_RSRC_FILE:
10780 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10781 rr.nr, u64_to_user_ptr(rr.tags));
10782 case IORING_RSRC_BUFFER:
10783 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10784 rr.nr, u64_to_user_ptr(rr.tags));
10789 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
10790 void __user *arg, unsigned len)
10792 struct io_uring_task *tctx = current->io_uring;
10793 cpumask_var_t new_mask;
10796 if (!tctx || !tctx->io_wq)
10799 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10802 cpumask_clear(new_mask);
10803 if (len > cpumask_size())
10804 len = cpumask_size();
10806 if (copy_from_user(new_mask, arg, len)) {
10807 free_cpumask_var(new_mask);
10811 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10812 free_cpumask_var(new_mask);
10816 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10818 struct io_uring_task *tctx = current->io_uring;
10820 if (!tctx || !tctx->io_wq)
10823 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10826 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10828 __must_hold(&ctx->uring_lock)
10830 struct io_tctx_node *node;
10831 struct io_uring_task *tctx = NULL;
10832 struct io_sq_data *sqd = NULL;
10833 __u32 new_count[2];
10836 if (copy_from_user(new_count, arg, sizeof(new_count)))
10838 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10839 if (new_count[i] > INT_MAX)
10842 if (ctx->flags & IORING_SETUP_SQPOLL) {
10843 sqd = ctx->sq_data;
10846 * Observe the correct sqd->lock -> ctx->uring_lock
10847 * ordering. Fine to drop uring_lock here, we hold
10848 * a ref to the ctx.
10850 refcount_inc(&sqd->refs);
10851 mutex_unlock(&ctx->uring_lock);
10852 mutex_lock(&sqd->lock);
10853 mutex_lock(&ctx->uring_lock);
10855 tctx = sqd->thread->io_uring;
10858 tctx = current->io_uring;
10861 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10863 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10865 ctx->iowq_limits[i] = new_count[i];
10866 ctx->iowq_limits_set = true;
10868 if (tctx && tctx->io_wq) {
10869 ret = io_wq_max_workers(tctx->io_wq, new_count);
10873 memset(new_count, 0, sizeof(new_count));
10877 mutex_unlock(&sqd->lock);
10878 io_put_sq_data(sqd);
10881 if (copy_to_user(arg, new_count, sizeof(new_count)))
10884 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10888 /* now propagate the restriction to all registered users */
10889 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10890 struct io_uring_task *tctx = node->task->io_uring;
10892 if (WARN_ON_ONCE(!tctx->io_wq))
10895 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10896 new_count[i] = ctx->iowq_limits[i];
10897 /* ignore errors, it always returns zero anyway */
10898 (void)io_wq_max_workers(tctx->io_wq, new_count);
10903 mutex_unlock(&sqd->lock);
10904 io_put_sq_data(sqd);
10909 static bool io_register_op_must_quiesce(int op)
10912 case IORING_REGISTER_BUFFERS:
10913 case IORING_UNREGISTER_BUFFERS:
10914 case IORING_REGISTER_FILES:
10915 case IORING_UNREGISTER_FILES:
10916 case IORING_REGISTER_FILES_UPDATE:
10917 case IORING_REGISTER_PROBE:
10918 case IORING_REGISTER_PERSONALITY:
10919 case IORING_UNREGISTER_PERSONALITY:
10920 case IORING_REGISTER_FILES2:
10921 case IORING_REGISTER_FILES_UPDATE2:
10922 case IORING_REGISTER_BUFFERS2:
10923 case IORING_REGISTER_BUFFERS_UPDATE:
10924 case IORING_REGISTER_IOWQ_AFF:
10925 case IORING_UNREGISTER_IOWQ_AFF:
10926 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10933 static __cold int io_ctx_quiesce(struct io_ring_ctx *ctx)
10937 percpu_ref_kill(&ctx->refs);
10940 * Drop uring mutex before waiting for references to exit. If another
10941 * thread is currently inside io_uring_enter() it might need to grab the
10942 * uring_lock to make progress. If we hold it here across the drain
10943 * wait, then we can deadlock. It's safe to drop the mutex here, since
10944 * no new references will come in after we've killed the percpu ref.
10946 mutex_unlock(&ctx->uring_lock);
10948 ret = wait_for_completion_interruptible_timeout(&ctx->ref_comp, HZ);
10950 ret = min(0L, ret);
10954 ret = io_run_task_work_sig();
10955 io_req_caches_free(ctx);
10956 } while (ret >= 0);
10957 mutex_lock(&ctx->uring_lock);
10960 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10964 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10965 void __user *arg, unsigned nr_args)
10966 __releases(ctx->uring_lock)
10967 __acquires(ctx->uring_lock)
10972 * We're inside the ring mutex, if the ref is already dying, then
10973 * someone else killed the ctx or is already going through
10974 * io_uring_register().
10976 if (percpu_ref_is_dying(&ctx->refs))
10979 if (ctx->restricted) {
10980 if (opcode >= IORING_REGISTER_LAST)
10982 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10983 if (!test_bit(opcode, ctx->restrictions.register_op))
10987 if (io_register_op_must_quiesce(opcode)) {
10988 ret = io_ctx_quiesce(ctx);
10994 case IORING_REGISTER_BUFFERS:
10995 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10997 case IORING_UNREGISTER_BUFFERS:
10999 if (arg || nr_args)
11001 ret = io_sqe_buffers_unregister(ctx);
11003 case IORING_REGISTER_FILES:
11004 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11006 case IORING_UNREGISTER_FILES:
11008 if (arg || nr_args)
11010 ret = io_sqe_files_unregister(ctx);
11012 case IORING_REGISTER_FILES_UPDATE:
11013 ret = io_register_files_update(ctx, arg, nr_args);
11015 case IORING_REGISTER_EVENTFD:
11016 case IORING_REGISTER_EVENTFD_ASYNC:
11020 ret = io_eventfd_register(ctx, arg);
11023 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
11024 ctx->eventfd_async = 1;
11026 ctx->eventfd_async = 0;
11028 case IORING_UNREGISTER_EVENTFD:
11030 if (arg || nr_args)
11032 ret = io_eventfd_unregister(ctx);
11034 case IORING_REGISTER_PROBE:
11036 if (!arg || nr_args > 256)
11038 ret = io_probe(ctx, arg, nr_args);
11040 case IORING_REGISTER_PERSONALITY:
11042 if (arg || nr_args)
11044 ret = io_register_personality(ctx);
11046 case IORING_UNREGISTER_PERSONALITY:
11050 ret = io_unregister_personality(ctx, nr_args);
11052 case IORING_REGISTER_ENABLE_RINGS:
11054 if (arg || nr_args)
11056 ret = io_register_enable_rings(ctx);
11058 case IORING_REGISTER_RESTRICTIONS:
11059 ret = io_register_restrictions(ctx, arg, nr_args);
11061 case IORING_REGISTER_FILES2:
11062 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11064 case IORING_REGISTER_FILES_UPDATE2:
11065 ret = io_register_rsrc_update(ctx, arg, nr_args,
11068 case IORING_REGISTER_BUFFERS2:
11069 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11071 case IORING_REGISTER_BUFFERS_UPDATE:
11072 ret = io_register_rsrc_update(ctx, arg, nr_args,
11073 IORING_RSRC_BUFFER);
11075 case IORING_REGISTER_IOWQ_AFF:
11077 if (!arg || !nr_args)
11079 ret = io_register_iowq_aff(ctx, arg, nr_args);
11081 case IORING_UNREGISTER_IOWQ_AFF:
11083 if (arg || nr_args)
11085 ret = io_unregister_iowq_aff(ctx);
11087 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11089 if (!arg || nr_args != 2)
11091 ret = io_register_iowq_max_workers(ctx, arg);
11098 if (io_register_op_must_quiesce(opcode)) {
11099 /* bring the ctx back to life */
11100 percpu_ref_reinit(&ctx->refs);
11101 reinit_completion(&ctx->ref_comp);
11106 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11107 void __user *, arg, unsigned int, nr_args)
11109 struct io_ring_ctx *ctx;
11118 if (f.file->f_op != &io_uring_fops)
11121 ctx = f.file->private_data;
11123 io_run_task_work();
11125 mutex_lock(&ctx->uring_lock);
11126 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11127 mutex_unlock(&ctx->uring_lock);
11128 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
11129 ctx->cq_ev_fd != NULL, ret);
11135 static int __init io_uring_init(void)
11137 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11138 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11139 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11142 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11143 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11144 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11145 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11146 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11147 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11148 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11149 BUILD_BUG_SQE_ELEM(8, __u64, off);
11150 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11151 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11152 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11153 BUILD_BUG_SQE_ELEM(24, __u32, len);
11154 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11155 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11156 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11157 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11158 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11159 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11160 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11161 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11162 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11163 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11164 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11165 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11166 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11167 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11168 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11169 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11170 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11171 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11172 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11173 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11174 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11176 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11177 sizeof(struct io_uring_rsrc_update));
11178 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11179 sizeof(struct io_uring_rsrc_update2));
11181 /* ->buf_index is u16 */
11182 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11184 /* should fit into one byte */
11185 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11186 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11187 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11189 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11190 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11192 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11196 __initcall(io_uring_init);