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 <net/busy_poll.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/splice.h>
79 #include <linux/task_work.h>
80 #include <linux/pagemap.h>
81 #include <linux/io_uring.h>
82 #include <linux/tracehook.h>
83 #include <linux/audit.h>
84 #include <linux/security.h>
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
89 #include <uapi/linux/io_uring.h>
94 #define IORING_MAX_ENTRIES 32768
95 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
96 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
99 #define IORING_MAX_FIXED_FILES (1U << 15)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
104 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
105 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
107 #define IORING_MAX_REG_BUFFERS (1U << 14)
109 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
110 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
112 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
113 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
115 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
116 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
119 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
122 u32 head ____cacheline_aligned_in_smp;
123 u32 tail ____cacheline_aligned_in_smp;
127 * This data is shared with the application through the mmap at offsets
128 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
130 * The offsets to the member fields are published through struct
131 * io_sqring_offsets when calling io_uring_setup.
135 * Head and tail offsets into the ring; the offsets need to be
136 * masked to get valid indices.
138 * The kernel controls head of the sq ring and the tail of the cq ring,
139 * and the application controls tail of the sq ring and the head of the
142 struct io_uring sq, cq;
144 * Bitmasks to apply to head and tail offsets (constant, equals
147 u32 sq_ring_mask, cq_ring_mask;
148 /* Ring sizes (constant, power of 2) */
149 u32 sq_ring_entries, cq_ring_entries;
151 * Number of invalid entries dropped by the kernel due to
152 * invalid index stored in array
154 * Written by the kernel, shouldn't be modified by the
155 * application (i.e. get number of "new events" by comparing to
158 * After a new SQ head value was read by the application this
159 * counter includes all submissions that were dropped reaching
160 * the new SQ head (and possibly more).
166 * Written by the kernel, shouldn't be modified by the
169 * The application needs a full memory barrier before checking
170 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
176 * Written by the application, shouldn't be modified by the
181 * Number of completion events lost because the queue was full;
182 * this should be avoided by the application by making sure
183 * there are not more requests pending than there is space in
184 * the completion queue.
186 * Written by the kernel, shouldn't be modified by the
187 * application (i.e. get number of "new events" by comparing to
190 * As completion events come in out of order this counter is not
191 * ordered with any other data.
195 * Ring buffer of completion events.
197 * The kernel writes completion events fresh every time they are
198 * produced, so the application is allowed to modify pending
201 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
204 enum io_uring_cmd_flags {
205 IO_URING_F_COMPLETE_DEFER = 1,
206 IO_URING_F_UNLOCKED = 2,
207 /* int's last bit, sign checks are usually faster than a bit test */
208 IO_URING_F_NONBLOCK = INT_MIN,
211 struct io_mapped_ubuf {
214 unsigned int nr_bvecs;
215 unsigned long acct_pages;
216 struct bio_vec bvec[];
221 struct io_overflow_cqe {
222 struct io_uring_cqe cqe;
223 struct list_head list;
226 struct io_fixed_file {
227 /* file * with additional FFS_* flags */
228 unsigned long file_ptr;
232 struct list_head list;
237 struct io_mapped_ubuf *buf;
241 struct io_file_table {
242 struct io_fixed_file *files;
245 struct io_rsrc_node {
246 struct percpu_ref refs;
247 struct list_head node;
248 struct list_head rsrc_list;
249 struct io_rsrc_data *rsrc_data;
250 struct llist_node llist;
254 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
256 struct io_rsrc_data {
257 struct io_ring_ctx *ctx;
263 struct completion done;
267 struct io_buffer_list {
268 struct list_head list;
269 struct list_head buf_list;
274 struct list_head list;
281 struct io_restriction {
282 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
283 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
284 u8 sqe_flags_allowed;
285 u8 sqe_flags_required;
290 IO_SQ_THREAD_SHOULD_STOP = 0,
291 IO_SQ_THREAD_SHOULD_PARK,
296 atomic_t park_pending;
299 /* ctx's that are using this sqd */
300 struct list_head ctx_list;
302 struct task_struct *thread;
303 struct wait_queue_head wait;
305 unsigned sq_thread_idle;
311 struct completion exited;
314 #define IO_COMPL_BATCH 32
315 #define IO_REQ_CACHE_SIZE 32
316 #define IO_REQ_ALLOC_BATCH 8
318 struct io_submit_link {
319 struct io_kiocb *head;
320 struct io_kiocb *last;
323 struct io_submit_state {
324 /* inline/task_work completion list, under ->uring_lock */
325 struct io_wq_work_node free_list;
326 /* batch completion logic */
327 struct io_wq_work_list compl_reqs;
328 struct io_submit_link link;
333 unsigned short submit_nr;
334 struct blk_plug plug;
338 struct eventfd_ctx *cq_ev_fd;
339 unsigned int eventfd_async: 1;
343 #define IO_BUFFERS_HASH_BITS 5
346 /* const or read-mostly hot data */
348 struct percpu_ref refs;
350 struct io_rings *rings;
352 unsigned int compat: 1;
353 unsigned int drain_next: 1;
354 unsigned int restricted: 1;
355 unsigned int off_timeout_used: 1;
356 unsigned int drain_active: 1;
357 unsigned int drain_disabled: 1;
358 unsigned int has_evfd: 1;
359 } ____cacheline_aligned_in_smp;
361 /* submission data */
363 struct mutex uring_lock;
366 * Ring buffer of indices into array of io_uring_sqe, which is
367 * mmapped by the application using the IORING_OFF_SQES offset.
369 * This indirection could e.g. be used to assign fixed
370 * io_uring_sqe entries to operations and only submit them to
371 * the queue when needed.
373 * The kernel modifies neither the indices array nor the entries
377 struct io_uring_sqe *sq_sqes;
378 unsigned cached_sq_head;
380 struct list_head defer_list;
383 * Fixed resources fast path, should be accessed only under
384 * uring_lock, and updated through io_uring_register(2)
386 struct io_rsrc_node *rsrc_node;
387 int rsrc_cached_refs;
388 struct io_file_table file_table;
389 unsigned nr_user_files;
390 unsigned nr_user_bufs;
391 struct io_mapped_ubuf **user_bufs;
393 struct io_submit_state submit_state;
394 struct list_head timeout_list;
395 struct list_head ltimeout_list;
396 struct list_head cq_overflow_list;
397 struct list_head *io_buffers;
398 struct list_head io_buffers_cache;
399 struct list_head apoll_cache;
400 struct xarray personalities;
402 unsigned sq_thread_idle;
403 } ____cacheline_aligned_in_smp;
405 /* IRQ completion list, under ->completion_lock */
406 struct io_wq_work_list locked_free_list;
407 unsigned int locked_free_nr;
409 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
410 struct io_sq_data *sq_data; /* if using sq thread polling */
412 struct wait_queue_head sqo_sq_wait;
413 struct list_head sqd_list;
415 unsigned long check_cq_overflow;
416 #ifdef CONFIG_NET_RX_BUSY_POLL
417 /* used to track busy poll napi_id */
418 struct list_head napi_list;
419 spinlock_t napi_lock; /* napi_list lock */
423 unsigned cached_cq_tail;
425 struct io_ev_fd __rcu *io_ev_fd;
426 struct wait_queue_head cq_wait;
428 atomic_t cq_timeouts;
429 unsigned cq_last_tm_flush;
430 } ____cacheline_aligned_in_smp;
433 spinlock_t completion_lock;
435 spinlock_t timeout_lock;
438 * ->iopoll_list is protected by the ctx->uring_lock for
439 * io_uring instances that don't use IORING_SETUP_SQPOLL.
440 * For SQPOLL, only the single threaded io_sq_thread() will
441 * manipulate the list, hence no extra locking is needed there.
443 struct io_wq_work_list iopoll_list;
444 struct hlist_head *cancel_hash;
445 unsigned cancel_hash_bits;
446 bool poll_multi_queue;
448 struct list_head io_buffers_comp;
449 } ____cacheline_aligned_in_smp;
451 struct io_restriction restrictions;
453 /* slow path rsrc auxilary data, used by update/register */
455 struct io_rsrc_node *rsrc_backup_node;
456 struct io_mapped_ubuf *dummy_ubuf;
457 struct io_rsrc_data *file_data;
458 struct io_rsrc_data *buf_data;
460 struct delayed_work rsrc_put_work;
461 struct llist_head rsrc_put_llist;
462 struct list_head rsrc_ref_list;
463 spinlock_t rsrc_ref_lock;
465 struct list_head io_buffers_pages;
468 /* Keep this last, we don't need it for the fast path */
470 #if defined(CONFIG_UNIX)
471 struct socket *ring_sock;
473 /* hashed buffered write serialization */
474 struct io_wq_hash *hash_map;
476 /* Only used for accounting purposes */
477 struct user_struct *user;
478 struct mm_struct *mm_account;
480 /* ctx exit and cancelation */
481 struct llist_head fallback_llist;
482 struct delayed_work fallback_work;
483 struct work_struct exit_work;
484 struct list_head tctx_list;
485 struct completion ref_comp;
487 bool iowq_limits_set;
492 * Arbitrary limit, can be raised if need be
494 #define IO_RINGFD_REG_MAX 16
496 struct io_uring_task {
497 /* submission side */
500 struct wait_queue_head wait;
501 const struct io_ring_ctx *last;
503 struct percpu_counter inflight;
504 atomic_t inflight_tracked;
507 spinlock_t task_lock;
508 struct io_wq_work_list task_list;
509 struct io_wq_work_list prior_task_list;
510 struct callback_head task_work;
511 struct file **registered_rings;
516 * First field must be the file pointer in all the
517 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
519 struct io_poll_iocb {
521 struct wait_queue_head *head;
523 struct wait_queue_entry wait;
526 struct io_poll_update {
532 bool update_user_data;
541 struct io_timeout_data {
542 struct io_kiocb *req;
543 struct hrtimer timer;
544 struct timespec64 ts;
545 enum hrtimer_mode mode;
551 struct sockaddr __user *addr;
552 int __user *addr_len;
555 unsigned long nofile;
575 struct list_head list;
576 /* head of the link, used by linked timeouts only */
577 struct io_kiocb *head;
578 /* for linked completions */
579 struct io_kiocb *prev;
582 struct io_timeout_rem {
587 struct timespec64 ts;
593 /* NOTE: kiocb has the file as the first member, so don't do it here */
601 struct sockaddr __user *addr;
608 struct compat_msghdr __user *umsg_compat;
609 struct user_msghdr __user *umsg;
622 struct filename *filename;
624 unsigned long nofile;
627 struct io_rsrc_update {
653 struct epoll_event event;
657 struct file *file_out;
658 struct file *file_in;
665 struct io_provide_buf {
679 const char __user *filename;
680 struct statx __user *buffer;
692 struct filename *oldpath;
693 struct filename *newpath;
701 struct filename *filename;
708 struct filename *filename;
714 struct filename *oldpath;
715 struct filename *newpath;
722 struct filename *oldpath;
723 struct filename *newpath;
733 struct io_async_connect {
734 struct sockaddr_storage address;
737 struct io_async_msghdr {
738 struct iovec fast_iov[UIO_FASTIOV];
739 /* points to an allocated iov, if NULL we use fast_iov instead */
740 struct iovec *free_iov;
741 struct sockaddr __user *uaddr;
743 struct sockaddr_storage addr;
747 struct iov_iter iter;
748 struct iov_iter_state iter_state;
749 struct iovec fast_iov[UIO_FASTIOV];
753 struct io_rw_state s;
754 const struct iovec *free_iovec;
756 struct wait_page_queue wpq;
760 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
761 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
762 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
763 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
764 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
765 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
766 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
768 /* first byte is taken by user flags, shift it to not overlap */
773 REQ_F_LINK_TIMEOUT_BIT,
774 REQ_F_NEED_CLEANUP_BIT,
776 REQ_F_BUFFER_SELECTED_BIT,
777 REQ_F_COMPLETE_INLINE_BIT,
781 REQ_F_ARM_LTIMEOUT_BIT,
782 REQ_F_ASYNC_DATA_BIT,
783 REQ_F_SKIP_LINK_CQES_BIT,
784 REQ_F_SINGLE_POLL_BIT,
785 REQ_F_DOUBLE_POLL_BIT,
786 REQ_F_PARTIAL_IO_BIT,
787 /* keep async read/write and isreg together and in order */
788 REQ_F_SUPPORT_NOWAIT_BIT,
791 /* not a real bit, just to check we're not overflowing the space */
797 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
798 /* drain existing IO first */
799 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
801 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
802 /* doesn't sever on completion < 0 */
803 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
805 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
806 /* IOSQE_BUFFER_SELECT */
807 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
808 /* IOSQE_CQE_SKIP_SUCCESS */
809 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
811 /* fail rest of links */
812 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
813 /* on inflight list, should be cancelled and waited on exit reliably */
814 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
815 /* read/write uses file position */
816 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
817 /* must not punt to workers */
818 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
819 /* has or had linked timeout */
820 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
822 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
823 /* already went through poll handler */
824 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
825 /* buffer already selected */
826 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
827 /* completion is deferred through io_comp_state */
828 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
829 /* caller should reissue async */
830 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
831 /* supports async reads/writes */
832 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
834 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
835 /* has creds assigned */
836 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
837 /* skip refcounting if not set */
838 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
839 /* there is a linked timeout that has to be armed */
840 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
841 /* ->async_data allocated */
842 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
843 /* don't post CQEs while failing linked requests */
844 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
845 /* single poll may be active */
846 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
847 /* double poll may active */
848 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
849 /* request has already done partial IO */
850 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
854 struct io_poll_iocb poll;
855 struct io_poll_iocb *double_poll;
858 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
860 struct io_task_work {
862 struct io_wq_work_node node;
863 struct llist_node fallback_node;
865 io_req_tw_func_t func;
869 IORING_RSRC_FILE = 0,
870 IORING_RSRC_BUFFER = 1,
874 * NOTE! Each of the iocb union members has the file pointer
875 * as the first entry in their struct definition. So you can
876 * access the file pointer through any of the sub-structs,
877 * or directly as just 'file' in this struct.
883 struct io_poll_iocb poll;
884 struct io_poll_update poll_update;
885 struct io_accept accept;
887 struct io_cancel cancel;
888 struct io_timeout timeout;
889 struct io_timeout_rem timeout_rem;
890 struct io_connect connect;
891 struct io_sr_msg sr_msg;
893 struct io_close close;
894 struct io_rsrc_update rsrc_update;
895 struct io_fadvise fadvise;
896 struct io_madvise madvise;
897 struct io_epoll epoll;
898 struct io_splice splice;
899 struct io_provide_buf pbuf;
900 struct io_statx statx;
901 struct io_shutdown shutdown;
902 struct io_rename rename;
903 struct io_unlink unlink;
904 struct io_mkdir mkdir;
905 struct io_symlink symlink;
906 struct io_hardlink hardlink;
911 /* polled IO has completed */
920 struct io_ring_ctx *ctx;
921 struct task_struct *task;
923 struct percpu_ref *fixed_rsrc_refs;
924 /* store used ubuf, so we can prevent reloading */
925 struct io_mapped_ubuf *imu;
927 /* used by request caches, completion batching and iopoll */
928 struct io_wq_work_node comp_list;
931 struct io_task_work io_task_work;
932 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
933 struct hlist_node hash_node;
934 /* internal polling, see IORING_FEAT_FAST_POLL */
935 struct async_poll *apoll;
936 /* opcode allocated if it needs to store data for async defer */
938 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
939 struct io_buffer *kbuf;
940 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
941 struct io_kiocb *link;
942 /* custom credentials, valid IFF REQ_F_CREDS is set */
943 const struct cred *creds;
944 struct io_wq_work work;
947 struct io_tctx_node {
948 struct list_head ctx_node;
949 struct task_struct *task;
950 struct io_ring_ctx *ctx;
953 struct io_defer_entry {
954 struct list_head list;
955 struct io_kiocb *req;
960 /* needs req->file assigned */
961 unsigned needs_file : 1;
962 /* should block plug */
964 /* hash wq insertion if file is a regular file */
965 unsigned hash_reg_file : 1;
966 /* unbound wq insertion if file is a non-regular file */
967 unsigned unbound_nonreg_file : 1;
968 /* set if opcode supports polled "wait" */
970 unsigned pollout : 1;
971 unsigned poll_exclusive : 1;
972 /* op supports buffer selection */
973 unsigned buffer_select : 1;
974 /* do prep async if is going to be punted */
975 unsigned needs_async_setup : 1;
976 /* opcode is not supported by this kernel */
977 unsigned not_supported : 1;
979 unsigned audit_skip : 1;
980 /* size of async data needed, if any */
981 unsigned short async_size;
984 static const struct io_op_def io_op_defs[] = {
985 [IORING_OP_NOP] = {},
986 [IORING_OP_READV] = {
988 .unbound_nonreg_file = 1,
991 .needs_async_setup = 1,
994 .async_size = sizeof(struct io_async_rw),
996 [IORING_OP_WRITEV] = {
999 .unbound_nonreg_file = 1,
1001 .needs_async_setup = 1,
1004 .async_size = sizeof(struct io_async_rw),
1006 [IORING_OP_FSYNC] = {
1010 [IORING_OP_READ_FIXED] = {
1012 .unbound_nonreg_file = 1,
1016 .async_size = sizeof(struct io_async_rw),
1018 [IORING_OP_WRITE_FIXED] = {
1021 .unbound_nonreg_file = 1,
1025 .async_size = sizeof(struct io_async_rw),
1027 [IORING_OP_POLL_ADD] = {
1029 .unbound_nonreg_file = 1,
1032 [IORING_OP_POLL_REMOVE] = {
1035 [IORING_OP_SYNC_FILE_RANGE] = {
1039 [IORING_OP_SENDMSG] = {
1041 .unbound_nonreg_file = 1,
1043 .needs_async_setup = 1,
1044 .async_size = sizeof(struct io_async_msghdr),
1046 [IORING_OP_RECVMSG] = {
1048 .unbound_nonreg_file = 1,
1051 .needs_async_setup = 1,
1052 .async_size = sizeof(struct io_async_msghdr),
1054 [IORING_OP_TIMEOUT] = {
1056 .async_size = sizeof(struct io_timeout_data),
1058 [IORING_OP_TIMEOUT_REMOVE] = {
1059 /* used by timeout updates' prep() */
1062 [IORING_OP_ACCEPT] = {
1064 .unbound_nonreg_file = 1,
1066 .poll_exclusive = 1,
1068 [IORING_OP_ASYNC_CANCEL] = {
1071 [IORING_OP_LINK_TIMEOUT] = {
1073 .async_size = sizeof(struct io_timeout_data),
1075 [IORING_OP_CONNECT] = {
1077 .unbound_nonreg_file = 1,
1079 .needs_async_setup = 1,
1080 .async_size = sizeof(struct io_async_connect),
1082 [IORING_OP_FALLOCATE] = {
1085 [IORING_OP_OPENAT] = {},
1086 [IORING_OP_CLOSE] = {},
1087 [IORING_OP_FILES_UPDATE] = {
1090 [IORING_OP_STATX] = {
1093 [IORING_OP_READ] = {
1095 .unbound_nonreg_file = 1,
1100 .async_size = sizeof(struct io_async_rw),
1102 [IORING_OP_WRITE] = {
1105 .unbound_nonreg_file = 1,
1109 .async_size = sizeof(struct io_async_rw),
1111 [IORING_OP_FADVISE] = {
1115 [IORING_OP_MADVISE] = {},
1116 [IORING_OP_SEND] = {
1118 .unbound_nonreg_file = 1,
1122 [IORING_OP_RECV] = {
1124 .unbound_nonreg_file = 1,
1129 [IORING_OP_OPENAT2] = {
1131 [IORING_OP_EPOLL_CTL] = {
1132 .unbound_nonreg_file = 1,
1135 [IORING_OP_SPLICE] = {
1138 .unbound_nonreg_file = 1,
1141 [IORING_OP_PROVIDE_BUFFERS] = {
1144 [IORING_OP_REMOVE_BUFFERS] = {
1150 .unbound_nonreg_file = 1,
1153 [IORING_OP_SHUTDOWN] = {
1156 [IORING_OP_RENAMEAT] = {},
1157 [IORING_OP_UNLINKAT] = {},
1158 [IORING_OP_MKDIRAT] = {},
1159 [IORING_OP_SYMLINKAT] = {},
1160 [IORING_OP_LINKAT] = {},
1161 [IORING_OP_MSG_RING] = {
1166 /* requests with any of those set should undergo io_disarm_next() */
1167 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1169 static bool io_disarm_next(struct io_kiocb *req);
1170 static void io_uring_del_tctx_node(unsigned long index);
1171 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1172 struct task_struct *task,
1174 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1176 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1178 static void io_put_req(struct io_kiocb *req);
1179 static void io_put_req_deferred(struct io_kiocb *req);
1180 static void io_dismantle_req(struct io_kiocb *req);
1181 static void io_queue_linked_timeout(struct io_kiocb *req);
1182 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1183 struct io_uring_rsrc_update2 *up,
1185 static void io_clean_op(struct io_kiocb *req);
1186 static struct file *io_file_get(struct io_ring_ctx *ctx,
1187 struct io_kiocb *req, int fd, bool fixed);
1188 static void __io_queue_sqe(struct io_kiocb *req);
1189 static void io_rsrc_put_work(struct work_struct *work);
1191 static void io_req_task_queue(struct io_kiocb *req);
1192 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1193 static int io_req_prep_async(struct io_kiocb *req);
1195 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1196 unsigned int issue_flags, u32 slot_index);
1197 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1199 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1200 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1202 static struct kmem_cache *req_cachep;
1204 static const struct file_operations io_uring_fops;
1206 struct sock *io_uring_get_socket(struct file *file)
1208 #if defined(CONFIG_UNIX)
1209 if (file->f_op == &io_uring_fops) {
1210 struct io_ring_ctx *ctx = file->private_data;
1212 return ctx->ring_sock->sk;
1217 EXPORT_SYMBOL(io_uring_get_socket);
1219 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1222 mutex_lock(&ctx->uring_lock);
1227 #define io_for_each_link(pos, head) \
1228 for (pos = (head); pos; pos = pos->link)
1231 * Shamelessly stolen from the mm implementation of page reference checking,
1232 * see commit f958d7b528b1 for details.
1234 #define req_ref_zero_or_close_to_overflow(req) \
1235 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1237 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1239 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1240 return atomic_inc_not_zero(&req->refs);
1243 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1245 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1248 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1249 return atomic_dec_and_test(&req->refs);
1252 static inline void req_ref_get(struct io_kiocb *req)
1254 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1255 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1256 atomic_inc(&req->refs);
1259 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1261 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1262 __io_submit_flush_completions(ctx);
1265 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1267 if (!(req->flags & REQ_F_REFCOUNT)) {
1268 req->flags |= REQ_F_REFCOUNT;
1269 atomic_set(&req->refs, nr);
1273 static inline void io_req_set_refcount(struct io_kiocb *req)
1275 __io_req_set_refcount(req, 1);
1278 #define IO_RSRC_REF_BATCH 100
1280 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1281 struct io_ring_ctx *ctx)
1282 __must_hold(&ctx->uring_lock)
1284 struct percpu_ref *ref = req->fixed_rsrc_refs;
1287 if (ref == &ctx->rsrc_node->refs)
1288 ctx->rsrc_cached_refs++;
1290 percpu_ref_put(ref);
1294 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1296 if (req->fixed_rsrc_refs)
1297 percpu_ref_put(req->fixed_rsrc_refs);
1300 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1301 __must_hold(&ctx->uring_lock)
1303 if (ctx->rsrc_cached_refs) {
1304 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1305 ctx->rsrc_cached_refs = 0;
1309 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1310 __must_hold(&ctx->uring_lock)
1312 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1313 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1316 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1317 struct io_ring_ctx *ctx)
1319 if (!req->fixed_rsrc_refs) {
1320 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1321 ctx->rsrc_cached_refs--;
1322 if (unlikely(ctx->rsrc_cached_refs < 0))
1323 io_rsrc_refs_refill(ctx);
1327 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1329 struct io_buffer *kbuf = req->kbuf;
1330 unsigned int cflags;
1332 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1333 req->flags &= ~REQ_F_BUFFER_SELECTED;
1334 list_add(&kbuf->list, list);
1339 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1341 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1343 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1346 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1347 unsigned issue_flags)
1349 unsigned int cflags;
1351 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1355 * We can add this buffer back to two lists:
1357 * 1) The io_buffers_cache list. This one is protected by the
1358 * ctx->uring_lock. If we already hold this lock, add back to this
1359 * list as we can grab it from issue as well.
1360 * 2) The io_buffers_comp list. This one is protected by the
1361 * ctx->completion_lock.
1363 * We migrate buffers from the comp_list to the issue cache list
1366 if (issue_flags & IO_URING_F_UNLOCKED) {
1367 struct io_ring_ctx *ctx = req->ctx;
1369 spin_lock(&ctx->completion_lock);
1370 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1371 spin_unlock(&ctx->completion_lock);
1373 lockdep_assert_held(&req->ctx->uring_lock);
1375 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1381 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1384 struct list_head *hash_list;
1385 struct io_buffer_list *bl;
1387 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1388 list_for_each_entry(bl, hash_list, list)
1389 if (bl->bgid == bgid || bgid == -1U)
1395 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1397 struct io_ring_ctx *ctx = req->ctx;
1398 struct io_buffer_list *bl;
1399 struct io_buffer *buf;
1401 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1403 /* don't recycle if we already did IO to this buffer */
1404 if (req->flags & REQ_F_PARTIAL_IO)
1407 if (issue_flags & IO_URING_F_UNLOCKED)
1408 mutex_lock(&ctx->uring_lock);
1410 lockdep_assert_held(&ctx->uring_lock);
1413 bl = io_buffer_get_list(ctx, buf->bgid);
1414 list_add(&buf->list, &bl->buf_list);
1415 req->flags &= ~REQ_F_BUFFER_SELECTED;
1418 if (issue_flags & IO_URING_F_UNLOCKED)
1419 mutex_unlock(&ctx->uring_lock);
1422 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1424 __must_hold(&req->ctx->timeout_lock)
1426 struct io_kiocb *req;
1428 if (task && head->task != task)
1433 io_for_each_link(req, head) {
1434 if (req->flags & REQ_F_INFLIGHT)
1440 static bool io_match_linked(struct io_kiocb *head)
1442 struct io_kiocb *req;
1444 io_for_each_link(req, head) {
1445 if (req->flags & REQ_F_INFLIGHT)
1452 * As io_match_task() but protected against racing with linked timeouts.
1453 * User must not hold timeout_lock.
1455 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1460 if (task && head->task != task)
1465 if (head->flags & REQ_F_LINK_TIMEOUT) {
1466 struct io_ring_ctx *ctx = head->ctx;
1468 /* protect against races with linked timeouts */
1469 spin_lock_irq(&ctx->timeout_lock);
1470 matched = io_match_linked(head);
1471 spin_unlock_irq(&ctx->timeout_lock);
1473 matched = io_match_linked(head);
1478 static inline bool req_has_async_data(struct io_kiocb *req)
1480 return req->flags & REQ_F_ASYNC_DATA;
1483 static inline void req_set_fail(struct io_kiocb *req)
1485 req->flags |= REQ_F_FAIL;
1486 if (req->flags & REQ_F_CQE_SKIP) {
1487 req->flags &= ~REQ_F_CQE_SKIP;
1488 req->flags |= REQ_F_SKIP_LINK_CQES;
1492 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1498 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1500 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1502 complete(&ctx->ref_comp);
1505 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1507 return !req->timeout.off;
1510 static __cold void io_fallback_req_func(struct work_struct *work)
1512 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1513 fallback_work.work);
1514 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1515 struct io_kiocb *req, *tmp;
1516 bool locked = false;
1518 percpu_ref_get(&ctx->refs);
1519 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1520 req->io_task_work.func(req, &locked);
1523 io_submit_flush_completions(ctx);
1524 mutex_unlock(&ctx->uring_lock);
1526 percpu_ref_put(&ctx->refs);
1529 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1531 struct io_ring_ctx *ctx;
1534 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1539 * Use 5 bits less than the max cq entries, that should give us around
1540 * 32 entries per hash list if totally full and uniformly spread.
1542 hash_bits = ilog2(p->cq_entries);
1546 ctx->cancel_hash_bits = hash_bits;
1547 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1549 if (!ctx->cancel_hash)
1551 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1553 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1554 if (!ctx->dummy_ubuf)
1556 /* set invalid range, so io_import_fixed() fails meeting it */
1557 ctx->dummy_ubuf->ubuf = -1UL;
1559 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1560 sizeof(struct list_head), GFP_KERNEL);
1561 if (!ctx->io_buffers)
1563 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1564 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1566 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1567 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1570 ctx->flags = p->flags;
1571 init_waitqueue_head(&ctx->sqo_sq_wait);
1572 INIT_LIST_HEAD(&ctx->sqd_list);
1573 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1574 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1575 INIT_LIST_HEAD(&ctx->apoll_cache);
1576 init_completion(&ctx->ref_comp);
1577 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1578 mutex_init(&ctx->uring_lock);
1579 init_waitqueue_head(&ctx->cq_wait);
1580 spin_lock_init(&ctx->completion_lock);
1581 spin_lock_init(&ctx->timeout_lock);
1582 INIT_WQ_LIST(&ctx->iopoll_list);
1583 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1584 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1585 INIT_LIST_HEAD(&ctx->defer_list);
1586 INIT_LIST_HEAD(&ctx->timeout_list);
1587 INIT_LIST_HEAD(&ctx->ltimeout_list);
1588 spin_lock_init(&ctx->rsrc_ref_lock);
1589 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1590 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1591 init_llist_head(&ctx->rsrc_put_llist);
1592 INIT_LIST_HEAD(&ctx->tctx_list);
1593 ctx->submit_state.free_list.next = NULL;
1594 INIT_WQ_LIST(&ctx->locked_free_list);
1595 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1596 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1597 #ifdef CONFIG_NET_RX_BUSY_POLL
1598 INIT_LIST_HEAD(&ctx->napi_list);
1599 spin_lock_init(&ctx->napi_lock);
1603 kfree(ctx->dummy_ubuf);
1604 kfree(ctx->cancel_hash);
1605 kfree(ctx->io_buffers);
1610 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1612 struct io_rings *r = ctx->rings;
1614 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1618 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1620 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1621 struct io_ring_ctx *ctx = req->ctx;
1623 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1629 #define FFS_NOWAIT 0x1UL
1630 #define FFS_ISREG 0x2UL
1631 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1633 static inline bool io_req_ffs_set(struct io_kiocb *req)
1635 return req->flags & REQ_F_FIXED_FILE;
1638 static inline void io_req_track_inflight(struct io_kiocb *req)
1640 if (!(req->flags & REQ_F_INFLIGHT)) {
1641 req->flags |= REQ_F_INFLIGHT;
1642 atomic_inc(¤t->io_uring->inflight_tracked);
1646 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1648 if (WARN_ON_ONCE(!req->link))
1651 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1652 req->flags |= REQ_F_LINK_TIMEOUT;
1654 /* linked timeouts should have two refs once prep'ed */
1655 io_req_set_refcount(req);
1656 __io_req_set_refcount(req->link, 2);
1660 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1662 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1664 return __io_prep_linked_timeout(req);
1667 static void io_prep_async_work(struct io_kiocb *req)
1669 const struct io_op_def *def = &io_op_defs[req->opcode];
1670 struct io_ring_ctx *ctx = req->ctx;
1672 if (!(req->flags & REQ_F_CREDS)) {
1673 req->flags |= REQ_F_CREDS;
1674 req->creds = get_current_cred();
1677 req->work.list.next = NULL;
1678 req->work.flags = 0;
1679 if (req->flags & REQ_F_FORCE_ASYNC)
1680 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1682 if (req->flags & REQ_F_ISREG) {
1683 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1684 io_wq_hash_work(&req->work, file_inode(req->file));
1685 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1686 if (def->unbound_nonreg_file)
1687 req->work.flags |= IO_WQ_WORK_UNBOUND;
1690 switch (req->opcode) {
1691 case IORING_OP_SPLICE:
1693 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1694 req->work.flags |= IO_WQ_WORK_UNBOUND;
1699 static void io_prep_async_link(struct io_kiocb *req)
1701 struct io_kiocb *cur;
1703 if (req->flags & REQ_F_LINK_TIMEOUT) {
1704 struct io_ring_ctx *ctx = req->ctx;
1706 spin_lock_irq(&ctx->timeout_lock);
1707 io_for_each_link(cur, req)
1708 io_prep_async_work(cur);
1709 spin_unlock_irq(&ctx->timeout_lock);
1711 io_for_each_link(cur, req)
1712 io_prep_async_work(cur);
1716 static inline void io_req_add_compl_list(struct io_kiocb *req)
1718 struct io_ring_ctx *ctx = req->ctx;
1719 struct io_submit_state *state = &ctx->submit_state;
1721 if (!(req->flags & REQ_F_CQE_SKIP))
1722 ctx->submit_state.flush_cqes = true;
1723 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1726 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1728 struct io_ring_ctx *ctx = req->ctx;
1729 struct io_kiocb *link = io_prep_linked_timeout(req);
1730 struct io_uring_task *tctx = req->task->io_uring;
1733 BUG_ON(!tctx->io_wq);
1735 /* init ->work of the whole link before punting */
1736 io_prep_async_link(req);
1739 * Not expected to happen, but if we do have a bug where this _can_
1740 * happen, catch it here and ensure the request is marked as
1741 * canceled. That will make io-wq go through the usual work cancel
1742 * procedure rather than attempt to run this request (or create a new
1745 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1746 req->work.flags |= IO_WQ_WORK_CANCEL;
1748 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1749 &req->work, io_wq_is_hashed(&req->work));
1750 io_wq_enqueue(tctx->io_wq, &req->work);
1752 io_queue_linked_timeout(link);
1755 static void io_kill_timeout(struct io_kiocb *req, int status)
1756 __must_hold(&req->ctx->completion_lock)
1757 __must_hold(&req->ctx->timeout_lock)
1759 struct io_timeout_data *io = req->async_data;
1761 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1764 atomic_set(&req->ctx->cq_timeouts,
1765 atomic_read(&req->ctx->cq_timeouts) + 1);
1766 list_del_init(&req->timeout.list);
1767 io_fill_cqe_req(req, status, 0);
1768 io_put_req_deferred(req);
1772 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1774 while (!list_empty(&ctx->defer_list)) {
1775 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1776 struct io_defer_entry, list);
1778 if (req_need_defer(de->req, de->seq))
1780 list_del_init(&de->list);
1781 io_req_task_queue(de->req);
1786 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1787 __must_hold(&ctx->completion_lock)
1789 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1791 spin_lock_irq(&ctx->timeout_lock);
1792 while (!list_empty(&ctx->timeout_list)) {
1793 u32 events_needed, events_got;
1794 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1795 struct io_kiocb, timeout.list);
1797 if (io_is_timeout_noseq(req))
1801 * Since seq can easily wrap around over time, subtract
1802 * the last seq at which timeouts were flushed before comparing.
1803 * Assuming not more than 2^31-1 events have happened since,
1804 * these subtractions won't have wrapped, so we can check if
1805 * target is in [last_seq, current_seq] by comparing the two.
1807 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1808 events_got = seq - ctx->cq_last_tm_flush;
1809 if (events_got < events_needed)
1812 list_del_init(&req->timeout.list);
1813 io_kill_timeout(req, 0);
1815 ctx->cq_last_tm_flush = seq;
1816 spin_unlock_irq(&ctx->timeout_lock);
1819 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1821 /* order cqe stores with ring update */
1822 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1825 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1827 if (ctx->off_timeout_used || ctx->drain_active) {
1828 spin_lock(&ctx->completion_lock);
1829 if (ctx->off_timeout_used)
1830 io_flush_timeouts(ctx);
1831 if (ctx->drain_active)
1832 io_queue_deferred(ctx);
1833 io_commit_cqring(ctx);
1834 spin_unlock(&ctx->completion_lock);
1837 io_eventfd_signal(ctx);
1840 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1842 struct io_rings *r = ctx->rings;
1844 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1847 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1849 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1852 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1854 struct io_rings *rings = ctx->rings;
1855 unsigned tail, mask = ctx->cq_entries - 1;
1858 * writes to the cq entry need to come after reading head; the
1859 * control dependency is enough as we're using WRITE_ONCE to
1862 if (__io_cqring_events(ctx) == ctx->cq_entries)
1865 tail = ctx->cached_cq_tail++;
1866 return &rings->cqes[tail & mask];
1869 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1871 struct io_ev_fd *ev_fd;
1875 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1876 * and eventfd_signal
1878 ev_fd = rcu_dereference(ctx->io_ev_fd);
1881 * Check again if ev_fd exists incase an io_eventfd_unregister call
1882 * completed between the NULL check of ctx->io_ev_fd at the start of
1883 * the function and rcu_read_lock.
1885 if (unlikely(!ev_fd))
1887 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1890 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1891 eventfd_signal(ev_fd->cq_ev_fd, 1);
1896 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1899 * wake_up_all() may seem excessive, but io_wake_function() and
1900 * io_should_wake() handle the termination of the loop and only
1901 * wake as many waiters as we need to.
1903 if (wq_has_sleeper(&ctx->cq_wait))
1904 wake_up_all(&ctx->cq_wait);
1908 * This should only get called when at least one event has been posted.
1909 * Some applications rely on the eventfd notification count only changing
1910 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1911 * 1:1 relationship between how many times this function is called (and
1912 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1914 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1916 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1918 __io_commit_cqring_flush(ctx);
1920 io_cqring_wake(ctx);
1923 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1925 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1927 __io_commit_cqring_flush(ctx);
1929 if (ctx->flags & IORING_SETUP_SQPOLL)
1930 io_cqring_wake(ctx);
1933 /* Returns true if there are no backlogged entries after the flush */
1934 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1936 bool all_flushed, posted;
1938 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1942 spin_lock(&ctx->completion_lock);
1943 while (!list_empty(&ctx->cq_overflow_list)) {
1944 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1945 struct io_overflow_cqe *ocqe;
1949 ocqe = list_first_entry(&ctx->cq_overflow_list,
1950 struct io_overflow_cqe, list);
1952 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1954 io_account_cq_overflow(ctx);
1957 list_del(&ocqe->list);
1961 all_flushed = list_empty(&ctx->cq_overflow_list);
1963 clear_bit(0, &ctx->check_cq_overflow);
1964 WRITE_ONCE(ctx->rings->sq_flags,
1965 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1969 io_commit_cqring(ctx);
1970 spin_unlock(&ctx->completion_lock);
1972 io_cqring_ev_posted(ctx);
1976 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1980 if (test_bit(0, &ctx->check_cq_overflow)) {
1981 /* iopoll syncs against uring_lock, not completion_lock */
1982 if (ctx->flags & IORING_SETUP_IOPOLL)
1983 mutex_lock(&ctx->uring_lock);
1984 ret = __io_cqring_overflow_flush(ctx, false);
1985 if (ctx->flags & IORING_SETUP_IOPOLL)
1986 mutex_unlock(&ctx->uring_lock);
1992 /* must to be called somewhat shortly after putting a request */
1993 static inline void io_put_task(struct task_struct *task, int nr)
1995 struct io_uring_task *tctx = task->io_uring;
1997 if (likely(task == current)) {
1998 tctx->cached_refs += nr;
2000 percpu_counter_sub(&tctx->inflight, nr);
2001 if (unlikely(atomic_read(&tctx->in_idle)))
2002 wake_up(&tctx->wait);
2003 put_task_struct_many(task, nr);
2007 static void io_task_refs_refill(struct io_uring_task *tctx)
2009 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2011 percpu_counter_add(&tctx->inflight, refill);
2012 refcount_add(refill, ¤t->usage);
2013 tctx->cached_refs += refill;
2016 static inline void io_get_task_refs(int nr)
2018 struct io_uring_task *tctx = current->io_uring;
2020 tctx->cached_refs -= nr;
2021 if (unlikely(tctx->cached_refs < 0))
2022 io_task_refs_refill(tctx);
2025 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2027 struct io_uring_task *tctx = task->io_uring;
2028 unsigned int refs = tctx->cached_refs;
2031 tctx->cached_refs = 0;
2032 percpu_counter_sub(&tctx->inflight, refs);
2033 put_task_struct_many(task, refs);
2037 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2038 s32 res, u32 cflags)
2040 struct io_overflow_cqe *ocqe;
2042 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2045 * If we're in ring overflow flush mode, or in task cancel mode,
2046 * or cannot allocate an overflow entry, then we need to drop it
2049 io_account_cq_overflow(ctx);
2052 if (list_empty(&ctx->cq_overflow_list)) {
2053 set_bit(0, &ctx->check_cq_overflow);
2054 WRITE_ONCE(ctx->rings->sq_flags,
2055 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2058 ocqe->cqe.user_data = user_data;
2059 ocqe->cqe.res = res;
2060 ocqe->cqe.flags = cflags;
2061 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2065 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2066 s32 res, u32 cflags)
2068 struct io_uring_cqe *cqe;
2071 * If we can't get a cq entry, userspace overflowed the
2072 * submission (by quite a lot). Increment the overflow count in
2075 cqe = io_get_cqe(ctx);
2077 WRITE_ONCE(cqe->user_data, user_data);
2078 WRITE_ONCE(cqe->res, res);
2079 WRITE_ONCE(cqe->flags, cflags);
2082 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2085 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2087 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2088 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2091 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2093 if (!(req->flags & REQ_F_CQE_SKIP))
2094 __io_fill_cqe_req(req, res, cflags);
2097 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2098 s32 res, u32 cflags)
2101 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2102 return __io_fill_cqe(ctx, user_data, res, cflags);
2105 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2108 struct io_ring_ctx *ctx = req->ctx;
2110 if (!(req->flags & REQ_F_CQE_SKIP))
2111 __io_fill_cqe_req(req, res, cflags);
2113 * If we're the last reference to this request, add to our locked
2116 if (req_ref_put_and_test(req)) {
2117 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2118 if (req->flags & IO_DISARM_MASK)
2119 io_disarm_next(req);
2121 io_req_task_queue(req->link);
2125 io_req_put_rsrc(req, ctx);
2126 io_dismantle_req(req);
2127 io_put_task(req->task, 1);
2128 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2129 ctx->locked_free_nr++;
2133 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2136 struct io_ring_ctx *ctx = req->ctx;
2138 spin_lock(&ctx->completion_lock);
2139 __io_req_complete_post(req, res, cflags);
2140 io_commit_cqring(ctx);
2141 spin_unlock(&ctx->completion_lock);
2142 io_cqring_ev_posted(ctx);
2145 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2149 req->cflags = cflags;
2150 req->flags |= REQ_F_COMPLETE_INLINE;
2153 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2154 s32 res, u32 cflags)
2156 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2157 io_req_complete_state(req, res, cflags);
2159 io_req_complete_post(req, res, cflags);
2162 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2164 __io_req_complete(req, 0, res, 0);
2167 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2170 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2173 static void io_req_complete_fail_submit(struct io_kiocb *req)
2176 * We don't submit, fail them all, for that replace hardlinks with
2177 * normal links. Extra REQ_F_LINK is tolerated.
2179 req->flags &= ~REQ_F_HARDLINK;
2180 req->flags |= REQ_F_LINK;
2181 io_req_complete_failed(req, req->result);
2185 * Don't initialise the fields below on every allocation, but do that in
2186 * advance and keep them valid across allocations.
2188 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2192 req->async_data = NULL;
2193 /* not necessary, but safer to zero */
2197 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2198 struct io_submit_state *state)
2200 spin_lock(&ctx->completion_lock);
2201 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2202 ctx->locked_free_nr = 0;
2203 spin_unlock(&ctx->completion_lock);
2206 /* Returns true IFF there are requests in the cache */
2207 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2209 struct io_submit_state *state = &ctx->submit_state;
2212 * If we have more than a batch's worth of requests in our IRQ side
2213 * locked cache, grab the lock and move them over to our submission
2216 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2217 io_flush_cached_locked_reqs(ctx, state);
2218 return !!state->free_list.next;
2222 * A request might get retired back into the request caches even before opcode
2223 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2224 * Because of that, io_alloc_req() should be called only under ->uring_lock
2225 * and with extra caution to not get a request that is still worked on.
2227 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2228 __must_hold(&ctx->uring_lock)
2230 struct io_submit_state *state = &ctx->submit_state;
2231 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2232 void *reqs[IO_REQ_ALLOC_BATCH];
2233 struct io_kiocb *req;
2236 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2239 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2242 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2243 * retry single alloc to be on the safe side.
2245 if (unlikely(ret <= 0)) {
2246 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2252 percpu_ref_get_many(&ctx->refs, ret);
2253 for (i = 0; i < ret; i++) {
2256 io_preinit_req(req, ctx);
2257 wq_stack_add_head(&req->comp_list, &state->free_list);
2262 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2264 if (unlikely(!ctx->submit_state.free_list.next))
2265 return __io_alloc_req_refill(ctx);
2269 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2271 struct io_wq_work_node *node;
2273 node = wq_stack_extract(&ctx->submit_state.free_list);
2274 return container_of(node, struct io_kiocb, comp_list);
2277 static inline void io_put_file(struct file *file)
2283 static inline void io_dismantle_req(struct io_kiocb *req)
2285 unsigned int flags = req->flags;
2287 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2289 if (!(flags & REQ_F_FIXED_FILE))
2290 io_put_file(req->file);
2293 static __cold void __io_free_req(struct io_kiocb *req)
2295 struct io_ring_ctx *ctx = req->ctx;
2297 io_req_put_rsrc(req, ctx);
2298 io_dismantle_req(req);
2299 io_put_task(req->task, 1);
2301 spin_lock(&ctx->completion_lock);
2302 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2303 ctx->locked_free_nr++;
2304 spin_unlock(&ctx->completion_lock);
2307 static inline void io_remove_next_linked(struct io_kiocb *req)
2309 struct io_kiocb *nxt = req->link;
2311 req->link = nxt->link;
2315 static bool io_kill_linked_timeout(struct io_kiocb *req)
2316 __must_hold(&req->ctx->completion_lock)
2317 __must_hold(&req->ctx->timeout_lock)
2319 struct io_kiocb *link = req->link;
2321 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2322 struct io_timeout_data *io = link->async_data;
2324 io_remove_next_linked(req);
2325 link->timeout.head = NULL;
2326 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2327 list_del(&link->timeout.list);
2328 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2329 io_fill_cqe_req(link, -ECANCELED, 0);
2330 io_put_req_deferred(link);
2337 static void io_fail_links(struct io_kiocb *req)
2338 __must_hold(&req->ctx->completion_lock)
2340 struct io_kiocb *nxt, *link = req->link;
2341 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2345 long res = -ECANCELED;
2347 if (link->flags & REQ_F_FAIL)
2353 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2357 link->flags &= ~REQ_F_CQE_SKIP;
2358 io_fill_cqe_req(link, res, 0);
2360 io_put_req_deferred(link);
2365 static bool io_disarm_next(struct io_kiocb *req)
2366 __must_hold(&req->ctx->completion_lock)
2368 bool posted = false;
2370 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2371 struct io_kiocb *link = req->link;
2373 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2374 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2375 io_remove_next_linked(req);
2376 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2377 io_fill_cqe_req(link, -ECANCELED, 0);
2378 io_put_req_deferred(link);
2381 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2382 struct io_ring_ctx *ctx = req->ctx;
2384 spin_lock_irq(&ctx->timeout_lock);
2385 posted = io_kill_linked_timeout(req);
2386 spin_unlock_irq(&ctx->timeout_lock);
2388 if (unlikely((req->flags & REQ_F_FAIL) &&
2389 !(req->flags & REQ_F_HARDLINK))) {
2390 posted |= (req->link != NULL);
2396 static void __io_req_find_next_prep(struct io_kiocb *req)
2398 struct io_ring_ctx *ctx = req->ctx;
2401 spin_lock(&ctx->completion_lock);
2402 posted = io_disarm_next(req);
2404 io_commit_cqring(ctx);
2405 spin_unlock(&ctx->completion_lock);
2407 io_cqring_ev_posted(ctx);
2410 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2412 struct io_kiocb *nxt;
2414 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2417 * If LINK is set, we have dependent requests in this chain. If we
2418 * didn't fail this request, queue the first one up, moving any other
2419 * dependencies to the next request. In case of failure, fail the rest
2422 if (unlikely(req->flags & IO_DISARM_MASK))
2423 __io_req_find_next_prep(req);
2429 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2434 io_submit_flush_completions(ctx);
2435 mutex_unlock(&ctx->uring_lock);
2438 percpu_ref_put(&ctx->refs);
2441 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2443 io_commit_cqring(ctx);
2444 spin_unlock(&ctx->completion_lock);
2445 io_cqring_ev_posted(ctx);
2448 static void handle_prev_tw_list(struct io_wq_work_node *node,
2449 struct io_ring_ctx **ctx, bool *uring_locked)
2451 if (*ctx && !*uring_locked)
2452 spin_lock(&(*ctx)->completion_lock);
2455 struct io_wq_work_node *next = node->next;
2456 struct io_kiocb *req = container_of(node, struct io_kiocb,
2459 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2461 if (req->ctx != *ctx) {
2462 if (unlikely(!*uring_locked && *ctx))
2463 ctx_commit_and_unlock(*ctx);
2465 ctx_flush_and_put(*ctx, uring_locked);
2467 /* if not contended, grab and improve batching */
2468 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2469 percpu_ref_get(&(*ctx)->refs);
2470 if (unlikely(!*uring_locked))
2471 spin_lock(&(*ctx)->completion_lock);
2473 if (likely(*uring_locked))
2474 req->io_task_work.func(req, uring_locked);
2476 __io_req_complete_post(req, req->result,
2477 io_put_kbuf_comp(req));
2481 if (unlikely(!*uring_locked))
2482 ctx_commit_and_unlock(*ctx);
2485 static void handle_tw_list(struct io_wq_work_node *node,
2486 struct io_ring_ctx **ctx, bool *locked)
2489 struct io_wq_work_node *next = node->next;
2490 struct io_kiocb *req = container_of(node, struct io_kiocb,
2493 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2495 if (req->ctx != *ctx) {
2496 ctx_flush_and_put(*ctx, locked);
2498 /* if not contended, grab and improve batching */
2499 *locked = mutex_trylock(&(*ctx)->uring_lock);
2500 percpu_ref_get(&(*ctx)->refs);
2502 req->io_task_work.func(req, locked);
2507 static void tctx_task_work(struct callback_head *cb)
2509 bool uring_locked = false;
2510 struct io_ring_ctx *ctx = NULL;
2511 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2515 struct io_wq_work_node *node1, *node2;
2517 if (!tctx->task_list.first &&
2518 !tctx->prior_task_list.first && uring_locked)
2519 io_submit_flush_completions(ctx);
2521 spin_lock_irq(&tctx->task_lock);
2522 node1 = tctx->prior_task_list.first;
2523 node2 = tctx->task_list.first;
2524 INIT_WQ_LIST(&tctx->task_list);
2525 INIT_WQ_LIST(&tctx->prior_task_list);
2526 if (!node2 && !node1)
2527 tctx->task_running = false;
2528 spin_unlock_irq(&tctx->task_lock);
2529 if (!node2 && !node1)
2533 handle_prev_tw_list(node1, &ctx, &uring_locked);
2536 handle_tw_list(node2, &ctx, &uring_locked);
2540 ctx_flush_and_put(ctx, &uring_locked);
2542 /* relaxed read is enough as only the task itself sets ->in_idle */
2543 if (unlikely(atomic_read(&tctx->in_idle)))
2544 io_uring_drop_tctx_refs(current);
2547 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2549 struct task_struct *tsk = req->task;
2550 struct io_uring_task *tctx = tsk->io_uring;
2551 enum task_work_notify_mode notify;
2552 struct io_wq_work_node *node;
2553 unsigned long flags;
2556 WARN_ON_ONCE(!tctx);
2558 spin_lock_irqsave(&tctx->task_lock, flags);
2560 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2562 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2563 running = tctx->task_running;
2565 tctx->task_running = true;
2566 spin_unlock_irqrestore(&tctx->task_lock, flags);
2568 /* task_work already pending, we're done */
2573 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2574 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2575 * processing task_work. There's no reliable way to tell if TWA_RESUME
2578 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2579 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2580 if (notify == TWA_NONE)
2581 wake_up_process(tsk);
2585 spin_lock_irqsave(&tctx->task_lock, flags);
2586 tctx->task_running = false;
2587 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2588 spin_unlock_irqrestore(&tctx->task_lock, flags);
2591 req = container_of(node, struct io_kiocb, io_task_work.node);
2593 if (llist_add(&req->io_task_work.fallback_node,
2594 &req->ctx->fallback_llist))
2595 schedule_delayed_work(&req->ctx->fallback_work, 1);
2599 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2601 struct io_ring_ctx *ctx = req->ctx;
2603 /* not needed for normal modes, but SQPOLL depends on it */
2604 io_tw_lock(ctx, locked);
2605 io_req_complete_failed(req, req->result);
2608 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2610 struct io_ring_ctx *ctx = req->ctx;
2612 io_tw_lock(ctx, locked);
2613 /* req->task == current here, checking PF_EXITING is safe */
2614 if (likely(!(req->task->flags & PF_EXITING)))
2615 __io_queue_sqe(req);
2617 io_req_complete_failed(req, -EFAULT);
2620 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2623 req->io_task_work.func = io_req_task_cancel;
2624 io_req_task_work_add(req, false);
2627 static void io_req_task_queue(struct io_kiocb *req)
2629 req->io_task_work.func = io_req_task_submit;
2630 io_req_task_work_add(req, false);
2633 static void io_req_task_queue_reissue(struct io_kiocb *req)
2635 req->io_task_work.func = io_queue_async_work;
2636 io_req_task_work_add(req, false);
2639 static inline void io_queue_next(struct io_kiocb *req)
2641 struct io_kiocb *nxt = io_req_find_next(req);
2644 io_req_task_queue(nxt);
2647 static void io_free_req(struct io_kiocb *req)
2653 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2658 static void io_free_batch_list(struct io_ring_ctx *ctx,
2659 struct io_wq_work_node *node)
2660 __must_hold(&ctx->uring_lock)
2662 struct task_struct *task = NULL;
2666 struct io_kiocb *req = container_of(node, struct io_kiocb,
2669 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2670 node = req->comp_list.next;
2671 if (!req_ref_put_and_test(req))
2675 io_req_put_rsrc_locked(req, ctx);
2677 io_dismantle_req(req);
2679 if (req->task != task) {
2681 io_put_task(task, task_refs);
2686 node = req->comp_list.next;
2687 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2691 io_put_task(task, task_refs);
2694 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2695 __must_hold(&ctx->uring_lock)
2697 struct io_wq_work_node *node, *prev;
2698 struct io_submit_state *state = &ctx->submit_state;
2700 if (state->flush_cqes) {
2701 spin_lock(&ctx->completion_lock);
2702 wq_list_for_each(node, prev, &state->compl_reqs) {
2703 struct io_kiocb *req = container_of(node, struct io_kiocb,
2706 if (!(req->flags & REQ_F_CQE_SKIP))
2707 __io_fill_cqe_req(req, req->result, req->cflags);
2708 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2709 struct async_poll *apoll = req->apoll;
2711 if (apoll->double_poll)
2712 kfree(apoll->double_poll);
2713 list_add(&apoll->poll.wait.entry,
2715 req->flags &= ~REQ_F_POLLED;
2719 io_commit_cqring(ctx);
2720 spin_unlock(&ctx->completion_lock);
2721 io_cqring_ev_posted(ctx);
2722 state->flush_cqes = false;
2725 io_free_batch_list(ctx, state->compl_reqs.first);
2726 INIT_WQ_LIST(&state->compl_reqs);
2730 * Drop reference to request, return next in chain (if there is one) if this
2731 * was the last reference to this request.
2733 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2735 struct io_kiocb *nxt = NULL;
2737 if (req_ref_put_and_test(req)) {
2738 nxt = io_req_find_next(req);
2744 static inline void io_put_req(struct io_kiocb *req)
2746 if (req_ref_put_and_test(req))
2750 static inline void io_put_req_deferred(struct io_kiocb *req)
2752 if (req_ref_put_and_test(req)) {
2753 req->io_task_work.func = io_free_req_work;
2754 io_req_task_work_add(req, false);
2758 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2760 /* See comment at the top of this file */
2762 return __io_cqring_events(ctx);
2765 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2767 struct io_rings *rings = ctx->rings;
2769 /* make sure SQ entry isn't read before tail */
2770 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2773 static inline bool io_run_task_work(void)
2775 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2776 __set_current_state(TASK_RUNNING);
2777 tracehook_notify_signal();
2784 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2786 struct io_wq_work_node *pos, *start, *prev;
2787 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2788 DEFINE_IO_COMP_BATCH(iob);
2792 * Only spin for completions if we don't have multiple devices hanging
2793 * off our complete list.
2795 if (ctx->poll_multi_queue || force_nonspin)
2796 poll_flags |= BLK_POLL_ONESHOT;
2798 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2799 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2800 struct kiocb *kiocb = &req->rw.kiocb;
2804 * Move completed and retryable entries to our local lists.
2805 * If we find a request that requires polling, break out
2806 * and complete those lists first, if we have entries there.
2808 if (READ_ONCE(req->iopoll_completed))
2811 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2812 if (unlikely(ret < 0))
2815 poll_flags |= BLK_POLL_ONESHOT;
2817 /* iopoll may have completed current req */
2818 if (!rq_list_empty(iob.req_list) ||
2819 READ_ONCE(req->iopoll_completed))
2823 if (!rq_list_empty(iob.req_list))
2829 wq_list_for_each_resume(pos, prev) {
2830 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2832 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2833 if (!smp_load_acquire(&req->iopoll_completed))
2835 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2838 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2842 if (unlikely(!nr_events))
2845 io_commit_cqring(ctx);
2846 io_cqring_ev_posted_iopoll(ctx);
2847 pos = start ? start->next : ctx->iopoll_list.first;
2848 wq_list_cut(&ctx->iopoll_list, prev, start);
2849 io_free_batch_list(ctx, pos);
2854 * We can't just wait for polled events to come to us, we have to actively
2855 * find and complete them.
2857 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2859 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2862 mutex_lock(&ctx->uring_lock);
2863 while (!wq_list_empty(&ctx->iopoll_list)) {
2864 /* let it sleep and repeat later if can't complete a request */
2865 if (io_do_iopoll(ctx, true) == 0)
2868 * Ensure we allow local-to-the-cpu processing to take place,
2869 * in this case we need to ensure that we reap all events.
2870 * Also let task_work, etc. to progress by releasing the mutex
2872 if (need_resched()) {
2873 mutex_unlock(&ctx->uring_lock);
2875 mutex_lock(&ctx->uring_lock);
2878 mutex_unlock(&ctx->uring_lock);
2881 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2883 unsigned int nr_events = 0;
2887 * We disallow the app entering submit/complete with polling, but we
2888 * still need to lock the ring to prevent racing with polled issue
2889 * that got punted to a workqueue.
2891 mutex_lock(&ctx->uring_lock);
2893 * Don't enter poll loop if we already have events pending.
2894 * If we do, we can potentially be spinning for commands that
2895 * already triggered a CQE (eg in error).
2897 if (test_bit(0, &ctx->check_cq_overflow))
2898 __io_cqring_overflow_flush(ctx, false);
2899 if (io_cqring_events(ctx))
2903 * If a submit got punted to a workqueue, we can have the
2904 * application entering polling for a command before it gets
2905 * issued. That app will hold the uring_lock for the duration
2906 * of the poll right here, so we need to take a breather every
2907 * now and then to ensure that the issue has a chance to add
2908 * the poll to the issued list. Otherwise we can spin here
2909 * forever, while the workqueue is stuck trying to acquire the
2912 if (wq_list_empty(&ctx->iopoll_list)) {
2913 u32 tail = ctx->cached_cq_tail;
2915 mutex_unlock(&ctx->uring_lock);
2917 mutex_lock(&ctx->uring_lock);
2919 /* some requests don't go through iopoll_list */
2920 if (tail != ctx->cached_cq_tail ||
2921 wq_list_empty(&ctx->iopoll_list))
2924 ret = io_do_iopoll(ctx, !min);
2929 } while (nr_events < min && !need_resched());
2931 mutex_unlock(&ctx->uring_lock);
2935 static void kiocb_end_write(struct io_kiocb *req)
2938 * Tell lockdep we inherited freeze protection from submission
2941 if (req->flags & REQ_F_ISREG) {
2942 struct super_block *sb = file_inode(req->file)->i_sb;
2944 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2950 static bool io_resubmit_prep(struct io_kiocb *req)
2952 struct io_async_rw *rw = req->async_data;
2954 if (!req_has_async_data(req))
2955 return !io_req_prep_async(req);
2956 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2960 static bool io_rw_should_reissue(struct io_kiocb *req)
2962 umode_t mode = file_inode(req->file)->i_mode;
2963 struct io_ring_ctx *ctx = req->ctx;
2965 if (!S_ISBLK(mode) && !S_ISREG(mode))
2967 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2968 !(ctx->flags & IORING_SETUP_IOPOLL)))
2971 * If ref is dying, we might be running poll reap from the exit work.
2972 * Don't attempt to reissue from that path, just let it fail with
2975 if (percpu_ref_is_dying(&ctx->refs))
2978 * Play it safe and assume not safe to re-import and reissue if we're
2979 * not in the original thread group (or in task context).
2981 if (!same_thread_group(req->task, current) || !in_task())
2986 static bool io_resubmit_prep(struct io_kiocb *req)
2990 static bool io_rw_should_reissue(struct io_kiocb *req)
2996 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2998 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
2999 kiocb_end_write(req);
3000 fsnotify_modify(req->file);
3002 fsnotify_access(req->file);
3004 if (unlikely(res != req->result)) {
3005 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3006 io_rw_should_reissue(req)) {
3007 req->flags |= REQ_F_REISSUE;
3016 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3018 int res = req->result;
3021 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3022 io_req_add_compl_list(req);
3024 io_req_complete_post(req, res,
3025 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3029 static void __io_complete_rw(struct io_kiocb *req, long res,
3030 unsigned int issue_flags)
3032 if (__io_complete_rw_common(req, res))
3034 __io_req_complete(req, issue_flags, req->result,
3035 io_put_kbuf(req, issue_flags));
3038 static void io_complete_rw(struct kiocb *kiocb, long res)
3040 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3042 if (__io_complete_rw_common(req, res))
3045 req->io_task_work.func = io_req_task_complete;
3046 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3049 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3051 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3053 if (kiocb->ki_flags & IOCB_WRITE)
3054 kiocb_end_write(req);
3055 if (unlikely(res != req->result)) {
3056 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3057 req->flags |= REQ_F_REISSUE;
3063 /* order with io_iopoll_complete() checking ->iopoll_completed */
3064 smp_store_release(&req->iopoll_completed, 1);
3068 * After the iocb has been issued, it's safe to be found on the poll list.
3069 * Adding the kiocb to the list AFTER submission ensures that we don't
3070 * find it from a io_do_iopoll() thread before the issuer is done
3071 * accessing the kiocb cookie.
3073 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3075 struct io_ring_ctx *ctx = req->ctx;
3076 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3078 /* workqueue context doesn't hold uring_lock, grab it now */
3079 if (unlikely(needs_lock))
3080 mutex_lock(&ctx->uring_lock);
3083 * Track whether we have multiple files in our lists. This will impact
3084 * how we do polling eventually, not spinning if we're on potentially
3085 * different devices.
3087 if (wq_list_empty(&ctx->iopoll_list)) {
3088 ctx->poll_multi_queue = false;
3089 } else if (!ctx->poll_multi_queue) {
3090 struct io_kiocb *list_req;
3092 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3094 if (list_req->file != req->file)
3095 ctx->poll_multi_queue = true;
3099 * For fast devices, IO may have already completed. If it has, add
3100 * it to the front so we find it first.
3102 if (READ_ONCE(req->iopoll_completed))
3103 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3105 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3107 if (unlikely(needs_lock)) {
3109 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3110 * in sq thread task context or in io worker task context. If
3111 * current task context is sq thread, we don't need to check
3112 * whether should wake up sq thread.
3114 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3115 wq_has_sleeper(&ctx->sq_data->wait))
3116 wake_up(&ctx->sq_data->wait);
3118 mutex_unlock(&ctx->uring_lock);
3122 static bool io_bdev_nowait(struct block_device *bdev)
3124 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3128 * If we tracked the file through the SCM inflight mechanism, we could support
3129 * any file. For now, just ensure that anything potentially problematic is done
3132 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3134 if (S_ISBLK(mode)) {
3135 if (IS_ENABLED(CONFIG_BLOCK) &&
3136 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3142 if (S_ISREG(mode)) {
3143 if (IS_ENABLED(CONFIG_BLOCK) &&
3144 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3145 file->f_op != &io_uring_fops)
3150 /* any ->read/write should understand O_NONBLOCK */
3151 if (file->f_flags & O_NONBLOCK)
3153 return file->f_mode & FMODE_NOWAIT;
3157 * If we tracked the file through the SCM inflight mechanism, we could support
3158 * any file. For now, just ensure that anything potentially problematic is done
3161 static unsigned int io_file_get_flags(struct file *file)
3163 umode_t mode = file_inode(file)->i_mode;
3164 unsigned int res = 0;
3168 if (__io_file_supports_nowait(file, mode))
3173 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3175 return req->flags & REQ_F_SUPPORT_NOWAIT;
3178 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3180 struct io_ring_ctx *ctx = req->ctx;
3181 struct kiocb *kiocb = &req->rw.kiocb;
3182 struct file *file = req->file;
3186 if (!io_req_ffs_set(req))
3187 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3189 kiocb->ki_pos = READ_ONCE(sqe->off);
3190 kiocb->ki_flags = iocb_flags(file);
3191 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3196 * If the file is marked O_NONBLOCK, still allow retry for it if it
3197 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3198 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3200 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3201 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3202 req->flags |= REQ_F_NOWAIT;
3204 if (ctx->flags & IORING_SETUP_IOPOLL) {
3205 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3208 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3209 kiocb->ki_complete = io_complete_rw_iopoll;
3210 req->iopoll_completed = 0;
3212 if (kiocb->ki_flags & IOCB_HIPRI)
3214 kiocb->ki_complete = io_complete_rw;
3217 ioprio = READ_ONCE(sqe->ioprio);
3219 ret = ioprio_check_cap(ioprio);
3223 kiocb->ki_ioprio = ioprio;
3225 kiocb->ki_ioprio = get_current_ioprio();
3229 req->rw.addr = READ_ONCE(sqe->addr);
3230 req->rw.len = READ_ONCE(sqe->len);
3231 req->buf_index = READ_ONCE(sqe->buf_index);
3235 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3241 case -ERESTARTNOINTR:
3242 case -ERESTARTNOHAND:
3243 case -ERESTART_RESTARTBLOCK:
3245 * We can't just restart the syscall, since previously
3246 * submitted sqes may already be in progress. Just fail this
3252 kiocb->ki_complete(kiocb, ret);
3256 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3258 struct kiocb *kiocb = &req->rw.kiocb;
3259 bool is_stream = req->file->f_mode & FMODE_STREAM;
3261 if (kiocb->ki_pos == -1) {
3263 req->flags |= REQ_F_CUR_POS;
3264 kiocb->ki_pos = req->file->f_pos;
3265 return &kiocb->ki_pos;
3271 return is_stream ? NULL : &kiocb->ki_pos;
3274 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3275 unsigned int issue_flags)
3277 struct io_async_rw *io = req->async_data;
3279 /* add previously done IO, if any */
3280 if (req_has_async_data(req) && io->bytes_done > 0) {
3282 ret = io->bytes_done;
3284 ret += io->bytes_done;
3287 if (req->flags & REQ_F_CUR_POS)
3288 req->file->f_pos = req->rw.kiocb.ki_pos;
3289 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3290 __io_complete_rw(req, ret, issue_flags);
3292 io_rw_done(&req->rw.kiocb, ret);
3294 if (req->flags & REQ_F_REISSUE) {
3295 req->flags &= ~REQ_F_REISSUE;
3296 if (io_resubmit_prep(req))
3297 io_req_task_queue_reissue(req);
3299 io_req_task_queue_fail(req, ret);
3303 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3304 struct io_mapped_ubuf *imu)
3306 size_t len = req->rw.len;
3307 u64 buf_end, buf_addr = req->rw.addr;
3310 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3312 /* not inside the mapped region */
3313 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3317 * May not be a start of buffer, set size appropriately
3318 * and advance us to the beginning.
3320 offset = buf_addr - imu->ubuf;
3321 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3325 * Don't use iov_iter_advance() here, as it's really slow for
3326 * using the latter parts of a big fixed buffer - it iterates
3327 * over each segment manually. We can cheat a bit here, because
3330 * 1) it's a BVEC iter, we set it up
3331 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3332 * first and last bvec
3334 * So just find our index, and adjust the iterator afterwards.
3335 * If the offset is within the first bvec (or the whole first
3336 * bvec, just use iov_iter_advance(). This makes it easier
3337 * since we can just skip the first segment, which may not
3338 * be PAGE_SIZE aligned.
3340 const struct bio_vec *bvec = imu->bvec;
3342 if (offset <= bvec->bv_len) {
3343 iov_iter_advance(iter, offset);
3345 unsigned long seg_skip;
3347 /* skip first vec */
3348 offset -= bvec->bv_len;
3349 seg_skip = 1 + (offset >> PAGE_SHIFT);
3351 iter->bvec = bvec + seg_skip;
3352 iter->nr_segs -= seg_skip;
3353 iter->count -= bvec->bv_len + offset;
3354 iter->iov_offset = offset & ~PAGE_MASK;
3361 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3363 struct io_mapped_ubuf *imu = req->imu;
3364 u16 index, buf_index = req->buf_index;
3367 struct io_ring_ctx *ctx = req->ctx;
3369 if (unlikely(buf_index >= ctx->nr_user_bufs))
3371 io_req_set_rsrc_node(req, ctx);
3372 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3373 imu = READ_ONCE(ctx->user_bufs[index]);
3376 return __io_import_fixed(req, rw, iter, imu);
3379 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3382 mutex_unlock(&ctx->uring_lock);
3385 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3388 * "Normal" inline submissions always hold the uring_lock, since we
3389 * grab it from the system call. Same is true for the SQPOLL offload.
3390 * The only exception is when we've detached the request and issue it
3391 * from an async worker thread, grab the lock for that case.
3394 mutex_lock(&ctx->uring_lock);
3397 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3398 struct io_buffer_list *bl, unsigned int bgid)
3400 struct list_head *list;
3402 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3403 INIT_LIST_HEAD(&bl->buf_list);
3405 list_add(&bl->list, list);
3408 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3409 int bgid, unsigned int issue_flags)
3411 struct io_buffer *kbuf = req->kbuf;
3412 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3413 struct io_ring_ctx *ctx = req->ctx;
3414 struct io_buffer_list *bl;
3416 if (req->flags & REQ_F_BUFFER_SELECTED)
3419 io_ring_submit_lock(ctx, needs_lock);
3421 lockdep_assert_held(&ctx->uring_lock);
3423 bl = io_buffer_get_list(ctx, bgid);
3424 if (bl && !list_empty(&bl->buf_list)) {
3425 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3426 list_del(&kbuf->list);
3427 if (*len > kbuf->len)
3429 req->flags |= REQ_F_BUFFER_SELECTED;
3432 kbuf = ERR_PTR(-ENOBUFS);
3435 io_ring_submit_unlock(req->ctx, needs_lock);
3439 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3440 unsigned int issue_flags)
3442 struct io_buffer *kbuf;
3445 bgid = req->buf_index;
3446 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3449 return u64_to_user_ptr(kbuf->addr);
3452 #ifdef CONFIG_COMPAT
3453 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3454 unsigned int issue_flags)
3456 struct compat_iovec __user *uiov;
3457 compat_ssize_t clen;
3461 uiov = u64_to_user_ptr(req->rw.addr);
3462 if (!access_ok(uiov, sizeof(*uiov)))
3464 if (__get_user(clen, &uiov->iov_len))
3470 buf = io_rw_buffer_select(req, &len, issue_flags);
3472 return PTR_ERR(buf);
3473 iov[0].iov_base = buf;
3474 iov[0].iov_len = (compat_size_t) len;
3479 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3480 unsigned int issue_flags)
3482 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3486 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3489 len = iov[0].iov_len;
3492 buf = io_rw_buffer_select(req, &len, issue_flags);
3494 return PTR_ERR(buf);
3495 iov[0].iov_base = buf;
3496 iov[0].iov_len = len;
3500 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3501 unsigned int issue_flags)
3503 if (req->flags & REQ_F_BUFFER_SELECTED) {
3504 struct io_buffer *kbuf = req->kbuf;
3506 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3507 iov[0].iov_len = kbuf->len;
3510 if (req->rw.len != 1)
3513 #ifdef CONFIG_COMPAT
3514 if (req->ctx->compat)
3515 return io_compat_import(req, iov, issue_flags);
3518 return __io_iov_buffer_select(req, iov, issue_flags);
3521 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3522 struct io_rw_state *s,
3523 unsigned int issue_flags)
3525 struct iov_iter *iter = &s->iter;
3526 u8 opcode = req->opcode;
3527 struct iovec *iovec;
3532 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3533 ret = io_import_fixed(req, rw, iter);
3535 return ERR_PTR(ret);
3539 /* buffer index only valid with fixed read/write, or buffer select */
3540 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3541 return ERR_PTR(-EINVAL);
3543 buf = u64_to_user_ptr(req->rw.addr);
3544 sqe_len = req->rw.len;
3546 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3547 if (req->flags & REQ_F_BUFFER_SELECT) {
3548 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3550 return ERR_CAST(buf);
3551 req->rw.len = sqe_len;
3554 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3556 return ERR_PTR(ret);
3560 iovec = s->fast_iov;
3561 if (req->flags & REQ_F_BUFFER_SELECT) {
3562 ret = io_iov_buffer_select(req, iovec, issue_flags);
3564 return ERR_PTR(ret);
3565 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3569 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3571 if (unlikely(ret < 0))
3572 return ERR_PTR(ret);
3576 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3577 struct iovec **iovec, struct io_rw_state *s,
3578 unsigned int issue_flags)
3580 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3581 if (unlikely(IS_ERR(*iovec)))
3582 return PTR_ERR(*iovec);
3584 iov_iter_save_state(&s->iter, &s->iter_state);
3588 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3590 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3594 * For files that don't have ->read_iter() and ->write_iter(), handle them
3595 * by looping over ->read() or ->write() manually.
3597 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3599 struct kiocb *kiocb = &req->rw.kiocb;
3600 struct file *file = req->file;
3605 * Don't support polled IO through this interface, and we can't
3606 * support non-blocking either. For the latter, this just causes
3607 * the kiocb to be handled from an async context.
3609 if (kiocb->ki_flags & IOCB_HIPRI)
3611 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3612 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3615 ppos = io_kiocb_ppos(kiocb);
3617 while (iov_iter_count(iter)) {
3621 if (!iov_iter_is_bvec(iter)) {
3622 iovec = iov_iter_iovec(iter);
3624 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3625 iovec.iov_len = req->rw.len;
3629 nr = file->f_op->read(file, iovec.iov_base,
3630 iovec.iov_len, ppos);
3632 nr = file->f_op->write(file, iovec.iov_base,
3633 iovec.iov_len, ppos);
3642 if (!iov_iter_is_bvec(iter)) {
3643 iov_iter_advance(iter, nr);
3650 if (nr != iovec.iov_len)
3657 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3658 const struct iovec *fast_iov, struct iov_iter *iter)
3660 struct io_async_rw *rw = req->async_data;
3662 memcpy(&rw->s.iter, iter, sizeof(*iter));
3663 rw->free_iovec = iovec;
3665 /* can only be fixed buffers, no need to do anything */
3666 if (iov_iter_is_bvec(iter))
3669 unsigned iov_off = 0;
3671 rw->s.iter.iov = rw->s.fast_iov;
3672 if (iter->iov != fast_iov) {
3673 iov_off = iter->iov - fast_iov;
3674 rw->s.iter.iov += iov_off;
3676 if (rw->s.fast_iov != fast_iov)
3677 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3678 sizeof(struct iovec) * iter->nr_segs);
3680 req->flags |= REQ_F_NEED_CLEANUP;
3684 static inline bool io_alloc_async_data(struct io_kiocb *req)
3686 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3687 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3688 if (req->async_data) {
3689 req->flags |= REQ_F_ASYNC_DATA;
3695 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3696 struct io_rw_state *s, bool force)
3698 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3700 if (!req_has_async_data(req)) {
3701 struct io_async_rw *iorw;
3703 if (io_alloc_async_data(req)) {
3708 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3709 iorw = req->async_data;
3710 /* we've copied and mapped the iter, ensure state is saved */
3711 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3716 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3718 struct io_async_rw *iorw = req->async_data;
3722 /* submission path, ->uring_lock should already be taken */
3723 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3724 if (unlikely(ret < 0))
3727 iorw->bytes_done = 0;
3728 iorw->free_iovec = iov;
3730 req->flags |= REQ_F_NEED_CLEANUP;
3734 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3736 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3738 return io_prep_rw(req, sqe);
3742 * This is our waitqueue callback handler, registered through __folio_lock_async()
3743 * when we initially tried to do the IO with the iocb armed our waitqueue.
3744 * This gets called when the page is unlocked, and we generally expect that to
3745 * happen when the page IO is completed and the page is now uptodate. This will
3746 * queue a task_work based retry of the operation, attempting to copy the data
3747 * again. If the latter fails because the page was NOT uptodate, then we will
3748 * do a thread based blocking retry of the operation. That's the unexpected
3751 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3752 int sync, void *arg)
3754 struct wait_page_queue *wpq;
3755 struct io_kiocb *req = wait->private;
3756 struct wait_page_key *key = arg;
3758 wpq = container_of(wait, struct wait_page_queue, wait);
3760 if (!wake_page_match(wpq, key))
3763 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3764 list_del_init(&wait->entry);
3765 io_req_task_queue(req);
3770 * This controls whether a given IO request should be armed for async page
3771 * based retry. If we return false here, the request is handed to the async
3772 * worker threads for retry. If we're doing buffered reads on a regular file,
3773 * we prepare a private wait_page_queue entry and retry the operation. This
3774 * will either succeed because the page is now uptodate and unlocked, or it
3775 * will register a callback when the page is unlocked at IO completion. Through
3776 * that callback, io_uring uses task_work to setup a retry of the operation.
3777 * That retry will attempt the buffered read again. The retry will generally
3778 * succeed, or in rare cases where it fails, we then fall back to using the
3779 * async worker threads for a blocking retry.
3781 static bool io_rw_should_retry(struct io_kiocb *req)
3783 struct io_async_rw *rw = req->async_data;
3784 struct wait_page_queue *wait = &rw->wpq;
3785 struct kiocb *kiocb = &req->rw.kiocb;
3787 /* never retry for NOWAIT, we just complete with -EAGAIN */
3788 if (req->flags & REQ_F_NOWAIT)
3791 /* Only for buffered IO */
3792 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3796 * just use poll if we can, and don't attempt if the fs doesn't
3797 * support callback based unlocks
3799 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3802 wait->wait.func = io_async_buf_func;
3803 wait->wait.private = req;
3804 wait->wait.flags = 0;
3805 INIT_LIST_HEAD(&wait->wait.entry);
3806 kiocb->ki_flags |= IOCB_WAITQ;
3807 kiocb->ki_flags &= ~IOCB_NOWAIT;
3808 kiocb->ki_waitq = wait;
3812 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3814 if (likely(req->file->f_op->read_iter))
3815 return call_read_iter(req->file, &req->rw.kiocb, iter);
3816 else if (req->file->f_op->read)
3817 return loop_rw_iter(READ, req, iter);
3822 static bool need_read_all(struct io_kiocb *req)
3824 return req->flags & REQ_F_ISREG ||
3825 S_ISBLK(file_inode(req->file)->i_mode);
3828 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3830 struct io_rw_state __s, *s = &__s;
3831 struct iovec *iovec;
3832 struct kiocb *kiocb = &req->rw.kiocb;
3833 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3834 struct io_async_rw *rw;
3838 if (!req_has_async_data(req)) {
3839 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3840 if (unlikely(ret < 0))
3844 * Safe and required to re-import if we're using provided
3845 * buffers, as we dropped the selected one before retry.
3847 if (req->flags & REQ_F_BUFFER_SELECT) {
3848 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3849 if (unlikely(ret < 0))
3853 rw = req->async_data;
3856 * We come here from an earlier attempt, restore our state to
3857 * match in case it doesn't. It's cheap enough that we don't
3858 * need to make this conditional.
3860 iov_iter_restore(&s->iter, &s->iter_state);
3863 req->result = iov_iter_count(&s->iter);
3865 if (force_nonblock) {
3866 /* If the file doesn't support async, just async punt */
3867 if (unlikely(!io_file_supports_nowait(req))) {
3868 ret = io_setup_async_rw(req, iovec, s, true);
3869 return ret ?: -EAGAIN;
3871 kiocb->ki_flags |= IOCB_NOWAIT;
3873 /* Ensure we clear previously set non-block flag */
3874 kiocb->ki_flags &= ~IOCB_NOWAIT;
3877 ppos = io_kiocb_update_pos(req);
3879 ret = rw_verify_area(READ, req->file, ppos, req->result);
3880 if (unlikely(ret)) {
3885 ret = io_iter_do_read(req, &s->iter);
3887 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3888 req->flags &= ~REQ_F_REISSUE;
3889 /* if we can poll, just do that */
3890 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3892 /* IOPOLL retry should happen for io-wq threads */
3893 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3895 /* no retry on NONBLOCK nor RWF_NOWAIT */
3896 if (req->flags & REQ_F_NOWAIT)
3899 } else if (ret == -EIOCBQUEUED) {
3901 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3902 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3903 /* read all, failed, already did sync or don't want to retry */
3908 * Don't depend on the iter state matching what was consumed, or being
3909 * untouched in case of error. Restore it and we'll advance it
3910 * manually if we need to.
3912 iov_iter_restore(&s->iter, &s->iter_state);
3914 ret2 = io_setup_async_rw(req, iovec, s, true);
3919 rw = req->async_data;
3922 * Now use our persistent iterator and state, if we aren't already.
3923 * We've restored and mapped the iter to match.
3928 * We end up here because of a partial read, either from
3929 * above or inside this loop. Advance the iter by the bytes
3930 * that were consumed.
3932 iov_iter_advance(&s->iter, ret);
3933 if (!iov_iter_count(&s->iter))
3935 rw->bytes_done += ret;
3936 iov_iter_save_state(&s->iter, &s->iter_state);
3938 /* if we can retry, do so with the callbacks armed */
3939 if (!io_rw_should_retry(req)) {
3940 kiocb->ki_flags &= ~IOCB_WAITQ;
3945 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3946 * we get -EIOCBQUEUED, then we'll get a notification when the
3947 * desired page gets unlocked. We can also get a partial read
3948 * here, and if we do, then just retry at the new offset.
3950 ret = io_iter_do_read(req, &s->iter);
3951 if (ret == -EIOCBQUEUED)
3953 /* we got some bytes, but not all. retry. */
3954 kiocb->ki_flags &= ~IOCB_WAITQ;
3955 iov_iter_restore(&s->iter, &s->iter_state);
3958 kiocb_done(req, ret, issue_flags);
3960 /* it's faster to check here then delegate to kfree */
3966 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3968 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3970 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
3971 return io_prep_rw(req, sqe);
3974 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3976 struct io_rw_state __s, *s = &__s;
3977 struct iovec *iovec;
3978 struct kiocb *kiocb = &req->rw.kiocb;
3979 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3983 if (!req_has_async_data(req)) {
3984 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3985 if (unlikely(ret < 0))
3988 struct io_async_rw *rw = req->async_data;
3991 iov_iter_restore(&s->iter, &s->iter_state);
3994 req->result = iov_iter_count(&s->iter);
3996 if (force_nonblock) {
3997 /* If the file doesn't support async, just async punt */
3998 if (unlikely(!io_file_supports_nowait(req)))
4001 /* file path doesn't support NOWAIT for non-direct_IO */
4002 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4003 (req->flags & REQ_F_ISREG))
4006 kiocb->ki_flags |= IOCB_NOWAIT;
4008 /* Ensure we clear previously set non-block flag */
4009 kiocb->ki_flags &= ~IOCB_NOWAIT;
4012 ppos = io_kiocb_update_pos(req);
4014 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
4019 * Open-code file_start_write here to grab freeze protection,
4020 * which will be released by another thread in
4021 * io_complete_rw(). Fool lockdep by telling it the lock got
4022 * released so that it doesn't complain about the held lock when
4023 * we return to userspace.
4025 if (req->flags & REQ_F_ISREG) {
4026 sb_start_write(file_inode(req->file)->i_sb);
4027 __sb_writers_release(file_inode(req->file)->i_sb,
4030 kiocb->ki_flags |= IOCB_WRITE;
4032 if (likely(req->file->f_op->write_iter))
4033 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4034 else if (req->file->f_op->write)
4035 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4039 if (req->flags & REQ_F_REISSUE) {
4040 req->flags &= ~REQ_F_REISSUE;
4045 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4046 * retry them without IOCB_NOWAIT.
4048 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4050 /* no retry on NONBLOCK nor RWF_NOWAIT */
4051 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4053 if (!force_nonblock || ret2 != -EAGAIN) {
4054 /* IOPOLL retry should happen for io-wq threads */
4055 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4058 kiocb_done(req, ret2, issue_flags);
4061 iov_iter_restore(&s->iter, &s->iter_state);
4062 ret = io_setup_async_rw(req, iovec, s, false);
4063 return ret ?: -EAGAIN;
4066 /* it's reportedly faster than delegating the null check to kfree() */
4072 static int io_renameat_prep(struct io_kiocb *req,
4073 const struct io_uring_sqe *sqe)
4075 struct io_rename *ren = &req->rename;
4076 const char __user *oldf, *newf;
4078 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4080 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4082 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4085 ren->old_dfd = READ_ONCE(sqe->fd);
4086 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4087 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4088 ren->new_dfd = READ_ONCE(sqe->len);
4089 ren->flags = READ_ONCE(sqe->rename_flags);
4091 ren->oldpath = getname(oldf);
4092 if (IS_ERR(ren->oldpath))
4093 return PTR_ERR(ren->oldpath);
4095 ren->newpath = getname(newf);
4096 if (IS_ERR(ren->newpath)) {
4097 putname(ren->oldpath);
4098 return PTR_ERR(ren->newpath);
4101 req->flags |= REQ_F_NEED_CLEANUP;
4105 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4107 struct io_rename *ren = &req->rename;
4110 if (issue_flags & IO_URING_F_NONBLOCK)
4113 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4114 ren->newpath, ren->flags);
4116 req->flags &= ~REQ_F_NEED_CLEANUP;
4119 io_req_complete(req, ret);
4123 static int io_unlinkat_prep(struct io_kiocb *req,
4124 const struct io_uring_sqe *sqe)
4126 struct io_unlink *un = &req->unlink;
4127 const char __user *fname;
4129 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4131 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4134 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4137 un->dfd = READ_ONCE(sqe->fd);
4139 un->flags = READ_ONCE(sqe->unlink_flags);
4140 if (un->flags & ~AT_REMOVEDIR)
4143 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4144 un->filename = getname(fname);
4145 if (IS_ERR(un->filename))
4146 return PTR_ERR(un->filename);
4148 req->flags |= REQ_F_NEED_CLEANUP;
4152 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4154 struct io_unlink *un = &req->unlink;
4157 if (issue_flags & IO_URING_F_NONBLOCK)
4160 if (un->flags & AT_REMOVEDIR)
4161 ret = do_rmdir(un->dfd, un->filename);
4163 ret = do_unlinkat(un->dfd, un->filename);
4165 req->flags &= ~REQ_F_NEED_CLEANUP;
4168 io_req_complete(req, ret);
4172 static int io_mkdirat_prep(struct io_kiocb *req,
4173 const struct io_uring_sqe *sqe)
4175 struct io_mkdir *mkd = &req->mkdir;
4176 const char __user *fname;
4178 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4180 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4183 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4186 mkd->dfd = READ_ONCE(sqe->fd);
4187 mkd->mode = READ_ONCE(sqe->len);
4189 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4190 mkd->filename = getname(fname);
4191 if (IS_ERR(mkd->filename))
4192 return PTR_ERR(mkd->filename);
4194 req->flags |= REQ_F_NEED_CLEANUP;
4198 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4200 struct io_mkdir *mkd = &req->mkdir;
4203 if (issue_flags & IO_URING_F_NONBLOCK)
4206 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4208 req->flags &= ~REQ_F_NEED_CLEANUP;
4211 io_req_complete(req, ret);
4215 static int io_symlinkat_prep(struct io_kiocb *req,
4216 const struct io_uring_sqe *sqe)
4218 struct io_symlink *sl = &req->symlink;
4219 const char __user *oldpath, *newpath;
4221 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4223 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4226 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4229 sl->new_dfd = READ_ONCE(sqe->fd);
4230 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4231 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4233 sl->oldpath = getname(oldpath);
4234 if (IS_ERR(sl->oldpath))
4235 return PTR_ERR(sl->oldpath);
4237 sl->newpath = getname(newpath);
4238 if (IS_ERR(sl->newpath)) {
4239 putname(sl->oldpath);
4240 return PTR_ERR(sl->newpath);
4243 req->flags |= REQ_F_NEED_CLEANUP;
4247 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4249 struct io_symlink *sl = &req->symlink;
4252 if (issue_flags & IO_URING_F_NONBLOCK)
4255 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4257 req->flags &= ~REQ_F_NEED_CLEANUP;
4260 io_req_complete(req, ret);
4264 static int io_linkat_prep(struct io_kiocb *req,
4265 const struct io_uring_sqe *sqe)
4267 struct io_hardlink *lnk = &req->hardlink;
4268 const char __user *oldf, *newf;
4270 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4272 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4274 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4277 lnk->old_dfd = READ_ONCE(sqe->fd);
4278 lnk->new_dfd = READ_ONCE(sqe->len);
4279 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4280 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4281 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4283 lnk->oldpath = getname(oldf);
4284 if (IS_ERR(lnk->oldpath))
4285 return PTR_ERR(lnk->oldpath);
4287 lnk->newpath = getname(newf);
4288 if (IS_ERR(lnk->newpath)) {
4289 putname(lnk->oldpath);
4290 return PTR_ERR(lnk->newpath);
4293 req->flags |= REQ_F_NEED_CLEANUP;
4297 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4299 struct io_hardlink *lnk = &req->hardlink;
4302 if (issue_flags & IO_URING_F_NONBLOCK)
4305 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4306 lnk->newpath, lnk->flags);
4308 req->flags &= ~REQ_F_NEED_CLEANUP;
4311 io_req_complete(req, ret);
4315 static int io_shutdown_prep(struct io_kiocb *req,
4316 const struct io_uring_sqe *sqe)
4318 #if defined(CONFIG_NET)
4319 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4321 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4322 sqe->buf_index || sqe->splice_fd_in))
4325 req->shutdown.how = READ_ONCE(sqe->len);
4332 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4334 #if defined(CONFIG_NET)
4335 struct socket *sock;
4338 if (issue_flags & IO_URING_F_NONBLOCK)
4341 sock = sock_from_file(req->file);
4342 if (unlikely(!sock))
4345 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4348 io_req_complete(req, ret);
4355 static int __io_splice_prep(struct io_kiocb *req,
4356 const struct io_uring_sqe *sqe)
4358 struct io_splice *sp = &req->splice;
4359 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4361 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4365 sp->len = READ_ONCE(sqe->len);
4366 sp->flags = READ_ONCE(sqe->splice_flags);
4368 if (unlikely(sp->flags & ~valid_flags))
4371 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4372 (sp->flags & SPLICE_F_FD_IN_FIXED));
4375 req->flags |= REQ_F_NEED_CLEANUP;
4379 static int io_tee_prep(struct io_kiocb *req,
4380 const struct io_uring_sqe *sqe)
4382 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4384 return __io_splice_prep(req, sqe);
4387 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4389 struct io_splice *sp = &req->splice;
4390 struct file *in = sp->file_in;
4391 struct file *out = sp->file_out;
4392 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4395 if (issue_flags & IO_URING_F_NONBLOCK)
4398 ret = do_tee(in, out, sp->len, flags);
4400 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4402 req->flags &= ~REQ_F_NEED_CLEANUP;
4406 io_req_complete(req, ret);
4410 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4412 struct io_splice *sp = &req->splice;
4414 sp->off_in = READ_ONCE(sqe->splice_off_in);
4415 sp->off_out = READ_ONCE(sqe->off);
4416 return __io_splice_prep(req, sqe);
4419 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4421 struct io_splice *sp = &req->splice;
4422 struct file *in = sp->file_in;
4423 struct file *out = sp->file_out;
4424 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4425 loff_t *poff_in, *poff_out;
4428 if (issue_flags & IO_URING_F_NONBLOCK)
4431 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4432 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4435 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4437 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4439 req->flags &= ~REQ_F_NEED_CLEANUP;
4443 io_req_complete(req, ret);
4448 * IORING_OP_NOP just posts a completion event, nothing else.
4450 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4452 struct io_ring_ctx *ctx = req->ctx;
4454 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4457 __io_req_complete(req, issue_flags, 0, 0);
4461 static int io_msg_ring_prep(struct io_kiocb *req,
4462 const struct io_uring_sqe *sqe)
4464 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4465 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4468 if (req->file->f_op != &io_uring_fops)
4471 req->msg.user_data = READ_ONCE(sqe->off);
4472 req->msg.len = READ_ONCE(sqe->len);
4476 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4478 struct io_ring_ctx *target_ctx;
4479 struct io_msg *msg = &req->msg;
4480 int ret = -EOVERFLOW;
4483 target_ctx = req->file->private_data;
4485 spin_lock(&target_ctx->completion_lock);
4486 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4487 io_commit_cqring(target_ctx);
4488 spin_unlock(&target_ctx->completion_lock);
4491 io_cqring_ev_posted(target_ctx);
4495 __io_req_complete(req, issue_flags, ret, 0);
4499 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4501 struct io_ring_ctx *ctx = req->ctx;
4506 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4508 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4512 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4513 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4516 req->sync.off = READ_ONCE(sqe->off);
4517 req->sync.len = READ_ONCE(sqe->len);
4521 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4523 loff_t end = req->sync.off + req->sync.len;
4526 /* fsync always requires a blocking context */
4527 if (issue_flags & IO_URING_F_NONBLOCK)
4530 ret = vfs_fsync_range(req->file, req->sync.off,
4531 end > 0 ? end : LLONG_MAX,
4532 req->sync.flags & IORING_FSYNC_DATASYNC);
4535 io_req_complete(req, ret);
4539 static int io_fallocate_prep(struct io_kiocb *req,
4540 const struct io_uring_sqe *sqe)
4542 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4545 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4548 req->sync.off = READ_ONCE(sqe->off);
4549 req->sync.len = READ_ONCE(sqe->addr);
4550 req->sync.mode = READ_ONCE(sqe->len);
4554 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4558 /* fallocate always requiring blocking context */
4559 if (issue_flags & IO_URING_F_NONBLOCK)
4561 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4566 fsnotify_modify(req->file);
4567 io_req_complete(req, ret);
4571 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4573 const char __user *fname;
4576 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4578 if (unlikely(sqe->ioprio || sqe->buf_index))
4580 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4583 /* open.how should be already initialised */
4584 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4585 req->open.how.flags |= O_LARGEFILE;
4587 req->open.dfd = READ_ONCE(sqe->fd);
4588 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4589 req->open.filename = getname(fname);
4590 if (IS_ERR(req->open.filename)) {
4591 ret = PTR_ERR(req->open.filename);
4592 req->open.filename = NULL;
4596 req->open.file_slot = READ_ONCE(sqe->file_index);
4597 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4600 req->open.nofile = rlimit(RLIMIT_NOFILE);
4601 req->flags |= REQ_F_NEED_CLEANUP;
4605 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4607 u64 mode = READ_ONCE(sqe->len);
4608 u64 flags = READ_ONCE(sqe->open_flags);
4610 req->open.how = build_open_how(flags, mode);
4611 return __io_openat_prep(req, sqe);
4614 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4616 struct open_how __user *how;
4620 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4621 len = READ_ONCE(sqe->len);
4622 if (len < OPEN_HOW_SIZE_VER0)
4625 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4630 return __io_openat_prep(req, sqe);
4633 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4635 struct open_flags op;
4637 bool resolve_nonblock, nonblock_set;
4638 bool fixed = !!req->open.file_slot;
4641 ret = build_open_flags(&req->open.how, &op);
4644 nonblock_set = op.open_flag & O_NONBLOCK;
4645 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4646 if (issue_flags & IO_URING_F_NONBLOCK) {
4648 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4649 * it'll always -EAGAIN
4651 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4653 op.lookup_flags |= LOOKUP_CACHED;
4654 op.open_flag |= O_NONBLOCK;
4658 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4663 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4666 * We could hang on to this 'fd' on retrying, but seems like
4667 * marginal gain for something that is now known to be a slower
4668 * path. So just put it, and we'll get a new one when we retry.
4673 ret = PTR_ERR(file);
4674 /* only retry if RESOLVE_CACHED wasn't already set by application */
4675 if (ret == -EAGAIN &&
4676 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4681 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4682 file->f_flags &= ~O_NONBLOCK;
4683 fsnotify_open(file);
4686 fd_install(ret, file);
4688 ret = io_install_fixed_file(req, file, issue_flags,
4689 req->open.file_slot - 1);
4691 putname(req->open.filename);
4692 req->flags &= ~REQ_F_NEED_CLEANUP;
4695 __io_req_complete(req, issue_flags, ret, 0);
4699 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4701 return io_openat2(req, issue_flags);
4704 static int io_remove_buffers_prep(struct io_kiocb *req,
4705 const struct io_uring_sqe *sqe)
4707 struct io_provide_buf *p = &req->pbuf;
4710 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4714 tmp = READ_ONCE(sqe->fd);
4715 if (!tmp || tmp > USHRT_MAX)
4718 memset(p, 0, sizeof(*p));
4720 p->bgid = READ_ONCE(sqe->buf_group);
4724 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4725 struct io_buffer_list *bl, unsigned nbufs)
4729 /* shouldn't happen */
4733 /* the head kbuf is the list itself */
4734 while (!list_empty(&bl->buf_list)) {
4735 struct io_buffer *nxt;
4737 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4738 list_del(&nxt->list);
4748 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4750 struct io_provide_buf *p = &req->pbuf;
4751 struct io_ring_ctx *ctx = req->ctx;
4752 struct io_buffer_list *bl;
4754 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4756 io_ring_submit_lock(ctx, needs_lock);
4758 lockdep_assert_held(&ctx->uring_lock);
4761 bl = io_buffer_get_list(ctx, p->bgid);
4763 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4767 /* complete before unlock, IOPOLL may need the lock */
4768 __io_req_complete(req, issue_flags, ret, 0);
4769 io_ring_submit_unlock(ctx, needs_lock);
4773 static int io_provide_buffers_prep(struct io_kiocb *req,
4774 const struct io_uring_sqe *sqe)
4776 unsigned long size, tmp_check;
4777 struct io_provide_buf *p = &req->pbuf;
4780 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4783 tmp = READ_ONCE(sqe->fd);
4784 if (!tmp || tmp > USHRT_MAX)
4787 p->addr = READ_ONCE(sqe->addr);
4788 p->len = READ_ONCE(sqe->len);
4790 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4793 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4796 size = (unsigned long)p->len * p->nbufs;
4797 if (!access_ok(u64_to_user_ptr(p->addr), size))
4800 p->bgid = READ_ONCE(sqe->buf_group);
4801 tmp = READ_ONCE(sqe->off);
4802 if (tmp > USHRT_MAX)
4808 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4810 struct io_buffer *buf;
4815 * Completions that don't happen inline (eg not under uring_lock) will
4816 * add to ->io_buffers_comp. If we don't have any free buffers, check
4817 * the completion list and splice those entries first.
4819 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4820 spin_lock(&ctx->completion_lock);
4821 if (!list_empty(&ctx->io_buffers_comp)) {
4822 list_splice_init(&ctx->io_buffers_comp,
4823 &ctx->io_buffers_cache);
4824 spin_unlock(&ctx->completion_lock);
4827 spin_unlock(&ctx->completion_lock);
4831 * No free buffers and no completion entries either. Allocate a new
4832 * page worth of buffer entries and add those to our freelist.
4834 page = alloc_page(GFP_KERNEL_ACCOUNT);
4838 list_add(&page->lru, &ctx->io_buffers_pages);
4840 buf = page_address(page);
4841 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4842 while (bufs_in_page) {
4843 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4851 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4852 struct io_buffer_list *bl)
4854 struct io_buffer *buf;
4855 u64 addr = pbuf->addr;
4856 int i, bid = pbuf->bid;
4858 for (i = 0; i < pbuf->nbufs; i++) {
4859 if (list_empty(&ctx->io_buffers_cache) &&
4860 io_refill_buffer_cache(ctx))
4862 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4864 list_move_tail(&buf->list, &bl->buf_list);
4866 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4868 buf->bgid = pbuf->bgid;
4874 return i ? 0 : -ENOMEM;
4877 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4879 struct io_provide_buf *p = &req->pbuf;
4880 struct io_ring_ctx *ctx = req->ctx;
4881 struct io_buffer_list *bl;
4883 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4885 io_ring_submit_lock(ctx, needs_lock);
4887 lockdep_assert_held(&ctx->uring_lock);
4889 bl = io_buffer_get_list(ctx, p->bgid);
4890 if (unlikely(!bl)) {
4891 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4896 io_buffer_add_list(ctx, bl, p->bgid);
4899 ret = io_add_buffers(ctx, p, bl);
4903 /* complete before unlock, IOPOLL may need the lock */
4904 __io_req_complete(req, issue_flags, ret, 0);
4905 io_ring_submit_unlock(ctx, needs_lock);
4909 static int io_epoll_ctl_prep(struct io_kiocb *req,
4910 const struct io_uring_sqe *sqe)
4912 #if defined(CONFIG_EPOLL)
4913 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4915 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4918 req->epoll.epfd = READ_ONCE(sqe->fd);
4919 req->epoll.op = READ_ONCE(sqe->len);
4920 req->epoll.fd = READ_ONCE(sqe->off);
4922 if (ep_op_has_event(req->epoll.op)) {
4923 struct epoll_event __user *ev;
4925 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4926 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4936 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4938 #if defined(CONFIG_EPOLL)
4939 struct io_epoll *ie = &req->epoll;
4941 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4943 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4944 if (force_nonblock && ret == -EAGAIN)
4949 __io_req_complete(req, issue_flags, ret, 0);
4956 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4958 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4959 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4961 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4964 req->madvise.addr = READ_ONCE(sqe->addr);
4965 req->madvise.len = READ_ONCE(sqe->len);
4966 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4973 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4975 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4976 struct io_madvise *ma = &req->madvise;
4979 if (issue_flags & IO_URING_F_NONBLOCK)
4982 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4985 io_req_complete(req, ret);
4992 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4994 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4996 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4999 req->fadvise.offset = READ_ONCE(sqe->off);
5000 req->fadvise.len = READ_ONCE(sqe->len);
5001 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5005 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5007 struct io_fadvise *fa = &req->fadvise;
5010 if (issue_flags & IO_URING_F_NONBLOCK) {
5011 switch (fa->advice) {
5012 case POSIX_FADV_NORMAL:
5013 case POSIX_FADV_RANDOM:
5014 case POSIX_FADV_SEQUENTIAL:
5021 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5024 __io_req_complete(req, issue_flags, ret, 0);
5028 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5030 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5032 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5034 if (req->flags & REQ_F_FIXED_FILE)
5037 req->statx.dfd = READ_ONCE(sqe->fd);
5038 req->statx.mask = READ_ONCE(sqe->len);
5039 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
5040 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5041 req->statx.flags = READ_ONCE(sqe->statx_flags);
5046 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5048 struct io_statx *ctx = &req->statx;
5051 if (issue_flags & IO_URING_F_NONBLOCK)
5054 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5059 io_req_complete(req, ret);
5063 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5065 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5067 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5068 sqe->rw_flags || sqe->buf_index)
5070 if (req->flags & REQ_F_FIXED_FILE)
5073 req->close.fd = READ_ONCE(sqe->fd);
5074 req->close.file_slot = READ_ONCE(sqe->file_index);
5075 if (req->close.file_slot && req->close.fd)
5081 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5083 struct files_struct *files = current->files;
5084 struct io_close *close = &req->close;
5085 struct fdtable *fdt;
5086 struct file *file = NULL;
5089 if (req->close.file_slot) {
5090 ret = io_close_fixed(req, issue_flags);
5094 spin_lock(&files->file_lock);
5095 fdt = files_fdtable(files);
5096 if (close->fd >= fdt->max_fds) {
5097 spin_unlock(&files->file_lock);
5100 file = fdt->fd[close->fd];
5101 if (!file || file->f_op == &io_uring_fops) {
5102 spin_unlock(&files->file_lock);
5107 /* if the file has a flush method, be safe and punt to async */
5108 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5109 spin_unlock(&files->file_lock);
5113 ret = __close_fd_get_file(close->fd, &file);
5114 spin_unlock(&files->file_lock);
5121 /* No ->flush() or already async, safely close from here */
5122 ret = filp_close(file, current->files);
5128 __io_req_complete(req, issue_flags, ret, 0);
5132 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5134 struct io_ring_ctx *ctx = req->ctx;
5136 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5138 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5142 req->sync.off = READ_ONCE(sqe->off);
5143 req->sync.len = READ_ONCE(sqe->len);
5144 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5148 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5152 /* sync_file_range always requires a blocking context */
5153 if (issue_flags & IO_URING_F_NONBLOCK)
5156 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5160 io_req_complete(req, ret);
5164 #if defined(CONFIG_NET)
5165 static int io_setup_async_msg(struct io_kiocb *req,
5166 struct io_async_msghdr *kmsg)
5168 struct io_async_msghdr *async_msg = req->async_data;
5172 if (io_alloc_async_data(req)) {
5173 kfree(kmsg->free_iov);
5176 async_msg = req->async_data;
5177 req->flags |= REQ_F_NEED_CLEANUP;
5178 memcpy(async_msg, kmsg, sizeof(*kmsg));
5179 async_msg->msg.msg_name = &async_msg->addr;
5180 /* if were using fast_iov, set it to the new one */
5181 if (!async_msg->free_iov)
5182 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5187 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5188 struct io_async_msghdr *iomsg)
5190 iomsg->msg.msg_name = &iomsg->addr;
5191 iomsg->free_iov = iomsg->fast_iov;
5192 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5193 req->sr_msg.msg_flags, &iomsg->free_iov);
5196 static int io_sendmsg_prep_async(struct io_kiocb *req)
5200 ret = io_sendmsg_copy_hdr(req, req->async_data);
5202 req->flags |= REQ_F_NEED_CLEANUP;
5206 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5208 struct io_sr_msg *sr = &req->sr_msg;
5210 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5213 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5214 sr->len = READ_ONCE(sqe->len);
5215 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5216 if (sr->msg_flags & MSG_DONTWAIT)
5217 req->flags |= REQ_F_NOWAIT;
5219 #ifdef CONFIG_COMPAT
5220 if (req->ctx->compat)
5221 sr->msg_flags |= MSG_CMSG_COMPAT;
5226 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5228 struct io_async_msghdr iomsg, *kmsg;
5229 struct socket *sock;
5234 sock = sock_from_file(req->file);
5235 if (unlikely(!sock))
5238 if (req_has_async_data(req)) {
5239 kmsg = req->async_data;
5241 ret = io_sendmsg_copy_hdr(req, &iomsg);
5247 flags = req->sr_msg.msg_flags;
5248 if (issue_flags & IO_URING_F_NONBLOCK)
5249 flags |= MSG_DONTWAIT;
5250 if (flags & MSG_WAITALL)
5251 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5253 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5255 if (ret < min_ret) {
5256 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5257 return io_setup_async_msg(req, kmsg);
5258 if (ret == -ERESTARTSYS)
5262 /* fast path, check for non-NULL to avoid function call */
5264 kfree(kmsg->free_iov);
5265 req->flags &= ~REQ_F_NEED_CLEANUP;
5266 __io_req_complete(req, issue_flags, ret, 0);
5270 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5272 struct io_sr_msg *sr = &req->sr_msg;
5275 struct socket *sock;
5280 sock = sock_from_file(req->file);
5281 if (unlikely(!sock))
5284 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5288 msg.msg_name = NULL;
5289 msg.msg_control = NULL;
5290 msg.msg_controllen = 0;
5291 msg.msg_namelen = 0;
5293 flags = req->sr_msg.msg_flags;
5294 if (issue_flags & IO_URING_F_NONBLOCK)
5295 flags |= MSG_DONTWAIT;
5296 if (flags & MSG_WAITALL)
5297 min_ret = iov_iter_count(&msg.msg_iter);
5299 msg.msg_flags = flags;
5300 ret = sock_sendmsg(sock, &msg);
5301 if (ret < min_ret) {
5302 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5304 if (ret == -ERESTARTSYS)
5308 __io_req_complete(req, issue_flags, ret, 0);
5312 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5313 struct io_async_msghdr *iomsg)
5315 struct io_sr_msg *sr = &req->sr_msg;
5316 struct iovec __user *uiov;
5320 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5321 &iomsg->uaddr, &uiov, &iov_len);
5325 if (req->flags & REQ_F_BUFFER_SELECT) {
5328 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5330 sr->len = iomsg->fast_iov[0].iov_len;
5331 iomsg->free_iov = NULL;
5333 iomsg->free_iov = iomsg->fast_iov;
5334 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5335 &iomsg->free_iov, &iomsg->msg.msg_iter,
5344 #ifdef CONFIG_COMPAT
5345 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5346 struct io_async_msghdr *iomsg)
5348 struct io_sr_msg *sr = &req->sr_msg;
5349 struct compat_iovec __user *uiov;
5354 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5359 uiov = compat_ptr(ptr);
5360 if (req->flags & REQ_F_BUFFER_SELECT) {
5361 compat_ssize_t clen;
5365 if (!access_ok(uiov, sizeof(*uiov)))
5367 if (__get_user(clen, &uiov->iov_len))
5372 iomsg->free_iov = NULL;
5374 iomsg->free_iov = iomsg->fast_iov;
5375 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5376 UIO_FASTIOV, &iomsg->free_iov,
5377 &iomsg->msg.msg_iter, true);
5386 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5387 struct io_async_msghdr *iomsg)
5389 iomsg->msg.msg_name = &iomsg->addr;
5391 #ifdef CONFIG_COMPAT
5392 if (req->ctx->compat)
5393 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5396 return __io_recvmsg_copy_hdr(req, iomsg);
5399 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5400 unsigned int issue_flags)
5402 struct io_sr_msg *sr = &req->sr_msg;
5404 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5407 static int io_recvmsg_prep_async(struct io_kiocb *req)
5411 ret = io_recvmsg_copy_hdr(req, req->async_data);
5413 req->flags |= REQ_F_NEED_CLEANUP;
5417 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5419 struct io_sr_msg *sr = &req->sr_msg;
5421 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5424 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5425 sr->len = READ_ONCE(sqe->len);
5426 sr->bgid = READ_ONCE(sqe->buf_group);
5427 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5428 if (sr->msg_flags & MSG_DONTWAIT)
5429 req->flags |= REQ_F_NOWAIT;
5431 #ifdef CONFIG_COMPAT
5432 if (req->ctx->compat)
5433 sr->msg_flags |= MSG_CMSG_COMPAT;
5439 static bool io_net_retry(struct socket *sock, int flags)
5441 if (!(flags & MSG_WAITALL))
5443 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5446 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5448 struct io_async_msghdr iomsg, *kmsg;
5449 struct io_sr_msg *sr = &req->sr_msg;
5450 struct socket *sock;
5451 struct io_buffer *kbuf;
5453 int ret, min_ret = 0;
5454 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5456 sock = sock_from_file(req->file);
5457 if (unlikely(!sock))
5460 if (req_has_async_data(req)) {
5461 kmsg = req->async_data;
5463 ret = io_recvmsg_copy_hdr(req, &iomsg);
5469 if (req->flags & REQ_F_BUFFER_SELECT) {
5470 kbuf = io_recv_buffer_select(req, issue_flags);
5472 return PTR_ERR(kbuf);
5473 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5474 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5475 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5476 1, req->sr_msg.len);
5479 flags = req->sr_msg.msg_flags;
5481 flags |= MSG_DONTWAIT;
5482 if (flags & MSG_WAITALL)
5483 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5485 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5486 kmsg->uaddr, flags);
5487 if (ret < min_ret) {
5488 if (ret == -EAGAIN && force_nonblock)
5489 return io_setup_async_msg(req, kmsg);
5490 if (ret == -ERESTARTSYS)
5492 if (ret > 0 && io_net_retry(sock, flags)) {
5494 req->flags |= REQ_F_PARTIAL_IO;
5495 return io_setup_async_msg(req, kmsg);
5498 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5502 /* fast path, check for non-NULL to avoid function call */
5504 kfree(kmsg->free_iov);
5505 req->flags &= ~REQ_F_NEED_CLEANUP;
5508 else if (sr->done_io)
5510 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5514 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5516 struct io_buffer *kbuf;
5517 struct io_sr_msg *sr = &req->sr_msg;
5519 void __user *buf = sr->buf;
5520 struct socket *sock;
5523 int ret, min_ret = 0;
5524 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5526 sock = sock_from_file(req->file);
5527 if (unlikely(!sock))
5530 if (req->flags & REQ_F_BUFFER_SELECT) {
5531 kbuf = io_recv_buffer_select(req, issue_flags);
5533 return PTR_ERR(kbuf);
5534 buf = u64_to_user_ptr(kbuf->addr);
5537 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5541 msg.msg_name = NULL;
5542 msg.msg_control = NULL;
5543 msg.msg_controllen = 0;
5544 msg.msg_namelen = 0;
5545 msg.msg_iocb = NULL;
5548 flags = req->sr_msg.msg_flags;
5550 flags |= MSG_DONTWAIT;
5551 if (flags & MSG_WAITALL)
5552 min_ret = iov_iter_count(&msg.msg_iter);
5554 ret = sock_recvmsg(sock, &msg, flags);
5555 if (ret < min_ret) {
5556 if (ret == -EAGAIN && force_nonblock)
5558 if (ret == -ERESTARTSYS)
5560 if (ret > 0 && io_net_retry(sock, flags)) {
5564 req->flags |= REQ_F_PARTIAL_IO;
5568 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5575 else if (sr->done_io)
5577 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5581 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5583 struct io_accept *accept = &req->accept;
5585 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5587 if (sqe->ioprio || sqe->len || sqe->buf_index)
5590 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5591 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5592 accept->flags = READ_ONCE(sqe->accept_flags);
5593 accept->nofile = rlimit(RLIMIT_NOFILE);
5595 accept->file_slot = READ_ONCE(sqe->file_index);
5596 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5598 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5600 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5601 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5605 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5607 struct io_accept *accept = &req->accept;
5608 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5609 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5610 bool fixed = !!accept->file_slot;
5615 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5616 if (unlikely(fd < 0))
5619 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5624 ret = PTR_ERR(file);
5625 if (ret == -EAGAIN && force_nonblock)
5627 if (ret == -ERESTARTSYS)
5630 } else if (!fixed) {
5631 fd_install(fd, file);
5634 ret = io_install_fixed_file(req, file, issue_flags,
5635 accept->file_slot - 1);
5637 __io_req_complete(req, issue_flags, ret, 0);
5641 static int io_connect_prep_async(struct io_kiocb *req)
5643 struct io_async_connect *io = req->async_data;
5644 struct io_connect *conn = &req->connect;
5646 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5649 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5651 struct io_connect *conn = &req->connect;
5653 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5655 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5659 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5660 conn->addr_len = READ_ONCE(sqe->addr2);
5664 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5666 struct io_async_connect __io, *io;
5667 unsigned file_flags;
5669 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5671 if (req_has_async_data(req)) {
5672 io = req->async_data;
5674 ret = move_addr_to_kernel(req->connect.addr,
5675 req->connect.addr_len,
5682 file_flags = force_nonblock ? O_NONBLOCK : 0;
5684 ret = __sys_connect_file(req->file, &io->address,
5685 req->connect.addr_len, file_flags);
5686 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5687 if (req_has_async_data(req))
5689 if (io_alloc_async_data(req)) {
5693 memcpy(req->async_data, &__io, sizeof(__io));
5696 if (ret == -ERESTARTSYS)
5701 __io_req_complete(req, issue_flags, ret, 0);
5704 #else /* !CONFIG_NET */
5705 #define IO_NETOP_FN(op) \
5706 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5708 return -EOPNOTSUPP; \
5711 #define IO_NETOP_PREP(op) \
5713 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5715 return -EOPNOTSUPP; \
5718 #define IO_NETOP_PREP_ASYNC(op) \
5720 static int io_##op##_prep_async(struct io_kiocb *req) \
5722 return -EOPNOTSUPP; \
5725 IO_NETOP_PREP_ASYNC(sendmsg);
5726 IO_NETOP_PREP_ASYNC(recvmsg);
5727 IO_NETOP_PREP_ASYNC(connect);
5728 IO_NETOP_PREP(accept);
5731 #endif /* CONFIG_NET */
5733 #ifdef CONFIG_NET_RX_BUSY_POLL
5735 #define NAPI_TIMEOUT (60 * SEC_CONVERSION)
5738 struct list_head list;
5739 unsigned int napi_id;
5740 unsigned long timeout;
5744 * Add busy poll NAPI ID from sk.
5746 static void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5748 unsigned int napi_id;
5749 struct socket *sock;
5751 struct napi_entry *ne;
5753 if (!net_busy_loop_on())
5756 sock = sock_from_file(file);
5764 napi_id = READ_ONCE(sk->sk_napi_id);
5766 /* Non-NAPI IDs can be rejected */
5767 if (napi_id < MIN_NAPI_ID)
5770 spin_lock(&ctx->napi_lock);
5771 list_for_each_entry(ne, &ctx->napi_list, list) {
5772 if (ne->napi_id == napi_id) {
5773 ne->timeout = jiffies + NAPI_TIMEOUT;
5778 ne = kmalloc(sizeof(*ne), GFP_NOWAIT);
5782 ne->napi_id = napi_id;
5783 ne->timeout = jiffies + NAPI_TIMEOUT;
5784 list_add_tail(&ne->list, &ctx->napi_list);
5786 spin_unlock(&ctx->napi_lock);
5789 static inline void io_check_napi_entry_timeout(struct napi_entry *ne)
5791 if (time_after(jiffies, ne->timeout)) {
5792 list_del(&ne->list);
5798 * Busy poll if globally on and supporting sockets found
5800 static bool io_napi_busy_loop(struct list_head *napi_list)
5802 struct napi_entry *ne, *n;
5804 list_for_each_entry_safe(ne, n, napi_list, list) {
5805 napi_busy_loop(ne->napi_id, NULL, NULL, true,
5807 io_check_napi_entry_timeout(ne);
5809 return !list_empty(napi_list);
5812 static void io_free_napi_list(struct io_ring_ctx *ctx)
5814 spin_lock(&ctx->napi_lock);
5815 while (!list_empty(&ctx->napi_list)) {
5816 struct napi_entry *ne =
5817 list_first_entry(&ctx->napi_list, struct napi_entry,
5820 list_del(&ne->list);
5823 spin_unlock(&ctx->napi_lock);
5826 static inline void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5830 static inline void io_free_napi_list(struct io_ring_ctx *ctx)
5833 #endif /* CONFIG_NET_RX_BUSY_POLL */
5835 struct io_poll_table {
5836 struct poll_table_struct pt;
5837 struct io_kiocb *req;
5842 #define IO_POLL_CANCEL_FLAG BIT(31)
5843 #define IO_POLL_REF_MASK GENMASK(30, 0)
5846 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5847 * bump it and acquire ownership. It's disallowed to modify requests while not
5848 * owning it, that prevents from races for enqueueing task_work's and b/w
5849 * arming poll and wakeups.
5851 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5853 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5856 static void io_poll_mark_cancelled(struct io_kiocb *req)
5858 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5861 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5863 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5864 if (req->opcode == IORING_OP_POLL_ADD)
5865 return req->async_data;
5866 return req->apoll->double_poll;
5869 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5871 if (req->opcode == IORING_OP_POLL_ADD)
5873 return &req->apoll->poll;
5876 static void io_poll_req_insert(struct io_kiocb *req)
5878 struct io_ring_ctx *ctx = req->ctx;
5879 struct hlist_head *list;
5881 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5882 hlist_add_head(&req->hash_node, list);
5885 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5886 wait_queue_func_t wake_func)
5889 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5890 /* mask in events that we always want/need */
5891 poll->events = events | IO_POLL_UNMASK;
5892 INIT_LIST_HEAD(&poll->wait.entry);
5893 init_waitqueue_func_entry(&poll->wait, wake_func);
5896 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5898 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5901 spin_lock_irq(&head->lock);
5902 list_del_init(&poll->wait.entry);
5904 spin_unlock_irq(&head->lock);
5908 static void io_poll_remove_entries(struct io_kiocb *req)
5911 * Nothing to do if neither of those flags are set. Avoid dipping
5912 * into the poll/apoll/double cachelines if we can.
5914 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5918 * While we hold the waitqueue lock and the waitqueue is nonempty,
5919 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5920 * lock in the first place can race with the waitqueue being freed.
5922 * We solve this as eventpoll does: by taking advantage of the fact that
5923 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5924 * we enter rcu_read_lock() and see that the pointer to the queue is
5925 * non-NULL, we can then lock it without the memory being freed out from
5928 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5929 * case the caller deletes the entry from the queue, leaving it empty.
5930 * In that case, only RCU prevents the queue memory from being freed.
5933 if (req->flags & REQ_F_SINGLE_POLL)
5934 io_poll_remove_entry(io_poll_get_single(req));
5935 if (req->flags & REQ_F_DOUBLE_POLL)
5936 io_poll_remove_entry(io_poll_get_double(req));
5941 * All poll tw should go through this. Checks for poll events, manages
5942 * references, does rewait, etc.
5944 * Returns a negative error on failure. >0 when no action require, which is
5945 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5946 * the request, then the mask is stored in req->result.
5948 static int io_poll_check_events(struct io_kiocb *req)
5950 struct io_ring_ctx *ctx = req->ctx;
5951 struct io_poll_iocb *poll = io_poll_get_single(req);
5954 /* req->task == current here, checking PF_EXITING is safe */
5955 if (unlikely(req->task->flags & PF_EXITING))
5956 io_poll_mark_cancelled(req);
5959 v = atomic_read(&req->poll_refs);
5961 /* tw handler should be the owner, and so have some references */
5962 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5964 if (v & IO_POLL_CANCEL_FLAG)
5968 struct poll_table_struct pt = { ._key = req->cflags };
5970 req->result = vfs_poll(req->file, &pt) & req->cflags;
5973 /* multishot, just fill an CQE and proceed */
5974 if (req->result && !(req->cflags & EPOLLONESHOT)) {
5975 __poll_t mask = mangle_poll(req->result & poll->events);
5978 spin_lock(&ctx->completion_lock);
5979 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5981 io_commit_cqring(ctx);
5982 spin_unlock(&ctx->completion_lock);
5983 if (unlikely(!filled))
5985 io_cqring_ev_posted(ctx);
5986 io_add_napi(req->file, ctx);
5987 } else if (req->result) {
5992 * Release all references, retry if someone tried to restart
5993 * task_work while we were executing it.
5995 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6000 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6002 struct io_ring_ctx *ctx = req->ctx;
6005 ret = io_poll_check_events(req);
6010 req->result = mangle_poll(req->result & req->poll.events);
6016 io_poll_remove_entries(req);
6017 spin_lock(&ctx->completion_lock);
6018 hash_del(&req->hash_node);
6019 __io_req_complete_post(req, req->result, 0);
6020 io_commit_cqring(ctx);
6021 spin_unlock(&ctx->completion_lock);
6022 io_cqring_ev_posted(ctx);
6025 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6027 struct io_ring_ctx *ctx = req->ctx;
6030 ret = io_poll_check_events(req);
6034 io_poll_remove_entries(req);
6035 spin_lock(&ctx->completion_lock);
6036 hash_del(&req->hash_node);
6037 spin_unlock(&ctx->completion_lock);
6040 io_req_task_submit(req, locked);
6042 io_req_complete_failed(req, ret);
6045 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
6049 * This is useful for poll that is armed on behalf of another
6050 * request, and where the wakeup path could be on a different
6051 * CPU. We want to avoid pulling in req->apoll->events for that
6054 req->cflags = events;
6055 if (req->opcode == IORING_OP_POLL_ADD)
6056 req->io_task_work.func = io_poll_task_func;
6058 req->io_task_work.func = io_apoll_task_func;
6060 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
6061 io_req_task_work_add(req, false);
6064 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6066 if (io_poll_get_ownership(req))
6067 __io_poll_execute(req, res, events);
6070 static void io_poll_cancel_req(struct io_kiocb *req)
6072 io_poll_mark_cancelled(req);
6073 /* kick tw, which should complete the request */
6074 io_poll_execute(req, 0, 0);
6077 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6078 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6080 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6083 struct io_kiocb *req = wqe_to_req(wait);
6084 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6086 __poll_t mask = key_to_poll(key);
6088 if (unlikely(mask & POLLFREE)) {
6089 io_poll_mark_cancelled(req);
6090 /* we have to kick tw in case it's not already */
6091 io_poll_execute(req, 0, poll->events);
6094 * If the waitqueue is being freed early but someone is already
6095 * holds ownership over it, we have to tear down the request as
6096 * best we can. That means immediately removing the request from
6097 * its waitqueue and preventing all further accesses to the
6098 * waitqueue via the request.
6100 list_del_init(&poll->wait.entry);
6103 * Careful: this *must* be the last step, since as soon
6104 * as req->head is NULL'ed out, the request can be
6105 * completed and freed, since aio_poll_complete_work()
6106 * will no longer need to take the waitqueue lock.
6108 smp_store_release(&poll->head, NULL);
6112 /* for instances that support it check for an event match first */
6113 if (mask && !(mask & poll->events))
6116 if (io_poll_get_ownership(req)) {
6117 /* optional, saves extra locking for removal in tw handler */
6118 if (mask && poll->events & EPOLLONESHOT) {
6119 list_del_init(&poll->wait.entry);
6121 if (wqe_is_double(wait))
6122 req->flags &= ~REQ_F_DOUBLE_POLL;
6124 req->flags &= ~REQ_F_SINGLE_POLL;
6126 __io_poll_execute(req, mask, poll->events);
6131 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6132 struct wait_queue_head *head,
6133 struct io_poll_iocb **poll_ptr)
6135 struct io_kiocb *req = pt->req;
6136 unsigned long wqe_private = (unsigned long) req;
6139 * The file being polled uses multiple waitqueues for poll handling
6140 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6143 if (unlikely(pt->nr_entries)) {
6144 struct io_poll_iocb *first = poll;
6146 /* double add on the same waitqueue head, ignore */
6147 if (first->head == head)
6149 /* already have a 2nd entry, fail a third attempt */
6151 if ((*poll_ptr)->head == head)
6153 pt->error = -EINVAL;
6157 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6159 pt->error = -ENOMEM;
6162 /* mark as double wq entry */
6164 req->flags |= REQ_F_DOUBLE_POLL;
6165 io_init_poll_iocb(poll, first->events, first->wait.func);
6167 if (req->opcode == IORING_OP_POLL_ADD)
6168 req->flags |= REQ_F_ASYNC_DATA;
6171 req->flags |= REQ_F_SINGLE_POLL;
6174 poll->wait.private = (void *) wqe_private;
6176 if (poll->events & EPOLLEXCLUSIVE)
6177 add_wait_queue_exclusive(head, &poll->wait);
6179 add_wait_queue(head, &poll->wait);
6182 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6183 struct poll_table_struct *p)
6185 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6187 __io_queue_proc(&pt->req->poll, pt, head,
6188 (struct io_poll_iocb **) &pt->req->async_data);
6191 static int __io_arm_poll_handler(struct io_kiocb *req,
6192 struct io_poll_iocb *poll,
6193 struct io_poll_table *ipt, __poll_t mask)
6195 struct io_ring_ctx *ctx = req->ctx;
6198 INIT_HLIST_NODE(&req->hash_node);
6199 io_init_poll_iocb(poll, mask, io_poll_wake);
6200 poll->file = req->file;
6202 ipt->pt._key = mask;
6205 ipt->nr_entries = 0;
6208 * Take the ownership to delay any tw execution up until we're done
6209 * with poll arming. see io_poll_get_ownership().
6211 atomic_set(&req->poll_refs, 1);
6212 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6214 if (mask && (poll->events & EPOLLONESHOT)) {
6215 io_poll_remove_entries(req);
6216 /* no one else has access to the req, forget about the ref */
6219 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6220 io_poll_remove_entries(req);
6222 ipt->error = -EINVAL;
6226 spin_lock(&ctx->completion_lock);
6227 io_poll_req_insert(req);
6228 spin_unlock(&ctx->completion_lock);
6231 /* can't multishot if failed, just queue the event we've got */
6232 if (unlikely(ipt->error || !ipt->nr_entries))
6233 poll->events |= EPOLLONESHOT;
6234 __io_poll_execute(req, mask, poll->events);
6237 io_add_napi(req->file, req->ctx);
6240 * Release ownership. If someone tried to queue a tw while it was
6241 * locked, kick it off for them.
6243 v = atomic_dec_return(&req->poll_refs);
6244 if (unlikely(v & IO_POLL_REF_MASK))
6245 __io_poll_execute(req, 0, poll->events);
6249 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6250 struct poll_table_struct *p)
6252 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6253 struct async_poll *apoll = pt->req->apoll;
6255 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6264 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6266 const struct io_op_def *def = &io_op_defs[req->opcode];
6267 struct io_ring_ctx *ctx = req->ctx;
6268 struct async_poll *apoll;
6269 struct io_poll_table ipt;
6270 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6273 if (!def->pollin && !def->pollout)
6274 return IO_APOLL_ABORTED;
6275 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6276 return IO_APOLL_ABORTED;
6279 mask |= POLLIN | POLLRDNORM;
6281 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6282 if ((req->opcode == IORING_OP_RECVMSG) &&
6283 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6286 mask |= POLLOUT | POLLWRNORM;
6288 if (def->poll_exclusive)
6289 mask |= EPOLLEXCLUSIVE;
6290 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6291 !list_empty(&ctx->apoll_cache)) {
6292 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6294 list_del_init(&apoll->poll.wait.entry);
6296 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6297 if (unlikely(!apoll))
6298 return IO_APOLL_ABORTED;
6300 apoll->double_poll = NULL;
6302 req->flags |= REQ_F_POLLED;
6303 ipt.pt._qproc = io_async_queue_proc;
6305 io_kbuf_recycle(req, issue_flags);
6307 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6308 if (ret || ipt.error)
6309 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6311 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6312 mask, apoll->poll.events);
6317 * Returns true if we found and killed one or more poll requests
6319 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6320 struct task_struct *tsk, bool cancel_all)
6322 struct hlist_node *tmp;
6323 struct io_kiocb *req;
6327 spin_lock(&ctx->completion_lock);
6328 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6329 struct hlist_head *list;
6331 list = &ctx->cancel_hash[i];
6332 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6333 if (io_match_task_safe(req, tsk, cancel_all)) {
6334 hlist_del_init(&req->hash_node);
6335 io_poll_cancel_req(req);
6340 spin_unlock(&ctx->completion_lock);
6344 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6346 __must_hold(&ctx->completion_lock)
6348 struct hlist_head *list;
6349 struct io_kiocb *req;
6351 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6352 hlist_for_each_entry(req, list, hash_node) {
6353 if (sqe_addr != req->user_data)
6355 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6362 static bool io_poll_disarm(struct io_kiocb *req)
6363 __must_hold(&ctx->completion_lock)
6365 if (!io_poll_get_ownership(req))
6367 io_poll_remove_entries(req);
6368 hash_del(&req->hash_node);
6372 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6374 __must_hold(&ctx->completion_lock)
6376 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6380 io_poll_cancel_req(req);
6384 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6389 events = READ_ONCE(sqe->poll32_events);
6391 events = swahw32(events);
6393 if (!(flags & IORING_POLL_ADD_MULTI))
6394 events |= EPOLLONESHOT;
6395 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6398 static int io_poll_update_prep(struct io_kiocb *req,
6399 const struct io_uring_sqe *sqe)
6401 struct io_poll_update *upd = &req->poll_update;
6404 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6406 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6408 flags = READ_ONCE(sqe->len);
6409 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6410 IORING_POLL_ADD_MULTI))
6412 /* meaningless without update */
6413 if (flags == IORING_POLL_ADD_MULTI)
6416 upd->old_user_data = READ_ONCE(sqe->addr);
6417 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6418 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6420 upd->new_user_data = READ_ONCE(sqe->off);
6421 if (!upd->update_user_data && upd->new_user_data)
6423 if (upd->update_events)
6424 upd->events = io_poll_parse_events(sqe, flags);
6425 else if (sqe->poll32_events)
6431 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6433 struct io_poll_iocb *poll = &req->poll;
6436 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6438 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6440 flags = READ_ONCE(sqe->len);
6441 if (flags & ~IORING_POLL_ADD_MULTI)
6443 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6446 io_req_set_refcount(req);
6447 req->cflags = poll->events = io_poll_parse_events(sqe, flags);
6451 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6453 struct io_poll_iocb *poll = &req->poll;
6454 struct io_poll_table ipt;
6457 ipt.pt._qproc = io_poll_queue_proc;
6459 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6460 ret = ret ?: ipt.error;
6462 __io_req_complete(req, issue_flags, ret, 0);
6466 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6468 struct io_ring_ctx *ctx = req->ctx;
6469 struct io_kiocb *preq;
6473 spin_lock(&ctx->completion_lock);
6474 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6475 if (!preq || !io_poll_disarm(preq)) {
6476 spin_unlock(&ctx->completion_lock);
6477 ret = preq ? -EALREADY : -ENOENT;
6480 spin_unlock(&ctx->completion_lock);
6482 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6483 /* only mask one event flags, keep behavior flags */
6484 if (req->poll_update.update_events) {
6485 preq->poll.events &= ~0xffff;
6486 preq->poll.events |= req->poll_update.events & 0xffff;
6487 preq->poll.events |= IO_POLL_UNMASK;
6489 if (req->poll_update.update_user_data)
6490 preq->user_data = req->poll_update.new_user_data;
6492 ret2 = io_poll_add(preq, issue_flags);
6493 /* successfully updated, don't complete poll request */
6499 preq->result = -ECANCELED;
6500 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6501 io_req_task_complete(preq, &locked);
6505 /* complete update request, we're done with it */
6506 __io_req_complete(req, issue_flags, ret, 0);
6510 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6512 struct io_timeout_data *data = container_of(timer,
6513 struct io_timeout_data, timer);
6514 struct io_kiocb *req = data->req;
6515 struct io_ring_ctx *ctx = req->ctx;
6516 unsigned long flags;
6518 spin_lock_irqsave(&ctx->timeout_lock, flags);
6519 list_del_init(&req->timeout.list);
6520 atomic_set(&req->ctx->cq_timeouts,
6521 atomic_read(&req->ctx->cq_timeouts) + 1);
6522 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6524 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6527 req->result = -ETIME;
6528 req->io_task_work.func = io_req_task_complete;
6529 io_req_task_work_add(req, false);
6530 return HRTIMER_NORESTART;
6533 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6535 __must_hold(&ctx->timeout_lock)
6537 struct io_timeout_data *io;
6538 struct io_kiocb *req;
6541 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6542 found = user_data == req->user_data;
6547 return ERR_PTR(-ENOENT);
6549 io = req->async_data;
6550 if (hrtimer_try_to_cancel(&io->timer) == -1)
6551 return ERR_PTR(-EALREADY);
6552 list_del_init(&req->timeout.list);
6556 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6557 __must_hold(&ctx->completion_lock)
6558 __must_hold(&ctx->timeout_lock)
6560 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6563 return PTR_ERR(req);
6564 io_req_task_queue_fail(req, -ECANCELED);
6568 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6570 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6571 case IORING_TIMEOUT_BOOTTIME:
6572 return CLOCK_BOOTTIME;
6573 case IORING_TIMEOUT_REALTIME:
6574 return CLOCK_REALTIME;
6576 /* can't happen, vetted at prep time */
6580 return CLOCK_MONOTONIC;
6584 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6585 struct timespec64 *ts, enum hrtimer_mode mode)
6586 __must_hold(&ctx->timeout_lock)
6588 struct io_timeout_data *io;
6589 struct io_kiocb *req;
6592 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6593 found = user_data == req->user_data;
6600 io = req->async_data;
6601 if (hrtimer_try_to_cancel(&io->timer) == -1)
6603 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6604 io->timer.function = io_link_timeout_fn;
6605 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6609 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6610 struct timespec64 *ts, enum hrtimer_mode mode)
6611 __must_hold(&ctx->timeout_lock)
6613 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6614 struct io_timeout_data *data;
6617 return PTR_ERR(req);
6619 req->timeout.off = 0; /* noseq */
6620 data = req->async_data;
6621 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6622 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6623 data->timer.function = io_timeout_fn;
6624 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6628 static int io_timeout_remove_prep(struct io_kiocb *req,
6629 const struct io_uring_sqe *sqe)
6631 struct io_timeout_rem *tr = &req->timeout_rem;
6633 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6635 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6637 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6640 tr->ltimeout = false;
6641 tr->addr = READ_ONCE(sqe->addr);
6642 tr->flags = READ_ONCE(sqe->timeout_flags);
6643 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6644 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6646 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6647 tr->ltimeout = true;
6648 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6650 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6652 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6654 } else if (tr->flags) {
6655 /* timeout removal doesn't support flags */
6662 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6664 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6669 * Remove or update an existing timeout command
6671 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6673 struct io_timeout_rem *tr = &req->timeout_rem;
6674 struct io_ring_ctx *ctx = req->ctx;
6677 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6678 spin_lock(&ctx->completion_lock);
6679 spin_lock_irq(&ctx->timeout_lock);
6680 ret = io_timeout_cancel(ctx, tr->addr);
6681 spin_unlock_irq(&ctx->timeout_lock);
6682 spin_unlock(&ctx->completion_lock);
6684 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6686 spin_lock_irq(&ctx->timeout_lock);
6688 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6690 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6691 spin_unlock_irq(&ctx->timeout_lock);
6696 io_req_complete_post(req, ret, 0);
6700 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6701 bool is_timeout_link)
6703 struct io_timeout_data *data;
6705 u32 off = READ_ONCE(sqe->off);
6707 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6709 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6712 if (off && is_timeout_link)
6714 flags = READ_ONCE(sqe->timeout_flags);
6715 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6716 IORING_TIMEOUT_ETIME_SUCCESS))
6718 /* more than one clock specified is invalid, obviously */
6719 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6722 INIT_LIST_HEAD(&req->timeout.list);
6723 req->timeout.off = off;
6724 if (unlikely(off && !req->ctx->off_timeout_used))
6725 req->ctx->off_timeout_used = true;
6727 if (WARN_ON_ONCE(req_has_async_data(req)))
6729 if (io_alloc_async_data(req))
6732 data = req->async_data;
6734 data->flags = flags;
6736 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6739 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6742 data->mode = io_translate_timeout_mode(flags);
6743 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6745 if (is_timeout_link) {
6746 struct io_submit_link *link = &req->ctx->submit_state.link;
6750 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6752 req->timeout.head = link->last;
6753 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6758 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6760 struct io_ring_ctx *ctx = req->ctx;
6761 struct io_timeout_data *data = req->async_data;
6762 struct list_head *entry;
6763 u32 tail, off = req->timeout.off;
6765 spin_lock_irq(&ctx->timeout_lock);
6768 * sqe->off holds how many events that need to occur for this
6769 * timeout event to be satisfied. If it isn't set, then this is
6770 * a pure timeout request, sequence isn't used.
6772 if (io_is_timeout_noseq(req)) {
6773 entry = ctx->timeout_list.prev;
6777 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6778 req->timeout.target_seq = tail + off;
6780 /* Update the last seq here in case io_flush_timeouts() hasn't.
6781 * This is safe because ->completion_lock is held, and submissions
6782 * and completions are never mixed in the same ->completion_lock section.
6784 ctx->cq_last_tm_flush = tail;
6787 * Insertion sort, ensuring the first entry in the list is always
6788 * the one we need first.
6790 list_for_each_prev(entry, &ctx->timeout_list) {
6791 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6794 if (io_is_timeout_noseq(nxt))
6796 /* nxt.seq is behind @tail, otherwise would've been completed */
6797 if (off >= nxt->timeout.target_seq - tail)
6801 list_add(&req->timeout.list, entry);
6802 data->timer.function = io_timeout_fn;
6803 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6804 spin_unlock_irq(&ctx->timeout_lock);
6808 struct io_cancel_data {
6809 struct io_ring_ctx *ctx;
6813 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6815 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6816 struct io_cancel_data *cd = data;
6818 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6821 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6822 struct io_ring_ctx *ctx)
6824 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6825 enum io_wq_cancel cancel_ret;
6828 if (!tctx || !tctx->io_wq)
6831 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6832 switch (cancel_ret) {
6833 case IO_WQ_CANCEL_OK:
6836 case IO_WQ_CANCEL_RUNNING:
6839 case IO_WQ_CANCEL_NOTFOUND:
6847 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6849 struct io_ring_ctx *ctx = req->ctx;
6852 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6854 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6856 * Fall-through even for -EALREADY, as we may have poll armed
6857 * that need unarming.
6862 spin_lock(&ctx->completion_lock);
6863 ret = io_poll_cancel(ctx, sqe_addr, false);
6867 spin_lock_irq(&ctx->timeout_lock);
6868 ret = io_timeout_cancel(ctx, sqe_addr);
6869 spin_unlock_irq(&ctx->timeout_lock);
6871 spin_unlock(&ctx->completion_lock);
6875 static int io_async_cancel_prep(struct io_kiocb *req,
6876 const struct io_uring_sqe *sqe)
6878 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6880 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6882 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6886 req->cancel.addr = READ_ONCE(sqe->addr);
6890 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6892 struct io_ring_ctx *ctx = req->ctx;
6893 u64 sqe_addr = req->cancel.addr;
6894 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6895 struct io_tctx_node *node;
6898 ret = io_try_cancel_userdata(req, sqe_addr);
6902 /* slow path, try all io-wq's */
6903 io_ring_submit_lock(ctx, needs_lock);
6905 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6906 struct io_uring_task *tctx = node->task->io_uring;
6908 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6912 io_ring_submit_unlock(ctx, needs_lock);
6916 io_req_complete_post(req, ret, 0);
6920 static int io_rsrc_update_prep(struct io_kiocb *req,
6921 const struct io_uring_sqe *sqe)
6923 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6925 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6928 req->rsrc_update.offset = READ_ONCE(sqe->off);
6929 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6930 if (!req->rsrc_update.nr_args)
6932 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6936 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6938 struct io_ring_ctx *ctx = req->ctx;
6939 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6940 struct io_uring_rsrc_update2 up;
6943 up.offset = req->rsrc_update.offset;
6944 up.data = req->rsrc_update.arg;
6949 io_ring_submit_lock(ctx, needs_lock);
6950 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6951 &up, req->rsrc_update.nr_args);
6952 io_ring_submit_unlock(ctx, needs_lock);
6956 __io_req_complete(req, issue_flags, ret, 0);
6960 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6962 switch (req->opcode) {
6965 case IORING_OP_READV:
6966 case IORING_OP_READ_FIXED:
6967 case IORING_OP_READ:
6968 return io_read_prep(req, sqe);
6969 case IORING_OP_WRITEV:
6970 case IORING_OP_WRITE_FIXED:
6971 case IORING_OP_WRITE:
6972 return io_write_prep(req, sqe);
6973 case IORING_OP_POLL_ADD:
6974 return io_poll_add_prep(req, sqe);
6975 case IORING_OP_POLL_REMOVE:
6976 return io_poll_update_prep(req, sqe);
6977 case IORING_OP_FSYNC:
6978 return io_fsync_prep(req, sqe);
6979 case IORING_OP_SYNC_FILE_RANGE:
6980 return io_sfr_prep(req, sqe);
6981 case IORING_OP_SENDMSG:
6982 case IORING_OP_SEND:
6983 return io_sendmsg_prep(req, sqe);
6984 case IORING_OP_RECVMSG:
6985 case IORING_OP_RECV:
6986 return io_recvmsg_prep(req, sqe);
6987 case IORING_OP_CONNECT:
6988 return io_connect_prep(req, sqe);
6989 case IORING_OP_TIMEOUT:
6990 return io_timeout_prep(req, sqe, false);
6991 case IORING_OP_TIMEOUT_REMOVE:
6992 return io_timeout_remove_prep(req, sqe);
6993 case IORING_OP_ASYNC_CANCEL:
6994 return io_async_cancel_prep(req, sqe);
6995 case IORING_OP_LINK_TIMEOUT:
6996 return io_timeout_prep(req, sqe, true);
6997 case IORING_OP_ACCEPT:
6998 return io_accept_prep(req, sqe);
6999 case IORING_OP_FALLOCATE:
7000 return io_fallocate_prep(req, sqe);
7001 case IORING_OP_OPENAT:
7002 return io_openat_prep(req, sqe);
7003 case IORING_OP_CLOSE:
7004 return io_close_prep(req, sqe);
7005 case IORING_OP_FILES_UPDATE:
7006 return io_rsrc_update_prep(req, sqe);
7007 case IORING_OP_STATX:
7008 return io_statx_prep(req, sqe);
7009 case IORING_OP_FADVISE:
7010 return io_fadvise_prep(req, sqe);
7011 case IORING_OP_MADVISE:
7012 return io_madvise_prep(req, sqe);
7013 case IORING_OP_OPENAT2:
7014 return io_openat2_prep(req, sqe);
7015 case IORING_OP_EPOLL_CTL:
7016 return io_epoll_ctl_prep(req, sqe);
7017 case IORING_OP_SPLICE:
7018 return io_splice_prep(req, sqe);
7019 case IORING_OP_PROVIDE_BUFFERS:
7020 return io_provide_buffers_prep(req, sqe);
7021 case IORING_OP_REMOVE_BUFFERS:
7022 return io_remove_buffers_prep(req, sqe);
7024 return io_tee_prep(req, sqe);
7025 case IORING_OP_SHUTDOWN:
7026 return io_shutdown_prep(req, sqe);
7027 case IORING_OP_RENAMEAT:
7028 return io_renameat_prep(req, sqe);
7029 case IORING_OP_UNLINKAT:
7030 return io_unlinkat_prep(req, sqe);
7031 case IORING_OP_MKDIRAT:
7032 return io_mkdirat_prep(req, sqe);
7033 case IORING_OP_SYMLINKAT:
7034 return io_symlinkat_prep(req, sqe);
7035 case IORING_OP_LINKAT:
7036 return io_linkat_prep(req, sqe);
7037 case IORING_OP_MSG_RING:
7038 return io_msg_ring_prep(req, sqe);
7041 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
7046 static int io_req_prep_async(struct io_kiocb *req)
7048 if (!io_op_defs[req->opcode].needs_async_setup)
7050 if (WARN_ON_ONCE(req_has_async_data(req)))
7052 if (io_alloc_async_data(req))
7055 switch (req->opcode) {
7056 case IORING_OP_READV:
7057 return io_rw_prep_async(req, READ);
7058 case IORING_OP_WRITEV:
7059 return io_rw_prep_async(req, WRITE);
7060 case IORING_OP_SENDMSG:
7061 return io_sendmsg_prep_async(req);
7062 case IORING_OP_RECVMSG:
7063 return io_recvmsg_prep_async(req);
7064 case IORING_OP_CONNECT:
7065 return io_connect_prep_async(req);
7067 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7072 static u32 io_get_sequence(struct io_kiocb *req)
7074 u32 seq = req->ctx->cached_sq_head;
7076 /* need original cached_sq_head, but it was increased for each req */
7077 io_for_each_link(req, req)
7082 static __cold void io_drain_req(struct io_kiocb *req)
7084 struct io_ring_ctx *ctx = req->ctx;
7085 struct io_defer_entry *de;
7087 u32 seq = io_get_sequence(req);
7089 /* Still need defer if there is pending req in defer list. */
7090 spin_lock(&ctx->completion_lock);
7091 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7092 spin_unlock(&ctx->completion_lock);
7094 ctx->drain_active = false;
7095 io_req_task_queue(req);
7098 spin_unlock(&ctx->completion_lock);
7100 ret = io_req_prep_async(req);
7103 io_req_complete_failed(req, ret);
7106 io_prep_async_link(req);
7107 de = kmalloc(sizeof(*de), GFP_KERNEL);
7113 spin_lock(&ctx->completion_lock);
7114 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7115 spin_unlock(&ctx->completion_lock);
7120 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7123 list_add_tail(&de->list, &ctx->defer_list);
7124 spin_unlock(&ctx->completion_lock);
7127 static void io_clean_op(struct io_kiocb *req)
7129 if (req->flags & REQ_F_BUFFER_SELECTED)
7130 io_put_kbuf_comp(req);
7132 if (req->flags & REQ_F_NEED_CLEANUP) {
7133 switch (req->opcode) {
7134 case IORING_OP_READV:
7135 case IORING_OP_READ_FIXED:
7136 case IORING_OP_READ:
7137 case IORING_OP_WRITEV:
7138 case IORING_OP_WRITE_FIXED:
7139 case IORING_OP_WRITE: {
7140 struct io_async_rw *io = req->async_data;
7142 kfree(io->free_iovec);
7145 case IORING_OP_RECVMSG:
7146 case IORING_OP_SENDMSG: {
7147 struct io_async_msghdr *io = req->async_data;
7149 kfree(io->free_iov);
7152 case IORING_OP_SPLICE:
7154 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
7155 io_put_file(req->splice.file_in);
7157 case IORING_OP_OPENAT:
7158 case IORING_OP_OPENAT2:
7159 if (req->open.filename)
7160 putname(req->open.filename);
7162 case IORING_OP_RENAMEAT:
7163 putname(req->rename.oldpath);
7164 putname(req->rename.newpath);
7166 case IORING_OP_UNLINKAT:
7167 putname(req->unlink.filename);
7169 case IORING_OP_MKDIRAT:
7170 putname(req->mkdir.filename);
7172 case IORING_OP_SYMLINKAT:
7173 putname(req->symlink.oldpath);
7174 putname(req->symlink.newpath);
7176 case IORING_OP_LINKAT:
7177 putname(req->hardlink.oldpath);
7178 putname(req->hardlink.newpath);
7182 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7183 kfree(req->apoll->double_poll);
7187 if (req->flags & REQ_F_INFLIGHT) {
7188 struct io_uring_task *tctx = req->task->io_uring;
7190 atomic_dec(&tctx->inflight_tracked);
7192 if (req->flags & REQ_F_CREDS)
7193 put_cred(req->creds);
7194 if (req->flags & REQ_F_ASYNC_DATA) {
7195 kfree(req->async_data);
7196 req->async_data = NULL;
7198 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7201 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7203 const struct cred *creds = NULL;
7206 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7207 creds = override_creds(req->creds);
7209 if (!io_op_defs[req->opcode].audit_skip)
7210 audit_uring_entry(req->opcode);
7212 switch (req->opcode) {
7214 ret = io_nop(req, issue_flags);
7216 case IORING_OP_READV:
7217 case IORING_OP_READ_FIXED:
7218 case IORING_OP_READ:
7219 ret = io_read(req, issue_flags);
7221 case IORING_OP_WRITEV:
7222 case IORING_OP_WRITE_FIXED:
7223 case IORING_OP_WRITE:
7224 ret = io_write(req, issue_flags);
7226 case IORING_OP_FSYNC:
7227 ret = io_fsync(req, issue_flags);
7229 case IORING_OP_POLL_ADD:
7230 ret = io_poll_add(req, issue_flags);
7232 case IORING_OP_POLL_REMOVE:
7233 ret = io_poll_update(req, issue_flags);
7235 case IORING_OP_SYNC_FILE_RANGE:
7236 ret = io_sync_file_range(req, issue_flags);
7238 case IORING_OP_SENDMSG:
7239 ret = io_sendmsg(req, issue_flags);
7241 case IORING_OP_SEND:
7242 ret = io_send(req, issue_flags);
7244 case IORING_OP_RECVMSG:
7245 ret = io_recvmsg(req, issue_flags);
7247 case IORING_OP_RECV:
7248 ret = io_recv(req, issue_flags);
7250 case IORING_OP_TIMEOUT:
7251 ret = io_timeout(req, issue_flags);
7253 case IORING_OP_TIMEOUT_REMOVE:
7254 ret = io_timeout_remove(req, issue_flags);
7256 case IORING_OP_ACCEPT:
7257 ret = io_accept(req, issue_flags);
7259 case IORING_OP_CONNECT:
7260 ret = io_connect(req, issue_flags);
7262 case IORING_OP_ASYNC_CANCEL:
7263 ret = io_async_cancel(req, issue_flags);
7265 case IORING_OP_FALLOCATE:
7266 ret = io_fallocate(req, issue_flags);
7268 case IORING_OP_OPENAT:
7269 ret = io_openat(req, issue_flags);
7271 case IORING_OP_CLOSE:
7272 ret = io_close(req, issue_flags);
7274 case IORING_OP_FILES_UPDATE:
7275 ret = io_files_update(req, issue_flags);
7277 case IORING_OP_STATX:
7278 ret = io_statx(req, issue_flags);
7280 case IORING_OP_FADVISE:
7281 ret = io_fadvise(req, issue_flags);
7283 case IORING_OP_MADVISE:
7284 ret = io_madvise(req, issue_flags);
7286 case IORING_OP_OPENAT2:
7287 ret = io_openat2(req, issue_flags);
7289 case IORING_OP_EPOLL_CTL:
7290 ret = io_epoll_ctl(req, issue_flags);
7292 case IORING_OP_SPLICE:
7293 ret = io_splice(req, issue_flags);
7295 case IORING_OP_PROVIDE_BUFFERS:
7296 ret = io_provide_buffers(req, issue_flags);
7298 case IORING_OP_REMOVE_BUFFERS:
7299 ret = io_remove_buffers(req, issue_flags);
7302 ret = io_tee(req, issue_flags);
7304 case IORING_OP_SHUTDOWN:
7305 ret = io_shutdown(req, issue_flags);
7307 case IORING_OP_RENAMEAT:
7308 ret = io_renameat(req, issue_flags);
7310 case IORING_OP_UNLINKAT:
7311 ret = io_unlinkat(req, issue_flags);
7313 case IORING_OP_MKDIRAT:
7314 ret = io_mkdirat(req, issue_flags);
7316 case IORING_OP_SYMLINKAT:
7317 ret = io_symlinkat(req, issue_flags);
7319 case IORING_OP_LINKAT:
7320 ret = io_linkat(req, issue_flags);
7322 case IORING_OP_MSG_RING:
7323 ret = io_msg_ring(req, issue_flags);
7330 if (!io_op_defs[req->opcode].audit_skip)
7331 audit_uring_exit(!ret, ret);
7334 revert_creds(creds);
7337 /* If the op doesn't have a file, we're not polling for it */
7338 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7339 io_iopoll_req_issued(req, issue_flags);
7344 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7346 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7348 req = io_put_req_find_next(req);
7349 return req ? &req->work : NULL;
7352 static void io_wq_submit_work(struct io_wq_work *work)
7354 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7355 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7356 bool needs_poll = false;
7357 struct io_kiocb *timeout;
7360 /* one will be dropped by ->io_free_work() after returning to io-wq */
7361 if (!(req->flags & REQ_F_REFCOUNT))
7362 __io_req_set_refcount(req, 2);
7366 timeout = io_prep_linked_timeout(req);
7368 io_queue_linked_timeout(timeout);
7370 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7371 if (work->flags & IO_WQ_WORK_CANCEL) {
7372 io_req_task_queue_fail(req, -ECANCELED);
7376 if (req->flags & REQ_F_FORCE_ASYNC) {
7377 const struct io_op_def *def = &io_op_defs[req->opcode];
7378 bool opcode_poll = def->pollin || def->pollout;
7380 if (opcode_poll && file_can_poll(req->file)) {
7382 issue_flags |= IO_URING_F_NONBLOCK;
7387 ret = io_issue_sqe(req, issue_flags);
7391 * We can get EAGAIN for iopolled IO even though we're
7392 * forcing a sync submission from here, since we can't
7393 * wait for request slots on the block side.
7400 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7402 /* aborted or ready, in either case retry blocking */
7404 issue_flags &= ~IO_URING_F_NONBLOCK;
7407 /* avoid locking problems by failing it from a clean context */
7409 io_req_task_queue_fail(req, ret);
7412 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7415 return &table->files[i];
7418 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7421 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7423 return (struct file *) (slot->file_ptr & FFS_MASK);
7426 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7428 unsigned long file_ptr = (unsigned long) file;
7430 file_ptr |= io_file_get_flags(file);
7431 file_slot->file_ptr = file_ptr;
7434 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7435 struct io_kiocb *req, int fd)
7438 unsigned long file_ptr;
7440 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7442 fd = array_index_nospec(fd, ctx->nr_user_files);
7443 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7444 file = (struct file *) (file_ptr & FFS_MASK);
7445 file_ptr &= ~FFS_MASK;
7446 /* mask in overlapping REQ_F and FFS bits */
7447 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7448 io_req_set_rsrc_node(req, ctx);
7452 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7453 struct io_kiocb *req, int fd)
7455 struct file *file = fget(fd);
7457 trace_io_uring_file_get(ctx, req, req->user_data, fd);
7459 /* we don't allow fixed io_uring files */
7460 if (file && unlikely(file->f_op == &io_uring_fops))
7461 io_req_track_inflight(req);
7465 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7466 struct io_kiocb *req, int fd, bool fixed)
7469 return io_file_get_fixed(ctx, req, fd);
7471 return io_file_get_normal(ctx, req, fd);
7474 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7476 struct io_kiocb *prev = req->timeout.prev;
7480 if (!(req->task->flags & PF_EXITING))
7481 ret = io_try_cancel_userdata(req, prev->user_data);
7482 io_req_complete_post(req, ret ?: -ETIME, 0);
7485 io_req_complete_post(req, -ETIME, 0);
7489 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7491 struct io_timeout_data *data = container_of(timer,
7492 struct io_timeout_data, timer);
7493 struct io_kiocb *prev, *req = data->req;
7494 struct io_ring_ctx *ctx = req->ctx;
7495 unsigned long flags;
7497 spin_lock_irqsave(&ctx->timeout_lock, flags);
7498 prev = req->timeout.head;
7499 req->timeout.head = NULL;
7502 * We don't expect the list to be empty, that will only happen if we
7503 * race with the completion of the linked work.
7506 io_remove_next_linked(prev);
7507 if (!req_ref_inc_not_zero(prev))
7510 list_del(&req->timeout.list);
7511 req->timeout.prev = prev;
7512 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7514 req->io_task_work.func = io_req_task_link_timeout;
7515 io_req_task_work_add(req, false);
7516 return HRTIMER_NORESTART;
7519 static void io_queue_linked_timeout(struct io_kiocb *req)
7521 struct io_ring_ctx *ctx = req->ctx;
7523 spin_lock_irq(&ctx->timeout_lock);
7525 * If the back reference is NULL, then our linked request finished
7526 * before we got a chance to setup the timer
7528 if (req->timeout.head) {
7529 struct io_timeout_data *data = req->async_data;
7531 data->timer.function = io_link_timeout_fn;
7532 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7534 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7536 spin_unlock_irq(&ctx->timeout_lock);
7537 /* drop submission reference */
7541 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7542 __must_hold(&req->ctx->uring_lock)
7544 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7546 switch (io_arm_poll_handler(req, 0)) {
7547 case IO_APOLL_READY:
7548 io_req_task_queue(req);
7550 case IO_APOLL_ABORTED:
7552 * Queued up for async execution, worker will release
7553 * submit reference when the iocb is actually submitted.
7555 io_queue_async_work(req, NULL);
7562 io_queue_linked_timeout(linked_timeout);
7565 static inline void __io_queue_sqe(struct io_kiocb *req)
7566 __must_hold(&req->ctx->uring_lock)
7568 struct io_kiocb *linked_timeout;
7571 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7573 if (req->flags & REQ_F_COMPLETE_INLINE) {
7574 io_req_add_compl_list(req);
7578 * We async punt it if the file wasn't marked NOWAIT, or if the file
7579 * doesn't support non-blocking read/write attempts
7582 linked_timeout = io_prep_linked_timeout(req);
7584 io_queue_linked_timeout(linked_timeout);
7585 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7586 io_queue_sqe_arm_apoll(req);
7588 io_req_complete_failed(req, ret);
7592 static void io_queue_sqe_fallback(struct io_kiocb *req)
7593 __must_hold(&req->ctx->uring_lock)
7595 if (req->flags & REQ_F_FAIL) {
7596 io_req_complete_fail_submit(req);
7597 } else if (unlikely(req->ctx->drain_active)) {
7600 int ret = io_req_prep_async(req);
7603 io_req_complete_failed(req, ret);
7605 io_queue_async_work(req, NULL);
7609 static inline void io_queue_sqe(struct io_kiocb *req)
7610 __must_hold(&req->ctx->uring_lock)
7612 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7613 __io_queue_sqe(req);
7615 io_queue_sqe_fallback(req);
7619 * Check SQE restrictions (opcode and flags).
7621 * Returns 'true' if SQE is allowed, 'false' otherwise.
7623 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7624 struct io_kiocb *req,
7625 unsigned int sqe_flags)
7627 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7630 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7631 ctx->restrictions.sqe_flags_required)
7634 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7635 ctx->restrictions.sqe_flags_required))
7641 static void io_init_req_drain(struct io_kiocb *req)
7643 struct io_ring_ctx *ctx = req->ctx;
7644 struct io_kiocb *head = ctx->submit_state.link.head;
7646 ctx->drain_active = true;
7649 * If we need to drain a request in the middle of a link, drain
7650 * the head request and the next request/link after the current
7651 * link. Considering sequential execution of links,
7652 * REQ_F_IO_DRAIN will be maintained for every request of our
7655 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7656 ctx->drain_next = true;
7660 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7661 const struct io_uring_sqe *sqe)
7662 __must_hold(&ctx->uring_lock)
7664 unsigned int sqe_flags;
7668 /* req is partially pre-initialised, see io_preinit_req() */
7669 req->opcode = opcode = READ_ONCE(sqe->opcode);
7670 /* same numerical values with corresponding REQ_F_*, safe to copy */
7671 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7672 req->user_data = READ_ONCE(sqe->user_data);
7674 req->fixed_rsrc_refs = NULL;
7675 req->task = current;
7677 if (unlikely(opcode >= IORING_OP_LAST)) {
7681 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7682 /* enforce forwards compatibility on users */
7683 if (sqe_flags & ~SQE_VALID_FLAGS)
7685 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7686 !io_op_defs[opcode].buffer_select)
7688 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7689 ctx->drain_disabled = true;
7690 if (sqe_flags & IOSQE_IO_DRAIN) {
7691 if (ctx->drain_disabled)
7693 io_init_req_drain(req);
7696 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7697 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7699 /* knock it to the slow queue path, will be drained there */
7700 if (ctx->drain_active)
7701 req->flags |= REQ_F_FORCE_ASYNC;
7702 /* if there is no link, we're at "next" request and need to drain */
7703 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7704 ctx->drain_next = false;
7705 ctx->drain_active = true;
7706 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7710 if (io_op_defs[opcode].needs_file) {
7711 struct io_submit_state *state = &ctx->submit_state;
7714 * Plug now if we have more than 2 IO left after this, and the
7715 * target is potentially a read/write to block based storage.
7717 if (state->need_plug && io_op_defs[opcode].plug) {
7718 state->plug_started = true;
7719 state->need_plug = false;
7720 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7723 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7724 (sqe_flags & IOSQE_FIXED_FILE));
7725 if (unlikely(!req->file))
7729 personality = READ_ONCE(sqe->personality);
7733 req->creds = xa_load(&ctx->personalities, personality);
7736 get_cred(req->creds);
7737 ret = security_uring_override_creds(req->creds);
7739 put_cred(req->creds);
7742 req->flags |= REQ_F_CREDS;
7745 return io_req_prep(req, sqe);
7748 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7749 const struct io_uring_sqe *sqe)
7750 __must_hold(&ctx->uring_lock)
7752 struct io_submit_link *link = &ctx->submit_state.link;
7755 ret = io_init_req(ctx, req, sqe);
7756 if (unlikely(ret)) {
7757 trace_io_uring_req_failed(sqe, ctx, req, ret);
7759 /* fail even hard links since we don't submit */
7762 * we can judge a link req is failed or cancelled by if
7763 * REQ_F_FAIL is set, but the head is an exception since
7764 * it may be set REQ_F_FAIL because of other req's failure
7765 * so let's leverage req->result to distinguish if a head
7766 * is set REQ_F_FAIL because of its failure or other req's
7767 * failure so that we can set the correct ret code for it.
7768 * init result here to avoid affecting the normal path.
7770 if (!(link->head->flags & REQ_F_FAIL))
7771 req_fail_link_node(link->head, -ECANCELED);
7772 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7774 * the current req is a normal req, we should return
7775 * error and thus break the submittion loop.
7777 io_req_complete_failed(req, ret);
7780 req_fail_link_node(req, ret);
7783 /* don't need @sqe from now on */
7784 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7786 ctx->flags & IORING_SETUP_SQPOLL);
7789 * If we already have a head request, queue this one for async
7790 * submittal once the head completes. If we don't have a head but
7791 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7792 * submitted sync once the chain is complete. If none of those
7793 * conditions are true (normal request), then just queue it.
7796 struct io_kiocb *head = link->head;
7798 if (!(req->flags & REQ_F_FAIL)) {
7799 ret = io_req_prep_async(req);
7800 if (unlikely(ret)) {
7801 req_fail_link_node(req, ret);
7802 if (!(head->flags & REQ_F_FAIL))
7803 req_fail_link_node(head, -ECANCELED);
7806 trace_io_uring_link(ctx, req, head);
7807 link->last->link = req;
7810 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7812 /* last request of a link, enqueue the link */
7815 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7826 * Batched submission is done, ensure local IO is flushed out.
7828 static void io_submit_state_end(struct io_ring_ctx *ctx)
7830 struct io_submit_state *state = &ctx->submit_state;
7832 if (state->link.head)
7833 io_queue_sqe(state->link.head);
7834 /* flush only after queuing links as they can generate completions */
7835 io_submit_flush_completions(ctx);
7836 if (state->plug_started)
7837 blk_finish_plug(&state->plug);
7841 * Start submission side cache.
7843 static void io_submit_state_start(struct io_submit_state *state,
7844 unsigned int max_ios)
7846 state->plug_started = false;
7847 state->need_plug = max_ios > 2;
7848 state->submit_nr = max_ios;
7849 /* set only head, no need to init link_last in advance */
7850 state->link.head = NULL;
7853 static void io_commit_sqring(struct io_ring_ctx *ctx)
7855 struct io_rings *rings = ctx->rings;
7858 * Ensure any loads from the SQEs are done at this point,
7859 * since once we write the new head, the application could
7860 * write new data to them.
7862 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7866 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7867 * that is mapped by userspace. This means that care needs to be taken to
7868 * ensure that reads are stable, as we cannot rely on userspace always
7869 * being a good citizen. If members of the sqe are validated and then later
7870 * used, it's important that those reads are done through READ_ONCE() to
7871 * prevent a re-load down the line.
7873 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7875 unsigned head, mask = ctx->sq_entries - 1;
7876 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7879 * The cached sq head (or cq tail) serves two purposes:
7881 * 1) allows us to batch the cost of updating the user visible
7883 * 2) allows the kernel side to track the head on its own, even
7884 * though the application is the one updating it.
7886 head = READ_ONCE(ctx->sq_array[sq_idx]);
7887 if (likely(head < ctx->sq_entries))
7888 return &ctx->sq_sqes[head];
7890 /* drop invalid entries */
7892 WRITE_ONCE(ctx->rings->sq_dropped,
7893 READ_ONCE(ctx->rings->sq_dropped) + 1);
7897 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7898 __must_hold(&ctx->uring_lock)
7900 unsigned int entries = io_sqring_entries(ctx);
7903 if (unlikely(!entries))
7905 /* make sure SQ entry isn't read before tail */
7906 nr = min3(nr, ctx->sq_entries, entries);
7907 io_get_task_refs(nr);
7909 io_submit_state_start(&ctx->submit_state, nr);
7911 const struct io_uring_sqe *sqe;
7912 struct io_kiocb *req;
7914 if (unlikely(!io_alloc_req_refill(ctx))) {
7916 submitted = -EAGAIN;
7919 req = io_alloc_req(ctx);
7920 sqe = io_get_sqe(ctx);
7921 if (unlikely(!sqe)) {
7922 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7925 /* will complete beyond this point, count as submitted */
7927 if (io_submit_sqe(ctx, req, sqe)) {
7929 * Continue submitting even for sqe failure if the
7930 * ring was setup with IORING_SETUP_SUBMIT_ALL
7932 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7935 } while (submitted < nr);
7937 if (unlikely(submitted != nr)) {
7938 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7939 int unused = nr - ref_used;
7941 current->io_uring->cached_refs += unused;
7944 io_submit_state_end(ctx);
7945 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7946 io_commit_sqring(ctx);
7951 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7953 return READ_ONCE(sqd->state);
7956 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7958 /* Tell userspace we may need a wakeup call */
7959 spin_lock(&ctx->completion_lock);
7960 WRITE_ONCE(ctx->rings->sq_flags,
7961 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7962 spin_unlock(&ctx->completion_lock);
7965 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7967 spin_lock(&ctx->completion_lock);
7968 WRITE_ONCE(ctx->rings->sq_flags,
7969 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7970 spin_unlock(&ctx->completion_lock);
7973 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7975 unsigned int to_submit;
7978 to_submit = io_sqring_entries(ctx);
7979 /* if we're handling multiple rings, cap submit size for fairness */
7980 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7981 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7983 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7984 const struct cred *creds = NULL;
7986 if (ctx->sq_creds != current_cred())
7987 creds = override_creds(ctx->sq_creds);
7989 mutex_lock(&ctx->uring_lock);
7990 if (!wq_list_empty(&ctx->iopoll_list))
7991 io_do_iopoll(ctx, true);
7994 * Don't submit if refs are dying, good for io_uring_register(),
7995 * but also it is relied upon by io_ring_exit_work()
7997 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7998 !(ctx->flags & IORING_SETUP_R_DISABLED))
7999 ret = io_submit_sqes(ctx, to_submit);
8000 mutex_unlock(&ctx->uring_lock);
8001 #ifdef CONFIG_NET_RX_BUSY_POLL
8002 spin_lock(&ctx->napi_lock);
8003 if (!list_empty(&ctx->napi_list) &&
8004 io_napi_busy_loop(&ctx->napi_list))
8006 spin_unlock(&ctx->napi_lock);
8008 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8009 wake_up(&ctx->sqo_sq_wait);
8011 revert_creds(creds);
8017 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8019 struct io_ring_ctx *ctx;
8020 unsigned sq_thread_idle = 0;
8022 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8023 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8024 sqd->sq_thread_idle = sq_thread_idle;
8027 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8029 bool did_sig = false;
8030 struct ksignal ksig;
8032 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8033 signal_pending(current)) {
8034 mutex_unlock(&sqd->lock);
8035 if (signal_pending(current))
8036 did_sig = get_signal(&ksig);
8038 mutex_lock(&sqd->lock);
8040 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8043 static int io_sq_thread(void *data)
8045 struct io_sq_data *sqd = data;
8046 struct io_ring_ctx *ctx;
8047 unsigned long timeout = 0;
8048 char buf[TASK_COMM_LEN];
8051 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8052 set_task_comm(current, buf);
8054 if (sqd->sq_cpu != -1)
8055 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8057 set_cpus_allowed_ptr(current, cpu_online_mask);
8058 current->flags |= PF_NO_SETAFFINITY;
8060 audit_alloc_kernel(current);
8062 mutex_lock(&sqd->lock);
8064 bool cap_entries, sqt_spin = false;
8066 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8067 if (io_sqd_handle_event(sqd))
8069 timeout = jiffies + sqd->sq_thread_idle;
8072 cap_entries = !list_is_singular(&sqd->ctx_list);
8073 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8074 int ret = __io_sq_thread(ctx, cap_entries);
8076 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8079 if (io_run_task_work())
8082 if (sqt_spin || !time_after(jiffies, timeout)) {
8085 timeout = jiffies + sqd->sq_thread_idle;
8089 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8090 if (!io_sqd_events_pending(sqd) && !current->task_works) {
8091 bool needs_sched = true;
8093 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8094 io_ring_set_wakeup_flag(ctx);
8096 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8097 !wq_list_empty(&ctx->iopoll_list)) {
8098 needs_sched = false;
8103 * Ensure the store of the wakeup flag is not
8104 * reordered with the load of the SQ tail
8108 if (io_sqring_entries(ctx)) {
8109 needs_sched = false;
8115 mutex_unlock(&sqd->lock);
8117 mutex_lock(&sqd->lock);
8119 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8120 io_ring_clear_wakeup_flag(ctx);
8123 finish_wait(&sqd->wait, &wait);
8124 timeout = jiffies + sqd->sq_thread_idle;
8127 io_uring_cancel_generic(true, sqd);
8129 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8130 io_ring_set_wakeup_flag(ctx);
8132 mutex_unlock(&sqd->lock);
8134 audit_free(current);
8136 complete(&sqd->exited);
8140 struct io_wait_queue {
8141 struct wait_queue_entry wq;
8142 struct io_ring_ctx *ctx;
8144 unsigned nr_timeouts;
8145 #ifdef CONFIG_NET_RX_BUSY_POLL
8146 unsigned busy_poll_to;
8150 static inline bool io_should_wake(struct io_wait_queue *iowq)
8152 struct io_ring_ctx *ctx = iowq->ctx;
8153 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8156 * Wake up if we have enough events, or if a timeout occurred since we
8157 * started waiting. For timeouts, we always want to return to userspace,
8158 * regardless of event count.
8160 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8163 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8164 int wake_flags, void *key)
8166 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8170 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8171 * the task, and the next invocation will do it.
8173 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8174 return autoremove_wake_function(curr, mode, wake_flags, key);
8178 static int io_run_task_work_sig(void)
8180 if (io_run_task_work())
8182 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8183 return -ERESTARTSYS;
8184 if (task_sigpending(current))
8189 /* when returns >0, the caller should retry */
8190 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8191 struct io_wait_queue *iowq,
8196 /* make sure we run task_work before checking for signals */
8197 ret = io_run_task_work_sig();
8198 if (ret || io_should_wake(iowq))
8200 /* let the caller flush overflows, retry */
8201 if (test_bit(0, &ctx->check_cq_overflow))
8204 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8209 #ifdef CONFIG_NET_RX_BUSY_POLL
8210 static void io_adjust_busy_loop_timeout(struct timespec64 *ts,
8211 struct io_wait_queue *iowq)
8213 unsigned busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8214 struct timespec64 pollto = ns_to_timespec64(1000 * (s64)busy_poll_to);
8216 if (timespec64_compare(ts, &pollto) > 0) {
8217 *ts = timespec64_sub(*ts, pollto);
8218 iowq->busy_poll_to = busy_poll_to;
8220 u64 to = timespec64_to_ns(ts);
8223 iowq->busy_poll_to = to;
8229 static inline bool io_busy_loop_timeout(unsigned long start_time,
8230 unsigned long bp_usec)
8233 unsigned long end_time = start_time + bp_usec;
8234 unsigned long now = busy_loop_current_time();
8236 return time_after(now, end_time);
8241 static bool io_busy_loop_end(void *p, unsigned long start_time)
8243 struct io_wait_queue *iowq = p;
8245 return signal_pending(current) ||
8246 io_should_wake(iowq) ||
8247 io_busy_loop_timeout(start_time, iowq->busy_poll_to);
8250 static void io_blocking_napi_busy_loop(struct list_head *napi_list,
8251 struct io_wait_queue *iowq)
8253 unsigned long start_time =
8254 list_is_singular(napi_list) ? 0 :
8255 busy_loop_current_time();
8258 if (list_is_singular(napi_list)) {
8259 struct napi_entry *ne =
8260 list_first_entry(napi_list,
8261 struct napi_entry, list);
8263 napi_busy_loop(ne->napi_id, io_busy_loop_end, iowq,
8264 true, BUSY_POLL_BUDGET);
8265 io_check_napi_entry_timeout(ne);
8268 } while (io_napi_busy_loop(napi_list) &&
8269 !io_busy_loop_end(iowq, start_time));
8272 static void io_putback_napi_list(struct io_ring_ctx *ctx,
8273 struct list_head *napi_list)
8275 struct napi_entry *cne, *lne;
8277 spin_lock(&ctx->napi_lock);
8278 list_for_each_entry(cne, &ctx->napi_list, list)
8279 list_for_each_entry(lne, napi_list, list)
8280 if (cne->napi_id == lne->napi_id) {
8281 list_del(&lne->list);
8285 list_splice(napi_list, &ctx->napi_list);
8286 spin_unlock(&ctx->napi_lock);
8288 #endif /* CONFIG_NET_RX_BUSY_POLL */
8291 * Wait until events become available, if we don't already have some. The
8292 * application must reap them itself, as they reside on the shared cq ring.
8294 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8295 const sigset_t __user *sig, size_t sigsz,
8296 struct __kernel_timespec __user *uts)
8298 struct io_wait_queue iowq;
8299 struct io_rings *rings = ctx->rings;
8300 ktime_t timeout = KTIME_MAX;
8302 #ifdef CONFIG_NET_RX_BUSY_POLL
8303 LIST_HEAD(local_napi_list);
8307 io_cqring_overflow_flush(ctx);
8308 if (io_cqring_events(ctx) >= min_events)
8310 if (!io_run_task_work())
8315 #ifdef CONFIG_COMPAT
8316 if (in_compat_syscall())
8317 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8321 ret = set_user_sigmask(sig, sigsz);
8327 #ifdef CONFIG_NET_RX_BUSY_POLL
8328 iowq.busy_poll_to = 0;
8329 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8330 spin_lock(&ctx->napi_lock);
8331 list_splice_init(&ctx->napi_list, &local_napi_list);
8332 spin_unlock(&ctx->napi_lock);
8336 struct timespec64 ts;
8338 if (get_timespec64(&ts, uts))
8340 #ifdef CONFIG_NET_RX_BUSY_POLL
8341 if (!list_empty(&local_napi_list))
8342 io_adjust_busy_loop_timeout(&ts, &iowq);
8344 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8346 #ifdef CONFIG_NET_RX_BUSY_POLL
8347 else if (!list_empty(&local_napi_list))
8348 iowq.busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8351 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8352 iowq.wq.private = current;
8353 INIT_LIST_HEAD(&iowq.wq.entry);
8355 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8356 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8358 trace_io_uring_cqring_wait(ctx, min_events);
8359 #ifdef CONFIG_NET_RX_BUSY_POLL
8360 if (iowq.busy_poll_to)
8361 io_blocking_napi_busy_loop(&local_napi_list, &iowq);
8362 if (!list_empty(&local_napi_list))
8363 io_putback_napi_list(ctx, &local_napi_list);
8366 /* if we can't even flush overflow, don't wait for more */
8367 if (!io_cqring_overflow_flush(ctx)) {
8371 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8372 TASK_INTERRUPTIBLE);
8373 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8374 finish_wait(&ctx->cq_wait, &iowq.wq);
8378 restore_saved_sigmask_unless(ret == -EINTR);
8380 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8383 static void io_free_page_table(void **table, size_t size)
8385 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8387 for (i = 0; i < nr_tables; i++)
8392 static __cold void **io_alloc_page_table(size_t size)
8394 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8395 size_t init_size = size;
8398 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8402 for (i = 0; i < nr_tables; i++) {
8403 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8405 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8407 io_free_page_table(table, init_size);
8415 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8417 percpu_ref_exit(&ref_node->refs);
8421 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8423 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8424 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8425 unsigned long flags;
8426 bool first_add = false;
8427 unsigned long delay = HZ;
8429 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8432 /* if we are mid-quiesce then do not delay */
8433 if (node->rsrc_data->quiesce)
8436 while (!list_empty(&ctx->rsrc_ref_list)) {
8437 node = list_first_entry(&ctx->rsrc_ref_list,
8438 struct io_rsrc_node, node);
8439 /* recycle ref nodes in order */
8442 list_del(&node->node);
8443 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8445 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8448 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8451 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8453 struct io_rsrc_node *ref_node;
8455 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8459 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8464 INIT_LIST_HEAD(&ref_node->node);
8465 INIT_LIST_HEAD(&ref_node->rsrc_list);
8466 ref_node->done = false;
8470 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8471 struct io_rsrc_data *data_to_kill)
8472 __must_hold(&ctx->uring_lock)
8474 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8475 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8477 io_rsrc_refs_drop(ctx);
8480 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8482 rsrc_node->rsrc_data = data_to_kill;
8483 spin_lock_irq(&ctx->rsrc_ref_lock);
8484 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8485 spin_unlock_irq(&ctx->rsrc_ref_lock);
8487 atomic_inc(&data_to_kill->refs);
8488 percpu_ref_kill(&rsrc_node->refs);
8489 ctx->rsrc_node = NULL;
8492 if (!ctx->rsrc_node) {
8493 ctx->rsrc_node = ctx->rsrc_backup_node;
8494 ctx->rsrc_backup_node = NULL;
8498 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8500 if (ctx->rsrc_backup_node)
8502 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8503 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8506 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8507 struct io_ring_ctx *ctx)
8511 /* As we may drop ->uring_lock, other task may have started quiesce */
8515 data->quiesce = true;
8517 ret = io_rsrc_node_switch_start(ctx);
8520 io_rsrc_node_switch(ctx, data);
8522 /* kill initial ref, already quiesced if zero */
8523 if (atomic_dec_and_test(&data->refs))
8525 mutex_unlock(&ctx->uring_lock);
8526 flush_delayed_work(&ctx->rsrc_put_work);
8527 ret = wait_for_completion_interruptible(&data->done);
8529 mutex_lock(&ctx->uring_lock);
8530 if (atomic_read(&data->refs) > 0) {
8532 * it has been revived by another thread while
8535 mutex_unlock(&ctx->uring_lock);
8541 atomic_inc(&data->refs);
8542 /* wait for all works potentially completing data->done */
8543 flush_delayed_work(&ctx->rsrc_put_work);
8544 reinit_completion(&data->done);
8546 ret = io_run_task_work_sig();
8547 mutex_lock(&ctx->uring_lock);
8549 data->quiesce = false;
8554 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8556 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8557 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8559 return &data->tags[table_idx][off];
8562 static void io_rsrc_data_free(struct io_rsrc_data *data)
8564 size_t size = data->nr * sizeof(data->tags[0][0]);
8567 io_free_page_table((void **)data->tags, size);
8571 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8572 u64 __user *utags, unsigned nr,
8573 struct io_rsrc_data **pdata)
8575 struct io_rsrc_data *data;
8579 data = kzalloc(sizeof(*data), GFP_KERNEL);
8582 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8590 data->do_put = do_put;
8593 for (i = 0; i < nr; i++) {
8594 u64 *tag_slot = io_get_tag_slot(data, i);
8596 if (copy_from_user(tag_slot, &utags[i],
8602 atomic_set(&data->refs, 1);
8603 init_completion(&data->done);
8607 io_rsrc_data_free(data);
8611 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8613 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8614 GFP_KERNEL_ACCOUNT);
8615 return !!table->files;
8618 static void io_free_file_tables(struct io_file_table *table)
8620 kvfree(table->files);
8621 table->files = NULL;
8624 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8626 #if defined(CONFIG_UNIX)
8627 if (ctx->ring_sock) {
8628 struct sock *sock = ctx->ring_sock->sk;
8629 struct sk_buff *skb;
8631 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8637 for (i = 0; i < ctx->nr_user_files; i++) {
8640 file = io_file_from_index(ctx, i);
8645 io_free_file_tables(&ctx->file_table);
8646 io_rsrc_data_free(ctx->file_data);
8647 ctx->file_data = NULL;
8648 ctx->nr_user_files = 0;
8651 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8655 if (!ctx->file_data)
8657 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8659 __io_sqe_files_unregister(ctx);
8663 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8664 __releases(&sqd->lock)
8666 WARN_ON_ONCE(sqd->thread == current);
8669 * Do the dance but not conditional clear_bit() because it'd race with
8670 * other threads incrementing park_pending and setting the bit.
8672 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8673 if (atomic_dec_return(&sqd->park_pending))
8674 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8675 mutex_unlock(&sqd->lock);
8678 static void io_sq_thread_park(struct io_sq_data *sqd)
8679 __acquires(&sqd->lock)
8681 WARN_ON_ONCE(sqd->thread == current);
8683 atomic_inc(&sqd->park_pending);
8684 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8685 mutex_lock(&sqd->lock);
8687 wake_up_process(sqd->thread);
8690 static void io_sq_thread_stop(struct io_sq_data *sqd)
8692 WARN_ON_ONCE(sqd->thread == current);
8693 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8695 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8696 mutex_lock(&sqd->lock);
8698 wake_up_process(sqd->thread);
8699 mutex_unlock(&sqd->lock);
8700 wait_for_completion(&sqd->exited);
8703 static void io_put_sq_data(struct io_sq_data *sqd)
8705 if (refcount_dec_and_test(&sqd->refs)) {
8706 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8708 io_sq_thread_stop(sqd);
8713 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8715 struct io_sq_data *sqd = ctx->sq_data;
8718 io_sq_thread_park(sqd);
8719 list_del_init(&ctx->sqd_list);
8720 io_sqd_update_thread_idle(sqd);
8721 io_sq_thread_unpark(sqd);
8723 io_put_sq_data(sqd);
8724 ctx->sq_data = NULL;
8728 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8730 struct io_ring_ctx *ctx_attach;
8731 struct io_sq_data *sqd;
8734 f = fdget(p->wq_fd);
8736 return ERR_PTR(-ENXIO);
8737 if (f.file->f_op != &io_uring_fops) {
8739 return ERR_PTR(-EINVAL);
8742 ctx_attach = f.file->private_data;
8743 sqd = ctx_attach->sq_data;
8746 return ERR_PTR(-EINVAL);
8748 if (sqd->task_tgid != current->tgid) {
8750 return ERR_PTR(-EPERM);
8753 refcount_inc(&sqd->refs);
8758 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8761 struct io_sq_data *sqd;
8764 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8765 sqd = io_attach_sq_data(p);
8770 /* fall through for EPERM case, setup new sqd/task */
8771 if (PTR_ERR(sqd) != -EPERM)
8775 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8777 return ERR_PTR(-ENOMEM);
8779 atomic_set(&sqd->park_pending, 0);
8780 refcount_set(&sqd->refs, 1);
8781 INIT_LIST_HEAD(&sqd->ctx_list);
8782 mutex_init(&sqd->lock);
8783 init_waitqueue_head(&sqd->wait);
8784 init_completion(&sqd->exited);
8788 #if defined(CONFIG_UNIX)
8790 * Ensure the UNIX gc is aware of our file set, so we are certain that
8791 * the io_uring can be safely unregistered on process exit, even if we have
8792 * loops in the file referencing.
8794 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8796 struct sock *sk = ctx->ring_sock->sk;
8797 struct scm_fp_list *fpl;
8798 struct sk_buff *skb;
8801 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8805 skb = alloc_skb(0, GFP_KERNEL);
8814 fpl->user = get_uid(current_user());
8815 for (i = 0; i < nr; i++) {
8816 struct file *file = io_file_from_index(ctx, i + offset);
8820 fpl->fp[nr_files] = get_file(file);
8821 unix_inflight(fpl->user, fpl->fp[nr_files]);
8826 fpl->max = SCM_MAX_FD;
8827 fpl->count = nr_files;
8828 UNIXCB(skb).fp = fpl;
8829 skb->destructor = unix_destruct_scm;
8830 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8831 skb_queue_head(&sk->sk_receive_queue, skb);
8833 for (i = 0; i < nr_files; i++)
8844 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8845 * causes regular reference counting to break down. We rely on the UNIX
8846 * garbage collection to take care of this problem for us.
8848 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8850 unsigned left, total;
8854 left = ctx->nr_user_files;
8856 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8858 ret = __io_sqe_files_scm(ctx, this_files, total);
8862 total += this_files;
8868 while (total < ctx->nr_user_files) {
8869 struct file *file = io_file_from_index(ctx, total);
8879 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8885 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8887 struct file *file = prsrc->file;
8888 #if defined(CONFIG_UNIX)
8889 struct sock *sock = ctx->ring_sock->sk;
8890 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8891 struct sk_buff *skb;
8894 __skb_queue_head_init(&list);
8897 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8898 * remove this entry and rearrange the file array.
8900 skb = skb_dequeue(head);
8902 struct scm_fp_list *fp;
8904 fp = UNIXCB(skb).fp;
8905 for (i = 0; i < fp->count; i++) {
8908 if (fp->fp[i] != file)
8911 unix_notinflight(fp->user, fp->fp[i]);
8912 left = fp->count - 1 - i;
8914 memmove(&fp->fp[i], &fp->fp[i + 1],
8915 left * sizeof(struct file *));
8922 __skb_queue_tail(&list, skb);
8932 __skb_queue_tail(&list, skb);
8934 skb = skb_dequeue(head);
8937 if (skb_peek(&list)) {
8938 spin_lock_irq(&head->lock);
8939 while ((skb = __skb_dequeue(&list)) != NULL)
8940 __skb_queue_tail(head, skb);
8941 spin_unlock_irq(&head->lock);
8948 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8950 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8951 struct io_ring_ctx *ctx = rsrc_data->ctx;
8952 struct io_rsrc_put *prsrc, *tmp;
8954 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8955 list_del(&prsrc->list);
8958 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8960 io_ring_submit_lock(ctx, lock_ring);
8961 spin_lock(&ctx->completion_lock);
8962 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8963 io_commit_cqring(ctx);
8964 spin_unlock(&ctx->completion_lock);
8965 io_cqring_ev_posted(ctx);
8966 io_ring_submit_unlock(ctx, lock_ring);
8969 rsrc_data->do_put(ctx, prsrc);
8973 io_rsrc_node_destroy(ref_node);
8974 if (atomic_dec_and_test(&rsrc_data->refs))
8975 complete(&rsrc_data->done);
8978 static void io_rsrc_put_work(struct work_struct *work)
8980 struct io_ring_ctx *ctx;
8981 struct llist_node *node;
8983 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8984 node = llist_del_all(&ctx->rsrc_put_llist);
8987 struct io_rsrc_node *ref_node;
8988 struct llist_node *next = node->next;
8990 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8991 __io_rsrc_put_work(ref_node);
8996 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8997 unsigned nr_args, u64 __user *tags)
8999 __s32 __user *fds = (__s32 __user *) arg;
9008 if (nr_args > IORING_MAX_FIXED_FILES)
9010 if (nr_args > rlimit(RLIMIT_NOFILE))
9012 ret = io_rsrc_node_switch_start(ctx);
9015 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9021 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
9024 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9025 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
9029 /* allow sparse sets */
9032 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9039 if (unlikely(!file))
9043 * Don't allow io_uring instances to be registered. If UNIX
9044 * isn't enabled, then this causes a reference cycle and this
9045 * instance can never get freed. If UNIX is enabled we'll
9046 * handle it just fine, but there's still no point in allowing
9047 * a ring fd as it doesn't support regular read/write anyway.
9049 if (file->f_op == &io_uring_fops) {
9053 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
9056 ret = io_sqe_files_scm(ctx);
9058 __io_sqe_files_unregister(ctx);
9062 io_rsrc_node_switch(ctx, NULL);
9065 for (i = 0; i < ctx->nr_user_files; i++) {
9066 file = io_file_from_index(ctx, i);
9070 io_free_file_tables(&ctx->file_table);
9071 ctx->nr_user_files = 0;
9073 io_rsrc_data_free(ctx->file_data);
9074 ctx->file_data = NULL;
9078 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
9081 #if defined(CONFIG_UNIX)
9082 struct sock *sock = ctx->ring_sock->sk;
9083 struct sk_buff_head *head = &sock->sk_receive_queue;
9084 struct sk_buff *skb;
9087 * See if we can merge this file into an existing skb SCM_RIGHTS
9088 * file set. If there's no room, fall back to allocating a new skb
9089 * and filling it in.
9091 spin_lock_irq(&head->lock);
9092 skb = skb_peek(head);
9094 struct scm_fp_list *fpl = UNIXCB(skb).fp;
9096 if (fpl->count < SCM_MAX_FD) {
9097 __skb_unlink(skb, head);
9098 spin_unlock_irq(&head->lock);
9099 fpl->fp[fpl->count] = get_file(file);
9100 unix_inflight(fpl->user, fpl->fp[fpl->count]);
9102 spin_lock_irq(&head->lock);
9103 __skb_queue_head(head, skb);
9108 spin_unlock_irq(&head->lock);
9115 return __io_sqe_files_scm(ctx, 1, index);
9121 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9122 struct io_rsrc_node *node, void *rsrc)
9124 struct io_rsrc_put *prsrc;
9126 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9130 prsrc->tag = *io_get_tag_slot(data, idx);
9132 list_add(&prsrc->list, &node->rsrc_list);
9136 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9137 unsigned int issue_flags, u32 slot_index)
9139 struct io_ring_ctx *ctx = req->ctx;
9140 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9141 bool needs_switch = false;
9142 struct io_fixed_file *file_slot;
9145 io_ring_submit_lock(ctx, needs_lock);
9146 if (file->f_op == &io_uring_fops)
9149 if (!ctx->file_data)
9152 if (slot_index >= ctx->nr_user_files)
9155 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9156 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9158 if (file_slot->file_ptr) {
9159 struct file *old_file;
9161 ret = io_rsrc_node_switch_start(ctx);
9165 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9166 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9167 ctx->rsrc_node, old_file);
9170 file_slot->file_ptr = 0;
9171 needs_switch = true;
9174 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9175 io_fixed_file_set(file_slot, file);
9176 ret = io_sqe_file_register(ctx, file, slot_index);
9178 file_slot->file_ptr = 0;
9185 io_rsrc_node_switch(ctx, ctx->file_data);
9186 io_ring_submit_unlock(ctx, needs_lock);
9192 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9194 unsigned int offset = req->close.file_slot - 1;
9195 struct io_ring_ctx *ctx = req->ctx;
9196 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9197 struct io_fixed_file *file_slot;
9201 io_ring_submit_lock(ctx, needs_lock);
9203 if (unlikely(!ctx->file_data))
9206 if (offset >= ctx->nr_user_files)
9208 ret = io_rsrc_node_switch_start(ctx);
9212 i = array_index_nospec(offset, ctx->nr_user_files);
9213 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9215 if (!file_slot->file_ptr)
9218 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9219 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9223 file_slot->file_ptr = 0;
9224 io_rsrc_node_switch(ctx, ctx->file_data);
9227 io_ring_submit_unlock(ctx, needs_lock);
9231 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9232 struct io_uring_rsrc_update2 *up,
9235 u64 __user *tags = u64_to_user_ptr(up->tags);
9236 __s32 __user *fds = u64_to_user_ptr(up->data);
9237 struct io_rsrc_data *data = ctx->file_data;
9238 struct io_fixed_file *file_slot;
9242 bool needs_switch = false;
9244 if (!ctx->file_data)
9246 if (up->offset + nr_args > ctx->nr_user_files)
9249 for (done = 0; done < nr_args; done++) {
9252 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9253 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9257 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9261 if (fd == IORING_REGISTER_FILES_SKIP)
9264 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9265 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9267 if (file_slot->file_ptr) {
9268 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9269 err = io_queue_rsrc_removal(data, up->offset + done,
9270 ctx->rsrc_node, file);
9273 file_slot->file_ptr = 0;
9274 needs_switch = true;
9283 * Don't allow io_uring instances to be registered. If
9284 * UNIX isn't enabled, then this causes a reference
9285 * cycle and this instance can never get freed. If UNIX
9286 * is enabled we'll handle it just fine, but there's
9287 * still no point in allowing a ring fd as it doesn't
9288 * support regular read/write anyway.
9290 if (file->f_op == &io_uring_fops) {
9295 *io_get_tag_slot(data, up->offset + done) = tag;
9296 io_fixed_file_set(file_slot, file);
9297 err = io_sqe_file_register(ctx, file, i);
9299 file_slot->file_ptr = 0;
9307 io_rsrc_node_switch(ctx, data);
9308 return done ? done : err;
9311 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9312 struct task_struct *task)
9314 struct io_wq_hash *hash;
9315 struct io_wq_data data;
9316 unsigned int concurrency;
9318 mutex_lock(&ctx->uring_lock);
9319 hash = ctx->hash_map;
9321 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9323 mutex_unlock(&ctx->uring_lock);
9324 return ERR_PTR(-ENOMEM);
9326 refcount_set(&hash->refs, 1);
9327 init_waitqueue_head(&hash->wait);
9328 ctx->hash_map = hash;
9330 mutex_unlock(&ctx->uring_lock);
9334 data.free_work = io_wq_free_work;
9335 data.do_work = io_wq_submit_work;
9337 /* Do QD, or 4 * CPUS, whatever is smallest */
9338 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9340 return io_wq_create(concurrency, &data);
9343 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9344 struct io_ring_ctx *ctx)
9346 struct io_uring_task *tctx;
9349 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9350 if (unlikely(!tctx))
9353 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9354 sizeof(struct file *), GFP_KERNEL);
9355 if (unlikely(!tctx->registered_rings)) {
9360 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9361 if (unlikely(ret)) {
9362 kfree(tctx->registered_rings);
9367 tctx->io_wq = io_init_wq_offload(ctx, task);
9368 if (IS_ERR(tctx->io_wq)) {
9369 ret = PTR_ERR(tctx->io_wq);
9370 percpu_counter_destroy(&tctx->inflight);
9371 kfree(tctx->registered_rings);
9377 init_waitqueue_head(&tctx->wait);
9378 atomic_set(&tctx->in_idle, 0);
9379 atomic_set(&tctx->inflight_tracked, 0);
9380 task->io_uring = tctx;
9381 spin_lock_init(&tctx->task_lock);
9382 INIT_WQ_LIST(&tctx->task_list);
9383 INIT_WQ_LIST(&tctx->prior_task_list);
9384 init_task_work(&tctx->task_work, tctx_task_work);
9388 void __io_uring_free(struct task_struct *tsk)
9390 struct io_uring_task *tctx = tsk->io_uring;
9392 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9393 WARN_ON_ONCE(tctx->io_wq);
9394 WARN_ON_ONCE(tctx->cached_refs);
9396 kfree(tctx->registered_rings);
9397 percpu_counter_destroy(&tctx->inflight);
9399 tsk->io_uring = NULL;
9402 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9403 struct io_uring_params *p)
9407 /* Retain compatibility with failing for an invalid attach attempt */
9408 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9409 IORING_SETUP_ATTACH_WQ) {
9412 f = fdget(p->wq_fd);
9415 if (f.file->f_op != &io_uring_fops) {
9421 if (ctx->flags & IORING_SETUP_SQPOLL) {
9422 struct task_struct *tsk;
9423 struct io_sq_data *sqd;
9426 ret = security_uring_sqpoll();
9430 sqd = io_get_sq_data(p, &attached);
9436 ctx->sq_creds = get_current_cred();
9438 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9439 if (!ctx->sq_thread_idle)
9440 ctx->sq_thread_idle = HZ;
9442 io_sq_thread_park(sqd);
9443 list_add(&ctx->sqd_list, &sqd->ctx_list);
9444 io_sqd_update_thread_idle(sqd);
9445 /* don't attach to a dying SQPOLL thread, would be racy */
9446 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9447 io_sq_thread_unpark(sqd);
9454 if (p->flags & IORING_SETUP_SQ_AFF) {
9455 int cpu = p->sq_thread_cpu;
9458 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9465 sqd->task_pid = current->pid;
9466 sqd->task_tgid = current->tgid;
9467 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9474 ret = io_uring_alloc_task_context(tsk, ctx);
9475 wake_up_new_task(tsk);
9478 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9479 /* Can't have SQ_AFF without SQPOLL */
9486 complete(&ctx->sq_data->exited);
9488 io_sq_thread_finish(ctx);
9492 static inline void __io_unaccount_mem(struct user_struct *user,
9493 unsigned long nr_pages)
9495 atomic_long_sub(nr_pages, &user->locked_vm);
9498 static inline int __io_account_mem(struct user_struct *user,
9499 unsigned long nr_pages)
9501 unsigned long page_limit, cur_pages, new_pages;
9503 /* Don't allow more pages than we can safely lock */
9504 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9507 cur_pages = atomic_long_read(&user->locked_vm);
9508 new_pages = cur_pages + nr_pages;
9509 if (new_pages > page_limit)
9511 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9512 new_pages) != cur_pages);
9517 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9520 __io_unaccount_mem(ctx->user, nr_pages);
9522 if (ctx->mm_account)
9523 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9526 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9531 ret = __io_account_mem(ctx->user, nr_pages);
9536 if (ctx->mm_account)
9537 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9542 static void io_mem_free(void *ptr)
9549 page = virt_to_head_page(ptr);
9550 if (put_page_testzero(page))
9551 free_compound_page(page);
9554 static void *io_mem_alloc(size_t size)
9556 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9558 return (void *) __get_free_pages(gfp, get_order(size));
9561 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9564 struct io_rings *rings;
9565 size_t off, sq_array_size;
9567 off = struct_size(rings, cqes, cq_entries);
9568 if (off == SIZE_MAX)
9572 off = ALIGN(off, SMP_CACHE_BYTES);
9580 sq_array_size = array_size(sizeof(u32), sq_entries);
9581 if (sq_array_size == SIZE_MAX)
9584 if (check_add_overflow(off, sq_array_size, &off))
9590 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9592 struct io_mapped_ubuf *imu = *slot;
9595 if (imu != ctx->dummy_ubuf) {
9596 for (i = 0; i < imu->nr_bvecs; i++)
9597 unpin_user_page(imu->bvec[i].bv_page);
9598 if (imu->acct_pages)
9599 io_unaccount_mem(ctx, imu->acct_pages);
9605 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9607 io_buffer_unmap(ctx, &prsrc->buf);
9611 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9615 for (i = 0; i < ctx->nr_user_bufs; i++)
9616 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9617 kfree(ctx->user_bufs);
9618 io_rsrc_data_free(ctx->buf_data);
9619 ctx->user_bufs = NULL;
9620 ctx->buf_data = NULL;
9621 ctx->nr_user_bufs = 0;
9624 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9631 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9633 __io_sqe_buffers_unregister(ctx);
9637 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9638 void __user *arg, unsigned index)
9640 struct iovec __user *src;
9642 #ifdef CONFIG_COMPAT
9644 struct compat_iovec __user *ciovs;
9645 struct compat_iovec ciov;
9647 ciovs = (struct compat_iovec __user *) arg;
9648 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9651 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9652 dst->iov_len = ciov.iov_len;
9656 src = (struct iovec __user *) arg;
9657 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9663 * Not super efficient, but this is just a registration time. And we do cache
9664 * the last compound head, so generally we'll only do a full search if we don't
9667 * We check if the given compound head page has already been accounted, to
9668 * avoid double accounting it. This allows us to account the full size of the
9669 * page, not just the constituent pages of a huge page.
9671 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9672 int nr_pages, struct page *hpage)
9676 /* check current page array */
9677 for (i = 0; i < nr_pages; i++) {
9678 if (!PageCompound(pages[i]))
9680 if (compound_head(pages[i]) == hpage)
9684 /* check previously registered pages */
9685 for (i = 0; i < ctx->nr_user_bufs; i++) {
9686 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9688 for (j = 0; j < imu->nr_bvecs; j++) {
9689 if (!PageCompound(imu->bvec[j].bv_page))
9691 if (compound_head(imu->bvec[j].bv_page) == hpage)
9699 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9700 int nr_pages, struct io_mapped_ubuf *imu,
9701 struct page **last_hpage)
9705 imu->acct_pages = 0;
9706 for (i = 0; i < nr_pages; i++) {
9707 if (!PageCompound(pages[i])) {
9712 hpage = compound_head(pages[i]);
9713 if (hpage == *last_hpage)
9715 *last_hpage = hpage;
9716 if (headpage_already_acct(ctx, pages, i, hpage))
9718 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9722 if (!imu->acct_pages)
9725 ret = io_account_mem(ctx, imu->acct_pages);
9727 imu->acct_pages = 0;
9731 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9732 struct io_mapped_ubuf **pimu,
9733 struct page **last_hpage)
9735 struct io_mapped_ubuf *imu = NULL;
9736 struct vm_area_struct **vmas = NULL;
9737 struct page **pages = NULL;
9738 unsigned long off, start, end, ubuf;
9740 int ret, pret, nr_pages, i;
9742 if (!iov->iov_base) {
9743 *pimu = ctx->dummy_ubuf;
9747 ubuf = (unsigned long) iov->iov_base;
9748 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9749 start = ubuf >> PAGE_SHIFT;
9750 nr_pages = end - start;
9755 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9759 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9764 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9769 mmap_read_lock(current->mm);
9770 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9772 if (pret == nr_pages) {
9773 /* don't support file backed memory */
9774 for (i = 0; i < nr_pages; i++) {
9775 struct vm_area_struct *vma = vmas[i];
9777 if (vma_is_shmem(vma))
9780 !is_file_hugepages(vma->vm_file)) {
9786 ret = pret < 0 ? pret : -EFAULT;
9788 mmap_read_unlock(current->mm);
9791 * if we did partial map, or found file backed vmas,
9792 * release any pages we did get
9795 unpin_user_pages(pages, pret);
9799 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9801 unpin_user_pages(pages, pret);
9805 off = ubuf & ~PAGE_MASK;
9806 size = iov->iov_len;
9807 for (i = 0; i < nr_pages; i++) {
9810 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9811 imu->bvec[i].bv_page = pages[i];
9812 imu->bvec[i].bv_len = vec_len;
9813 imu->bvec[i].bv_offset = off;
9817 /* store original address for later verification */
9819 imu->ubuf_end = ubuf + iov->iov_len;
9820 imu->nr_bvecs = nr_pages;
9831 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9833 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9834 return ctx->user_bufs ? 0 : -ENOMEM;
9837 static int io_buffer_validate(struct iovec *iov)
9839 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9842 * Don't impose further limits on the size and buffer
9843 * constraints here, we'll -EINVAL later when IO is
9844 * submitted if they are wrong.
9847 return iov->iov_len ? -EFAULT : 0;
9851 /* arbitrary limit, but we need something */
9852 if (iov->iov_len > SZ_1G)
9855 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9861 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9862 unsigned int nr_args, u64 __user *tags)
9864 struct page *last_hpage = NULL;
9865 struct io_rsrc_data *data;
9871 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9873 ret = io_rsrc_node_switch_start(ctx);
9876 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9879 ret = io_buffers_map_alloc(ctx, nr_args);
9881 io_rsrc_data_free(data);
9885 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9886 ret = io_copy_iov(ctx, &iov, arg, i);
9889 ret = io_buffer_validate(&iov);
9892 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9897 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9903 WARN_ON_ONCE(ctx->buf_data);
9905 ctx->buf_data = data;
9907 __io_sqe_buffers_unregister(ctx);
9909 io_rsrc_node_switch(ctx, NULL);
9913 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9914 struct io_uring_rsrc_update2 *up,
9915 unsigned int nr_args)
9917 u64 __user *tags = u64_to_user_ptr(up->tags);
9918 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9919 struct page *last_hpage = NULL;
9920 bool needs_switch = false;
9926 if (up->offset + nr_args > ctx->nr_user_bufs)
9929 for (done = 0; done < nr_args; done++) {
9930 struct io_mapped_ubuf *imu;
9931 int offset = up->offset + done;
9934 err = io_copy_iov(ctx, &iov, iovs, done);
9937 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9941 err = io_buffer_validate(&iov);
9944 if (!iov.iov_base && tag) {
9948 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9952 i = array_index_nospec(offset, ctx->nr_user_bufs);
9953 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9954 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9955 ctx->rsrc_node, ctx->user_bufs[i]);
9956 if (unlikely(err)) {
9957 io_buffer_unmap(ctx, &imu);
9960 ctx->user_bufs[i] = NULL;
9961 needs_switch = true;
9964 ctx->user_bufs[i] = imu;
9965 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9969 io_rsrc_node_switch(ctx, ctx->buf_data);
9970 return done ? done : err;
9973 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9974 unsigned int eventfd_async)
9976 struct io_ev_fd *ev_fd;
9977 __s32 __user *fds = arg;
9980 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9981 lockdep_is_held(&ctx->uring_lock));
9985 if (copy_from_user(&fd, fds, sizeof(*fds)))
9988 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9992 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9993 if (IS_ERR(ev_fd->cq_ev_fd)) {
9994 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9998 ev_fd->eventfd_async = eventfd_async;
9999 ctx->has_evfd = true;
10000 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10004 static void io_eventfd_put(struct rcu_head *rcu)
10006 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10008 eventfd_ctx_put(ev_fd->cq_ev_fd);
10012 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10014 struct io_ev_fd *ev_fd;
10016 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10017 lockdep_is_held(&ctx->uring_lock));
10019 ctx->has_evfd = false;
10020 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10021 call_rcu(&ev_fd->rcu, io_eventfd_put);
10028 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10032 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
10033 struct list_head *list = &ctx->io_buffers[i];
10035 while (!list_empty(list)) {
10036 struct io_buffer_list *bl;
10038 bl = list_first_entry(list, struct io_buffer_list, list);
10039 __io_remove_buffers(ctx, bl, -1U);
10040 list_del(&bl->list);
10045 while (!list_empty(&ctx->io_buffers_pages)) {
10048 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10049 list_del_init(&page->lru);
10054 static void io_req_caches_free(struct io_ring_ctx *ctx)
10056 struct io_submit_state *state = &ctx->submit_state;
10059 mutex_lock(&ctx->uring_lock);
10060 io_flush_cached_locked_reqs(ctx, state);
10062 while (state->free_list.next) {
10063 struct io_wq_work_node *node;
10064 struct io_kiocb *req;
10066 node = wq_stack_extract(&state->free_list);
10067 req = container_of(node, struct io_kiocb, comp_list);
10068 kmem_cache_free(req_cachep, req);
10072 percpu_ref_put_many(&ctx->refs, nr);
10073 mutex_unlock(&ctx->uring_lock);
10076 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10078 if (data && !atomic_dec_and_test(&data->refs))
10079 wait_for_completion(&data->done);
10082 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10084 struct async_poll *apoll;
10086 while (!list_empty(&ctx->apoll_cache)) {
10087 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10089 list_del(&apoll->poll.wait.entry);
10094 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10096 io_sq_thread_finish(ctx);
10098 if (ctx->mm_account) {
10099 mmdrop(ctx->mm_account);
10100 ctx->mm_account = NULL;
10103 io_rsrc_refs_drop(ctx);
10104 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10105 io_wait_rsrc_data(ctx->buf_data);
10106 io_wait_rsrc_data(ctx->file_data);
10108 mutex_lock(&ctx->uring_lock);
10110 __io_sqe_buffers_unregister(ctx);
10111 if (ctx->file_data)
10112 __io_sqe_files_unregister(ctx);
10114 __io_cqring_overflow_flush(ctx, true);
10115 io_eventfd_unregister(ctx);
10116 io_flush_apoll_cache(ctx);
10117 mutex_unlock(&ctx->uring_lock);
10118 io_destroy_buffers(ctx);
10120 put_cred(ctx->sq_creds);
10122 /* there are no registered resources left, nobody uses it */
10123 if (ctx->rsrc_node)
10124 io_rsrc_node_destroy(ctx->rsrc_node);
10125 if (ctx->rsrc_backup_node)
10126 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10127 flush_delayed_work(&ctx->rsrc_put_work);
10128 flush_delayed_work(&ctx->fallback_work);
10130 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10131 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10133 #if defined(CONFIG_UNIX)
10134 if (ctx->ring_sock) {
10135 ctx->ring_sock->file = NULL; /* so that iput() is called */
10136 sock_release(ctx->ring_sock);
10139 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10141 io_mem_free(ctx->rings);
10142 io_mem_free(ctx->sq_sqes);
10144 percpu_ref_exit(&ctx->refs);
10145 free_uid(ctx->user);
10146 io_req_caches_free(ctx);
10148 io_wq_put_hash(ctx->hash_map);
10149 io_free_napi_list(ctx);
10150 kfree(ctx->cancel_hash);
10151 kfree(ctx->dummy_ubuf);
10152 kfree(ctx->io_buffers);
10156 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10158 struct io_ring_ctx *ctx = file->private_data;
10161 poll_wait(file, &ctx->cq_wait, wait);
10163 * synchronizes with barrier from wq_has_sleeper call in
10167 if (!io_sqring_full(ctx))
10168 mask |= EPOLLOUT | EPOLLWRNORM;
10171 * Don't flush cqring overflow list here, just do a simple check.
10172 * Otherwise there could possible be ABBA deadlock:
10175 * lock(&ctx->uring_lock);
10177 * lock(&ctx->uring_lock);
10180 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10181 * pushs them to do the flush.
10183 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
10184 mask |= EPOLLIN | EPOLLRDNORM;
10189 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10191 const struct cred *creds;
10193 creds = xa_erase(&ctx->personalities, id);
10202 struct io_tctx_exit {
10203 struct callback_head task_work;
10204 struct completion completion;
10205 struct io_ring_ctx *ctx;
10208 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10210 struct io_uring_task *tctx = current->io_uring;
10211 struct io_tctx_exit *work;
10213 work = container_of(cb, struct io_tctx_exit, task_work);
10215 * When @in_idle, we're in cancellation and it's racy to remove the
10216 * node. It'll be removed by the end of cancellation, just ignore it.
10218 if (!atomic_read(&tctx->in_idle))
10219 io_uring_del_tctx_node((unsigned long)work->ctx);
10220 complete(&work->completion);
10223 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10225 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10227 return req->ctx == data;
10230 static __cold void io_ring_exit_work(struct work_struct *work)
10232 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10233 unsigned long timeout = jiffies + HZ * 60 * 5;
10234 unsigned long interval = HZ / 20;
10235 struct io_tctx_exit exit;
10236 struct io_tctx_node *node;
10240 * If we're doing polled IO and end up having requests being
10241 * submitted async (out-of-line), then completions can come in while
10242 * we're waiting for refs to drop. We need to reap these manually,
10243 * as nobody else will be looking for them.
10246 io_uring_try_cancel_requests(ctx, NULL, true);
10247 if (ctx->sq_data) {
10248 struct io_sq_data *sqd = ctx->sq_data;
10249 struct task_struct *tsk;
10251 io_sq_thread_park(sqd);
10253 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10254 io_wq_cancel_cb(tsk->io_uring->io_wq,
10255 io_cancel_ctx_cb, ctx, true);
10256 io_sq_thread_unpark(sqd);
10259 io_req_caches_free(ctx);
10261 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10262 /* there is little hope left, don't run it too often */
10263 interval = HZ * 60;
10265 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10267 init_completion(&exit.completion);
10268 init_task_work(&exit.task_work, io_tctx_exit_cb);
10271 * Some may use context even when all refs and requests have been put,
10272 * and they are free to do so while still holding uring_lock or
10273 * completion_lock, see io_req_task_submit(). Apart from other work,
10274 * this lock/unlock section also waits them to finish.
10276 mutex_lock(&ctx->uring_lock);
10277 while (!list_empty(&ctx->tctx_list)) {
10278 WARN_ON_ONCE(time_after(jiffies, timeout));
10280 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10282 /* don't spin on a single task if cancellation failed */
10283 list_rotate_left(&ctx->tctx_list);
10284 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10285 if (WARN_ON_ONCE(ret))
10288 mutex_unlock(&ctx->uring_lock);
10289 wait_for_completion(&exit.completion);
10290 mutex_lock(&ctx->uring_lock);
10292 mutex_unlock(&ctx->uring_lock);
10293 spin_lock(&ctx->completion_lock);
10294 spin_unlock(&ctx->completion_lock);
10296 io_ring_ctx_free(ctx);
10299 /* Returns true if we found and killed one or more timeouts */
10300 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10301 struct task_struct *tsk, bool cancel_all)
10303 struct io_kiocb *req, *tmp;
10306 spin_lock(&ctx->completion_lock);
10307 spin_lock_irq(&ctx->timeout_lock);
10308 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10309 if (io_match_task(req, tsk, cancel_all)) {
10310 io_kill_timeout(req, -ECANCELED);
10314 spin_unlock_irq(&ctx->timeout_lock);
10316 io_commit_cqring(ctx);
10317 spin_unlock(&ctx->completion_lock);
10319 io_cqring_ev_posted(ctx);
10320 return canceled != 0;
10323 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10325 unsigned long index;
10326 struct creds *creds;
10328 mutex_lock(&ctx->uring_lock);
10329 percpu_ref_kill(&ctx->refs);
10331 __io_cqring_overflow_flush(ctx, true);
10332 xa_for_each(&ctx->personalities, index, creds)
10333 io_unregister_personality(ctx, index);
10334 mutex_unlock(&ctx->uring_lock);
10336 io_kill_timeouts(ctx, NULL, true);
10337 io_poll_remove_all(ctx, NULL, true);
10339 /* if we failed setting up the ctx, we might not have any rings */
10340 io_iopoll_try_reap_events(ctx);
10342 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10344 * Use system_unbound_wq to avoid spawning tons of event kworkers
10345 * if we're exiting a ton of rings at the same time. It just adds
10346 * noise and overhead, there's no discernable change in runtime
10347 * over using system_wq.
10349 queue_work(system_unbound_wq, &ctx->exit_work);
10352 static int io_uring_release(struct inode *inode, struct file *file)
10354 struct io_ring_ctx *ctx = file->private_data;
10356 file->private_data = NULL;
10357 io_ring_ctx_wait_and_kill(ctx);
10361 struct io_task_cancel {
10362 struct task_struct *task;
10366 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10368 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10369 struct io_task_cancel *cancel = data;
10371 return io_match_task_safe(req, cancel->task, cancel->all);
10374 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10375 struct task_struct *task,
10378 struct io_defer_entry *de;
10381 spin_lock(&ctx->completion_lock);
10382 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10383 if (io_match_task_safe(de->req, task, cancel_all)) {
10384 list_cut_position(&list, &ctx->defer_list, &de->list);
10388 spin_unlock(&ctx->completion_lock);
10389 if (list_empty(&list))
10392 while (!list_empty(&list)) {
10393 de = list_first_entry(&list, struct io_defer_entry, list);
10394 list_del_init(&de->list);
10395 io_req_complete_failed(de->req, -ECANCELED);
10401 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10403 struct io_tctx_node *node;
10404 enum io_wq_cancel cret;
10407 mutex_lock(&ctx->uring_lock);
10408 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10409 struct io_uring_task *tctx = node->task->io_uring;
10412 * io_wq will stay alive while we hold uring_lock, because it's
10413 * killed after ctx nodes, which requires to take the lock.
10415 if (!tctx || !tctx->io_wq)
10417 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10418 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10420 mutex_unlock(&ctx->uring_lock);
10425 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10426 struct task_struct *task,
10429 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10430 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10433 enum io_wq_cancel cret;
10437 ret |= io_uring_try_cancel_iowq(ctx);
10438 } else if (tctx && tctx->io_wq) {
10440 * Cancels requests of all rings, not only @ctx, but
10441 * it's fine as the task is in exit/exec.
10443 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10445 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10448 /* SQPOLL thread does its own polling */
10449 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10450 (ctx->sq_data && ctx->sq_data->thread == current)) {
10451 while (!wq_list_empty(&ctx->iopoll_list)) {
10452 io_iopoll_try_reap_events(ctx);
10457 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10458 ret |= io_poll_remove_all(ctx, task, cancel_all);
10459 ret |= io_kill_timeouts(ctx, task, cancel_all);
10461 ret |= io_run_task_work();
10468 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10470 struct io_uring_task *tctx = current->io_uring;
10471 struct io_tctx_node *node;
10474 if (unlikely(!tctx)) {
10475 ret = io_uring_alloc_task_context(current, ctx);
10479 tctx = current->io_uring;
10480 if (ctx->iowq_limits_set) {
10481 unsigned int limits[2] = { ctx->iowq_limits[0],
10482 ctx->iowq_limits[1], };
10484 ret = io_wq_max_workers(tctx->io_wq, limits);
10489 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10490 node = kmalloc(sizeof(*node), GFP_KERNEL);
10494 node->task = current;
10496 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10497 node, GFP_KERNEL));
10503 mutex_lock(&ctx->uring_lock);
10504 list_add(&node->ctx_node, &ctx->tctx_list);
10505 mutex_unlock(&ctx->uring_lock);
10512 * Note that this task has used io_uring. We use it for cancelation purposes.
10514 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10516 struct io_uring_task *tctx = current->io_uring;
10518 if (likely(tctx && tctx->last == ctx))
10520 return __io_uring_add_tctx_node(ctx);
10524 * Remove this io_uring_file -> task mapping.
10526 static __cold void io_uring_del_tctx_node(unsigned long index)
10528 struct io_uring_task *tctx = current->io_uring;
10529 struct io_tctx_node *node;
10533 node = xa_erase(&tctx->xa, index);
10537 WARN_ON_ONCE(current != node->task);
10538 WARN_ON_ONCE(list_empty(&node->ctx_node));
10540 mutex_lock(&node->ctx->uring_lock);
10541 list_del(&node->ctx_node);
10542 mutex_unlock(&node->ctx->uring_lock);
10544 if (tctx->last == node->ctx)
10549 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10551 struct io_wq *wq = tctx->io_wq;
10552 struct io_tctx_node *node;
10553 unsigned long index;
10555 xa_for_each(&tctx->xa, index, node) {
10556 io_uring_del_tctx_node(index);
10561 * Must be after io_uring_del_tctx_node() (removes nodes under
10562 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10564 io_wq_put_and_exit(wq);
10565 tctx->io_wq = NULL;
10569 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10572 return atomic_read(&tctx->inflight_tracked);
10573 return percpu_counter_sum(&tctx->inflight);
10577 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10578 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10580 static __cold void io_uring_cancel_generic(bool cancel_all,
10581 struct io_sq_data *sqd)
10583 struct io_uring_task *tctx = current->io_uring;
10584 struct io_ring_ctx *ctx;
10588 WARN_ON_ONCE(sqd && sqd->thread != current);
10590 if (!current->io_uring)
10593 io_wq_exit_start(tctx->io_wq);
10595 atomic_inc(&tctx->in_idle);
10597 io_uring_drop_tctx_refs(current);
10598 /* read completions before cancelations */
10599 inflight = tctx_inflight(tctx, !cancel_all);
10604 struct io_tctx_node *node;
10605 unsigned long index;
10607 xa_for_each(&tctx->xa, index, node) {
10608 /* sqpoll task will cancel all its requests */
10609 if (node->ctx->sq_data)
10611 io_uring_try_cancel_requests(node->ctx, current,
10615 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10616 io_uring_try_cancel_requests(ctx, current,
10620 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10621 io_run_task_work();
10622 io_uring_drop_tctx_refs(current);
10625 * If we've seen completions, retry without waiting. This
10626 * avoids a race where a completion comes in before we did
10627 * prepare_to_wait().
10629 if (inflight == tctx_inflight(tctx, !cancel_all))
10631 finish_wait(&tctx->wait, &wait);
10634 io_uring_clean_tctx(tctx);
10637 * We shouldn't run task_works after cancel, so just leave
10638 * ->in_idle set for normal exit.
10640 atomic_dec(&tctx->in_idle);
10641 /* for exec all current's requests should be gone, kill tctx */
10642 __io_uring_free(current);
10646 void __io_uring_cancel(bool cancel_all)
10648 io_uring_cancel_generic(cancel_all, NULL);
10651 void io_uring_unreg_ringfd(void)
10653 struct io_uring_task *tctx = current->io_uring;
10656 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10657 if (tctx->registered_rings[i]) {
10658 fput(tctx->registered_rings[i]);
10659 tctx->registered_rings[i] = NULL;
10664 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10665 int start, int end)
10670 for (offset = start; offset < end; offset++) {
10671 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10672 if (tctx->registered_rings[offset])
10678 } else if (file->f_op != &io_uring_fops) {
10680 return -EOPNOTSUPP;
10682 tctx->registered_rings[offset] = file;
10690 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10691 * invocation. User passes in an array of struct io_uring_rsrc_update
10692 * with ->data set to the ring_fd, and ->offset given for the desired
10693 * index. If no index is desired, application may set ->offset == -1U
10694 * and we'll find an available index. Returns number of entries
10695 * successfully processed, or < 0 on error if none were processed.
10697 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10700 struct io_uring_rsrc_update __user *arg = __arg;
10701 struct io_uring_rsrc_update reg;
10702 struct io_uring_task *tctx;
10705 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10708 mutex_unlock(&ctx->uring_lock);
10709 ret = io_uring_add_tctx_node(ctx);
10710 mutex_lock(&ctx->uring_lock);
10714 tctx = current->io_uring;
10715 for (i = 0; i < nr_args; i++) {
10718 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10723 if (reg.offset == -1U) {
10725 end = IO_RINGFD_REG_MAX;
10727 if (reg.offset >= IO_RINGFD_REG_MAX) {
10731 start = reg.offset;
10735 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10740 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10741 fput(tctx->registered_rings[reg.offset]);
10742 tctx->registered_rings[reg.offset] = NULL;
10748 return i ? i : ret;
10751 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10754 struct io_uring_rsrc_update __user *arg = __arg;
10755 struct io_uring_task *tctx = current->io_uring;
10756 struct io_uring_rsrc_update reg;
10759 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10764 for (i = 0; i < nr_args; i++) {
10765 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10769 if (reg.offset >= IO_RINGFD_REG_MAX) {
10774 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10775 if (tctx->registered_rings[reg.offset]) {
10776 fput(tctx->registered_rings[reg.offset]);
10777 tctx->registered_rings[reg.offset] = NULL;
10781 return i ? i : ret;
10784 static void *io_uring_validate_mmap_request(struct file *file,
10785 loff_t pgoff, size_t sz)
10787 struct io_ring_ctx *ctx = file->private_data;
10788 loff_t offset = pgoff << PAGE_SHIFT;
10793 case IORING_OFF_SQ_RING:
10794 case IORING_OFF_CQ_RING:
10797 case IORING_OFF_SQES:
10798 ptr = ctx->sq_sqes;
10801 return ERR_PTR(-EINVAL);
10804 page = virt_to_head_page(ptr);
10805 if (sz > page_size(page))
10806 return ERR_PTR(-EINVAL);
10813 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10815 size_t sz = vma->vm_end - vma->vm_start;
10819 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10821 return PTR_ERR(ptr);
10823 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10824 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10827 #else /* !CONFIG_MMU */
10829 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10831 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10834 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10836 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10839 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10840 unsigned long addr, unsigned long len,
10841 unsigned long pgoff, unsigned long flags)
10845 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10847 return PTR_ERR(ptr);
10849 return (unsigned long) ptr;
10852 #endif /* !CONFIG_MMU */
10854 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10859 if (!io_sqring_full(ctx))
10861 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10863 if (!io_sqring_full(ctx))
10866 } while (!signal_pending(current));
10868 finish_wait(&ctx->sqo_sq_wait, &wait);
10872 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10873 struct __kernel_timespec __user **ts,
10874 const sigset_t __user **sig)
10876 struct io_uring_getevents_arg arg;
10879 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10880 * is just a pointer to the sigset_t.
10882 if (!(flags & IORING_ENTER_EXT_ARG)) {
10883 *sig = (const sigset_t __user *) argp;
10889 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10890 * timespec and sigset_t pointers if good.
10892 if (*argsz != sizeof(arg))
10894 if (copy_from_user(&arg, argp, sizeof(arg)))
10896 *sig = u64_to_user_ptr(arg.sigmask);
10897 *argsz = arg.sigmask_sz;
10898 *ts = u64_to_user_ptr(arg.ts);
10902 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10903 u32, min_complete, u32, flags, const void __user *, argp,
10906 struct io_ring_ctx *ctx;
10911 io_run_task_work();
10913 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10914 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10915 IORING_ENTER_REGISTERED_RING)))
10919 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10920 * need only dereference our task private array to find it.
10922 if (flags & IORING_ENTER_REGISTERED_RING) {
10923 struct io_uring_task *tctx = current->io_uring;
10925 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10927 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10928 f.file = tctx->registered_rings[fd];
10929 if (unlikely(!f.file))
10933 if (unlikely(!f.file))
10938 if (unlikely(f.file->f_op != &io_uring_fops))
10942 ctx = f.file->private_data;
10943 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10947 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10951 * For SQ polling, the thread will do all submissions and completions.
10952 * Just return the requested submit count, and wake the thread if
10953 * we were asked to.
10956 if (ctx->flags & IORING_SETUP_SQPOLL) {
10957 io_cqring_overflow_flush(ctx);
10959 if (unlikely(ctx->sq_data->thread == NULL)) {
10963 if (flags & IORING_ENTER_SQ_WAKEUP)
10964 wake_up(&ctx->sq_data->wait);
10965 if (flags & IORING_ENTER_SQ_WAIT) {
10966 ret = io_sqpoll_wait_sq(ctx);
10970 submitted = to_submit;
10971 } else if (to_submit) {
10972 ret = io_uring_add_tctx_node(ctx);
10975 mutex_lock(&ctx->uring_lock);
10976 submitted = io_submit_sqes(ctx, to_submit);
10977 mutex_unlock(&ctx->uring_lock);
10979 if (submitted != to_submit)
10982 if (flags & IORING_ENTER_GETEVENTS) {
10983 const sigset_t __user *sig;
10984 struct __kernel_timespec __user *ts;
10986 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10990 min_complete = min(min_complete, ctx->cq_entries);
10993 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10994 * space applications don't need to do io completion events
10995 * polling again, they can rely on io_sq_thread to do polling
10996 * work, which can reduce cpu usage and uring_lock contention.
10998 if (ctx->flags & IORING_SETUP_IOPOLL &&
10999 !(ctx->flags & IORING_SETUP_SQPOLL)) {
11000 ret = io_iopoll_check(ctx, min_complete);
11002 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
11007 percpu_ref_put(&ctx->refs);
11009 if (!(flags & IORING_ENTER_REGISTERED_RING))
11011 return submitted ? submitted : ret;
11014 #ifdef CONFIG_PROC_FS
11015 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11016 const struct cred *cred)
11018 struct user_namespace *uns = seq_user_ns(m);
11019 struct group_info *gi;
11024 seq_printf(m, "%5d\n", id);
11025 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11026 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11027 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11028 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11029 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11030 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11031 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11032 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11033 seq_puts(m, "\n\tGroups:\t");
11034 gi = cred->group_info;
11035 for (g = 0; g < gi->ngroups; g++) {
11036 seq_put_decimal_ull(m, g ? " " : "",
11037 from_kgid_munged(uns, gi->gid[g]));
11039 seq_puts(m, "\n\tCapEff:\t");
11040 cap = cred->cap_effective;
11041 CAP_FOR_EACH_U32(__capi)
11042 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11047 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11048 struct seq_file *m)
11050 struct io_sq_data *sq = NULL;
11051 struct io_overflow_cqe *ocqe;
11052 struct io_rings *r = ctx->rings;
11053 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11054 unsigned int sq_head = READ_ONCE(r->sq.head);
11055 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11056 unsigned int cq_head = READ_ONCE(r->cq.head);
11057 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11058 unsigned int sq_entries, cq_entries;
11063 * we may get imprecise sqe and cqe info if uring is actively running
11064 * since we get cached_sq_head and cached_cq_tail without uring_lock
11065 * and sq_tail and cq_head are changed by userspace. But it's ok since
11066 * we usually use these info when it is stuck.
11068 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11069 seq_printf(m, "SqHead:\t%u\n", sq_head);
11070 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11071 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11072 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11073 seq_printf(m, "CqHead:\t%u\n", cq_head);
11074 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11075 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11076 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11077 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11078 for (i = 0; i < sq_entries; i++) {
11079 unsigned int entry = i + sq_head;
11080 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11081 struct io_uring_sqe *sqe;
11083 if (sq_idx > sq_mask)
11085 sqe = &ctx->sq_sqes[sq_idx];
11086 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11087 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11090 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11091 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11092 for (i = 0; i < cq_entries; i++) {
11093 unsigned int entry = i + cq_head;
11094 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
11096 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11097 entry & cq_mask, cqe->user_data, cqe->res,
11102 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11103 * since fdinfo case grabs it in the opposite direction of normal use
11104 * cases. If we fail to get the lock, we just don't iterate any
11105 * structures that could be going away outside the io_uring mutex.
11107 has_lock = mutex_trylock(&ctx->uring_lock);
11109 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11115 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11116 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11117 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11118 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11119 struct file *f = io_file_from_index(ctx, i);
11122 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11124 seq_printf(m, "%5u: <none>\n", i);
11126 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11127 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11128 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11129 unsigned int len = buf->ubuf_end - buf->ubuf;
11131 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11133 if (has_lock && !xa_empty(&ctx->personalities)) {
11134 unsigned long index;
11135 const struct cred *cred;
11137 seq_printf(m, "Personalities:\n");
11138 xa_for_each(&ctx->personalities, index, cred)
11139 io_uring_show_cred(m, index, cred);
11142 mutex_unlock(&ctx->uring_lock);
11144 seq_puts(m, "PollList:\n");
11145 spin_lock(&ctx->completion_lock);
11146 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11147 struct hlist_head *list = &ctx->cancel_hash[i];
11148 struct io_kiocb *req;
11150 hlist_for_each_entry(req, list, hash_node)
11151 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11152 req->task->task_works != NULL);
11155 seq_puts(m, "CqOverflowList:\n");
11156 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11157 struct io_uring_cqe *cqe = &ocqe->cqe;
11159 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11160 cqe->user_data, cqe->res, cqe->flags);
11164 spin_unlock(&ctx->completion_lock);
11167 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11169 struct io_ring_ctx *ctx = f->private_data;
11171 if (percpu_ref_tryget(&ctx->refs)) {
11172 __io_uring_show_fdinfo(ctx, m);
11173 percpu_ref_put(&ctx->refs);
11178 static const struct file_operations io_uring_fops = {
11179 .release = io_uring_release,
11180 .mmap = io_uring_mmap,
11182 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11183 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11185 .poll = io_uring_poll,
11186 #ifdef CONFIG_PROC_FS
11187 .show_fdinfo = io_uring_show_fdinfo,
11191 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11192 struct io_uring_params *p)
11194 struct io_rings *rings;
11195 size_t size, sq_array_offset;
11197 /* make sure these are sane, as we already accounted them */
11198 ctx->sq_entries = p->sq_entries;
11199 ctx->cq_entries = p->cq_entries;
11201 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11202 if (size == SIZE_MAX)
11205 rings = io_mem_alloc(size);
11209 ctx->rings = rings;
11210 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11211 rings->sq_ring_mask = p->sq_entries - 1;
11212 rings->cq_ring_mask = p->cq_entries - 1;
11213 rings->sq_ring_entries = p->sq_entries;
11214 rings->cq_ring_entries = p->cq_entries;
11216 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11217 if (size == SIZE_MAX) {
11218 io_mem_free(ctx->rings);
11223 ctx->sq_sqes = io_mem_alloc(size);
11224 if (!ctx->sq_sqes) {
11225 io_mem_free(ctx->rings);
11233 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11237 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11241 ret = io_uring_add_tctx_node(ctx);
11246 fd_install(fd, file);
11251 * Allocate an anonymous fd, this is what constitutes the application
11252 * visible backing of an io_uring instance. The application mmaps this
11253 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11254 * we have to tie this fd to a socket for file garbage collection purposes.
11256 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11259 #if defined(CONFIG_UNIX)
11262 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11265 return ERR_PTR(ret);
11268 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11269 O_RDWR | O_CLOEXEC, NULL);
11270 #if defined(CONFIG_UNIX)
11271 if (IS_ERR(file)) {
11272 sock_release(ctx->ring_sock);
11273 ctx->ring_sock = NULL;
11275 ctx->ring_sock->file = file;
11281 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11282 struct io_uring_params __user *params)
11284 struct io_ring_ctx *ctx;
11290 if (entries > IORING_MAX_ENTRIES) {
11291 if (!(p->flags & IORING_SETUP_CLAMP))
11293 entries = IORING_MAX_ENTRIES;
11297 * Use twice as many entries for the CQ ring. It's possible for the
11298 * application to drive a higher depth than the size of the SQ ring,
11299 * since the sqes are only used at submission time. This allows for
11300 * some flexibility in overcommitting a bit. If the application has
11301 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11302 * of CQ ring entries manually.
11304 p->sq_entries = roundup_pow_of_two(entries);
11305 if (p->flags & IORING_SETUP_CQSIZE) {
11307 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11308 * to a power-of-two, if it isn't already. We do NOT impose
11309 * any cq vs sq ring sizing.
11311 if (!p->cq_entries)
11313 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11314 if (!(p->flags & IORING_SETUP_CLAMP))
11316 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11318 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11319 if (p->cq_entries < p->sq_entries)
11322 p->cq_entries = 2 * p->sq_entries;
11325 ctx = io_ring_ctx_alloc(p);
11328 ctx->compat = in_compat_syscall();
11329 if (!capable(CAP_IPC_LOCK))
11330 ctx->user = get_uid(current_user());
11333 * This is just grabbed for accounting purposes. When a process exits,
11334 * the mm is exited and dropped before the files, hence we need to hang
11335 * on to this mm purely for the purposes of being able to unaccount
11336 * memory (locked/pinned vm). It's not used for anything else.
11338 mmgrab(current->mm);
11339 ctx->mm_account = current->mm;
11341 ret = io_allocate_scq_urings(ctx, p);
11345 ret = io_sq_offload_create(ctx, p);
11348 /* always set a rsrc node */
11349 ret = io_rsrc_node_switch_start(ctx);
11352 io_rsrc_node_switch(ctx, NULL);
11354 memset(&p->sq_off, 0, sizeof(p->sq_off));
11355 p->sq_off.head = offsetof(struct io_rings, sq.head);
11356 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11357 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11358 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11359 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11360 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11361 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11363 memset(&p->cq_off, 0, sizeof(p->cq_off));
11364 p->cq_off.head = offsetof(struct io_rings, cq.head);
11365 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11366 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11367 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11368 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11369 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11370 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11372 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11373 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11374 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11375 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11376 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11377 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
11379 if (copy_to_user(params, p, sizeof(*p))) {
11384 file = io_uring_get_file(ctx);
11385 if (IS_ERR(file)) {
11386 ret = PTR_ERR(file);
11391 * Install ring fd as the very last thing, so we don't risk someone
11392 * having closed it before we finish setup
11394 ret = io_uring_install_fd(ctx, file);
11396 /* fput will clean it up */
11401 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11404 io_ring_ctx_wait_and_kill(ctx);
11409 * Sets up an aio uring context, and returns the fd. Applications asks for a
11410 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11411 * params structure passed in.
11413 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11415 struct io_uring_params p;
11418 if (copy_from_user(&p, params, sizeof(p)))
11420 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11425 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11426 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11427 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11428 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11431 return io_uring_create(entries, &p, params);
11434 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11435 struct io_uring_params __user *, params)
11437 return io_uring_setup(entries, params);
11440 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11443 struct io_uring_probe *p;
11447 size = struct_size(p, ops, nr_args);
11448 if (size == SIZE_MAX)
11450 p = kzalloc(size, GFP_KERNEL);
11455 if (copy_from_user(p, arg, size))
11458 if (memchr_inv(p, 0, size))
11461 p->last_op = IORING_OP_LAST - 1;
11462 if (nr_args > IORING_OP_LAST)
11463 nr_args = IORING_OP_LAST;
11465 for (i = 0; i < nr_args; i++) {
11467 if (!io_op_defs[i].not_supported)
11468 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11473 if (copy_to_user(arg, p, size))
11480 static int io_register_personality(struct io_ring_ctx *ctx)
11482 const struct cred *creds;
11486 creds = get_current_cred();
11488 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11489 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11497 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11498 void __user *arg, unsigned int nr_args)
11500 struct io_uring_restriction *res;
11504 /* Restrictions allowed only if rings started disabled */
11505 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11508 /* We allow only a single restrictions registration */
11509 if (ctx->restrictions.registered)
11512 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11515 size = array_size(nr_args, sizeof(*res));
11516 if (size == SIZE_MAX)
11519 res = memdup_user(arg, size);
11521 return PTR_ERR(res);
11525 for (i = 0; i < nr_args; i++) {
11526 switch (res[i].opcode) {
11527 case IORING_RESTRICTION_REGISTER_OP:
11528 if (res[i].register_op >= IORING_REGISTER_LAST) {
11533 __set_bit(res[i].register_op,
11534 ctx->restrictions.register_op);
11536 case IORING_RESTRICTION_SQE_OP:
11537 if (res[i].sqe_op >= IORING_OP_LAST) {
11542 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11544 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11545 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11547 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11548 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11557 /* Reset all restrictions if an error happened */
11559 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11561 ctx->restrictions.registered = true;
11567 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11569 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11572 if (ctx->restrictions.registered)
11573 ctx->restricted = 1;
11575 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11576 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11577 wake_up(&ctx->sq_data->wait);
11581 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11582 struct io_uring_rsrc_update2 *up,
11590 if (check_add_overflow(up->offset, nr_args, &tmp))
11592 err = io_rsrc_node_switch_start(ctx);
11597 case IORING_RSRC_FILE:
11598 return __io_sqe_files_update(ctx, up, nr_args);
11599 case IORING_RSRC_BUFFER:
11600 return __io_sqe_buffers_update(ctx, up, nr_args);
11605 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11608 struct io_uring_rsrc_update2 up;
11612 memset(&up, 0, sizeof(up));
11613 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11615 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11618 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11619 unsigned size, unsigned type)
11621 struct io_uring_rsrc_update2 up;
11623 if (size != sizeof(up))
11625 if (copy_from_user(&up, arg, sizeof(up)))
11627 if (!up.nr || up.resv)
11629 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11632 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11633 unsigned int size, unsigned int type)
11635 struct io_uring_rsrc_register rr;
11637 /* keep it extendible */
11638 if (size != sizeof(rr))
11641 memset(&rr, 0, sizeof(rr));
11642 if (copy_from_user(&rr, arg, size))
11644 if (!rr.nr || rr.resv || rr.resv2)
11648 case IORING_RSRC_FILE:
11649 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11650 rr.nr, u64_to_user_ptr(rr.tags));
11651 case IORING_RSRC_BUFFER:
11652 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11653 rr.nr, u64_to_user_ptr(rr.tags));
11658 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11659 void __user *arg, unsigned len)
11661 struct io_uring_task *tctx = current->io_uring;
11662 cpumask_var_t new_mask;
11665 if (!tctx || !tctx->io_wq)
11668 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11671 cpumask_clear(new_mask);
11672 if (len > cpumask_size())
11673 len = cpumask_size();
11675 if (copy_from_user(new_mask, arg, len)) {
11676 free_cpumask_var(new_mask);
11680 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11681 free_cpumask_var(new_mask);
11685 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11687 struct io_uring_task *tctx = current->io_uring;
11689 if (!tctx || !tctx->io_wq)
11692 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11695 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11697 __must_hold(&ctx->uring_lock)
11699 struct io_tctx_node *node;
11700 struct io_uring_task *tctx = NULL;
11701 struct io_sq_data *sqd = NULL;
11702 __u32 new_count[2];
11705 if (copy_from_user(new_count, arg, sizeof(new_count)))
11707 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11708 if (new_count[i] > INT_MAX)
11711 if (ctx->flags & IORING_SETUP_SQPOLL) {
11712 sqd = ctx->sq_data;
11715 * Observe the correct sqd->lock -> ctx->uring_lock
11716 * ordering. Fine to drop uring_lock here, we hold
11717 * a ref to the ctx.
11719 refcount_inc(&sqd->refs);
11720 mutex_unlock(&ctx->uring_lock);
11721 mutex_lock(&sqd->lock);
11722 mutex_lock(&ctx->uring_lock);
11724 tctx = sqd->thread->io_uring;
11727 tctx = current->io_uring;
11730 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11732 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11734 ctx->iowq_limits[i] = new_count[i];
11735 ctx->iowq_limits_set = true;
11737 if (tctx && tctx->io_wq) {
11738 ret = io_wq_max_workers(tctx->io_wq, new_count);
11742 memset(new_count, 0, sizeof(new_count));
11746 mutex_unlock(&sqd->lock);
11747 io_put_sq_data(sqd);
11750 if (copy_to_user(arg, new_count, sizeof(new_count)))
11753 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11757 /* now propagate the restriction to all registered users */
11758 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11759 struct io_uring_task *tctx = node->task->io_uring;
11761 if (WARN_ON_ONCE(!tctx->io_wq))
11764 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11765 new_count[i] = ctx->iowq_limits[i];
11766 /* ignore errors, it always returns zero anyway */
11767 (void)io_wq_max_workers(tctx->io_wq, new_count);
11772 mutex_unlock(&sqd->lock);
11773 io_put_sq_data(sqd);
11778 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11779 void __user *arg, unsigned nr_args)
11780 __releases(ctx->uring_lock)
11781 __acquires(ctx->uring_lock)
11786 * We're inside the ring mutex, if the ref is already dying, then
11787 * someone else killed the ctx or is already going through
11788 * io_uring_register().
11790 if (percpu_ref_is_dying(&ctx->refs))
11793 if (ctx->restricted) {
11794 if (opcode >= IORING_REGISTER_LAST)
11796 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11797 if (!test_bit(opcode, ctx->restrictions.register_op))
11802 case IORING_REGISTER_BUFFERS:
11803 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11805 case IORING_UNREGISTER_BUFFERS:
11807 if (arg || nr_args)
11809 ret = io_sqe_buffers_unregister(ctx);
11811 case IORING_REGISTER_FILES:
11812 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11814 case IORING_UNREGISTER_FILES:
11816 if (arg || nr_args)
11818 ret = io_sqe_files_unregister(ctx);
11820 case IORING_REGISTER_FILES_UPDATE:
11821 ret = io_register_files_update(ctx, arg, nr_args);
11823 case IORING_REGISTER_EVENTFD:
11827 ret = io_eventfd_register(ctx, arg, 0);
11829 case IORING_REGISTER_EVENTFD_ASYNC:
11833 ret = io_eventfd_register(ctx, arg, 1);
11835 case IORING_UNREGISTER_EVENTFD:
11837 if (arg || nr_args)
11839 ret = io_eventfd_unregister(ctx);
11841 case IORING_REGISTER_PROBE:
11843 if (!arg || nr_args > 256)
11845 ret = io_probe(ctx, arg, nr_args);
11847 case IORING_REGISTER_PERSONALITY:
11849 if (arg || nr_args)
11851 ret = io_register_personality(ctx);
11853 case IORING_UNREGISTER_PERSONALITY:
11857 ret = io_unregister_personality(ctx, nr_args);
11859 case IORING_REGISTER_ENABLE_RINGS:
11861 if (arg || nr_args)
11863 ret = io_register_enable_rings(ctx);
11865 case IORING_REGISTER_RESTRICTIONS:
11866 ret = io_register_restrictions(ctx, arg, nr_args);
11868 case IORING_REGISTER_FILES2:
11869 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11871 case IORING_REGISTER_FILES_UPDATE2:
11872 ret = io_register_rsrc_update(ctx, arg, nr_args,
11875 case IORING_REGISTER_BUFFERS2:
11876 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11878 case IORING_REGISTER_BUFFERS_UPDATE:
11879 ret = io_register_rsrc_update(ctx, arg, nr_args,
11880 IORING_RSRC_BUFFER);
11882 case IORING_REGISTER_IOWQ_AFF:
11884 if (!arg || !nr_args)
11886 ret = io_register_iowq_aff(ctx, arg, nr_args);
11888 case IORING_UNREGISTER_IOWQ_AFF:
11890 if (arg || nr_args)
11892 ret = io_unregister_iowq_aff(ctx);
11894 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11896 if (!arg || nr_args != 2)
11898 ret = io_register_iowq_max_workers(ctx, arg);
11900 case IORING_REGISTER_RING_FDS:
11901 ret = io_ringfd_register(ctx, arg, nr_args);
11903 case IORING_UNREGISTER_RING_FDS:
11904 ret = io_ringfd_unregister(ctx, arg, nr_args);
11914 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11915 void __user *, arg, unsigned int, nr_args)
11917 struct io_ring_ctx *ctx;
11926 if (f.file->f_op != &io_uring_fops)
11929 ctx = f.file->private_data;
11931 io_run_task_work();
11933 mutex_lock(&ctx->uring_lock);
11934 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11935 mutex_unlock(&ctx->uring_lock);
11936 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11942 static int __init io_uring_init(void)
11944 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11945 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11946 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11949 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11950 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11951 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11952 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11953 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11954 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11955 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11956 BUILD_BUG_SQE_ELEM(8, __u64, off);
11957 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11958 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11959 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11960 BUILD_BUG_SQE_ELEM(24, __u32, len);
11961 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11962 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11963 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11964 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11965 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11966 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11967 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11968 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11969 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11970 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11971 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11972 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11973 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11974 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11975 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11976 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11977 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11978 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11979 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11980 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11981 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11983 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11984 sizeof(struct io_uring_rsrc_update));
11985 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11986 sizeof(struct io_uring_rsrc_update2));
11988 /* ->buf_index is u16 */
11989 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11991 /* should fit into one byte */
11992 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11993 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11994 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11996 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11997 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11999 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
12003 __initcall(io_uring_init);