1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/audit.h>
82 #include <linux/security.h>
84 #define CREATE_TRACE_POINTS
85 #include <trace/events/io_uring.h>
87 #include <uapi/linux/io_uring.h>
92 #define IORING_MAX_ENTRIES 32768
93 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
97 #define IORING_MAX_FIXED_FILES (1U << 15)
98 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
99 IORING_REGISTER_LAST + IORING_OP_LAST)
101 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
102 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
103 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
105 #define IORING_MAX_REG_BUFFERS (1U << 14)
107 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
108 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
111 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
114 REQ_F_POLLED | REQ_F_CREDS | REQ_F_ASYNC_DATA)
116 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
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 unsigned int syscall_iopoll: 1;
360 } ____cacheline_aligned_in_smp;
362 /* submission data */
364 struct mutex uring_lock;
367 * Ring buffer of indices into array of io_uring_sqe, which is
368 * mmapped by the application using the IORING_OFF_SQES offset.
370 * This indirection could e.g. be used to assign fixed
371 * io_uring_sqe entries to operations and only submit them to
372 * the queue when needed.
374 * The kernel modifies neither the indices array nor the entries
378 struct io_uring_sqe *sq_sqes;
379 unsigned cached_sq_head;
381 struct list_head defer_list;
384 * Fixed resources fast path, should be accessed only under
385 * uring_lock, and updated through io_uring_register(2)
387 struct io_rsrc_node *rsrc_node;
388 int rsrc_cached_refs;
389 struct io_file_table file_table;
390 unsigned nr_user_files;
391 unsigned nr_user_bufs;
392 struct io_mapped_ubuf **user_bufs;
394 struct io_submit_state submit_state;
395 struct list_head timeout_list;
396 struct list_head ltimeout_list;
397 struct list_head cq_overflow_list;
398 struct list_head *io_buffers;
399 struct list_head io_buffers_cache;
400 struct list_head apoll_cache;
401 struct xarray personalities;
403 unsigned sq_thread_idle;
404 } ____cacheline_aligned_in_smp;
406 /* IRQ completion list, under ->completion_lock */
407 struct io_wq_work_list locked_free_list;
408 unsigned int locked_free_nr;
410 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
411 struct io_sq_data *sq_data; /* if using sq thread polling */
413 struct wait_queue_head sqo_sq_wait;
414 struct list_head sqd_list;
416 unsigned long check_cq_overflow;
420 * We cache a range of free CQEs we can use, once exhausted it
421 * should go through a slower range setup, see __io_get_cqe()
423 struct io_uring_cqe *cqe_cached;
424 struct io_uring_cqe *cqe_sentinel;
426 unsigned cached_cq_tail;
428 struct io_ev_fd __rcu *io_ev_fd;
429 struct wait_queue_head cq_wait;
431 atomic_t cq_timeouts;
432 unsigned cq_last_tm_flush;
433 } ____cacheline_aligned_in_smp;
436 spinlock_t completion_lock;
438 spinlock_t timeout_lock;
441 * ->iopoll_list is protected by the ctx->uring_lock for
442 * io_uring instances that don't use IORING_SETUP_SQPOLL.
443 * For SQPOLL, only the single threaded io_sq_thread() will
444 * manipulate the list, hence no extra locking is needed there.
446 struct io_wq_work_list iopoll_list;
447 struct hlist_head *cancel_hash;
448 unsigned cancel_hash_bits;
449 bool poll_multi_queue;
451 struct list_head io_buffers_comp;
452 } ____cacheline_aligned_in_smp;
454 struct io_restriction restrictions;
456 /* slow path rsrc auxilary data, used by update/register */
458 struct io_rsrc_node *rsrc_backup_node;
459 struct io_mapped_ubuf *dummy_ubuf;
460 struct io_rsrc_data *file_data;
461 struct io_rsrc_data *buf_data;
463 struct delayed_work rsrc_put_work;
464 struct llist_head rsrc_put_llist;
465 struct list_head rsrc_ref_list;
466 spinlock_t rsrc_ref_lock;
468 struct list_head io_buffers_pages;
471 /* Keep this last, we don't need it for the fast path */
473 #if defined(CONFIG_UNIX)
474 struct socket *ring_sock;
476 /* hashed buffered write serialization */
477 struct io_wq_hash *hash_map;
479 /* Only used for accounting purposes */
480 struct user_struct *user;
481 struct mm_struct *mm_account;
483 /* ctx exit and cancelation */
484 struct llist_head fallback_llist;
485 struct delayed_work fallback_work;
486 struct work_struct exit_work;
487 struct list_head tctx_list;
488 struct completion ref_comp;
490 bool iowq_limits_set;
495 * Arbitrary limit, can be raised if need be
497 #define IO_RINGFD_REG_MAX 16
499 struct io_uring_task {
500 /* submission side */
503 struct wait_queue_head wait;
504 const struct io_ring_ctx *last;
506 struct percpu_counter inflight;
509 spinlock_t task_lock;
510 struct io_wq_work_list task_list;
511 struct io_wq_work_list prior_task_list;
512 struct callback_head task_work;
513 struct file **registered_rings;
518 * First field must be the file pointer in all the
519 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
521 struct io_poll_iocb {
523 struct wait_queue_head *head;
525 struct wait_queue_entry wait;
528 struct io_poll_update {
534 bool update_user_data;
543 struct io_timeout_data {
544 struct io_kiocb *req;
545 struct hrtimer timer;
546 struct timespec64 ts;
547 enum hrtimer_mode mode;
553 struct sockaddr __user *addr;
554 int __user *addr_len;
557 unsigned long nofile;
577 struct list_head list;
578 /* head of the link, used by linked timeouts only */
579 struct io_kiocb *head;
580 /* for linked completions */
581 struct io_kiocb *prev;
584 struct io_timeout_rem {
589 struct timespec64 ts;
595 /* NOTE: kiocb has the file as the first member, so don't do it here */
604 struct sockaddr __user *addr;
611 struct compat_msghdr __user *umsg_compat;
612 struct user_msghdr __user *umsg;
625 struct filename *filename;
627 unsigned long nofile;
630 struct io_rsrc_update {
656 struct epoll_event event;
660 struct file *file_out;
668 struct io_provide_buf {
682 struct filename *filename;
683 struct statx __user *buffer;
695 struct filename *oldpath;
696 struct filename *newpath;
704 struct filename *filename;
711 struct filename *filename;
717 struct filename *oldpath;
718 struct filename *newpath;
725 struct filename *oldpath;
726 struct filename *newpath;
736 struct io_async_connect {
737 struct sockaddr_storage address;
740 struct io_async_msghdr {
741 struct iovec fast_iov[UIO_FASTIOV];
742 /* points to an allocated iov, if NULL we use fast_iov instead */
743 struct iovec *free_iov;
744 struct sockaddr __user *uaddr;
746 struct sockaddr_storage addr;
750 struct iov_iter iter;
751 struct iov_iter_state iter_state;
752 struct iovec fast_iov[UIO_FASTIOV];
756 struct io_rw_state s;
757 const struct iovec *free_iovec;
759 struct wait_page_queue wpq;
763 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
764 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
765 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
766 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
767 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
768 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
769 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
771 /* first byte is taken by user flags, shift it to not overlap */
776 REQ_F_LINK_TIMEOUT_BIT,
777 REQ_F_NEED_CLEANUP_BIT,
779 REQ_F_BUFFER_SELECTED_BIT,
780 REQ_F_COMPLETE_INLINE_BIT,
784 REQ_F_ARM_LTIMEOUT_BIT,
785 REQ_F_ASYNC_DATA_BIT,
786 REQ_F_SKIP_LINK_CQES_BIT,
787 REQ_F_SINGLE_POLL_BIT,
788 REQ_F_DOUBLE_POLL_BIT,
789 REQ_F_PARTIAL_IO_BIT,
790 /* keep async read/write and isreg together and in order */
791 REQ_F_SUPPORT_NOWAIT_BIT,
794 /* not a real bit, just to check we're not overflowing the space */
800 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
801 /* drain existing IO first */
802 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
804 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
805 /* doesn't sever on completion < 0 */
806 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
808 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
809 /* IOSQE_BUFFER_SELECT */
810 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
811 /* IOSQE_CQE_SKIP_SUCCESS */
812 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
814 /* fail rest of links */
815 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
816 /* on inflight list, should be cancelled and waited on exit reliably */
817 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
818 /* read/write uses file position */
819 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
820 /* must not punt to workers */
821 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
822 /* has or had linked timeout */
823 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
825 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
826 /* already went through poll handler */
827 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
828 /* buffer already selected */
829 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
830 /* completion is deferred through io_comp_state */
831 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
832 /* caller should reissue async */
833 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
834 /* supports async reads/writes */
835 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
837 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
838 /* has creds assigned */
839 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
840 /* skip refcounting if not set */
841 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
842 /* there is a linked timeout that has to be armed */
843 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
844 /* ->async_data allocated */
845 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
846 /* don't post CQEs while failing linked requests */
847 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
848 /* single poll may be active */
849 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
850 /* double poll may active */
851 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
852 /* request has already done partial IO */
853 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
857 struct io_poll_iocb poll;
858 struct io_poll_iocb *double_poll;
861 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
863 struct io_task_work {
865 struct io_wq_work_node node;
866 struct llist_node fallback_node;
868 io_req_tw_func_t func;
872 IORING_RSRC_FILE = 0,
873 IORING_RSRC_BUFFER = 1,
879 /* fd initially, then cflags for completion */
887 * NOTE! Each of the iocb union members has the file pointer
888 * as the first entry in their struct definition. So you can
889 * access the file pointer through any of the sub-structs,
890 * or directly as just 'file' in this struct.
896 struct io_poll_iocb poll;
897 struct io_poll_update poll_update;
898 struct io_accept accept;
900 struct io_cancel cancel;
901 struct io_timeout timeout;
902 struct io_timeout_rem timeout_rem;
903 struct io_connect connect;
904 struct io_sr_msg sr_msg;
906 struct io_close close;
907 struct io_rsrc_update rsrc_update;
908 struct io_fadvise fadvise;
909 struct io_madvise madvise;
910 struct io_epoll epoll;
911 struct io_splice splice;
912 struct io_provide_buf pbuf;
913 struct io_statx statx;
914 struct io_shutdown shutdown;
915 struct io_rename rename;
916 struct io_unlink unlink;
917 struct io_mkdir mkdir;
918 struct io_symlink symlink;
919 struct io_hardlink hardlink;
924 /* polled IO has completed */
931 struct io_ring_ctx *ctx;
932 struct task_struct *task;
934 struct percpu_ref *fixed_rsrc_refs;
935 /* store used ubuf, so we can prevent reloading */
936 struct io_mapped_ubuf *imu;
939 /* used by request caches, completion batching and iopoll */
940 struct io_wq_work_node comp_list;
941 /* cache ->apoll->events */
946 struct io_task_work io_task_work;
947 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
948 struct hlist_node hash_node;
949 /* internal polling, see IORING_FEAT_FAST_POLL */
950 struct async_poll *apoll;
951 /* opcode allocated if it needs to store data for async defer */
953 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
954 struct io_buffer *kbuf;
955 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
956 struct io_kiocb *link;
957 /* custom credentials, valid IFF REQ_F_CREDS is set */
958 const struct cred *creds;
959 struct io_wq_work work;
962 struct io_tctx_node {
963 struct list_head ctx_node;
964 struct task_struct *task;
965 struct io_ring_ctx *ctx;
968 struct io_defer_entry {
969 struct list_head list;
970 struct io_kiocb *req;
975 /* needs req->file assigned */
976 unsigned needs_file : 1;
977 /* should block plug */
979 /* hash wq insertion if file is a regular file */
980 unsigned hash_reg_file : 1;
981 /* unbound wq insertion if file is a non-regular file */
982 unsigned unbound_nonreg_file : 1;
983 /* set if opcode supports polled "wait" */
985 unsigned pollout : 1;
986 unsigned poll_exclusive : 1;
987 /* op supports buffer selection */
988 unsigned buffer_select : 1;
989 /* do prep async if is going to be punted */
990 unsigned needs_async_setup : 1;
991 /* opcode is not supported by this kernel */
992 unsigned not_supported : 1;
994 unsigned audit_skip : 1;
995 /* size of async data needed, if any */
996 unsigned short async_size;
999 static const struct io_op_def io_op_defs[] = {
1000 [IORING_OP_NOP] = {},
1001 [IORING_OP_READV] = {
1003 .unbound_nonreg_file = 1,
1006 .needs_async_setup = 1,
1009 .async_size = sizeof(struct io_async_rw),
1011 [IORING_OP_WRITEV] = {
1014 .unbound_nonreg_file = 1,
1016 .needs_async_setup = 1,
1019 .async_size = sizeof(struct io_async_rw),
1021 [IORING_OP_FSYNC] = {
1025 [IORING_OP_READ_FIXED] = {
1027 .unbound_nonreg_file = 1,
1031 .async_size = sizeof(struct io_async_rw),
1033 [IORING_OP_WRITE_FIXED] = {
1036 .unbound_nonreg_file = 1,
1040 .async_size = sizeof(struct io_async_rw),
1042 [IORING_OP_POLL_ADD] = {
1044 .unbound_nonreg_file = 1,
1047 [IORING_OP_POLL_REMOVE] = {
1050 [IORING_OP_SYNC_FILE_RANGE] = {
1054 [IORING_OP_SENDMSG] = {
1056 .unbound_nonreg_file = 1,
1058 .needs_async_setup = 1,
1059 .async_size = sizeof(struct io_async_msghdr),
1061 [IORING_OP_RECVMSG] = {
1063 .unbound_nonreg_file = 1,
1066 .needs_async_setup = 1,
1067 .async_size = sizeof(struct io_async_msghdr),
1069 [IORING_OP_TIMEOUT] = {
1071 .async_size = sizeof(struct io_timeout_data),
1073 [IORING_OP_TIMEOUT_REMOVE] = {
1074 /* used by timeout updates' prep() */
1077 [IORING_OP_ACCEPT] = {
1079 .unbound_nonreg_file = 1,
1081 .poll_exclusive = 1,
1083 [IORING_OP_ASYNC_CANCEL] = {
1086 [IORING_OP_LINK_TIMEOUT] = {
1088 .async_size = sizeof(struct io_timeout_data),
1090 [IORING_OP_CONNECT] = {
1092 .unbound_nonreg_file = 1,
1094 .needs_async_setup = 1,
1095 .async_size = sizeof(struct io_async_connect),
1097 [IORING_OP_FALLOCATE] = {
1100 [IORING_OP_OPENAT] = {},
1101 [IORING_OP_CLOSE] = {},
1102 [IORING_OP_FILES_UPDATE] = {
1105 [IORING_OP_STATX] = {
1108 [IORING_OP_READ] = {
1110 .unbound_nonreg_file = 1,
1115 .async_size = sizeof(struct io_async_rw),
1117 [IORING_OP_WRITE] = {
1120 .unbound_nonreg_file = 1,
1124 .async_size = sizeof(struct io_async_rw),
1126 [IORING_OP_FADVISE] = {
1130 [IORING_OP_MADVISE] = {},
1131 [IORING_OP_SEND] = {
1133 .unbound_nonreg_file = 1,
1137 [IORING_OP_RECV] = {
1139 .unbound_nonreg_file = 1,
1144 [IORING_OP_OPENAT2] = {
1146 [IORING_OP_EPOLL_CTL] = {
1147 .unbound_nonreg_file = 1,
1150 [IORING_OP_SPLICE] = {
1153 .unbound_nonreg_file = 1,
1156 [IORING_OP_PROVIDE_BUFFERS] = {
1159 [IORING_OP_REMOVE_BUFFERS] = {
1165 .unbound_nonreg_file = 1,
1168 [IORING_OP_SHUTDOWN] = {
1171 [IORING_OP_RENAMEAT] = {},
1172 [IORING_OP_UNLINKAT] = {},
1173 [IORING_OP_MKDIRAT] = {},
1174 [IORING_OP_SYMLINKAT] = {},
1175 [IORING_OP_LINKAT] = {},
1176 [IORING_OP_MSG_RING] = {
1181 /* requests with any of those set should undergo io_disarm_next() */
1182 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1184 static bool io_disarm_next(struct io_kiocb *req);
1185 static void io_uring_del_tctx_node(unsigned long index);
1186 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1187 struct task_struct *task,
1189 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1191 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1192 static void io_dismantle_req(struct io_kiocb *req);
1193 static void io_queue_linked_timeout(struct io_kiocb *req);
1194 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1195 struct io_uring_rsrc_update2 *up,
1197 static void io_clean_op(struct io_kiocb *req);
1198 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1199 unsigned issue_flags);
1200 static inline struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1201 static void io_drop_inflight_file(struct io_kiocb *req);
1202 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags);
1203 static void io_queue_sqe(struct io_kiocb *req);
1204 static void io_rsrc_put_work(struct work_struct *work);
1206 static void io_req_task_queue(struct io_kiocb *req);
1207 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1208 static int io_req_prep_async(struct io_kiocb *req);
1210 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1211 unsigned int issue_flags, u32 slot_index);
1212 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1214 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1215 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1216 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1218 static struct kmem_cache *req_cachep;
1220 static const struct file_operations io_uring_fops;
1222 struct sock *io_uring_get_socket(struct file *file)
1224 #if defined(CONFIG_UNIX)
1225 if (file->f_op == &io_uring_fops) {
1226 struct io_ring_ctx *ctx = file->private_data;
1228 return ctx->ring_sock->sk;
1233 EXPORT_SYMBOL(io_uring_get_socket);
1235 #if defined(CONFIG_UNIX)
1236 static inline bool io_file_need_scm(struct file *filp)
1238 return !!unix_get_socket(filp);
1241 static inline bool io_file_need_scm(struct file *filp)
1247 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1249 lockdep_assert_held(&ctx->uring_lock);
1250 if (issue_flags & IO_URING_F_UNLOCKED)
1251 mutex_unlock(&ctx->uring_lock);
1254 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1257 * "Normal" inline submissions always hold the uring_lock, since we
1258 * grab it from the system call. Same is true for the SQPOLL offload.
1259 * The only exception is when we've detached the request and issue it
1260 * from an async worker thread, grab the lock for that case.
1262 if (issue_flags & IO_URING_F_UNLOCKED)
1263 mutex_lock(&ctx->uring_lock);
1264 lockdep_assert_held(&ctx->uring_lock);
1267 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1270 mutex_lock(&ctx->uring_lock);
1275 #define io_for_each_link(pos, head) \
1276 for (pos = (head); pos; pos = pos->link)
1279 * Shamelessly stolen from the mm implementation of page reference checking,
1280 * see commit f958d7b528b1 for details.
1282 #define req_ref_zero_or_close_to_overflow(req) \
1283 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1285 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1287 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1288 return atomic_inc_not_zero(&req->refs);
1291 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1293 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1296 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1297 return atomic_dec_and_test(&req->refs);
1300 static inline void req_ref_get(struct io_kiocb *req)
1302 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1303 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1304 atomic_inc(&req->refs);
1307 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1309 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1310 __io_submit_flush_completions(ctx);
1313 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1315 if (!(req->flags & REQ_F_REFCOUNT)) {
1316 req->flags |= REQ_F_REFCOUNT;
1317 atomic_set(&req->refs, nr);
1321 static inline void io_req_set_refcount(struct io_kiocb *req)
1323 __io_req_set_refcount(req, 1);
1326 #define IO_RSRC_REF_BATCH 100
1328 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1329 struct io_ring_ctx *ctx)
1330 __must_hold(&ctx->uring_lock)
1332 struct percpu_ref *ref = req->fixed_rsrc_refs;
1335 if (ref == &ctx->rsrc_node->refs)
1336 ctx->rsrc_cached_refs++;
1338 percpu_ref_put(ref);
1342 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1344 if (req->fixed_rsrc_refs)
1345 percpu_ref_put(req->fixed_rsrc_refs);
1348 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1349 __must_hold(&ctx->uring_lock)
1351 if (ctx->rsrc_cached_refs) {
1352 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1353 ctx->rsrc_cached_refs = 0;
1357 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1358 __must_hold(&ctx->uring_lock)
1360 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1361 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1364 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1365 struct io_ring_ctx *ctx,
1366 unsigned int issue_flags)
1368 if (!req->fixed_rsrc_refs) {
1369 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1371 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1372 lockdep_assert_held(&ctx->uring_lock);
1373 ctx->rsrc_cached_refs--;
1374 if (unlikely(ctx->rsrc_cached_refs < 0))
1375 io_rsrc_refs_refill(ctx);
1377 percpu_ref_get(req->fixed_rsrc_refs);
1382 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1384 struct io_buffer *kbuf = req->kbuf;
1385 unsigned int cflags;
1387 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1388 req->flags &= ~REQ_F_BUFFER_SELECTED;
1389 list_add(&kbuf->list, list);
1394 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1396 lockdep_assert_held(&req->ctx->completion_lock);
1398 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1400 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1403 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1404 unsigned issue_flags)
1406 unsigned int cflags;
1408 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1412 * We can add this buffer back to two lists:
1414 * 1) The io_buffers_cache list. This one is protected by the
1415 * ctx->uring_lock. If we already hold this lock, add back to this
1416 * list as we can grab it from issue as well.
1417 * 2) The io_buffers_comp list. This one is protected by the
1418 * ctx->completion_lock.
1420 * We migrate buffers from the comp_list to the issue cache list
1423 if (issue_flags & IO_URING_F_UNLOCKED) {
1424 struct io_ring_ctx *ctx = req->ctx;
1426 spin_lock(&ctx->completion_lock);
1427 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1428 spin_unlock(&ctx->completion_lock);
1430 lockdep_assert_held(&req->ctx->uring_lock);
1432 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1438 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1441 struct list_head *hash_list;
1442 struct io_buffer_list *bl;
1444 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1445 list_for_each_entry(bl, hash_list, list)
1446 if (bl->bgid == bgid || bgid == -1U)
1452 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1454 struct io_ring_ctx *ctx = req->ctx;
1455 struct io_buffer_list *bl;
1456 struct io_buffer *buf;
1458 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1460 /* don't recycle if we already did IO to this buffer */
1461 if (req->flags & REQ_F_PARTIAL_IO)
1464 io_ring_submit_lock(ctx, issue_flags);
1467 bl = io_buffer_get_list(ctx, buf->bgid);
1468 list_add(&buf->list, &bl->buf_list);
1469 req->flags &= ~REQ_F_BUFFER_SELECTED;
1472 io_ring_submit_unlock(ctx, issue_flags);
1475 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1477 __must_hold(&req->ctx->timeout_lock)
1479 if (task && head->task != task)
1485 * As io_match_task() but protected against racing with linked timeouts.
1486 * User must not hold timeout_lock.
1488 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1491 if (task && head->task != task)
1496 static inline bool req_has_async_data(struct io_kiocb *req)
1498 return req->flags & REQ_F_ASYNC_DATA;
1501 static inline void req_set_fail(struct io_kiocb *req)
1503 req->flags |= REQ_F_FAIL;
1504 if (req->flags & REQ_F_CQE_SKIP) {
1505 req->flags &= ~REQ_F_CQE_SKIP;
1506 req->flags |= REQ_F_SKIP_LINK_CQES;
1510 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1516 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1518 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1521 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1523 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1525 complete(&ctx->ref_comp);
1528 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1530 return !req->timeout.off;
1533 static __cold void io_fallback_req_func(struct work_struct *work)
1535 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1536 fallback_work.work);
1537 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1538 struct io_kiocb *req, *tmp;
1539 bool locked = false;
1541 percpu_ref_get(&ctx->refs);
1542 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1543 req->io_task_work.func(req, &locked);
1546 io_submit_flush_completions(ctx);
1547 mutex_unlock(&ctx->uring_lock);
1549 percpu_ref_put(&ctx->refs);
1552 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1554 struct io_ring_ctx *ctx;
1557 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1562 * Use 5 bits less than the max cq entries, that should give us around
1563 * 32 entries per hash list if totally full and uniformly spread.
1565 hash_bits = ilog2(p->cq_entries);
1569 ctx->cancel_hash_bits = hash_bits;
1570 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1572 if (!ctx->cancel_hash)
1574 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1576 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1577 if (!ctx->dummy_ubuf)
1579 /* set invalid range, so io_import_fixed() fails meeting it */
1580 ctx->dummy_ubuf->ubuf = -1UL;
1582 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1583 sizeof(struct list_head), GFP_KERNEL);
1584 if (!ctx->io_buffers)
1586 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1587 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1589 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1590 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1593 ctx->flags = p->flags;
1594 init_waitqueue_head(&ctx->sqo_sq_wait);
1595 INIT_LIST_HEAD(&ctx->sqd_list);
1596 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1597 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1598 INIT_LIST_HEAD(&ctx->apoll_cache);
1599 init_completion(&ctx->ref_comp);
1600 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1601 mutex_init(&ctx->uring_lock);
1602 init_waitqueue_head(&ctx->cq_wait);
1603 spin_lock_init(&ctx->completion_lock);
1604 spin_lock_init(&ctx->timeout_lock);
1605 INIT_WQ_LIST(&ctx->iopoll_list);
1606 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1607 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1608 INIT_LIST_HEAD(&ctx->defer_list);
1609 INIT_LIST_HEAD(&ctx->timeout_list);
1610 INIT_LIST_HEAD(&ctx->ltimeout_list);
1611 spin_lock_init(&ctx->rsrc_ref_lock);
1612 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1613 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1614 init_llist_head(&ctx->rsrc_put_llist);
1615 INIT_LIST_HEAD(&ctx->tctx_list);
1616 ctx->submit_state.free_list.next = NULL;
1617 INIT_WQ_LIST(&ctx->locked_free_list);
1618 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1619 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1622 kfree(ctx->dummy_ubuf);
1623 kfree(ctx->cancel_hash);
1624 kfree(ctx->io_buffers);
1629 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1631 struct io_rings *r = ctx->rings;
1633 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1637 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1639 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1640 struct io_ring_ctx *ctx = req->ctx;
1642 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1648 #define FFS_NOWAIT 0x1UL
1649 #define FFS_ISREG 0x2UL
1650 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1652 static inline bool io_req_ffs_set(struct io_kiocb *req)
1654 return req->flags & REQ_F_FIXED_FILE;
1657 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1659 if (WARN_ON_ONCE(!req->link))
1662 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1663 req->flags |= REQ_F_LINK_TIMEOUT;
1665 /* linked timeouts should have two refs once prep'ed */
1666 io_req_set_refcount(req);
1667 __io_req_set_refcount(req->link, 2);
1671 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1673 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1675 return __io_prep_linked_timeout(req);
1678 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1680 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1683 static inline void io_arm_ltimeout(struct io_kiocb *req)
1685 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1686 __io_arm_ltimeout(req);
1689 static void io_prep_async_work(struct io_kiocb *req)
1691 const struct io_op_def *def = &io_op_defs[req->opcode];
1692 struct io_ring_ctx *ctx = req->ctx;
1694 if (!(req->flags & REQ_F_CREDS)) {
1695 req->flags |= REQ_F_CREDS;
1696 req->creds = get_current_cred();
1699 req->work.list.next = NULL;
1700 req->work.flags = 0;
1701 if (req->flags & REQ_F_FORCE_ASYNC)
1702 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1704 if (req->flags & REQ_F_ISREG) {
1705 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1706 io_wq_hash_work(&req->work, file_inode(req->file));
1707 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1708 if (def->unbound_nonreg_file)
1709 req->work.flags |= IO_WQ_WORK_UNBOUND;
1713 static void io_prep_async_link(struct io_kiocb *req)
1715 struct io_kiocb *cur;
1717 if (req->flags & REQ_F_LINK_TIMEOUT) {
1718 struct io_ring_ctx *ctx = req->ctx;
1720 spin_lock_irq(&ctx->timeout_lock);
1721 io_for_each_link(cur, req)
1722 io_prep_async_work(cur);
1723 spin_unlock_irq(&ctx->timeout_lock);
1725 io_for_each_link(cur, req)
1726 io_prep_async_work(cur);
1730 static inline void io_req_add_compl_list(struct io_kiocb *req)
1732 struct io_submit_state *state = &req->ctx->submit_state;
1734 if (!(req->flags & REQ_F_CQE_SKIP))
1735 state->flush_cqes = true;
1736 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1739 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1741 struct io_kiocb *link = io_prep_linked_timeout(req);
1742 struct io_uring_task *tctx = req->task->io_uring;
1745 BUG_ON(!tctx->io_wq);
1747 /* init ->work of the whole link before punting */
1748 io_prep_async_link(req);
1751 * Not expected to happen, but if we do have a bug where this _can_
1752 * happen, catch it here and ensure the request is marked as
1753 * canceled. That will make io-wq go through the usual work cancel
1754 * procedure rather than attempt to run this request (or create a new
1757 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1758 req->work.flags |= IO_WQ_WORK_CANCEL;
1760 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1761 req->opcode, req->flags, &req->work,
1762 io_wq_is_hashed(&req->work));
1763 io_wq_enqueue(tctx->io_wq, &req->work);
1765 io_queue_linked_timeout(link);
1768 static void io_kill_timeout(struct io_kiocb *req, int status)
1769 __must_hold(&req->ctx->completion_lock)
1770 __must_hold(&req->ctx->timeout_lock)
1772 struct io_timeout_data *io = req->async_data;
1774 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1777 atomic_set(&req->ctx->cq_timeouts,
1778 atomic_read(&req->ctx->cq_timeouts) + 1);
1779 list_del_init(&req->timeout.list);
1780 io_req_tw_post_queue(req, status, 0);
1784 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1786 while (!list_empty(&ctx->defer_list)) {
1787 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1788 struct io_defer_entry, list);
1790 if (req_need_defer(de->req, de->seq))
1792 list_del_init(&de->list);
1793 io_req_task_queue(de->req);
1798 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1799 __must_hold(&ctx->completion_lock)
1801 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1802 struct io_kiocb *req, *tmp;
1804 spin_lock_irq(&ctx->timeout_lock);
1805 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1806 u32 events_needed, events_got;
1808 if (io_is_timeout_noseq(req))
1812 * Since seq can easily wrap around over time, subtract
1813 * the last seq at which timeouts were flushed before comparing.
1814 * Assuming not more than 2^31-1 events have happened since,
1815 * these subtractions won't have wrapped, so we can check if
1816 * target is in [last_seq, current_seq] by comparing the two.
1818 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1819 events_got = seq - ctx->cq_last_tm_flush;
1820 if (events_got < events_needed)
1823 io_kill_timeout(req, 0);
1825 ctx->cq_last_tm_flush = seq;
1826 spin_unlock_irq(&ctx->timeout_lock);
1829 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1831 /* order cqe stores with ring update */
1832 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1835 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1837 if (ctx->off_timeout_used || ctx->drain_active) {
1838 spin_lock(&ctx->completion_lock);
1839 if (ctx->off_timeout_used)
1840 io_flush_timeouts(ctx);
1841 if (ctx->drain_active)
1842 io_queue_deferred(ctx);
1843 io_commit_cqring(ctx);
1844 spin_unlock(&ctx->completion_lock);
1847 io_eventfd_signal(ctx);
1850 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1852 struct io_rings *r = ctx->rings;
1854 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1857 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1859 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1863 * writes to the cq entry need to come after reading head; the
1864 * control dependency is enough as we're using WRITE_ONCE to
1867 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1869 struct io_rings *rings = ctx->rings;
1870 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1871 unsigned int free, queued, len;
1873 /* userspace may cheat modifying the tail, be safe and do min */
1874 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1875 free = ctx->cq_entries - queued;
1876 /* we need a contiguous range, limit based on the current array offset */
1877 len = min(free, ctx->cq_entries - off);
1881 ctx->cached_cq_tail++;
1882 ctx->cqe_cached = &rings->cqes[off];
1883 ctx->cqe_sentinel = ctx->cqe_cached + len;
1884 return ctx->cqe_cached++;
1887 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1889 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
1890 ctx->cached_cq_tail++;
1891 return ctx->cqe_cached++;
1893 return __io_get_cqe(ctx);
1896 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1898 struct io_ev_fd *ev_fd;
1902 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1903 * and eventfd_signal
1905 ev_fd = rcu_dereference(ctx->io_ev_fd);
1908 * Check again if ev_fd exists incase an io_eventfd_unregister call
1909 * completed between the NULL check of ctx->io_ev_fd at the start of
1910 * the function and rcu_read_lock.
1912 if (unlikely(!ev_fd))
1914 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1917 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1918 eventfd_signal(ev_fd->cq_ev_fd, 1);
1923 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1926 * wake_up_all() may seem excessive, but io_wake_function() and
1927 * io_should_wake() handle the termination of the loop and only
1928 * wake as many waiters as we need to.
1930 if (wq_has_sleeper(&ctx->cq_wait))
1931 wake_up_all(&ctx->cq_wait);
1935 * This should only get called when at least one event has been posted.
1936 * Some applications rely on the eventfd notification count only changing
1937 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1938 * 1:1 relationship between how many times this function is called (and
1939 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1941 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1943 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1945 __io_commit_cqring_flush(ctx);
1947 io_cqring_wake(ctx);
1950 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1952 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1954 __io_commit_cqring_flush(ctx);
1956 if (ctx->flags & IORING_SETUP_SQPOLL)
1957 io_cqring_wake(ctx);
1960 /* Returns true if there are no backlogged entries after the flush */
1961 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1963 bool all_flushed, posted;
1965 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1969 spin_lock(&ctx->completion_lock);
1970 while (!list_empty(&ctx->cq_overflow_list)) {
1971 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1972 struct io_overflow_cqe *ocqe;
1976 ocqe = list_first_entry(&ctx->cq_overflow_list,
1977 struct io_overflow_cqe, list);
1979 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1981 io_account_cq_overflow(ctx);
1984 list_del(&ocqe->list);
1988 all_flushed = list_empty(&ctx->cq_overflow_list);
1990 clear_bit(0, &ctx->check_cq_overflow);
1991 WRITE_ONCE(ctx->rings->sq_flags,
1992 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1995 io_commit_cqring(ctx);
1996 spin_unlock(&ctx->completion_lock);
1998 io_cqring_ev_posted(ctx);
2002 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2006 if (test_bit(0, &ctx->check_cq_overflow)) {
2007 /* iopoll syncs against uring_lock, not completion_lock */
2008 if (ctx->flags & IORING_SETUP_IOPOLL)
2009 mutex_lock(&ctx->uring_lock);
2010 ret = __io_cqring_overflow_flush(ctx, false);
2011 if (ctx->flags & IORING_SETUP_IOPOLL)
2012 mutex_unlock(&ctx->uring_lock);
2018 static void __io_put_task(struct task_struct *task, int nr)
2020 struct io_uring_task *tctx = task->io_uring;
2022 percpu_counter_sub(&tctx->inflight, nr);
2023 if (unlikely(atomic_read(&tctx->in_idle)))
2024 wake_up(&tctx->wait);
2025 put_task_struct_many(task, nr);
2028 /* must to be called somewhat shortly after putting a request */
2029 static inline void io_put_task(struct task_struct *task, int nr)
2031 if (likely(task == current))
2032 task->io_uring->cached_refs += nr;
2034 __io_put_task(task, nr);
2037 static void io_task_refs_refill(struct io_uring_task *tctx)
2039 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2041 percpu_counter_add(&tctx->inflight, refill);
2042 refcount_add(refill, ¤t->usage);
2043 tctx->cached_refs += refill;
2046 static inline void io_get_task_refs(int nr)
2048 struct io_uring_task *tctx = current->io_uring;
2050 tctx->cached_refs -= nr;
2051 if (unlikely(tctx->cached_refs < 0))
2052 io_task_refs_refill(tctx);
2055 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2057 struct io_uring_task *tctx = task->io_uring;
2058 unsigned int refs = tctx->cached_refs;
2061 tctx->cached_refs = 0;
2062 percpu_counter_sub(&tctx->inflight, refs);
2063 put_task_struct_many(task, refs);
2067 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2068 s32 res, u32 cflags)
2070 struct io_overflow_cqe *ocqe;
2072 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2075 * If we're in ring overflow flush mode, or in task cancel mode,
2076 * or cannot allocate an overflow entry, then we need to drop it
2079 io_account_cq_overflow(ctx);
2082 if (list_empty(&ctx->cq_overflow_list)) {
2083 set_bit(0, &ctx->check_cq_overflow);
2084 WRITE_ONCE(ctx->rings->sq_flags,
2085 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2088 ocqe->cqe.user_data = user_data;
2089 ocqe->cqe.res = res;
2090 ocqe->cqe.flags = cflags;
2091 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2095 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2096 s32 res, u32 cflags)
2098 struct io_uring_cqe *cqe;
2101 * If we can't get a cq entry, userspace overflowed the
2102 * submission (by quite a lot). Increment the overflow count in
2105 cqe = io_get_cqe(ctx);
2107 WRITE_ONCE(cqe->user_data, user_data);
2108 WRITE_ONCE(cqe->res, res);
2109 WRITE_ONCE(cqe->flags, cflags);
2112 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2115 static inline bool __io_fill_cqe_req_filled(struct io_ring_ctx *ctx,
2116 struct io_kiocb *req)
2118 struct io_uring_cqe *cqe;
2120 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2121 req->cqe.res, req->cqe.flags);
2124 * If we can't get a cq entry, userspace overflowed the
2125 * submission (by quite a lot). Increment the overflow count in
2128 cqe = io_get_cqe(ctx);
2130 memcpy(cqe, &req->cqe, sizeof(*cqe));
2133 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2134 req->cqe.res, req->cqe.flags);
2137 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2139 trace_io_uring_complete(req->ctx, req, req->cqe.user_data, res, cflags);
2140 return __io_fill_cqe(req->ctx, req->cqe.user_data, res, cflags);
2143 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2144 s32 res, u32 cflags)
2147 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2148 return __io_fill_cqe(ctx, user_data, res, cflags);
2151 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2154 struct io_ring_ctx *ctx = req->ctx;
2156 if (!(req->flags & REQ_F_CQE_SKIP))
2157 __io_fill_cqe_req(req, res, cflags);
2159 * If we're the last reference to this request, add to our locked
2162 if (req_ref_put_and_test(req)) {
2163 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2164 if (req->flags & IO_DISARM_MASK)
2165 io_disarm_next(req);
2167 io_req_task_queue(req->link);
2171 io_req_put_rsrc(req, ctx);
2173 * Selected buffer deallocation in io_clean_op() assumes that
2174 * we don't hold ->completion_lock. Clean them here to avoid
2177 io_put_kbuf_comp(req);
2178 io_dismantle_req(req);
2179 io_put_task(req->task, 1);
2180 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2181 ctx->locked_free_nr++;
2185 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2188 struct io_ring_ctx *ctx = req->ctx;
2190 spin_lock(&ctx->completion_lock);
2191 __io_req_complete_post(req, res, cflags);
2192 io_commit_cqring(ctx);
2193 spin_unlock(&ctx->completion_lock);
2194 io_cqring_ev_posted(ctx);
2197 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2201 req->cqe.flags = cflags;
2202 req->flags |= REQ_F_COMPLETE_INLINE;
2205 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2206 s32 res, u32 cflags)
2208 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2209 io_req_complete_state(req, res, cflags);
2211 io_req_complete_post(req, res, cflags);
2214 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2216 __io_req_complete(req, 0, res, 0);
2219 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2222 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2225 static void io_req_complete_fail_submit(struct io_kiocb *req)
2228 * We don't submit, fail them all, for that replace hardlinks with
2229 * normal links. Extra REQ_F_LINK is tolerated.
2231 req->flags &= ~REQ_F_HARDLINK;
2232 req->flags |= REQ_F_LINK;
2233 io_req_complete_failed(req, req->cqe.res);
2237 * Don't initialise the fields below on every allocation, but do that in
2238 * advance and keep them valid across allocations.
2240 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2244 req->async_data = NULL;
2245 /* not necessary, but safer to zero */
2249 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2250 struct io_submit_state *state)
2252 spin_lock(&ctx->completion_lock);
2253 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2254 ctx->locked_free_nr = 0;
2255 spin_unlock(&ctx->completion_lock);
2258 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2260 return !ctx->submit_state.free_list.next;
2264 * A request might get retired back into the request caches even before opcode
2265 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2266 * Because of that, io_alloc_req() should be called only under ->uring_lock
2267 * and with extra caution to not get a request that is still worked on.
2269 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2270 __must_hold(&ctx->uring_lock)
2272 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2273 void *reqs[IO_REQ_ALLOC_BATCH];
2277 * If we have more than a batch's worth of requests in our IRQ side
2278 * locked cache, grab the lock and move them over to our submission
2281 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2282 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2283 if (!io_req_cache_empty(ctx))
2287 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2290 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2291 * retry single alloc to be on the safe side.
2293 if (unlikely(ret <= 0)) {
2294 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2300 percpu_ref_get_many(&ctx->refs, ret);
2301 for (i = 0; i < ret; i++) {
2302 struct io_kiocb *req = reqs[i];
2304 io_preinit_req(req, ctx);
2305 io_req_add_to_cache(req, ctx);
2310 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2312 if (unlikely(io_req_cache_empty(ctx)))
2313 return __io_alloc_req_refill(ctx);
2317 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2319 struct io_wq_work_node *node;
2321 node = wq_stack_extract(&ctx->submit_state.free_list);
2322 return container_of(node, struct io_kiocb, comp_list);
2325 static inline void io_put_file(struct file *file)
2331 static inline void io_dismantle_req(struct io_kiocb *req)
2333 unsigned int flags = req->flags;
2335 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2337 if (!(flags & REQ_F_FIXED_FILE))
2338 io_put_file(req->file);
2341 static __cold void io_free_req(struct io_kiocb *req)
2343 struct io_ring_ctx *ctx = req->ctx;
2345 io_req_put_rsrc(req, ctx);
2346 io_dismantle_req(req);
2347 io_put_task(req->task, 1);
2349 spin_lock(&ctx->completion_lock);
2350 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2351 ctx->locked_free_nr++;
2352 spin_unlock(&ctx->completion_lock);
2355 static inline void io_remove_next_linked(struct io_kiocb *req)
2357 struct io_kiocb *nxt = req->link;
2359 req->link = nxt->link;
2363 static bool io_kill_linked_timeout(struct io_kiocb *req)
2364 __must_hold(&req->ctx->completion_lock)
2365 __must_hold(&req->ctx->timeout_lock)
2367 struct io_kiocb *link = req->link;
2369 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2370 struct io_timeout_data *io = link->async_data;
2372 io_remove_next_linked(req);
2373 link->timeout.head = NULL;
2374 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2375 list_del(&link->timeout.list);
2376 io_req_tw_post_queue(link, -ECANCELED, 0);
2383 static void io_fail_links(struct io_kiocb *req)
2384 __must_hold(&req->ctx->completion_lock)
2386 struct io_kiocb *nxt, *link = req->link;
2387 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2391 long res = -ECANCELED;
2393 if (link->flags & REQ_F_FAIL)
2394 res = link->cqe.res;
2399 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2403 link->flags |= REQ_F_CQE_SKIP;
2405 link->flags &= ~REQ_F_CQE_SKIP;
2406 __io_req_complete_post(link, res, 0);
2411 static bool io_disarm_next(struct io_kiocb *req)
2412 __must_hold(&req->ctx->completion_lock)
2414 bool posted = false;
2416 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2417 struct io_kiocb *link = req->link;
2419 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2420 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2421 io_remove_next_linked(req);
2422 io_req_tw_post_queue(link, -ECANCELED, 0);
2425 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2426 struct io_ring_ctx *ctx = req->ctx;
2428 spin_lock_irq(&ctx->timeout_lock);
2429 posted = io_kill_linked_timeout(req);
2430 spin_unlock_irq(&ctx->timeout_lock);
2432 if (unlikely((req->flags & REQ_F_FAIL) &&
2433 !(req->flags & REQ_F_HARDLINK))) {
2434 posted |= (req->link != NULL);
2440 static void __io_req_find_next_prep(struct io_kiocb *req)
2442 struct io_ring_ctx *ctx = req->ctx;
2445 spin_lock(&ctx->completion_lock);
2446 posted = io_disarm_next(req);
2447 io_commit_cqring(ctx);
2448 spin_unlock(&ctx->completion_lock);
2450 io_cqring_ev_posted(ctx);
2453 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2455 struct io_kiocb *nxt;
2458 * If LINK is set, we have dependent requests in this chain. If we
2459 * didn't fail this request, queue the first one up, moving any other
2460 * dependencies to the next request. In case of failure, fail the rest
2463 if (unlikely(req->flags & IO_DISARM_MASK))
2464 __io_req_find_next_prep(req);
2470 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2475 io_submit_flush_completions(ctx);
2476 mutex_unlock(&ctx->uring_lock);
2479 percpu_ref_put(&ctx->refs);
2482 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2484 io_commit_cqring(ctx);
2485 spin_unlock(&ctx->completion_lock);
2486 io_cqring_ev_posted(ctx);
2489 static void handle_prev_tw_list(struct io_wq_work_node *node,
2490 struct io_ring_ctx **ctx, bool *uring_locked)
2492 if (*ctx && !*uring_locked)
2493 spin_lock(&(*ctx)->completion_lock);
2496 struct io_wq_work_node *next = node->next;
2497 struct io_kiocb *req = container_of(node, struct io_kiocb,
2500 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2502 if (req->ctx != *ctx) {
2503 if (unlikely(!*uring_locked && *ctx))
2504 ctx_commit_and_unlock(*ctx);
2506 ctx_flush_and_put(*ctx, uring_locked);
2508 /* if not contended, grab and improve batching */
2509 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2510 percpu_ref_get(&(*ctx)->refs);
2511 if (unlikely(!*uring_locked))
2512 spin_lock(&(*ctx)->completion_lock);
2514 if (likely(*uring_locked))
2515 req->io_task_work.func(req, uring_locked);
2517 __io_req_complete_post(req, req->cqe.res,
2518 io_put_kbuf_comp(req));
2522 if (unlikely(!*uring_locked))
2523 ctx_commit_and_unlock(*ctx);
2526 static void handle_tw_list(struct io_wq_work_node *node,
2527 struct io_ring_ctx **ctx, bool *locked)
2530 struct io_wq_work_node *next = node->next;
2531 struct io_kiocb *req = container_of(node, struct io_kiocb,
2534 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2536 if (req->ctx != *ctx) {
2537 ctx_flush_and_put(*ctx, locked);
2539 /* if not contended, grab and improve batching */
2540 *locked = mutex_trylock(&(*ctx)->uring_lock);
2541 percpu_ref_get(&(*ctx)->refs);
2543 req->io_task_work.func(req, locked);
2548 static void tctx_task_work(struct callback_head *cb)
2550 bool uring_locked = false;
2551 struct io_ring_ctx *ctx = NULL;
2552 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2556 struct io_wq_work_node *node1, *node2;
2558 spin_lock_irq(&tctx->task_lock);
2559 node1 = tctx->prior_task_list.first;
2560 node2 = tctx->task_list.first;
2561 INIT_WQ_LIST(&tctx->task_list);
2562 INIT_WQ_LIST(&tctx->prior_task_list);
2563 if (!node2 && !node1)
2564 tctx->task_running = false;
2565 spin_unlock_irq(&tctx->task_lock);
2566 if (!node2 && !node1)
2570 handle_prev_tw_list(node1, &ctx, &uring_locked);
2572 handle_tw_list(node2, &ctx, &uring_locked);
2575 if (!tctx->task_list.first &&
2576 !tctx->prior_task_list.first && uring_locked)
2577 io_submit_flush_completions(ctx);
2580 ctx_flush_and_put(ctx, &uring_locked);
2582 /* relaxed read is enough as only the task itself sets ->in_idle */
2583 if (unlikely(atomic_read(&tctx->in_idle)))
2584 io_uring_drop_tctx_refs(current);
2587 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2589 struct task_struct *tsk = req->task;
2590 struct io_uring_task *tctx = tsk->io_uring;
2591 enum task_work_notify_mode notify;
2592 struct io_wq_work_node *node;
2593 unsigned long flags;
2596 WARN_ON_ONCE(!tctx);
2598 io_drop_inflight_file(req);
2600 spin_lock_irqsave(&tctx->task_lock, flags);
2602 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2604 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2605 running = tctx->task_running;
2607 tctx->task_running = true;
2608 spin_unlock_irqrestore(&tctx->task_lock, flags);
2610 /* task_work already pending, we're done */
2615 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2616 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2617 * processing task_work. There's no reliable way to tell if TWA_RESUME
2620 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2621 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2622 if (notify == TWA_NONE)
2623 wake_up_process(tsk);
2627 spin_lock_irqsave(&tctx->task_lock, flags);
2628 tctx->task_running = false;
2629 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2630 spin_unlock_irqrestore(&tctx->task_lock, flags);
2633 req = container_of(node, struct io_kiocb, io_task_work.node);
2635 if (llist_add(&req->io_task_work.fallback_node,
2636 &req->ctx->fallback_llist))
2637 schedule_delayed_work(&req->ctx->fallback_work, 1);
2641 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2643 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2646 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2649 req->cqe.flags = cflags;
2650 req->io_task_work.func = io_req_tw_post;
2651 io_req_task_work_add(req, false);
2654 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2656 /* not needed for normal modes, but SQPOLL depends on it */
2657 io_tw_lock(req->ctx, locked);
2658 io_req_complete_failed(req, req->cqe.res);
2661 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2663 io_tw_lock(req->ctx, locked);
2664 /* req->task == current here, checking PF_EXITING is safe */
2665 if (likely(!(req->task->flags & PF_EXITING)))
2668 io_req_complete_failed(req, -EFAULT);
2671 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2674 req->io_task_work.func = io_req_task_cancel;
2675 io_req_task_work_add(req, false);
2678 static void io_req_task_queue(struct io_kiocb *req)
2680 req->io_task_work.func = io_req_task_submit;
2681 io_req_task_work_add(req, false);
2684 static void io_req_task_queue_reissue(struct io_kiocb *req)
2686 req->io_task_work.func = io_queue_iowq;
2687 io_req_task_work_add(req, false);
2690 static void io_queue_next(struct io_kiocb *req)
2692 struct io_kiocb *nxt = io_req_find_next(req);
2695 io_req_task_queue(nxt);
2698 static void io_free_batch_list(struct io_ring_ctx *ctx,
2699 struct io_wq_work_node *node)
2700 __must_hold(&ctx->uring_lock)
2702 struct task_struct *task = NULL;
2706 struct io_kiocb *req = container_of(node, struct io_kiocb,
2709 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2710 if (req->flags & REQ_F_REFCOUNT) {
2711 node = req->comp_list.next;
2712 if (!req_ref_put_and_test(req))
2715 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2716 struct async_poll *apoll = req->apoll;
2718 if (apoll->double_poll)
2719 kfree(apoll->double_poll);
2720 list_add(&apoll->poll.wait.entry,
2722 req->flags &= ~REQ_F_POLLED;
2724 if (req->flags & (REQ_F_LINK|REQ_F_HARDLINK))
2726 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2729 if (!(req->flags & REQ_F_FIXED_FILE))
2730 io_put_file(req->file);
2732 io_req_put_rsrc_locked(req, ctx);
2734 if (req->task != task) {
2736 io_put_task(task, task_refs);
2741 node = req->comp_list.next;
2742 io_req_add_to_cache(req, ctx);
2746 io_put_task(task, task_refs);
2749 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2750 __must_hold(&ctx->uring_lock)
2752 struct io_wq_work_node *node, *prev;
2753 struct io_submit_state *state = &ctx->submit_state;
2755 if (state->flush_cqes) {
2756 spin_lock(&ctx->completion_lock);
2757 wq_list_for_each(node, prev, &state->compl_reqs) {
2758 struct io_kiocb *req = container_of(node, struct io_kiocb,
2761 if (!(req->flags & REQ_F_CQE_SKIP))
2762 __io_fill_cqe_req_filled(ctx, req);
2765 io_commit_cqring(ctx);
2766 spin_unlock(&ctx->completion_lock);
2767 io_cqring_ev_posted(ctx);
2768 state->flush_cqes = false;
2771 io_free_batch_list(ctx, state->compl_reqs.first);
2772 INIT_WQ_LIST(&state->compl_reqs);
2776 * Drop reference to request, return next in chain (if there is one) if this
2777 * was the last reference to this request.
2779 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2781 struct io_kiocb *nxt = NULL;
2783 if (req_ref_put_and_test(req)) {
2784 if (unlikely(req->flags & (REQ_F_LINK|REQ_F_HARDLINK)))
2785 nxt = io_req_find_next(req);
2791 static inline void io_put_req(struct io_kiocb *req)
2793 if (req_ref_put_and_test(req)) {
2799 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2801 /* See comment at the top of this file */
2803 return __io_cqring_events(ctx);
2806 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2808 struct io_rings *rings = ctx->rings;
2810 /* make sure SQ entry isn't read before tail */
2811 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2814 static inline bool io_run_task_work(void)
2816 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2817 __set_current_state(TASK_RUNNING);
2818 clear_notify_signal();
2819 if (task_work_pending(current))
2827 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2829 struct io_wq_work_node *pos, *start, *prev;
2830 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2831 DEFINE_IO_COMP_BATCH(iob);
2835 * Only spin for completions if we don't have multiple devices hanging
2836 * off our complete list.
2838 if (ctx->poll_multi_queue || force_nonspin)
2839 poll_flags |= BLK_POLL_ONESHOT;
2841 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2842 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2843 struct kiocb *kiocb = &req->rw.kiocb;
2847 * Move completed and retryable entries to our local lists.
2848 * If we find a request that requires polling, break out
2849 * and complete those lists first, if we have entries there.
2851 if (READ_ONCE(req->iopoll_completed))
2854 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2855 if (unlikely(ret < 0))
2858 poll_flags |= BLK_POLL_ONESHOT;
2860 /* iopoll may have completed current req */
2861 if (!rq_list_empty(iob.req_list) ||
2862 READ_ONCE(req->iopoll_completed))
2866 if (!rq_list_empty(iob.req_list))
2872 wq_list_for_each_resume(pos, prev) {
2873 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2875 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2876 if (!smp_load_acquire(&req->iopoll_completed))
2879 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2881 __io_fill_cqe_req(req, req->cqe.res, io_put_kbuf(req, 0));
2884 if (unlikely(!nr_events))
2887 io_commit_cqring(ctx);
2888 io_cqring_ev_posted_iopoll(ctx);
2889 pos = start ? start->next : ctx->iopoll_list.first;
2890 wq_list_cut(&ctx->iopoll_list, prev, start);
2891 io_free_batch_list(ctx, pos);
2896 * We can't just wait for polled events to come to us, we have to actively
2897 * find and complete them.
2899 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2901 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2904 mutex_lock(&ctx->uring_lock);
2905 while (!wq_list_empty(&ctx->iopoll_list)) {
2906 /* let it sleep and repeat later if can't complete a request */
2907 if (io_do_iopoll(ctx, true) == 0)
2910 * Ensure we allow local-to-the-cpu processing to take place,
2911 * in this case we need to ensure that we reap all events.
2912 * Also let task_work, etc. to progress by releasing the mutex
2914 if (need_resched()) {
2915 mutex_unlock(&ctx->uring_lock);
2917 mutex_lock(&ctx->uring_lock);
2920 mutex_unlock(&ctx->uring_lock);
2923 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2925 unsigned int nr_events = 0;
2929 * Don't enter poll loop if we already have events pending.
2930 * If we do, we can potentially be spinning for commands that
2931 * already triggered a CQE (eg in error).
2933 if (test_bit(0, &ctx->check_cq_overflow))
2934 __io_cqring_overflow_flush(ctx, false);
2935 if (io_cqring_events(ctx))
2939 * If a submit got punted to a workqueue, we can have the
2940 * application entering polling for a command before it gets
2941 * issued. That app will hold the uring_lock for the duration
2942 * of the poll right here, so we need to take a breather every
2943 * now and then to ensure that the issue has a chance to add
2944 * the poll to the issued list. Otherwise we can spin here
2945 * forever, while the workqueue is stuck trying to acquire the
2948 if (wq_list_empty(&ctx->iopoll_list)) {
2949 u32 tail = ctx->cached_cq_tail;
2951 mutex_unlock(&ctx->uring_lock);
2953 mutex_lock(&ctx->uring_lock);
2955 /* some requests don't go through iopoll_list */
2956 if (tail != ctx->cached_cq_tail ||
2957 wq_list_empty(&ctx->iopoll_list))
2960 ret = io_do_iopoll(ctx, !min);
2965 } while (nr_events < min && !need_resched());
2970 static void kiocb_end_write(struct io_kiocb *req)
2973 * Tell lockdep we inherited freeze protection from submission
2976 if (req->flags & REQ_F_ISREG) {
2977 struct super_block *sb = file_inode(req->file)->i_sb;
2979 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2985 static bool io_resubmit_prep(struct io_kiocb *req)
2987 struct io_async_rw *rw = req->async_data;
2989 if (!req_has_async_data(req))
2990 return !io_req_prep_async(req);
2991 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2995 static bool io_rw_should_reissue(struct io_kiocb *req)
2997 umode_t mode = file_inode(req->file)->i_mode;
2998 struct io_ring_ctx *ctx = req->ctx;
3000 if (!S_ISBLK(mode) && !S_ISREG(mode))
3002 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3003 !(ctx->flags & IORING_SETUP_IOPOLL)))
3006 * If ref is dying, we might be running poll reap from the exit work.
3007 * Don't attempt to reissue from that path, just let it fail with
3010 if (percpu_ref_is_dying(&ctx->refs))
3013 * Play it safe and assume not safe to re-import and reissue if we're
3014 * not in the original thread group (or in task context).
3016 if (!same_thread_group(req->task, current) || !in_task())
3021 static bool io_resubmit_prep(struct io_kiocb *req)
3025 static bool io_rw_should_reissue(struct io_kiocb *req)
3031 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3033 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3034 kiocb_end_write(req);
3035 fsnotify_modify(req->file);
3037 fsnotify_access(req->file);
3039 if (unlikely(res != req->cqe.res)) {
3040 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3041 io_rw_should_reissue(req)) {
3042 req->flags |= REQ_F_REISSUE;
3051 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3053 int res = req->cqe.res;
3056 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3057 io_req_add_compl_list(req);
3059 io_req_complete_post(req, res,
3060 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3064 static void __io_complete_rw(struct io_kiocb *req, long res,
3065 unsigned int issue_flags)
3067 if (__io_complete_rw_common(req, res))
3069 __io_req_complete(req, issue_flags, req->cqe.res,
3070 io_put_kbuf(req, issue_flags));
3073 static void io_complete_rw(struct kiocb *kiocb, long res)
3075 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3077 if (__io_complete_rw_common(req, res))
3080 req->io_task_work.func = io_req_task_complete;
3081 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3084 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3086 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3088 if (kiocb->ki_flags & IOCB_WRITE)
3089 kiocb_end_write(req);
3090 if (unlikely(res != req->cqe.res)) {
3091 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3092 req->flags |= REQ_F_REISSUE;
3098 /* order with io_iopoll_complete() checking ->iopoll_completed */
3099 smp_store_release(&req->iopoll_completed, 1);
3103 * After the iocb has been issued, it's safe to be found on the poll list.
3104 * Adding the kiocb to the list AFTER submission ensures that we don't
3105 * find it from a io_do_iopoll() thread before the issuer is done
3106 * accessing the kiocb cookie.
3108 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3110 struct io_ring_ctx *ctx = req->ctx;
3111 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3113 /* workqueue context doesn't hold uring_lock, grab it now */
3114 if (unlikely(needs_lock))
3115 mutex_lock(&ctx->uring_lock);
3118 * Track whether we have multiple files in our lists. This will impact
3119 * how we do polling eventually, not spinning if we're on potentially
3120 * different devices.
3122 if (wq_list_empty(&ctx->iopoll_list)) {
3123 ctx->poll_multi_queue = false;
3124 } else if (!ctx->poll_multi_queue) {
3125 struct io_kiocb *list_req;
3127 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3129 if (list_req->file != req->file)
3130 ctx->poll_multi_queue = true;
3134 * For fast devices, IO may have already completed. If it has, add
3135 * it to the front so we find it first.
3137 if (READ_ONCE(req->iopoll_completed))
3138 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3140 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3142 if (unlikely(needs_lock)) {
3144 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3145 * in sq thread task context or in io worker task context. If
3146 * current task context is sq thread, we don't need to check
3147 * whether should wake up sq thread.
3149 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3150 wq_has_sleeper(&ctx->sq_data->wait))
3151 wake_up(&ctx->sq_data->wait);
3153 mutex_unlock(&ctx->uring_lock);
3157 static bool io_bdev_nowait(struct block_device *bdev)
3159 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3163 * If we tracked the file through the SCM inflight mechanism, we could support
3164 * any file. For now, just ensure that anything potentially problematic is done
3167 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3169 if (S_ISBLK(mode)) {
3170 if (IS_ENABLED(CONFIG_BLOCK) &&
3171 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3177 if (S_ISREG(mode)) {
3178 if (IS_ENABLED(CONFIG_BLOCK) &&
3179 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3180 file->f_op != &io_uring_fops)
3185 /* any ->read/write should understand O_NONBLOCK */
3186 if (file->f_flags & O_NONBLOCK)
3188 return file->f_mode & FMODE_NOWAIT;
3192 * If we tracked the file through the SCM inflight mechanism, we could support
3193 * any file. For now, just ensure that anything potentially problematic is done
3196 static unsigned int io_file_get_flags(struct file *file)
3198 umode_t mode = file_inode(file)->i_mode;
3199 unsigned int res = 0;
3203 if (__io_file_supports_nowait(file, mode))
3208 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3210 return req->flags & REQ_F_SUPPORT_NOWAIT;
3213 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3215 struct kiocb *kiocb = &req->rw.kiocb;
3219 kiocb->ki_pos = READ_ONCE(sqe->off);
3221 ioprio = READ_ONCE(sqe->ioprio);
3223 ret = ioprio_check_cap(ioprio);
3227 kiocb->ki_ioprio = ioprio;
3229 kiocb->ki_ioprio = get_current_ioprio();
3233 req->rw.addr = READ_ONCE(sqe->addr);
3234 req->rw.len = READ_ONCE(sqe->len);
3235 req->rw.flags = READ_ONCE(sqe->rw_flags);
3236 req->buf_index = READ_ONCE(sqe->buf_index);
3240 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3246 case -ERESTARTNOINTR:
3247 case -ERESTARTNOHAND:
3248 case -ERESTART_RESTARTBLOCK:
3250 * We can't just restart the syscall, since previously
3251 * submitted sqes may already be in progress. Just fail this
3257 kiocb->ki_complete(kiocb, ret);
3261 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3263 struct kiocb *kiocb = &req->rw.kiocb;
3265 if (kiocb->ki_pos != -1)
3266 return &kiocb->ki_pos;
3268 if (!(req->file->f_mode & FMODE_STREAM)) {
3269 req->flags |= REQ_F_CUR_POS;
3270 kiocb->ki_pos = req->file->f_pos;
3271 return &kiocb->ki_pos;
3278 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3279 unsigned int issue_flags)
3281 struct io_async_rw *io = req->async_data;
3283 /* add previously done IO, if any */
3284 if (req_has_async_data(req) && io->bytes_done > 0) {
3286 ret = io->bytes_done;
3288 ret += io->bytes_done;
3291 if (req->flags & REQ_F_CUR_POS)
3292 req->file->f_pos = req->rw.kiocb.ki_pos;
3293 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3294 __io_complete_rw(req, ret, issue_flags);
3296 io_rw_done(&req->rw.kiocb, ret);
3298 if (req->flags & REQ_F_REISSUE) {
3299 req->flags &= ~REQ_F_REISSUE;
3300 if (io_resubmit_prep(req))
3301 io_req_task_queue_reissue(req);
3303 io_req_task_queue_fail(req, ret);
3307 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3308 struct io_mapped_ubuf *imu)
3310 size_t len = req->rw.len;
3311 u64 buf_end, buf_addr = req->rw.addr;
3314 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3316 /* not inside the mapped region */
3317 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3321 * May not be a start of buffer, set size appropriately
3322 * and advance us to the beginning.
3324 offset = buf_addr - imu->ubuf;
3325 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3329 * Don't use iov_iter_advance() here, as it's really slow for
3330 * using the latter parts of a big fixed buffer - it iterates
3331 * over each segment manually. We can cheat a bit here, because
3334 * 1) it's a BVEC iter, we set it up
3335 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3336 * first and last bvec
3338 * So just find our index, and adjust the iterator afterwards.
3339 * If the offset is within the first bvec (or the whole first
3340 * bvec, just use iov_iter_advance(). This makes it easier
3341 * since we can just skip the first segment, which may not
3342 * be PAGE_SIZE aligned.
3344 const struct bio_vec *bvec = imu->bvec;
3346 if (offset <= bvec->bv_len) {
3347 iov_iter_advance(iter, offset);
3349 unsigned long seg_skip;
3351 /* skip first vec */
3352 offset -= bvec->bv_len;
3353 seg_skip = 1 + (offset >> PAGE_SHIFT);
3355 iter->bvec = bvec + seg_skip;
3356 iter->nr_segs -= seg_skip;
3357 iter->count -= bvec->bv_len + offset;
3358 iter->iov_offset = offset & ~PAGE_MASK;
3365 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3366 unsigned int issue_flags)
3368 struct io_mapped_ubuf *imu = req->imu;
3369 u16 index, buf_index = req->buf_index;
3372 struct io_ring_ctx *ctx = req->ctx;
3374 if (unlikely(buf_index >= ctx->nr_user_bufs))
3376 io_req_set_rsrc_node(req, ctx, issue_flags);
3377 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3378 imu = READ_ONCE(ctx->user_bufs[index]);
3381 return __io_import_fixed(req, rw, iter, imu);
3384 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3385 struct io_buffer_list *bl, unsigned int bgid)
3387 struct list_head *list;
3389 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3390 INIT_LIST_HEAD(&bl->buf_list);
3392 list_add(&bl->list, list);
3395 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3396 int bgid, unsigned int issue_flags)
3398 struct io_buffer *kbuf = req->kbuf;
3399 struct io_ring_ctx *ctx = req->ctx;
3400 struct io_buffer_list *bl;
3402 if (req->flags & REQ_F_BUFFER_SELECTED)
3405 io_ring_submit_lock(req->ctx, issue_flags);
3407 bl = io_buffer_get_list(ctx, bgid);
3408 if (bl && !list_empty(&bl->buf_list)) {
3409 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3410 list_del(&kbuf->list);
3411 if (*len > kbuf->len)
3413 req->flags |= REQ_F_BUFFER_SELECTED;
3416 kbuf = ERR_PTR(-ENOBUFS);
3419 io_ring_submit_unlock(req->ctx, issue_flags);
3423 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3424 unsigned int issue_flags)
3426 struct io_buffer *kbuf;
3429 bgid = req->buf_index;
3430 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3433 return u64_to_user_ptr(kbuf->addr);
3436 #ifdef CONFIG_COMPAT
3437 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3438 unsigned int issue_flags)
3440 struct compat_iovec __user *uiov;
3441 compat_ssize_t clen;
3445 uiov = u64_to_user_ptr(req->rw.addr);
3446 if (!access_ok(uiov, sizeof(*uiov)))
3448 if (__get_user(clen, &uiov->iov_len))
3454 buf = io_rw_buffer_select(req, &len, issue_flags);
3456 return PTR_ERR(buf);
3457 iov[0].iov_base = buf;
3458 iov[0].iov_len = (compat_size_t) len;
3463 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3464 unsigned int issue_flags)
3466 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3470 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3473 len = iov[0].iov_len;
3476 buf = io_rw_buffer_select(req, &len, issue_flags);
3478 return PTR_ERR(buf);
3479 iov[0].iov_base = buf;
3480 iov[0].iov_len = len;
3484 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3485 unsigned int issue_flags)
3487 if (req->flags & REQ_F_BUFFER_SELECTED) {
3488 struct io_buffer *kbuf = req->kbuf;
3490 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3491 iov[0].iov_len = kbuf->len;
3494 if (req->rw.len != 1)
3497 #ifdef CONFIG_COMPAT
3498 if (req->ctx->compat)
3499 return io_compat_import(req, iov, issue_flags);
3502 return __io_iov_buffer_select(req, iov, issue_flags);
3505 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3506 struct io_rw_state *s,
3507 unsigned int issue_flags)
3509 struct iov_iter *iter = &s->iter;
3510 u8 opcode = req->opcode;
3511 struct iovec *iovec;
3516 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3517 ret = io_import_fixed(req, rw, iter, issue_flags);
3519 return ERR_PTR(ret);
3523 /* buffer index only valid with fixed read/write, or buffer select */
3524 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3525 return ERR_PTR(-EINVAL);
3527 buf = u64_to_user_ptr(req->rw.addr);
3528 sqe_len = req->rw.len;
3530 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3531 if (req->flags & REQ_F_BUFFER_SELECT) {
3532 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3534 return ERR_CAST(buf);
3535 req->rw.len = sqe_len;
3538 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3540 return ERR_PTR(ret);
3544 iovec = s->fast_iov;
3545 if (req->flags & REQ_F_BUFFER_SELECT) {
3546 ret = io_iov_buffer_select(req, iovec, issue_flags);
3548 return ERR_PTR(ret);
3549 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3553 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3555 if (unlikely(ret < 0))
3556 return ERR_PTR(ret);
3560 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3561 struct iovec **iovec, struct io_rw_state *s,
3562 unsigned int issue_flags)
3564 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3565 if (unlikely(IS_ERR(*iovec)))
3566 return PTR_ERR(*iovec);
3568 iov_iter_save_state(&s->iter, &s->iter_state);
3572 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3574 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3578 * For files that don't have ->read_iter() and ->write_iter(), handle them
3579 * by looping over ->read() or ->write() manually.
3581 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3583 struct kiocb *kiocb = &req->rw.kiocb;
3584 struct file *file = req->file;
3589 * Don't support polled IO through this interface, and we can't
3590 * support non-blocking either. For the latter, this just causes
3591 * the kiocb to be handled from an async context.
3593 if (kiocb->ki_flags & IOCB_HIPRI)
3595 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3596 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3599 ppos = io_kiocb_ppos(kiocb);
3601 while (iov_iter_count(iter)) {
3605 if (!iov_iter_is_bvec(iter)) {
3606 iovec = iov_iter_iovec(iter);
3608 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3609 iovec.iov_len = req->rw.len;
3613 nr = file->f_op->read(file, iovec.iov_base,
3614 iovec.iov_len, ppos);
3616 nr = file->f_op->write(file, iovec.iov_base,
3617 iovec.iov_len, ppos);
3626 if (!iov_iter_is_bvec(iter)) {
3627 iov_iter_advance(iter, nr);
3634 if (nr != iovec.iov_len)
3641 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3642 const struct iovec *fast_iov, struct iov_iter *iter)
3644 struct io_async_rw *rw = req->async_data;
3646 memcpy(&rw->s.iter, iter, sizeof(*iter));
3647 rw->free_iovec = iovec;
3649 /* can only be fixed buffers, no need to do anything */
3650 if (iov_iter_is_bvec(iter))
3653 unsigned iov_off = 0;
3655 rw->s.iter.iov = rw->s.fast_iov;
3656 if (iter->iov != fast_iov) {
3657 iov_off = iter->iov - fast_iov;
3658 rw->s.iter.iov += iov_off;
3660 if (rw->s.fast_iov != fast_iov)
3661 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3662 sizeof(struct iovec) * iter->nr_segs);
3664 req->flags |= REQ_F_NEED_CLEANUP;
3668 static inline bool io_alloc_async_data(struct io_kiocb *req)
3670 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3671 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3672 if (req->async_data) {
3673 req->flags |= REQ_F_ASYNC_DATA;
3679 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3680 struct io_rw_state *s, bool force)
3682 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3684 if (!req_has_async_data(req)) {
3685 struct io_async_rw *iorw;
3687 if (io_alloc_async_data(req)) {
3692 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3693 iorw = req->async_data;
3694 /* we've copied and mapped the iter, ensure state is saved */
3695 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3700 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3702 struct io_async_rw *iorw = req->async_data;
3706 /* submission path, ->uring_lock should already be taken */
3707 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3708 if (unlikely(ret < 0))
3711 iorw->bytes_done = 0;
3712 iorw->free_iovec = iov;
3714 req->flags |= REQ_F_NEED_CLEANUP;
3719 * This is our waitqueue callback handler, registered through __folio_lock_async()
3720 * when we initially tried to do the IO with the iocb armed our waitqueue.
3721 * This gets called when the page is unlocked, and we generally expect that to
3722 * happen when the page IO is completed and the page is now uptodate. This will
3723 * queue a task_work based retry of the operation, attempting to copy the data
3724 * again. If the latter fails because the page was NOT uptodate, then we will
3725 * do a thread based blocking retry of the operation. That's the unexpected
3728 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3729 int sync, void *arg)
3731 struct wait_page_queue *wpq;
3732 struct io_kiocb *req = wait->private;
3733 struct wait_page_key *key = arg;
3735 wpq = container_of(wait, struct wait_page_queue, wait);
3737 if (!wake_page_match(wpq, key))
3740 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3741 list_del_init(&wait->entry);
3742 io_req_task_queue(req);
3747 * This controls whether a given IO request should be armed for async page
3748 * based retry. If we return false here, the request is handed to the async
3749 * worker threads for retry. If we're doing buffered reads on a regular file,
3750 * we prepare a private wait_page_queue entry and retry the operation. This
3751 * will either succeed because the page is now uptodate and unlocked, or it
3752 * will register a callback when the page is unlocked at IO completion. Through
3753 * that callback, io_uring uses task_work to setup a retry of the operation.
3754 * That retry will attempt the buffered read again. The retry will generally
3755 * succeed, or in rare cases where it fails, we then fall back to using the
3756 * async worker threads for a blocking retry.
3758 static bool io_rw_should_retry(struct io_kiocb *req)
3760 struct io_async_rw *rw = req->async_data;
3761 struct wait_page_queue *wait = &rw->wpq;
3762 struct kiocb *kiocb = &req->rw.kiocb;
3764 /* never retry for NOWAIT, we just complete with -EAGAIN */
3765 if (req->flags & REQ_F_NOWAIT)
3768 /* Only for buffered IO */
3769 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3773 * just use poll if we can, and don't attempt if the fs doesn't
3774 * support callback based unlocks
3776 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3779 wait->wait.func = io_async_buf_func;
3780 wait->wait.private = req;
3781 wait->wait.flags = 0;
3782 INIT_LIST_HEAD(&wait->wait.entry);
3783 kiocb->ki_flags |= IOCB_WAITQ;
3784 kiocb->ki_flags &= ~IOCB_NOWAIT;
3785 kiocb->ki_waitq = wait;
3789 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3791 if (likely(req->file->f_op->read_iter))
3792 return call_read_iter(req->file, &req->rw.kiocb, iter);
3793 else if (req->file->f_op->read)
3794 return loop_rw_iter(READ, req, iter);
3799 static bool need_read_all(struct io_kiocb *req)
3801 return req->flags & REQ_F_ISREG ||
3802 S_ISBLK(file_inode(req->file)->i_mode);
3805 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
3807 struct kiocb *kiocb = &req->rw.kiocb;
3808 struct io_ring_ctx *ctx = req->ctx;
3809 struct file *file = req->file;
3812 if (unlikely(!file || !(file->f_mode & mode)))
3815 if (!io_req_ffs_set(req))
3816 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3818 kiocb->ki_flags = iocb_flags(file);
3819 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
3824 * If the file is marked O_NONBLOCK, still allow retry for it if it
3825 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3826 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3828 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3829 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3830 req->flags |= REQ_F_NOWAIT;
3832 if (ctx->flags & IORING_SETUP_IOPOLL) {
3833 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3836 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3837 kiocb->ki_complete = io_complete_rw_iopoll;
3838 req->iopoll_completed = 0;
3840 if (kiocb->ki_flags & IOCB_HIPRI)
3842 kiocb->ki_complete = io_complete_rw;
3848 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3850 struct io_rw_state __s, *s = &__s;
3851 struct iovec *iovec;
3852 struct kiocb *kiocb = &req->rw.kiocb;
3853 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3854 struct io_async_rw *rw;
3858 if (!req_has_async_data(req)) {
3859 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3860 if (unlikely(ret < 0))
3864 * Safe and required to re-import if we're using provided
3865 * buffers, as we dropped the selected one before retry.
3867 if (req->flags & REQ_F_BUFFER_SELECT) {
3868 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3869 if (unlikely(ret < 0))
3873 rw = req->async_data;
3876 * We come here from an earlier attempt, restore our state to
3877 * match in case it doesn't. It's cheap enough that we don't
3878 * need to make this conditional.
3880 iov_iter_restore(&s->iter, &s->iter_state);
3883 ret = io_rw_init_file(req, FMODE_READ);
3884 if (unlikely(ret)) {
3888 req->cqe.res = iov_iter_count(&s->iter);
3890 if (force_nonblock) {
3891 /* If the file doesn't support async, just async punt */
3892 if (unlikely(!io_file_supports_nowait(req))) {
3893 ret = io_setup_async_rw(req, iovec, s, true);
3894 return ret ?: -EAGAIN;
3896 kiocb->ki_flags |= IOCB_NOWAIT;
3898 /* Ensure we clear previously set non-block flag */
3899 kiocb->ki_flags &= ~IOCB_NOWAIT;
3902 ppos = io_kiocb_update_pos(req);
3904 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
3905 if (unlikely(ret)) {
3910 ret = io_iter_do_read(req, &s->iter);
3912 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3913 req->flags &= ~REQ_F_REISSUE;
3914 /* if we can poll, just do that */
3915 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3917 /* IOPOLL retry should happen for io-wq threads */
3918 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3920 /* no retry on NONBLOCK nor RWF_NOWAIT */
3921 if (req->flags & REQ_F_NOWAIT)
3924 } else if (ret == -EIOCBQUEUED) {
3926 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
3927 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3928 /* read all, failed, already did sync or don't want to retry */
3933 * Don't depend on the iter state matching what was consumed, or being
3934 * untouched in case of error. Restore it and we'll advance it
3935 * manually if we need to.
3937 iov_iter_restore(&s->iter, &s->iter_state);
3939 ret2 = io_setup_async_rw(req, iovec, s, true);
3944 rw = req->async_data;
3947 * Now use our persistent iterator and state, if we aren't already.
3948 * We've restored and mapped the iter to match.
3953 * We end up here because of a partial read, either from
3954 * above or inside this loop. Advance the iter by the bytes
3955 * that were consumed.
3957 iov_iter_advance(&s->iter, ret);
3958 if (!iov_iter_count(&s->iter))
3960 rw->bytes_done += ret;
3961 iov_iter_save_state(&s->iter, &s->iter_state);
3963 /* if we can retry, do so with the callbacks armed */
3964 if (!io_rw_should_retry(req)) {
3965 kiocb->ki_flags &= ~IOCB_WAITQ;
3970 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3971 * we get -EIOCBQUEUED, then we'll get a notification when the
3972 * desired page gets unlocked. We can also get a partial read
3973 * here, and if we do, then just retry at the new offset.
3975 ret = io_iter_do_read(req, &s->iter);
3976 if (ret == -EIOCBQUEUED)
3978 /* we got some bytes, but not all. retry. */
3979 kiocb->ki_flags &= ~IOCB_WAITQ;
3980 iov_iter_restore(&s->iter, &s->iter_state);
3983 kiocb_done(req, ret, issue_flags);
3985 /* it's faster to check here then delegate to kfree */
3991 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3993 struct io_rw_state __s, *s = &__s;
3994 struct iovec *iovec;
3995 struct kiocb *kiocb = &req->rw.kiocb;
3996 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4000 if (!req_has_async_data(req)) {
4001 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4002 if (unlikely(ret < 0))
4005 struct io_async_rw *rw = req->async_data;
4008 iov_iter_restore(&s->iter, &s->iter_state);
4011 ret = io_rw_init_file(req, FMODE_WRITE);
4012 if (unlikely(ret)) {
4016 req->cqe.res = iov_iter_count(&s->iter);
4018 if (force_nonblock) {
4019 /* If the file doesn't support async, just async punt */
4020 if (unlikely(!io_file_supports_nowait(req)))
4023 /* file path doesn't support NOWAIT for non-direct_IO */
4024 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4025 (req->flags & REQ_F_ISREG))
4028 kiocb->ki_flags |= IOCB_NOWAIT;
4030 /* Ensure we clear previously set non-block flag */
4031 kiocb->ki_flags &= ~IOCB_NOWAIT;
4034 ppos = io_kiocb_update_pos(req);
4036 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4041 * Open-code file_start_write here to grab freeze protection,
4042 * which will be released by another thread in
4043 * io_complete_rw(). Fool lockdep by telling it the lock got
4044 * released so that it doesn't complain about the held lock when
4045 * we return to userspace.
4047 if (req->flags & REQ_F_ISREG) {
4048 sb_start_write(file_inode(req->file)->i_sb);
4049 __sb_writers_release(file_inode(req->file)->i_sb,
4052 kiocb->ki_flags |= IOCB_WRITE;
4054 if (likely(req->file->f_op->write_iter))
4055 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4056 else if (req->file->f_op->write)
4057 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4061 if (req->flags & REQ_F_REISSUE) {
4062 req->flags &= ~REQ_F_REISSUE;
4067 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4068 * retry them without IOCB_NOWAIT.
4070 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4072 /* no retry on NONBLOCK nor RWF_NOWAIT */
4073 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4075 if (!force_nonblock || ret2 != -EAGAIN) {
4076 /* IOPOLL retry should happen for io-wq threads */
4077 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4080 kiocb_done(req, ret2, issue_flags);
4083 iov_iter_restore(&s->iter, &s->iter_state);
4084 ret = io_setup_async_rw(req, iovec, s, false);
4085 return ret ?: -EAGAIN;
4088 /* it's reportedly faster than delegating the null check to kfree() */
4094 static int io_renameat_prep(struct io_kiocb *req,
4095 const struct io_uring_sqe *sqe)
4097 struct io_rename *ren = &req->rename;
4098 const char __user *oldf, *newf;
4100 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4102 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4104 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4107 ren->old_dfd = READ_ONCE(sqe->fd);
4108 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4109 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4110 ren->new_dfd = READ_ONCE(sqe->len);
4111 ren->flags = READ_ONCE(sqe->rename_flags);
4113 ren->oldpath = getname(oldf);
4114 if (IS_ERR(ren->oldpath))
4115 return PTR_ERR(ren->oldpath);
4117 ren->newpath = getname(newf);
4118 if (IS_ERR(ren->newpath)) {
4119 putname(ren->oldpath);
4120 return PTR_ERR(ren->newpath);
4123 req->flags |= REQ_F_NEED_CLEANUP;
4127 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4129 struct io_rename *ren = &req->rename;
4132 if (issue_flags & IO_URING_F_NONBLOCK)
4135 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4136 ren->newpath, ren->flags);
4138 req->flags &= ~REQ_F_NEED_CLEANUP;
4141 io_req_complete(req, ret);
4145 static int io_unlinkat_prep(struct io_kiocb *req,
4146 const struct io_uring_sqe *sqe)
4148 struct io_unlink *un = &req->unlink;
4149 const char __user *fname;
4151 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4153 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4156 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4159 un->dfd = READ_ONCE(sqe->fd);
4161 un->flags = READ_ONCE(sqe->unlink_flags);
4162 if (un->flags & ~AT_REMOVEDIR)
4165 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4166 un->filename = getname(fname);
4167 if (IS_ERR(un->filename))
4168 return PTR_ERR(un->filename);
4170 req->flags |= REQ_F_NEED_CLEANUP;
4174 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4176 struct io_unlink *un = &req->unlink;
4179 if (issue_flags & IO_URING_F_NONBLOCK)
4182 if (un->flags & AT_REMOVEDIR)
4183 ret = do_rmdir(un->dfd, un->filename);
4185 ret = do_unlinkat(un->dfd, un->filename);
4187 req->flags &= ~REQ_F_NEED_CLEANUP;
4190 io_req_complete(req, ret);
4194 static int io_mkdirat_prep(struct io_kiocb *req,
4195 const struct io_uring_sqe *sqe)
4197 struct io_mkdir *mkd = &req->mkdir;
4198 const char __user *fname;
4200 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4202 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4205 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4208 mkd->dfd = READ_ONCE(sqe->fd);
4209 mkd->mode = READ_ONCE(sqe->len);
4211 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4212 mkd->filename = getname(fname);
4213 if (IS_ERR(mkd->filename))
4214 return PTR_ERR(mkd->filename);
4216 req->flags |= REQ_F_NEED_CLEANUP;
4220 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4222 struct io_mkdir *mkd = &req->mkdir;
4225 if (issue_flags & IO_URING_F_NONBLOCK)
4228 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4230 req->flags &= ~REQ_F_NEED_CLEANUP;
4233 io_req_complete(req, ret);
4237 static int io_symlinkat_prep(struct io_kiocb *req,
4238 const struct io_uring_sqe *sqe)
4240 struct io_symlink *sl = &req->symlink;
4241 const char __user *oldpath, *newpath;
4243 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4245 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4248 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4251 sl->new_dfd = READ_ONCE(sqe->fd);
4252 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4253 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4255 sl->oldpath = getname(oldpath);
4256 if (IS_ERR(sl->oldpath))
4257 return PTR_ERR(sl->oldpath);
4259 sl->newpath = getname(newpath);
4260 if (IS_ERR(sl->newpath)) {
4261 putname(sl->oldpath);
4262 return PTR_ERR(sl->newpath);
4265 req->flags |= REQ_F_NEED_CLEANUP;
4269 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4271 struct io_symlink *sl = &req->symlink;
4274 if (issue_flags & IO_URING_F_NONBLOCK)
4277 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4279 req->flags &= ~REQ_F_NEED_CLEANUP;
4282 io_req_complete(req, ret);
4286 static int io_linkat_prep(struct io_kiocb *req,
4287 const struct io_uring_sqe *sqe)
4289 struct io_hardlink *lnk = &req->hardlink;
4290 const char __user *oldf, *newf;
4292 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4294 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4296 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4299 lnk->old_dfd = READ_ONCE(sqe->fd);
4300 lnk->new_dfd = READ_ONCE(sqe->len);
4301 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4302 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4303 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4305 lnk->oldpath = getname(oldf);
4306 if (IS_ERR(lnk->oldpath))
4307 return PTR_ERR(lnk->oldpath);
4309 lnk->newpath = getname(newf);
4310 if (IS_ERR(lnk->newpath)) {
4311 putname(lnk->oldpath);
4312 return PTR_ERR(lnk->newpath);
4315 req->flags |= REQ_F_NEED_CLEANUP;
4319 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4321 struct io_hardlink *lnk = &req->hardlink;
4324 if (issue_flags & IO_URING_F_NONBLOCK)
4327 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4328 lnk->newpath, lnk->flags);
4330 req->flags &= ~REQ_F_NEED_CLEANUP;
4333 io_req_complete(req, ret);
4337 static int io_shutdown_prep(struct io_kiocb *req,
4338 const struct io_uring_sqe *sqe)
4340 #if defined(CONFIG_NET)
4341 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4343 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4344 sqe->buf_index || sqe->splice_fd_in))
4347 req->shutdown.how = READ_ONCE(sqe->len);
4354 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4356 #if defined(CONFIG_NET)
4357 struct socket *sock;
4360 if (issue_flags & IO_URING_F_NONBLOCK)
4363 sock = sock_from_file(req->file);
4364 if (unlikely(!sock))
4367 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4370 io_req_complete(req, ret);
4377 static int __io_splice_prep(struct io_kiocb *req,
4378 const struct io_uring_sqe *sqe)
4380 struct io_splice *sp = &req->splice;
4381 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4383 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4386 sp->len = READ_ONCE(sqe->len);
4387 sp->flags = READ_ONCE(sqe->splice_flags);
4388 if (unlikely(sp->flags & ~valid_flags))
4390 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4394 static int io_tee_prep(struct io_kiocb *req,
4395 const struct io_uring_sqe *sqe)
4397 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4399 return __io_splice_prep(req, sqe);
4402 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4404 struct io_splice *sp = &req->splice;
4405 struct file *out = sp->file_out;
4406 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4410 if (issue_flags & IO_URING_F_NONBLOCK)
4413 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4414 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4416 in = io_file_get_normal(req, sp->splice_fd_in);
4423 ret = do_tee(in, out, sp->len, flags);
4425 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4430 io_req_complete(req, ret);
4434 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4436 struct io_splice *sp = &req->splice;
4438 sp->off_in = READ_ONCE(sqe->splice_off_in);
4439 sp->off_out = READ_ONCE(sqe->off);
4440 return __io_splice_prep(req, sqe);
4443 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4445 struct io_splice *sp = &req->splice;
4446 struct file *out = sp->file_out;
4447 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4448 loff_t *poff_in, *poff_out;
4452 if (issue_flags & IO_URING_F_NONBLOCK)
4455 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4456 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4458 in = io_file_get_normal(req, sp->splice_fd_in);
4464 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4465 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4468 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4470 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4475 io_req_complete(req, ret);
4480 * IORING_OP_NOP just posts a completion event, nothing else.
4482 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4484 struct io_ring_ctx *ctx = req->ctx;
4486 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4489 __io_req_complete(req, issue_flags, 0, 0);
4493 static int io_msg_ring_prep(struct io_kiocb *req,
4494 const struct io_uring_sqe *sqe)
4496 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4497 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4500 req->msg.user_data = READ_ONCE(sqe->off);
4501 req->msg.len = READ_ONCE(sqe->len);
4505 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4507 struct io_ring_ctx *target_ctx;
4508 struct io_msg *msg = &req->msg;
4513 if (req->file->f_op != &io_uring_fops)
4517 target_ctx = req->file->private_data;
4519 spin_lock(&target_ctx->completion_lock);
4520 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
4521 io_commit_cqring(target_ctx);
4522 spin_unlock(&target_ctx->completion_lock);
4525 io_cqring_ev_posted(target_ctx);
4532 __io_req_complete(req, issue_flags, ret, 0);
4536 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4538 struct io_ring_ctx *ctx = req->ctx;
4540 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4542 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4546 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4547 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4550 req->sync.off = READ_ONCE(sqe->off);
4551 req->sync.len = READ_ONCE(sqe->len);
4555 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4557 loff_t end = req->sync.off + req->sync.len;
4560 /* fsync always requires a blocking context */
4561 if (issue_flags & IO_URING_F_NONBLOCK)
4564 ret = vfs_fsync_range(req->file, req->sync.off,
4565 end > 0 ? end : LLONG_MAX,
4566 req->sync.flags & IORING_FSYNC_DATASYNC);
4569 io_req_complete(req, ret);
4573 static int io_fallocate_prep(struct io_kiocb *req,
4574 const struct io_uring_sqe *sqe)
4576 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4579 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4582 req->sync.off = READ_ONCE(sqe->off);
4583 req->sync.len = READ_ONCE(sqe->addr);
4584 req->sync.mode = READ_ONCE(sqe->len);
4588 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4592 /* fallocate always requiring blocking context */
4593 if (issue_flags & IO_URING_F_NONBLOCK)
4595 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4600 fsnotify_modify(req->file);
4601 io_req_complete(req, ret);
4605 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4607 const char __user *fname;
4610 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4612 if (unlikely(sqe->ioprio || sqe->buf_index))
4614 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4617 /* open.how should be already initialised */
4618 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4619 req->open.how.flags |= O_LARGEFILE;
4621 req->open.dfd = READ_ONCE(sqe->fd);
4622 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4623 req->open.filename = getname(fname);
4624 if (IS_ERR(req->open.filename)) {
4625 ret = PTR_ERR(req->open.filename);
4626 req->open.filename = NULL;
4630 req->open.file_slot = READ_ONCE(sqe->file_index);
4631 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4634 req->open.nofile = rlimit(RLIMIT_NOFILE);
4635 req->flags |= REQ_F_NEED_CLEANUP;
4639 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4641 u64 mode = READ_ONCE(sqe->len);
4642 u64 flags = READ_ONCE(sqe->open_flags);
4644 req->open.how = build_open_how(flags, mode);
4645 return __io_openat_prep(req, sqe);
4648 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4650 struct open_how __user *how;
4654 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4655 len = READ_ONCE(sqe->len);
4656 if (len < OPEN_HOW_SIZE_VER0)
4659 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4664 return __io_openat_prep(req, sqe);
4667 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4669 struct open_flags op;
4671 bool resolve_nonblock, nonblock_set;
4672 bool fixed = !!req->open.file_slot;
4675 ret = build_open_flags(&req->open.how, &op);
4678 nonblock_set = op.open_flag & O_NONBLOCK;
4679 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4680 if (issue_flags & IO_URING_F_NONBLOCK) {
4682 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4683 * it'll always -EAGAIN
4685 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4687 op.lookup_flags |= LOOKUP_CACHED;
4688 op.open_flag |= O_NONBLOCK;
4692 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4697 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4700 * We could hang on to this 'fd' on retrying, but seems like
4701 * marginal gain for something that is now known to be a slower
4702 * path. So just put it, and we'll get a new one when we retry.
4707 ret = PTR_ERR(file);
4708 /* only retry if RESOLVE_CACHED wasn't already set by application */
4709 if (ret == -EAGAIN &&
4710 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4715 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4716 file->f_flags &= ~O_NONBLOCK;
4717 fsnotify_open(file);
4720 fd_install(ret, file);
4722 ret = io_install_fixed_file(req, file, issue_flags,
4723 req->open.file_slot - 1);
4725 putname(req->open.filename);
4726 req->flags &= ~REQ_F_NEED_CLEANUP;
4729 __io_req_complete(req, issue_flags, ret, 0);
4733 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4735 return io_openat2(req, issue_flags);
4738 static int io_remove_buffers_prep(struct io_kiocb *req,
4739 const struct io_uring_sqe *sqe)
4741 struct io_provide_buf *p = &req->pbuf;
4744 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4748 tmp = READ_ONCE(sqe->fd);
4749 if (!tmp || tmp > USHRT_MAX)
4752 memset(p, 0, sizeof(*p));
4754 p->bgid = READ_ONCE(sqe->buf_group);
4758 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4759 struct io_buffer_list *bl, unsigned nbufs)
4763 /* shouldn't happen */
4767 /* the head kbuf is the list itself */
4768 while (!list_empty(&bl->buf_list)) {
4769 struct io_buffer *nxt;
4771 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4772 list_del(&nxt->list);
4782 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4784 struct io_provide_buf *p = &req->pbuf;
4785 struct io_ring_ctx *ctx = req->ctx;
4786 struct io_buffer_list *bl;
4789 io_ring_submit_lock(ctx, issue_flags);
4792 bl = io_buffer_get_list(ctx, p->bgid);
4794 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4798 /* complete before unlock, IOPOLL may need the lock */
4799 __io_req_complete(req, issue_flags, ret, 0);
4800 io_ring_submit_unlock(ctx, issue_flags);
4804 static int io_provide_buffers_prep(struct io_kiocb *req,
4805 const struct io_uring_sqe *sqe)
4807 unsigned long size, tmp_check;
4808 struct io_provide_buf *p = &req->pbuf;
4811 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4814 tmp = READ_ONCE(sqe->fd);
4815 if (!tmp || tmp > USHRT_MAX)
4818 p->addr = READ_ONCE(sqe->addr);
4819 p->len = READ_ONCE(sqe->len);
4821 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4824 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4827 size = (unsigned long)p->len * p->nbufs;
4828 if (!access_ok(u64_to_user_ptr(p->addr), size))
4831 p->bgid = READ_ONCE(sqe->buf_group);
4832 tmp = READ_ONCE(sqe->off);
4833 if (tmp > USHRT_MAX)
4839 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4841 struct io_buffer *buf;
4846 * Completions that don't happen inline (eg not under uring_lock) will
4847 * add to ->io_buffers_comp. If we don't have any free buffers, check
4848 * the completion list and splice those entries first.
4850 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4851 spin_lock(&ctx->completion_lock);
4852 if (!list_empty(&ctx->io_buffers_comp)) {
4853 list_splice_init(&ctx->io_buffers_comp,
4854 &ctx->io_buffers_cache);
4855 spin_unlock(&ctx->completion_lock);
4858 spin_unlock(&ctx->completion_lock);
4862 * No free buffers and no completion entries either. Allocate a new
4863 * page worth of buffer entries and add those to our freelist.
4865 page = alloc_page(GFP_KERNEL_ACCOUNT);
4869 list_add(&page->lru, &ctx->io_buffers_pages);
4871 buf = page_address(page);
4872 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4873 while (bufs_in_page) {
4874 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4882 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4883 struct io_buffer_list *bl)
4885 struct io_buffer *buf;
4886 u64 addr = pbuf->addr;
4887 int i, bid = pbuf->bid;
4889 for (i = 0; i < pbuf->nbufs; i++) {
4890 if (list_empty(&ctx->io_buffers_cache) &&
4891 io_refill_buffer_cache(ctx))
4893 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4895 list_move_tail(&buf->list, &bl->buf_list);
4897 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4899 buf->bgid = pbuf->bgid;
4905 return i ? 0 : -ENOMEM;
4908 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4910 struct io_provide_buf *p = &req->pbuf;
4911 struct io_ring_ctx *ctx = req->ctx;
4912 struct io_buffer_list *bl;
4915 io_ring_submit_lock(ctx, issue_flags);
4917 bl = io_buffer_get_list(ctx, p->bgid);
4918 if (unlikely(!bl)) {
4919 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4924 io_buffer_add_list(ctx, bl, p->bgid);
4927 ret = io_add_buffers(ctx, p, bl);
4931 /* complete before unlock, IOPOLL may need the lock */
4932 __io_req_complete(req, issue_flags, ret, 0);
4933 io_ring_submit_unlock(ctx, issue_flags);
4937 static int io_epoll_ctl_prep(struct io_kiocb *req,
4938 const struct io_uring_sqe *sqe)
4940 #if defined(CONFIG_EPOLL)
4941 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4943 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4946 req->epoll.epfd = READ_ONCE(sqe->fd);
4947 req->epoll.op = READ_ONCE(sqe->len);
4948 req->epoll.fd = READ_ONCE(sqe->off);
4950 if (ep_op_has_event(req->epoll.op)) {
4951 struct epoll_event __user *ev;
4953 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4954 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4964 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4966 #if defined(CONFIG_EPOLL)
4967 struct io_epoll *ie = &req->epoll;
4969 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4971 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4972 if (force_nonblock && ret == -EAGAIN)
4977 __io_req_complete(req, issue_flags, ret, 0);
4984 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4986 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4987 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4989 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4992 req->madvise.addr = READ_ONCE(sqe->addr);
4993 req->madvise.len = READ_ONCE(sqe->len);
4994 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5001 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5003 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5004 struct io_madvise *ma = &req->madvise;
5007 if (issue_flags & IO_URING_F_NONBLOCK)
5010 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5013 io_req_complete(req, ret);
5020 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5022 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5024 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5027 req->fadvise.offset = READ_ONCE(sqe->off);
5028 req->fadvise.len = READ_ONCE(sqe->len);
5029 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5033 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5035 struct io_fadvise *fa = &req->fadvise;
5038 if (issue_flags & IO_URING_F_NONBLOCK) {
5039 switch (fa->advice) {
5040 case POSIX_FADV_NORMAL:
5041 case POSIX_FADV_RANDOM:
5042 case POSIX_FADV_SEQUENTIAL:
5049 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5052 __io_req_complete(req, issue_flags, ret, 0);
5056 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5058 const char __user *path;
5060 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5062 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5064 if (req->flags & REQ_F_FIXED_FILE)
5067 req->statx.dfd = READ_ONCE(sqe->fd);
5068 req->statx.mask = READ_ONCE(sqe->len);
5069 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5070 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5071 req->statx.flags = READ_ONCE(sqe->statx_flags);
5073 req->statx.filename = getname_flags(path,
5074 getname_statx_lookup_flags(req->statx.flags),
5077 if (IS_ERR(req->statx.filename)) {
5078 int ret = PTR_ERR(req->statx.filename);
5080 req->statx.filename = NULL;
5084 req->flags |= REQ_F_NEED_CLEANUP;
5088 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5090 struct io_statx *ctx = &req->statx;
5093 if (issue_flags & IO_URING_F_NONBLOCK)
5096 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5101 io_req_complete(req, ret);
5105 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5107 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5109 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5110 sqe->rw_flags || sqe->buf_index)
5112 if (req->flags & REQ_F_FIXED_FILE)
5115 req->close.fd = READ_ONCE(sqe->fd);
5116 req->close.file_slot = READ_ONCE(sqe->file_index);
5117 if (req->close.file_slot && req->close.fd)
5123 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5125 struct files_struct *files = current->files;
5126 struct io_close *close = &req->close;
5127 struct fdtable *fdt;
5128 struct file *file = NULL;
5131 if (req->close.file_slot) {
5132 ret = io_close_fixed(req, issue_flags);
5136 spin_lock(&files->file_lock);
5137 fdt = files_fdtable(files);
5138 if (close->fd >= fdt->max_fds) {
5139 spin_unlock(&files->file_lock);
5142 file = fdt->fd[close->fd];
5143 if (!file || file->f_op == &io_uring_fops) {
5144 spin_unlock(&files->file_lock);
5149 /* if the file has a flush method, be safe and punt to async */
5150 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5151 spin_unlock(&files->file_lock);
5155 ret = __close_fd_get_file(close->fd, &file);
5156 spin_unlock(&files->file_lock);
5163 /* No ->flush() or already async, safely close from here */
5164 ret = filp_close(file, current->files);
5170 __io_req_complete(req, issue_flags, ret, 0);
5174 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5176 struct io_ring_ctx *ctx = req->ctx;
5178 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5180 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5184 req->sync.off = READ_ONCE(sqe->off);
5185 req->sync.len = READ_ONCE(sqe->len);
5186 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5190 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5194 /* sync_file_range always requires a blocking context */
5195 if (issue_flags & IO_URING_F_NONBLOCK)
5198 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5202 io_req_complete(req, ret);
5206 #if defined(CONFIG_NET)
5207 static int io_setup_async_msg(struct io_kiocb *req,
5208 struct io_async_msghdr *kmsg)
5210 struct io_async_msghdr *async_msg = req->async_data;
5214 if (io_alloc_async_data(req)) {
5215 kfree(kmsg->free_iov);
5218 async_msg = req->async_data;
5219 req->flags |= REQ_F_NEED_CLEANUP;
5220 memcpy(async_msg, kmsg, sizeof(*kmsg));
5221 async_msg->msg.msg_name = &async_msg->addr;
5222 /* if were using fast_iov, set it to the new one */
5223 if (!async_msg->free_iov)
5224 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5229 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5230 struct io_async_msghdr *iomsg)
5232 iomsg->msg.msg_name = &iomsg->addr;
5233 iomsg->free_iov = iomsg->fast_iov;
5234 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5235 req->sr_msg.msg_flags, &iomsg->free_iov);
5238 static int io_sendmsg_prep_async(struct io_kiocb *req)
5242 ret = io_sendmsg_copy_hdr(req, req->async_data);
5244 req->flags |= REQ_F_NEED_CLEANUP;
5248 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5250 struct io_sr_msg *sr = &req->sr_msg;
5252 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5255 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5256 sr->len = READ_ONCE(sqe->len);
5257 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5258 if (sr->msg_flags & MSG_DONTWAIT)
5259 req->flags |= REQ_F_NOWAIT;
5261 #ifdef CONFIG_COMPAT
5262 if (req->ctx->compat)
5263 sr->msg_flags |= MSG_CMSG_COMPAT;
5268 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5270 struct io_async_msghdr iomsg, *kmsg;
5271 struct socket *sock;
5276 sock = sock_from_file(req->file);
5277 if (unlikely(!sock))
5280 if (req_has_async_data(req)) {
5281 kmsg = req->async_data;
5283 ret = io_sendmsg_copy_hdr(req, &iomsg);
5289 flags = req->sr_msg.msg_flags;
5290 if (issue_flags & IO_URING_F_NONBLOCK)
5291 flags |= MSG_DONTWAIT;
5292 if (flags & MSG_WAITALL)
5293 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5295 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5297 if (ret < min_ret) {
5298 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5299 return io_setup_async_msg(req, kmsg);
5300 if (ret == -ERESTARTSYS)
5304 /* fast path, check for non-NULL to avoid function call */
5306 kfree(kmsg->free_iov);
5307 req->flags &= ~REQ_F_NEED_CLEANUP;
5308 __io_req_complete(req, issue_flags, ret, 0);
5312 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5314 struct io_sr_msg *sr = &req->sr_msg;
5317 struct socket *sock;
5322 sock = sock_from_file(req->file);
5323 if (unlikely(!sock))
5326 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5330 msg.msg_name = NULL;
5331 msg.msg_control = NULL;
5332 msg.msg_controllen = 0;
5333 msg.msg_namelen = 0;
5335 flags = req->sr_msg.msg_flags;
5336 if (issue_flags & IO_URING_F_NONBLOCK)
5337 flags |= MSG_DONTWAIT;
5338 if (flags & MSG_WAITALL)
5339 min_ret = iov_iter_count(&msg.msg_iter);
5341 msg.msg_flags = flags;
5342 ret = sock_sendmsg(sock, &msg);
5343 if (ret < min_ret) {
5344 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5346 if (ret == -ERESTARTSYS)
5350 __io_req_complete(req, issue_flags, ret, 0);
5354 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5355 struct io_async_msghdr *iomsg)
5357 struct io_sr_msg *sr = &req->sr_msg;
5358 struct iovec __user *uiov;
5362 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5363 &iomsg->uaddr, &uiov, &iov_len);
5367 if (req->flags & REQ_F_BUFFER_SELECT) {
5370 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5372 sr->len = iomsg->fast_iov[0].iov_len;
5373 iomsg->free_iov = NULL;
5375 iomsg->free_iov = iomsg->fast_iov;
5376 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5377 &iomsg->free_iov, &iomsg->msg.msg_iter,
5386 #ifdef CONFIG_COMPAT
5387 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5388 struct io_async_msghdr *iomsg)
5390 struct io_sr_msg *sr = &req->sr_msg;
5391 struct compat_iovec __user *uiov;
5396 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5401 uiov = compat_ptr(ptr);
5402 if (req->flags & REQ_F_BUFFER_SELECT) {
5403 compat_ssize_t clen;
5407 if (!access_ok(uiov, sizeof(*uiov)))
5409 if (__get_user(clen, &uiov->iov_len))
5414 iomsg->free_iov = NULL;
5416 iomsg->free_iov = iomsg->fast_iov;
5417 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5418 UIO_FASTIOV, &iomsg->free_iov,
5419 &iomsg->msg.msg_iter, true);
5428 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5429 struct io_async_msghdr *iomsg)
5431 iomsg->msg.msg_name = &iomsg->addr;
5433 #ifdef CONFIG_COMPAT
5434 if (req->ctx->compat)
5435 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5438 return __io_recvmsg_copy_hdr(req, iomsg);
5441 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5442 unsigned int issue_flags)
5444 struct io_sr_msg *sr = &req->sr_msg;
5446 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5449 static int io_recvmsg_prep_async(struct io_kiocb *req)
5453 ret = io_recvmsg_copy_hdr(req, req->async_data);
5455 req->flags |= REQ_F_NEED_CLEANUP;
5459 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5461 struct io_sr_msg *sr = &req->sr_msg;
5463 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5466 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5467 sr->len = READ_ONCE(sqe->len);
5468 sr->bgid = READ_ONCE(sqe->buf_group);
5469 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5470 if (sr->msg_flags & MSG_DONTWAIT)
5471 req->flags |= REQ_F_NOWAIT;
5473 #ifdef CONFIG_COMPAT
5474 if (req->ctx->compat)
5475 sr->msg_flags |= MSG_CMSG_COMPAT;
5481 static bool io_net_retry(struct socket *sock, int flags)
5483 if (!(flags & MSG_WAITALL))
5485 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5488 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5490 struct io_async_msghdr iomsg, *kmsg;
5491 struct io_sr_msg *sr = &req->sr_msg;
5492 struct socket *sock;
5493 struct io_buffer *kbuf;
5495 int ret, min_ret = 0;
5496 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5498 sock = sock_from_file(req->file);
5499 if (unlikely(!sock))
5502 if (req_has_async_data(req)) {
5503 kmsg = req->async_data;
5505 ret = io_recvmsg_copy_hdr(req, &iomsg);
5511 if (req->flags & REQ_F_BUFFER_SELECT) {
5512 kbuf = io_recv_buffer_select(req, issue_flags);
5514 return PTR_ERR(kbuf);
5515 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5516 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5517 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5518 1, req->sr_msg.len);
5521 flags = req->sr_msg.msg_flags;
5523 flags |= MSG_DONTWAIT;
5524 if (flags & MSG_WAITALL)
5525 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5527 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5528 kmsg->uaddr, flags);
5529 if (ret < min_ret) {
5530 if (ret == -EAGAIN && force_nonblock)
5531 return io_setup_async_msg(req, kmsg);
5532 if (ret == -ERESTARTSYS)
5534 if (ret > 0 && io_net_retry(sock, flags)) {
5536 req->flags |= REQ_F_PARTIAL_IO;
5537 return io_setup_async_msg(req, kmsg);
5540 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5544 /* fast path, check for non-NULL to avoid function call */
5546 kfree(kmsg->free_iov);
5547 req->flags &= ~REQ_F_NEED_CLEANUP;
5550 else if (sr->done_io)
5552 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5556 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5558 struct io_buffer *kbuf;
5559 struct io_sr_msg *sr = &req->sr_msg;
5561 void __user *buf = sr->buf;
5562 struct socket *sock;
5565 int ret, min_ret = 0;
5566 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5568 sock = sock_from_file(req->file);
5569 if (unlikely(!sock))
5572 if (req->flags & REQ_F_BUFFER_SELECT) {
5573 kbuf = io_recv_buffer_select(req, issue_flags);
5575 return PTR_ERR(kbuf);
5576 buf = u64_to_user_ptr(kbuf->addr);
5579 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5583 msg.msg_name = NULL;
5584 msg.msg_control = NULL;
5585 msg.msg_controllen = 0;
5586 msg.msg_namelen = 0;
5587 msg.msg_iocb = NULL;
5590 flags = req->sr_msg.msg_flags;
5592 flags |= MSG_DONTWAIT;
5593 if (flags & MSG_WAITALL)
5594 min_ret = iov_iter_count(&msg.msg_iter);
5596 ret = sock_recvmsg(sock, &msg, flags);
5597 if (ret < min_ret) {
5598 if (ret == -EAGAIN && force_nonblock)
5600 if (ret == -ERESTARTSYS)
5602 if (ret > 0 && io_net_retry(sock, flags)) {
5606 req->flags |= REQ_F_PARTIAL_IO;
5610 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5617 else if (sr->done_io)
5619 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5623 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5625 struct io_accept *accept = &req->accept;
5627 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5629 if (sqe->ioprio || sqe->len || sqe->buf_index)
5632 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5633 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5634 accept->flags = READ_ONCE(sqe->accept_flags);
5635 accept->nofile = rlimit(RLIMIT_NOFILE);
5637 accept->file_slot = READ_ONCE(sqe->file_index);
5638 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5640 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5642 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5643 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5647 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5649 struct io_accept *accept = &req->accept;
5650 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5651 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5652 bool fixed = !!accept->file_slot;
5657 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5658 if (unlikely(fd < 0))
5661 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5666 ret = PTR_ERR(file);
5667 if (ret == -EAGAIN && force_nonblock)
5669 if (ret == -ERESTARTSYS)
5672 } else if (!fixed) {
5673 fd_install(fd, file);
5676 ret = io_install_fixed_file(req, file, issue_flags,
5677 accept->file_slot - 1);
5679 __io_req_complete(req, issue_flags, ret, 0);
5683 static int io_connect_prep_async(struct io_kiocb *req)
5685 struct io_async_connect *io = req->async_data;
5686 struct io_connect *conn = &req->connect;
5688 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5691 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5693 struct io_connect *conn = &req->connect;
5695 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5697 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5701 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5702 conn->addr_len = READ_ONCE(sqe->addr2);
5706 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5708 struct io_async_connect __io, *io;
5709 unsigned file_flags;
5711 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5713 if (req_has_async_data(req)) {
5714 io = req->async_data;
5716 ret = move_addr_to_kernel(req->connect.addr,
5717 req->connect.addr_len,
5724 file_flags = force_nonblock ? O_NONBLOCK : 0;
5726 ret = __sys_connect_file(req->file, &io->address,
5727 req->connect.addr_len, file_flags);
5728 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5729 if (req_has_async_data(req))
5731 if (io_alloc_async_data(req)) {
5735 memcpy(req->async_data, &__io, sizeof(__io));
5738 if (ret == -ERESTARTSYS)
5743 __io_req_complete(req, issue_flags, ret, 0);
5746 #else /* !CONFIG_NET */
5747 #define IO_NETOP_FN(op) \
5748 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5750 return -EOPNOTSUPP; \
5753 #define IO_NETOP_PREP(op) \
5755 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5757 return -EOPNOTSUPP; \
5760 #define IO_NETOP_PREP_ASYNC(op) \
5762 static int io_##op##_prep_async(struct io_kiocb *req) \
5764 return -EOPNOTSUPP; \
5767 IO_NETOP_PREP_ASYNC(sendmsg);
5768 IO_NETOP_PREP_ASYNC(recvmsg);
5769 IO_NETOP_PREP_ASYNC(connect);
5770 IO_NETOP_PREP(accept);
5773 #endif /* CONFIG_NET */
5775 struct io_poll_table {
5776 struct poll_table_struct pt;
5777 struct io_kiocb *req;
5782 #define IO_POLL_CANCEL_FLAG BIT(31)
5783 #define IO_POLL_REF_MASK GENMASK(30, 0)
5786 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5787 * bump it and acquire ownership. It's disallowed to modify requests while not
5788 * owning it, that prevents from races for enqueueing task_work's and b/w
5789 * arming poll and wakeups.
5791 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5793 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5796 static void io_poll_mark_cancelled(struct io_kiocb *req)
5798 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5801 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5803 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5804 if (req->opcode == IORING_OP_POLL_ADD)
5805 return req->async_data;
5806 return req->apoll->double_poll;
5809 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5811 if (req->opcode == IORING_OP_POLL_ADD)
5813 return &req->apoll->poll;
5816 static void io_poll_req_insert(struct io_kiocb *req)
5818 struct io_ring_ctx *ctx = req->ctx;
5819 struct hlist_head *list;
5821 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
5822 hlist_add_head(&req->hash_node, list);
5825 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5826 wait_queue_func_t wake_func)
5829 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5830 /* mask in events that we always want/need */
5831 poll->events = events | IO_POLL_UNMASK;
5832 INIT_LIST_HEAD(&poll->wait.entry);
5833 init_waitqueue_func_entry(&poll->wait, wake_func);
5836 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5838 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5841 spin_lock_irq(&head->lock);
5842 list_del_init(&poll->wait.entry);
5844 spin_unlock_irq(&head->lock);
5848 static void io_poll_remove_entries(struct io_kiocb *req)
5851 * Nothing to do if neither of those flags are set. Avoid dipping
5852 * into the poll/apoll/double cachelines if we can.
5854 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5858 * While we hold the waitqueue lock and the waitqueue is nonempty,
5859 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5860 * lock in the first place can race with the waitqueue being freed.
5862 * We solve this as eventpoll does: by taking advantage of the fact that
5863 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5864 * we enter rcu_read_lock() and see that the pointer to the queue is
5865 * non-NULL, we can then lock it without the memory being freed out from
5868 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5869 * case the caller deletes the entry from the queue, leaving it empty.
5870 * In that case, only RCU prevents the queue memory from being freed.
5873 if (req->flags & REQ_F_SINGLE_POLL)
5874 io_poll_remove_entry(io_poll_get_single(req));
5875 if (req->flags & REQ_F_DOUBLE_POLL)
5876 io_poll_remove_entry(io_poll_get_double(req));
5881 * All poll tw should go through this. Checks for poll events, manages
5882 * references, does rewait, etc.
5884 * Returns a negative error on failure. >0 when no action require, which is
5885 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5886 * the request, then the mask is stored in req->cqe.res.
5888 static int io_poll_check_events(struct io_kiocb *req, bool locked)
5890 struct io_ring_ctx *ctx = req->ctx;
5893 /* req->task == current here, checking PF_EXITING is safe */
5894 if (unlikely(req->task->flags & PF_EXITING))
5898 v = atomic_read(&req->poll_refs);
5900 /* tw handler should be the owner, and so have some references */
5901 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5903 if (v & IO_POLL_CANCEL_FLAG)
5906 if (!req->cqe.res) {
5907 struct poll_table_struct pt = { ._key = req->apoll_events };
5908 unsigned flags = locked ? 0 : IO_URING_F_UNLOCKED;
5910 if (unlikely(!io_assign_file(req, flags)))
5912 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
5915 /* multishot, just fill an CQE and proceed */
5916 if (req->cqe.res && !(req->apoll_events & EPOLLONESHOT)) {
5917 __poll_t mask = mangle_poll(req->cqe.res & req->apoll_events);
5920 spin_lock(&ctx->completion_lock);
5921 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, mask,
5923 io_commit_cqring(ctx);
5924 spin_unlock(&ctx->completion_lock);
5925 if (unlikely(!filled))
5927 io_cqring_ev_posted(ctx);
5928 } else if (req->cqe.res) {
5933 * Release all references, retry if someone tried to restart
5934 * task_work while we were executing it.
5936 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5941 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5943 struct io_ring_ctx *ctx = req->ctx;
5946 ret = io_poll_check_events(req, *locked);
5951 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
5957 io_poll_remove_entries(req);
5958 spin_lock(&ctx->completion_lock);
5959 hash_del(&req->hash_node);
5960 __io_req_complete_post(req, req->cqe.res, 0);
5961 io_commit_cqring(ctx);
5962 spin_unlock(&ctx->completion_lock);
5963 io_cqring_ev_posted(ctx);
5966 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5968 struct io_ring_ctx *ctx = req->ctx;
5971 ret = io_poll_check_events(req, *locked);
5975 io_poll_remove_entries(req);
5976 spin_lock(&ctx->completion_lock);
5977 hash_del(&req->hash_node);
5978 spin_unlock(&ctx->completion_lock);
5981 io_req_task_submit(req, locked);
5983 io_req_complete_failed(req, ret);
5986 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
5988 req->cqe.res = mask;
5990 * This is useful for poll that is armed on behalf of another
5991 * request, and where the wakeup path could be on a different
5992 * CPU. We want to avoid pulling in req->apoll->events for that
5995 req->apoll_events = events;
5996 if (req->opcode == IORING_OP_POLL_ADD)
5997 req->io_task_work.func = io_poll_task_func;
5999 req->io_task_work.func = io_apoll_task_func;
6001 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6002 io_req_task_work_add(req, false);
6005 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6007 if (io_poll_get_ownership(req))
6008 __io_poll_execute(req, res, events);
6011 static void io_poll_cancel_req(struct io_kiocb *req)
6013 io_poll_mark_cancelled(req);
6014 /* kick tw, which should complete the request */
6015 io_poll_execute(req, 0, 0);
6018 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6019 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6021 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6024 struct io_kiocb *req = wqe_to_req(wait);
6025 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6027 __poll_t mask = key_to_poll(key);
6029 if (unlikely(mask & POLLFREE)) {
6030 io_poll_mark_cancelled(req);
6031 /* we have to kick tw in case it's not already */
6032 io_poll_execute(req, 0, poll->events);
6035 * If the waitqueue is being freed early but someone is already
6036 * holds ownership over it, we have to tear down the request as
6037 * best we can. That means immediately removing the request from
6038 * its waitqueue and preventing all further accesses to the
6039 * waitqueue via the request.
6041 list_del_init(&poll->wait.entry);
6044 * Careful: this *must* be the last step, since as soon
6045 * as req->head is NULL'ed out, the request can be
6046 * completed and freed, since aio_poll_complete_work()
6047 * will no longer need to take the waitqueue lock.
6049 smp_store_release(&poll->head, NULL);
6053 /* for instances that support it check for an event match first */
6054 if (mask && !(mask & poll->events))
6057 if (io_poll_get_ownership(req)) {
6058 /* optional, saves extra locking for removal in tw handler */
6059 if (mask && poll->events & EPOLLONESHOT) {
6060 list_del_init(&poll->wait.entry);
6062 if (wqe_is_double(wait))
6063 req->flags &= ~REQ_F_DOUBLE_POLL;
6065 req->flags &= ~REQ_F_SINGLE_POLL;
6067 __io_poll_execute(req, mask, poll->events);
6072 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6073 struct wait_queue_head *head,
6074 struct io_poll_iocb **poll_ptr)
6076 struct io_kiocb *req = pt->req;
6077 unsigned long wqe_private = (unsigned long) req;
6080 * The file being polled uses multiple waitqueues for poll handling
6081 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6084 if (unlikely(pt->nr_entries)) {
6085 struct io_poll_iocb *first = poll;
6087 /* double add on the same waitqueue head, ignore */
6088 if (first->head == head)
6090 /* already have a 2nd entry, fail a third attempt */
6092 if ((*poll_ptr)->head == head)
6094 pt->error = -EINVAL;
6098 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6100 pt->error = -ENOMEM;
6103 /* mark as double wq entry */
6105 req->flags |= REQ_F_DOUBLE_POLL;
6106 io_init_poll_iocb(poll, first->events, first->wait.func);
6108 if (req->opcode == IORING_OP_POLL_ADD)
6109 req->flags |= REQ_F_ASYNC_DATA;
6112 req->flags |= REQ_F_SINGLE_POLL;
6115 poll->wait.private = (void *) wqe_private;
6117 if (poll->events & EPOLLEXCLUSIVE)
6118 add_wait_queue_exclusive(head, &poll->wait);
6120 add_wait_queue(head, &poll->wait);
6123 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6124 struct poll_table_struct *p)
6126 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6128 __io_queue_proc(&pt->req->poll, pt, head,
6129 (struct io_poll_iocb **) &pt->req->async_data);
6132 static int __io_arm_poll_handler(struct io_kiocb *req,
6133 struct io_poll_iocb *poll,
6134 struct io_poll_table *ipt, __poll_t mask)
6136 struct io_ring_ctx *ctx = req->ctx;
6139 INIT_HLIST_NODE(&req->hash_node);
6140 io_init_poll_iocb(poll, mask, io_poll_wake);
6141 poll->file = req->file;
6143 ipt->pt._key = mask;
6146 ipt->nr_entries = 0;
6149 * Take the ownership to delay any tw execution up until we're done
6150 * with poll arming. see io_poll_get_ownership().
6152 atomic_set(&req->poll_refs, 1);
6153 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6155 if (mask && (poll->events & EPOLLONESHOT)) {
6156 io_poll_remove_entries(req);
6157 /* no one else has access to the req, forget about the ref */
6160 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6161 io_poll_remove_entries(req);
6163 ipt->error = -EINVAL;
6167 spin_lock(&ctx->completion_lock);
6168 io_poll_req_insert(req);
6169 spin_unlock(&ctx->completion_lock);
6172 /* can't multishot if failed, just queue the event we've got */
6173 if (unlikely(ipt->error || !ipt->nr_entries))
6174 poll->events |= EPOLLONESHOT;
6175 __io_poll_execute(req, mask, poll->events);
6180 * Release ownership. If someone tried to queue a tw while it was
6181 * locked, kick it off for them.
6183 v = atomic_dec_return(&req->poll_refs);
6184 if (unlikely(v & IO_POLL_REF_MASK))
6185 __io_poll_execute(req, 0, poll->events);
6189 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6190 struct poll_table_struct *p)
6192 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6193 struct async_poll *apoll = pt->req->apoll;
6195 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6204 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6206 const struct io_op_def *def = &io_op_defs[req->opcode];
6207 struct io_ring_ctx *ctx = req->ctx;
6208 struct async_poll *apoll;
6209 struct io_poll_table ipt;
6210 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6213 if (!def->pollin && !def->pollout)
6214 return IO_APOLL_ABORTED;
6215 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6216 return IO_APOLL_ABORTED;
6219 mask |= POLLIN | POLLRDNORM;
6221 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6222 if ((req->opcode == IORING_OP_RECVMSG) &&
6223 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6226 mask |= POLLOUT | POLLWRNORM;
6228 if (def->poll_exclusive)
6229 mask |= EPOLLEXCLUSIVE;
6230 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6231 !list_empty(&ctx->apoll_cache)) {
6232 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6234 list_del_init(&apoll->poll.wait.entry);
6236 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6237 if (unlikely(!apoll))
6238 return IO_APOLL_ABORTED;
6240 apoll->double_poll = NULL;
6242 req->flags |= REQ_F_POLLED;
6243 ipt.pt._qproc = io_async_queue_proc;
6245 io_kbuf_recycle(req, issue_flags);
6247 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6248 if (ret || ipt.error)
6249 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6251 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
6252 mask, apoll->poll.events);
6257 * Returns true if we found and killed one or more poll requests
6259 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6260 struct task_struct *tsk, bool cancel_all)
6262 struct hlist_node *tmp;
6263 struct io_kiocb *req;
6267 spin_lock(&ctx->completion_lock);
6268 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6269 struct hlist_head *list;
6271 list = &ctx->cancel_hash[i];
6272 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6273 if (io_match_task_safe(req, tsk, cancel_all)) {
6274 hlist_del_init(&req->hash_node);
6275 io_poll_cancel_req(req);
6280 spin_unlock(&ctx->completion_lock);
6284 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6286 __must_hold(&ctx->completion_lock)
6288 struct hlist_head *list;
6289 struct io_kiocb *req;
6291 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6292 hlist_for_each_entry(req, list, hash_node) {
6293 if (sqe_addr != req->cqe.user_data)
6295 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6302 static bool io_poll_disarm(struct io_kiocb *req)
6303 __must_hold(&ctx->completion_lock)
6305 if (!io_poll_get_ownership(req))
6307 io_poll_remove_entries(req);
6308 hash_del(&req->hash_node);
6312 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6314 __must_hold(&ctx->completion_lock)
6316 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6320 io_poll_cancel_req(req);
6324 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6329 events = READ_ONCE(sqe->poll32_events);
6331 events = swahw32(events);
6333 if (!(flags & IORING_POLL_ADD_MULTI))
6334 events |= EPOLLONESHOT;
6335 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6338 static int io_poll_update_prep(struct io_kiocb *req,
6339 const struct io_uring_sqe *sqe)
6341 struct io_poll_update *upd = &req->poll_update;
6344 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6346 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6348 flags = READ_ONCE(sqe->len);
6349 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6350 IORING_POLL_ADD_MULTI))
6352 /* meaningless without update */
6353 if (flags == IORING_POLL_ADD_MULTI)
6356 upd->old_user_data = READ_ONCE(sqe->addr);
6357 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6358 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6360 upd->new_user_data = READ_ONCE(sqe->off);
6361 if (!upd->update_user_data && upd->new_user_data)
6363 if (upd->update_events)
6364 upd->events = io_poll_parse_events(sqe, flags);
6365 else if (sqe->poll32_events)
6371 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6373 struct io_poll_iocb *poll = &req->poll;
6376 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6378 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6380 flags = READ_ONCE(sqe->len);
6381 if (flags & ~IORING_POLL_ADD_MULTI)
6383 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6386 io_req_set_refcount(req);
6387 req->apoll_events = poll->events = io_poll_parse_events(sqe, flags);
6391 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6393 struct io_poll_iocb *poll = &req->poll;
6394 struct io_poll_table ipt;
6397 ipt.pt._qproc = io_poll_queue_proc;
6399 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6400 ret = ret ?: ipt.error;
6402 __io_req_complete(req, issue_flags, ret, 0);
6406 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6408 struct io_ring_ctx *ctx = req->ctx;
6409 struct io_kiocb *preq;
6413 spin_lock(&ctx->completion_lock);
6414 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6415 if (!preq || !io_poll_disarm(preq)) {
6416 spin_unlock(&ctx->completion_lock);
6417 ret = preq ? -EALREADY : -ENOENT;
6420 spin_unlock(&ctx->completion_lock);
6422 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6423 /* only mask one event flags, keep behavior flags */
6424 if (req->poll_update.update_events) {
6425 preq->poll.events &= ~0xffff;
6426 preq->poll.events |= req->poll_update.events & 0xffff;
6427 preq->poll.events |= IO_POLL_UNMASK;
6429 if (req->poll_update.update_user_data)
6430 preq->cqe.user_data = req->poll_update.new_user_data;
6432 ret2 = io_poll_add(preq, issue_flags);
6433 /* successfully updated, don't complete poll request */
6439 preq->cqe.res = -ECANCELED;
6440 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6441 io_req_task_complete(preq, &locked);
6445 /* complete update request, we're done with it */
6446 __io_req_complete(req, issue_flags, ret, 0);
6450 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6452 struct io_timeout_data *data = container_of(timer,
6453 struct io_timeout_data, timer);
6454 struct io_kiocb *req = data->req;
6455 struct io_ring_ctx *ctx = req->ctx;
6456 unsigned long flags;
6458 spin_lock_irqsave(&ctx->timeout_lock, flags);
6459 list_del_init(&req->timeout.list);
6460 atomic_set(&req->ctx->cq_timeouts,
6461 atomic_read(&req->ctx->cq_timeouts) + 1);
6462 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6464 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6467 req->cqe.res = -ETIME;
6468 req->io_task_work.func = io_req_task_complete;
6469 io_req_task_work_add(req, false);
6470 return HRTIMER_NORESTART;
6473 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6475 __must_hold(&ctx->timeout_lock)
6477 struct io_timeout_data *io;
6478 struct io_kiocb *req;
6481 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6482 found = user_data == req->cqe.user_data;
6487 return ERR_PTR(-ENOENT);
6489 io = req->async_data;
6490 if (hrtimer_try_to_cancel(&io->timer) == -1)
6491 return ERR_PTR(-EALREADY);
6492 list_del_init(&req->timeout.list);
6496 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6497 __must_hold(&ctx->completion_lock)
6498 __must_hold(&ctx->timeout_lock)
6500 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6503 return PTR_ERR(req);
6504 io_req_task_queue_fail(req, -ECANCELED);
6508 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6510 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6511 case IORING_TIMEOUT_BOOTTIME:
6512 return CLOCK_BOOTTIME;
6513 case IORING_TIMEOUT_REALTIME:
6514 return CLOCK_REALTIME;
6516 /* can't happen, vetted at prep time */
6520 return CLOCK_MONOTONIC;
6524 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6525 struct timespec64 *ts, enum hrtimer_mode mode)
6526 __must_hold(&ctx->timeout_lock)
6528 struct io_timeout_data *io;
6529 struct io_kiocb *req;
6532 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6533 found = user_data == req->cqe.user_data;
6540 io = req->async_data;
6541 if (hrtimer_try_to_cancel(&io->timer) == -1)
6543 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6544 io->timer.function = io_link_timeout_fn;
6545 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6549 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6550 struct timespec64 *ts, enum hrtimer_mode mode)
6551 __must_hold(&ctx->timeout_lock)
6553 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6554 struct io_timeout_data *data;
6557 return PTR_ERR(req);
6559 req->timeout.off = 0; /* noseq */
6560 data = req->async_data;
6561 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6562 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6563 data->timer.function = io_timeout_fn;
6564 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6568 static int io_timeout_remove_prep(struct io_kiocb *req,
6569 const struct io_uring_sqe *sqe)
6571 struct io_timeout_rem *tr = &req->timeout_rem;
6573 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6575 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6577 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6580 tr->ltimeout = false;
6581 tr->addr = READ_ONCE(sqe->addr);
6582 tr->flags = READ_ONCE(sqe->timeout_flags);
6583 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6584 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6586 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6587 tr->ltimeout = true;
6588 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6590 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6592 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6594 } else if (tr->flags) {
6595 /* timeout removal doesn't support flags */
6602 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6604 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6609 * Remove or update an existing timeout command
6611 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6613 struct io_timeout_rem *tr = &req->timeout_rem;
6614 struct io_ring_ctx *ctx = req->ctx;
6617 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6618 spin_lock(&ctx->completion_lock);
6619 spin_lock_irq(&ctx->timeout_lock);
6620 ret = io_timeout_cancel(ctx, tr->addr);
6621 spin_unlock_irq(&ctx->timeout_lock);
6622 spin_unlock(&ctx->completion_lock);
6624 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6626 spin_lock_irq(&ctx->timeout_lock);
6628 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6630 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6631 spin_unlock_irq(&ctx->timeout_lock);
6636 io_req_complete_post(req, ret, 0);
6640 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6641 bool is_timeout_link)
6643 struct io_timeout_data *data;
6645 u32 off = READ_ONCE(sqe->off);
6647 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6649 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6652 if (off && is_timeout_link)
6654 flags = READ_ONCE(sqe->timeout_flags);
6655 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6656 IORING_TIMEOUT_ETIME_SUCCESS))
6658 /* more than one clock specified is invalid, obviously */
6659 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6662 INIT_LIST_HEAD(&req->timeout.list);
6663 req->timeout.off = off;
6664 if (unlikely(off && !req->ctx->off_timeout_used))
6665 req->ctx->off_timeout_used = true;
6667 if (WARN_ON_ONCE(req_has_async_data(req)))
6669 if (io_alloc_async_data(req))
6672 data = req->async_data;
6674 data->flags = flags;
6676 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6679 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6682 INIT_LIST_HEAD(&req->timeout.list);
6683 data->mode = io_translate_timeout_mode(flags);
6684 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6686 if (is_timeout_link) {
6687 struct io_submit_link *link = &req->ctx->submit_state.link;
6691 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6693 req->timeout.head = link->last;
6694 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6699 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6701 struct io_ring_ctx *ctx = req->ctx;
6702 struct io_timeout_data *data = req->async_data;
6703 struct list_head *entry;
6704 u32 tail, off = req->timeout.off;
6706 spin_lock_irq(&ctx->timeout_lock);
6709 * sqe->off holds how many events that need to occur for this
6710 * timeout event to be satisfied. If it isn't set, then this is
6711 * a pure timeout request, sequence isn't used.
6713 if (io_is_timeout_noseq(req)) {
6714 entry = ctx->timeout_list.prev;
6718 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6719 req->timeout.target_seq = tail + off;
6721 /* Update the last seq here in case io_flush_timeouts() hasn't.
6722 * This is safe because ->completion_lock is held, and submissions
6723 * and completions are never mixed in the same ->completion_lock section.
6725 ctx->cq_last_tm_flush = tail;
6728 * Insertion sort, ensuring the first entry in the list is always
6729 * the one we need first.
6731 list_for_each_prev(entry, &ctx->timeout_list) {
6732 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6735 if (io_is_timeout_noseq(nxt))
6737 /* nxt.seq is behind @tail, otherwise would've been completed */
6738 if (off >= nxt->timeout.target_seq - tail)
6742 list_add(&req->timeout.list, entry);
6743 data->timer.function = io_timeout_fn;
6744 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6745 spin_unlock_irq(&ctx->timeout_lock);
6749 struct io_cancel_data {
6750 struct io_ring_ctx *ctx;
6754 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6756 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6757 struct io_cancel_data *cd = data;
6759 return req->ctx == cd->ctx && req->cqe.user_data == cd->user_data;
6762 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6763 struct io_ring_ctx *ctx)
6765 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6766 enum io_wq_cancel cancel_ret;
6769 if (!tctx || !tctx->io_wq)
6772 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6773 switch (cancel_ret) {
6774 case IO_WQ_CANCEL_OK:
6777 case IO_WQ_CANCEL_RUNNING:
6780 case IO_WQ_CANCEL_NOTFOUND:
6788 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6790 struct io_ring_ctx *ctx = req->ctx;
6793 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6795 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6797 * Fall-through even for -EALREADY, as we may have poll armed
6798 * that need unarming.
6803 spin_lock(&ctx->completion_lock);
6804 ret = io_poll_cancel(ctx, sqe_addr, false);
6808 spin_lock_irq(&ctx->timeout_lock);
6809 ret = io_timeout_cancel(ctx, sqe_addr);
6810 spin_unlock_irq(&ctx->timeout_lock);
6812 spin_unlock(&ctx->completion_lock);
6816 static int io_async_cancel_prep(struct io_kiocb *req,
6817 const struct io_uring_sqe *sqe)
6819 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6821 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6823 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6827 req->cancel.addr = READ_ONCE(sqe->addr);
6831 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6833 struct io_ring_ctx *ctx = req->ctx;
6834 u64 sqe_addr = req->cancel.addr;
6835 struct io_tctx_node *node;
6838 ret = io_try_cancel_userdata(req, sqe_addr);
6842 /* slow path, try all io-wq's */
6843 io_ring_submit_lock(ctx, issue_flags);
6845 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6846 struct io_uring_task *tctx = node->task->io_uring;
6848 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6852 io_ring_submit_unlock(ctx, issue_flags);
6856 io_req_complete_post(req, ret, 0);
6860 static int io_rsrc_update_prep(struct io_kiocb *req,
6861 const struct io_uring_sqe *sqe)
6863 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6865 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6868 req->rsrc_update.offset = READ_ONCE(sqe->off);
6869 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6870 if (!req->rsrc_update.nr_args)
6872 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6876 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6878 struct io_ring_ctx *ctx = req->ctx;
6879 struct io_uring_rsrc_update2 up;
6882 up.offset = req->rsrc_update.offset;
6883 up.data = req->rsrc_update.arg;
6889 io_ring_submit_lock(ctx, issue_flags);
6890 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6891 &up, req->rsrc_update.nr_args);
6892 io_ring_submit_unlock(ctx, issue_flags);
6896 __io_req_complete(req, issue_flags, ret, 0);
6900 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6902 switch (req->opcode) {
6905 case IORING_OP_READV:
6906 case IORING_OP_READ_FIXED:
6907 case IORING_OP_READ:
6908 case IORING_OP_WRITEV:
6909 case IORING_OP_WRITE_FIXED:
6910 case IORING_OP_WRITE:
6911 return io_prep_rw(req, sqe);
6912 case IORING_OP_POLL_ADD:
6913 return io_poll_add_prep(req, sqe);
6914 case IORING_OP_POLL_REMOVE:
6915 return io_poll_update_prep(req, sqe);
6916 case IORING_OP_FSYNC:
6917 return io_fsync_prep(req, sqe);
6918 case IORING_OP_SYNC_FILE_RANGE:
6919 return io_sfr_prep(req, sqe);
6920 case IORING_OP_SENDMSG:
6921 case IORING_OP_SEND:
6922 return io_sendmsg_prep(req, sqe);
6923 case IORING_OP_RECVMSG:
6924 case IORING_OP_RECV:
6925 return io_recvmsg_prep(req, sqe);
6926 case IORING_OP_CONNECT:
6927 return io_connect_prep(req, sqe);
6928 case IORING_OP_TIMEOUT:
6929 return io_timeout_prep(req, sqe, false);
6930 case IORING_OP_TIMEOUT_REMOVE:
6931 return io_timeout_remove_prep(req, sqe);
6932 case IORING_OP_ASYNC_CANCEL:
6933 return io_async_cancel_prep(req, sqe);
6934 case IORING_OP_LINK_TIMEOUT:
6935 return io_timeout_prep(req, sqe, true);
6936 case IORING_OP_ACCEPT:
6937 return io_accept_prep(req, sqe);
6938 case IORING_OP_FALLOCATE:
6939 return io_fallocate_prep(req, sqe);
6940 case IORING_OP_OPENAT:
6941 return io_openat_prep(req, sqe);
6942 case IORING_OP_CLOSE:
6943 return io_close_prep(req, sqe);
6944 case IORING_OP_FILES_UPDATE:
6945 return io_rsrc_update_prep(req, sqe);
6946 case IORING_OP_STATX:
6947 return io_statx_prep(req, sqe);
6948 case IORING_OP_FADVISE:
6949 return io_fadvise_prep(req, sqe);
6950 case IORING_OP_MADVISE:
6951 return io_madvise_prep(req, sqe);
6952 case IORING_OP_OPENAT2:
6953 return io_openat2_prep(req, sqe);
6954 case IORING_OP_EPOLL_CTL:
6955 return io_epoll_ctl_prep(req, sqe);
6956 case IORING_OP_SPLICE:
6957 return io_splice_prep(req, sqe);
6958 case IORING_OP_PROVIDE_BUFFERS:
6959 return io_provide_buffers_prep(req, sqe);
6960 case IORING_OP_REMOVE_BUFFERS:
6961 return io_remove_buffers_prep(req, sqe);
6963 return io_tee_prep(req, sqe);
6964 case IORING_OP_SHUTDOWN:
6965 return io_shutdown_prep(req, sqe);
6966 case IORING_OP_RENAMEAT:
6967 return io_renameat_prep(req, sqe);
6968 case IORING_OP_UNLINKAT:
6969 return io_unlinkat_prep(req, sqe);
6970 case IORING_OP_MKDIRAT:
6971 return io_mkdirat_prep(req, sqe);
6972 case IORING_OP_SYMLINKAT:
6973 return io_symlinkat_prep(req, sqe);
6974 case IORING_OP_LINKAT:
6975 return io_linkat_prep(req, sqe);
6976 case IORING_OP_MSG_RING:
6977 return io_msg_ring_prep(req, sqe);
6980 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6985 static int io_req_prep_async(struct io_kiocb *req)
6987 if (!io_op_defs[req->opcode].needs_async_setup)
6989 if (WARN_ON_ONCE(req_has_async_data(req)))
6991 if (io_alloc_async_data(req))
6994 switch (req->opcode) {
6995 case IORING_OP_READV:
6996 return io_rw_prep_async(req, READ);
6997 case IORING_OP_WRITEV:
6998 return io_rw_prep_async(req, WRITE);
6999 case IORING_OP_SENDMSG:
7000 return io_sendmsg_prep_async(req);
7001 case IORING_OP_RECVMSG:
7002 return io_recvmsg_prep_async(req);
7003 case IORING_OP_CONNECT:
7004 return io_connect_prep_async(req);
7006 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7011 static u32 io_get_sequence(struct io_kiocb *req)
7013 u32 seq = req->ctx->cached_sq_head;
7014 struct io_kiocb *cur;
7016 /* need original cached_sq_head, but it was increased for each req */
7017 io_for_each_link(cur, req)
7022 static __cold void io_drain_req(struct io_kiocb *req)
7024 struct io_ring_ctx *ctx = req->ctx;
7025 struct io_defer_entry *de;
7027 u32 seq = io_get_sequence(req);
7029 /* Still need defer if there is pending req in defer list. */
7030 spin_lock(&ctx->completion_lock);
7031 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7032 spin_unlock(&ctx->completion_lock);
7034 ctx->drain_active = false;
7035 io_req_task_queue(req);
7038 spin_unlock(&ctx->completion_lock);
7040 ret = io_req_prep_async(req);
7043 io_req_complete_failed(req, ret);
7046 io_prep_async_link(req);
7047 de = kmalloc(sizeof(*de), GFP_KERNEL);
7053 spin_lock(&ctx->completion_lock);
7054 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7055 spin_unlock(&ctx->completion_lock);
7060 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7063 list_add_tail(&de->list, &ctx->defer_list);
7064 spin_unlock(&ctx->completion_lock);
7067 static void io_clean_op(struct io_kiocb *req)
7069 if (req->flags & REQ_F_BUFFER_SELECTED) {
7070 spin_lock(&req->ctx->completion_lock);
7071 io_put_kbuf_comp(req);
7072 spin_unlock(&req->ctx->completion_lock);
7075 if (req->flags & REQ_F_NEED_CLEANUP) {
7076 switch (req->opcode) {
7077 case IORING_OP_READV:
7078 case IORING_OP_READ_FIXED:
7079 case IORING_OP_READ:
7080 case IORING_OP_WRITEV:
7081 case IORING_OP_WRITE_FIXED:
7082 case IORING_OP_WRITE: {
7083 struct io_async_rw *io = req->async_data;
7085 kfree(io->free_iovec);
7088 case IORING_OP_RECVMSG:
7089 case IORING_OP_SENDMSG: {
7090 struct io_async_msghdr *io = req->async_data;
7092 kfree(io->free_iov);
7095 case IORING_OP_OPENAT:
7096 case IORING_OP_OPENAT2:
7097 if (req->open.filename)
7098 putname(req->open.filename);
7100 case IORING_OP_RENAMEAT:
7101 putname(req->rename.oldpath);
7102 putname(req->rename.newpath);
7104 case IORING_OP_UNLINKAT:
7105 putname(req->unlink.filename);
7107 case IORING_OP_MKDIRAT:
7108 putname(req->mkdir.filename);
7110 case IORING_OP_SYMLINKAT:
7111 putname(req->symlink.oldpath);
7112 putname(req->symlink.newpath);
7114 case IORING_OP_LINKAT:
7115 putname(req->hardlink.oldpath);
7116 putname(req->hardlink.newpath);
7118 case IORING_OP_STATX:
7119 if (req->statx.filename)
7120 putname(req->statx.filename);
7124 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7125 kfree(req->apoll->double_poll);
7129 if (req->flags & REQ_F_CREDS)
7130 put_cred(req->creds);
7131 if (req->flags & REQ_F_ASYNC_DATA) {
7132 kfree(req->async_data);
7133 req->async_data = NULL;
7135 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7138 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
7140 if (req->file || !io_op_defs[req->opcode].needs_file)
7143 if (req->flags & REQ_F_FIXED_FILE)
7144 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
7146 req->file = io_file_get_normal(req, req->cqe.fd);
7151 req->cqe.res = -EBADF;
7155 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7157 const struct cred *creds = NULL;
7160 if (unlikely(!io_assign_file(req, issue_flags)))
7163 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7164 creds = override_creds(req->creds);
7166 if (!io_op_defs[req->opcode].audit_skip)
7167 audit_uring_entry(req->opcode);
7169 switch (req->opcode) {
7171 ret = io_nop(req, issue_flags);
7173 case IORING_OP_READV:
7174 case IORING_OP_READ_FIXED:
7175 case IORING_OP_READ:
7176 ret = io_read(req, issue_flags);
7178 case IORING_OP_WRITEV:
7179 case IORING_OP_WRITE_FIXED:
7180 case IORING_OP_WRITE:
7181 ret = io_write(req, issue_flags);
7183 case IORING_OP_FSYNC:
7184 ret = io_fsync(req, issue_flags);
7186 case IORING_OP_POLL_ADD:
7187 ret = io_poll_add(req, issue_flags);
7189 case IORING_OP_POLL_REMOVE:
7190 ret = io_poll_update(req, issue_flags);
7192 case IORING_OP_SYNC_FILE_RANGE:
7193 ret = io_sync_file_range(req, issue_flags);
7195 case IORING_OP_SENDMSG:
7196 ret = io_sendmsg(req, issue_flags);
7198 case IORING_OP_SEND:
7199 ret = io_send(req, issue_flags);
7201 case IORING_OP_RECVMSG:
7202 ret = io_recvmsg(req, issue_flags);
7204 case IORING_OP_RECV:
7205 ret = io_recv(req, issue_flags);
7207 case IORING_OP_TIMEOUT:
7208 ret = io_timeout(req, issue_flags);
7210 case IORING_OP_TIMEOUT_REMOVE:
7211 ret = io_timeout_remove(req, issue_flags);
7213 case IORING_OP_ACCEPT:
7214 ret = io_accept(req, issue_flags);
7216 case IORING_OP_CONNECT:
7217 ret = io_connect(req, issue_flags);
7219 case IORING_OP_ASYNC_CANCEL:
7220 ret = io_async_cancel(req, issue_flags);
7222 case IORING_OP_FALLOCATE:
7223 ret = io_fallocate(req, issue_flags);
7225 case IORING_OP_OPENAT:
7226 ret = io_openat(req, issue_flags);
7228 case IORING_OP_CLOSE:
7229 ret = io_close(req, issue_flags);
7231 case IORING_OP_FILES_UPDATE:
7232 ret = io_files_update(req, issue_flags);
7234 case IORING_OP_STATX:
7235 ret = io_statx(req, issue_flags);
7237 case IORING_OP_FADVISE:
7238 ret = io_fadvise(req, issue_flags);
7240 case IORING_OP_MADVISE:
7241 ret = io_madvise(req, issue_flags);
7243 case IORING_OP_OPENAT2:
7244 ret = io_openat2(req, issue_flags);
7246 case IORING_OP_EPOLL_CTL:
7247 ret = io_epoll_ctl(req, issue_flags);
7249 case IORING_OP_SPLICE:
7250 ret = io_splice(req, issue_flags);
7252 case IORING_OP_PROVIDE_BUFFERS:
7253 ret = io_provide_buffers(req, issue_flags);
7255 case IORING_OP_REMOVE_BUFFERS:
7256 ret = io_remove_buffers(req, issue_flags);
7259 ret = io_tee(req, issue_flags);
7261 case IORING_OP_SHUTDOWN:
7262 ret = io_shutdown(req, issue_flags);
7264 case IORING_OP_RENAMEAT:
7265 ret = io_renameat(req, issue_flags);
7267 case IORING_OP_UNLINKAT:
7268 ret = io_unlinkat(req, issue_flags);
7270 case IORING_OP_MKDIRAT:
7271 ret = io_mkdirat(req, issue_flags);
7273 case IORING_OP_SYMLINKAT:
7274 ret = io_symlinkat(req, issue_flags);
7276 case IORING_OP_LINKAT:
7277 ret = io_linkat(req, issue_flags);
7279 case IORING_OP_MSG_RING:
7280 ret = io_msg_ring(req, issue_flags);
7287 if (!io_op_defs[req->opcode].audit_skip)
7288 audit_uring_exit(!ret, ret);
7291 revert_creds(creds);
7294 /* If the op doesn't have a file, we're not polling for it */
7295 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7296 io_iopoll_req_issued(req, issue_flags);
7301 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7303 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7305 req = io_put_req_find_next(req);
7306 return req ? &req->work : NULL;
7309 static void io_wq_submit_work(struct io_wq_work *work)
7311 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7312 const struct io_op_def *def = &io_op_defs[req->opcode];
7313 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7314 bool needs_poll = false;
7315 int ret = 0, err = -ECANCELED;
7317 /* one will be dropped by ->io_free_work() after returning to io-wq */
7318 if (!(req->flags & REQ_F_REFCOUNT))
7319 __io_req_set_refcount(req, 2);
7323 io_arm_ltimeout(req);
7325 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7326 if (work->flags & IO_WQ_WORK_CANCEL) {
7328 io_req_task_queue_fail(req, err);
7331 if (!io_assign_file(req, issue_flags)) {
7333 work->flags |= IO_WQ_WORK_CANCEL;
7337 if (req->flags & REQ_F_FORCE_ASYNC) {
7338 bool opcode_poll = def->pollin || def->pollout;
7340 if (opcode_poll && file_can_poll(req->file)) {
7342 issue_flags |= IO_URING_F_NONBLOCK;
7347 ret = io_issue_sqe(req, issue_flags);
7351 * We can get EAGAIN for iopolled IO even though we're
7352 * forcing a sync submission from here, since we can't
7353 * wait for request slots on the block side.
7360 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7362 /* aborted or ready, in either case retry blocking */
7364 issue_flags &= ~IO_URING_F_NONBLOCK;
7367 /* avoid locking problems by failing it from a clean context */
7369 io_req_task_queue_fail(req, ret);
7372 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7375 return &table->files[i];
7378 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7381 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7383 return (struct file *) (slot->file_ptr & FFS_MASK);
7386 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7388 unsigned long file_ptr = (unsigned long) file;
7390 file_ptr |= io_file_get_flags(file);
7391 file_slot->file_ptr = file_ptr;
7394 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
7395 unsigned int issue_flags)
7397 struct io_ring_ctx *ctx = req->ctx;
7398 struct file *file = NULL;
7399 unsigned long file_ptr;
7401 if (issue_flags & IO_URING_F_UNLOCKED)
7402 mutex_lock(&ctx->uring_lock);
7404 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7406 fd = array_index_nospec(fd, ctx->nr_user_files);
7407 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7408 file = (struct file *) (file_ptr & FFS_MASK);
7409 file_ptr &= ~FFS_MASK;
7410 /* mask in overlapping REQ_F and FFS bits */
7411 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7412 io_req_set_rsrc_node(req, ctx, 0);
7414 if (issue_flags & IO_URING_F_UNLOCKED)
7415 mutex_unlock(&ctx->uring_lock);
7420 * Drop the file for requeue operations. Only used of req->file is the
7421 * io_uring descriptor itself.
7423 static void io_drop_inflight_file(struct io_kiocb *req)
7425 if (unlikely(req->flags & REQ_F_INFLIGHT)) {
7428 req->flags &= ~REQ_F_INFLIGHT;
7432 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
7434 struct file *file = fget(fd);
7436 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
7438 /* we don't allow fixed io_uring files */
7439 if (file && file->f_op == &io_uring_fops)
7440 req->flags |= REQ_F_INFLIGHT;
7444 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7446 struct io_kiocb *prev = req->timeout.prev;
7450 if (!(req->task->flags & PF_EXITING))
7451 ret = io_try_cancel_userdata(req, prev->cqe.user_data);
7452 io_req_complete_post(req, ret ?: -ETIME, 0);
7455 io_req_complete_post(req, -ETIME, 0);
7459 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7461 struct io_timeout_data *data = container_of(timer,
7462 struct io_timeout_data, timer);
7463 struct io_kiocb *prev, *req = data->req;
7464 struct io_ring_ctx *ctx = req->ctx;
7465 unsigned long flags;
7467 spin_lock_irqsave(&ctx->timeout_lock, flags);
7468 prev = req->timeout.head;
7469 req->timeout.head = NULL;
7472 * We don't expect the list to be empty, that will only happen if we
7473 * race with the completion of the linked work.
7476 io_remove_next_linked(prev);
7477 if (!req_ref_inc_not_zero(prev))
7480 list_del(&req->timeout.list);
7481 req->timeout.prev = prev;
7482 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7484 req->io_task_work.func = io_req_task_link_timeout;
7485 io_req_task_work_add(req, false);
7486 return HRTIMER_NORESTART;
7489 static void io_queue_linked_timeout(struct io_kiocb *req)
7491 struct io_ring_ctx *ctx = req->ctx;
7493 spin_lock_irq(&ctx->timeout_lock);
7495 * If the back reference is NULL, then our linked request finished
7496 * before we got a chance to setup the timer
7498 if (req->timeout.head) {
7499 struct io_timeout_data *data = req->async_data;
7501 data->timer.function = io_link_timeout_fn;
7502 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7504 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7506 spin_unlock_irq(&ctx->timeout_lock);
7507 /* drop submission reference */
7511 static void io_queue_async(struct io_kiocb *req, int ret)
7512 __must_hold(&req->ctx->uring_lock)
7514 struct io_kiocb *linked_timeout;
7516 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
7517 io_req_complete_failed(req, ret);
7521 linked_timeout = io_prep_linked_timeout(req);
7523 switch (io_arm_poll_handler(req, 0)) {
7524 case IO_APOLL_READY:
7525 io_req_task_queue(req);
7527 case IO_APOLL_ABORTED:
7529 * Queued up for async execution, worker will release
7530 * submit reference when the iocb is actually submitted.
7532 io_queue_iowq(req, NULL);
7539 io_queue_linked_timeout(linked_timeout);
7542 static inline void io_queue_sqe(struct io_kiocb *req)
7543 __must_hold(&req->ctx->uring_lock)
7547 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7549 if (req->flags & REQ_F_COMPLETE_INLINE) {
7550 io_req_add_compl_list(req);
7554 * We async punt it if the file wasn't marked NOWAIT, or if the file
7555 * doesn't support non-blocking read/write attempts
7558 io_arm_ltimeout(req);
7560 io_queue_async(req, ret);
7563 static void io_queue_sqe_fallback(struct io_kiocb *req)
7564 __must_hold(&req->ctx->uring_lock)
7566 if (req->flags & REQ_F_FAIL) {
7567 io_req_complete_fail_submit(req);
7568 } else if (unlikely(req->ctx->drain_active)) {
7571 int ret = io_req_prep_async(req);
7574 io_req_complete_failed(req, ret);
7576 io_queue_iowq(req, NULL);
7581 * Check SQE restrictions (opcode and flags).
7583 * Returns 'true' if SQE is allowed, 'false' otherwise.
7585 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7586 struct io_kiocb *req,
7587 unsigned int sqe_flags)
7589 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7592 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7593 ctx->restrictions.sqe_flags_required)
7596 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7597 ctx->restrictions.sqe_flags_required))
7603 static void io_init_req_drain(struct io_kiocb *req)
7605 struct io_ring_ctx *ctx = req->ctx;
7606 struct io_kiocb *head = ctx->submit_state.link.head;
7608 ctx->drain_active = true;
7611 * If we need to drain a request in the middle of a link, drain
7612 * the head request and the next request/link after the current
7613 * link. Considering sequential execution of links,
7614 * REQ_F_IO_DRAIN will be maintained for every request of our
7617 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7618 ctx->drain_next = true;
7622 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7623 const struct io_uring_sqe *sqe)
7624 __must_hold(&ctx->uring_lock)
7626 unsigned int sqe_flags;
7630 /* req is partially pre-initialised, see io_preinit_req() */
7631 req->opcode = opcode = READ_ONCE(sqe->opcode);
7632 /* same numerical values with corresponding REQ_F_*, safe to copy */
7633 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7634 req->cqe.user_data = READ_ONCE(sqe->user_data);
7636 req->fixed_rsrc_refs = NULL;
7637 req->task = current;
7639 if (unlikely(opcode >= IORING_OP_LAST)) {
7643 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7644 /* enforce forwards compatibility on users */
7645 if (sqe_flags & ~SQE_VALID_FLAGS)
7647 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7648 !io_op_defs[opcode].buffer_select)
7650 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7651 ctx->drain_disabled = true;
7652 if (sqe_flags & IOSQE_IO_DRAIN) {
7653 if (ctx->drain_disabled)
7655 io_init_req_drain(req);
7658 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7659 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7661 /* knock it to the slow queue path, will be drained there */
7662 if (ctx->drain_active)
7663 req->flags |= REQ_F_FORCE_ASYNC;
7664 /* if there is no link, we're at "next" request and need to drain */
7665 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7666 ctx->drain_next = false;
7667 ctx->drain_active = true;
7668 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7672 if (io_op_defs[opcode].needs_file) {
7673 struct io_submit_state *state = &ctx->submit_state;
7675 req->cqe.fd = READ_ONCE(sqe->fd);
7678 * Plug now if we have more than 2 IO left after this, and the
7679 * target is potentially a read/write to block based storage.
7681 if (state->need_plug && io_op_defs[opcode].plug) {
7682 state->plug_started = true;
7683 state->need_plug = false;
7684 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7688 personality = READ_ONCE(sqe->personality);
7692 req->creds = xa_load(&ctx->personalities, personality);
7695 get_cred(req->creds);
7696 ret = security_uring_override_creds(req->creds);
7698 put_cred(req->creds);
7701 req->flags |= REQ_F_CREDS;
7704 return io_req_prep(req, sqe);
7707 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7708 const struct io_uring_sqe *sqe)
7709 __must_hold(&ctx->uring_lock)
7711 struct io_submit_link *link = &ctx->submit_state.link;
7714 ret = io_init_req(ctx, req, sqe);
7715 if (unlikely(ret)) {
7716 trace_io_uring_req_failed(sqe, ctx, req, ret);
7718 /* fail even hard links since we don't submit */
7721 * we can judge a link req is failed or cancelled by if
7722 * REQ_F_FAIL is set, but the head is an exception since
7723 * it may be set REQ_F_FAIL because of other req's failure
7724 * so let's leverage req->cqe.res to distinguish if a head
7725 * is set REQ_F_FAIL because of its failure or other req's
7726 * failure so that we can set the correct ret code for it.
7727 * init result here to avoid affecting the normal path.
7729 if (!(link->head->flags & REQ_F_FAIL))
7730 req_fail_link_node(link->head, -ECANCELED);
7731 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7733 * the current req is a normal req, we should return
7734 * error and thus break the submittion loop.
7736 io_req_complete_failed(req, ret);
7739 req_fail_link_node(req, ret);
7742 /* don't need @sqe from now on */
7743 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
7745 ctx->flags & IORING_SETUP_SQPOLL);
7748 * If we already have a head request, queue this one for async
7749 * submittal once the head completes. If we don't have a head but
7750 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7751 * submitted sync once the chain is complete. If none of those
7752 * conditions are true (normal request), then just queue it.
7755 struct io_kiocb *head = link->head;
7757 if (!(req->flags & REQ_F_FAIL)) {
7758 ret = io_req_prep_async(req);
7759 if (unlikely(ret)) {
7760 req_fail_link_node(req, ret);
7761 if (!(head->flags & REQ_F_FAIL))
7762 req_fail_link_node(head, -ECANCELED);
7765 trace_io_uring_link(ctx, req, head);
7766 link->last->link = req;
7769 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7771 /* last request of a link, enqueue the link */
7774 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7780 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7783 io_queue_sqe_fallback(req);
7789 * Batched submission is done, ensure local IO is flushed out.
7791 static void io_submit_state_end(struct io_ring_ctx *ctx)
7793 struct io_submit_state *state = &ctx->submit_state;
7795 if (unlikely(state->link.head))
7796 io_queue_sqe_fallback(state->link.head);
7797 /* flush only after queuing links as they can generate completions */
7798 io_submit_flush_completions(ctx);
7799 if (state->plug_started)
7800 blk_finish_plug(&state->plug);
7804 * Start submission side cache.
7806 static void io_submit_state_start(struct io_submit_state *state,
7807 unsigned int max_ios)
7809 state->plug_started = false;
7810 state->need_plug = max_ios > 2;
7811 state->submit_nr = max_ios;
7812 /* set only head, no need to init link_last in advance */
7813 state->link.head = NULL;
7816 static void io_commit_sqring(struct io_ring_ctx *ctx)
7818 struct io_rings *rings = ctx->rings;
7821 * Ensure any loads from the SQEs are done at this point,
7822 * since once we write the new head, the application could
7823 * write new data to them.
7825 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7829 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7830 * that is mapped by userspace. This means that care needs to be taken to
7831 * ensure that reads are stable, as we cannot rely on userspace always
7832 * being a good citizen. If members of the sqe are validated and then later
7833 * used, it's important that those reads are done through READ_ONCE() to
7834 * prevent a re-load down the line.
7836 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7838 unsigned head, mask = ctx->sq_entries - 1;
7839 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7842 * The cached sq head (or cq tail) serves two purposes:
7844 * 1) allows us to batch the cost of updating the user visible
7846 * 2) allows the kernel side to track the head on its own, even
7847 * though the application is the one updating it.
7849 head = READ_ONCE(ctx->sq_array[sq_idx]);
7850 if (likely(head < ctx->sq_entries))
7851 return &ctx->sq_sqes[head];
7853 /* drop invalid entries */
7855 WRITE_ONCE(ctx->rings->sq_dropped,
7856 READ_ONCE(ctx->rings->sq_dropped) + 1);
7860 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7861 __must_hold(&ctx->uring_lock)
7863 unsigned int entries = io_sqring_entries(ctx);
7867 if (unlikely(!entries))
7869 /* make sure SQ entry isn't read before tail */
7870 ret = left = min3(nr, ctx->sq_entries, entries);
7871 io_get_task_refs(left);
7872 io_submit_state_start(&ctx->submit_state, left);
7875 const struct io_uring_sqe *sqe;
7876 struct io_kiocb *req;
7878 if (unlikely(!io_alloc_req_refill(ctx)))
7880 req = io_alloc_req(ctx);
7881 sqe = io_get_sqe(ctx);
7882 if (unlikely(!sqe)) {
7883 io_req_add_to_cache(req, ctx);
7888 * Continue submitting even for sqe failure if the
7889 * ring was setup with IORING_SETUP_SUBMIT_ALL
7891 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
7892 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
7898 if (unlikely(left)) {
7900 /* try again if it submitted nothing and can't allocate a req */
7901 if (!ret && io_req_cache_empty(ctx))
7903 current->io_uring->cached_refs += left;
7906 io_submit_state_end(ctx);
7907 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7908 io_commit_sqring(ctx);
7912 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7914 return READ_ONCE(sqd->state);
7917 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7919 /* Tell userspace we may need a wakeup call */
7920 spin_lock(&ctx->completion_lock);
7921 WRITE_ONCE(ctx->rings->sq_flags,
7922 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7923 spin_unlock(&ctx->completion_lock);
7926 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7928 spin_lock(&ctx->completion_lock);
7929 WRITE_ONCE(ctx->rings->sq_flags,
7930 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7931 spin_unlock(&ctx->completion_lock);
7934 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7936 unsigned int to_submit;
7939 to_submit = io_sqring_entries(ctx);
7940 /* if we're handling multiple rings, cap submit size for fairness */
7941 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7942 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7944 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7945 const struct cred *creds = NULL;
7947 if (ctx->sq_creds != current_cred())
7948 creds = override_creds(ctx->sq_creds);
7950 mutex_lock(&ctx->uring_lock);
7951 if (!wq_list_empty(&ctx->iopoll_list))
7952 io_do_iopoll(ctx, true);
7955 * Don't submit if refs are dying, good for io_uring_register(),
7956 * but also it is relied upon by io_ring_exit_work()
7958 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7959 !(ctx->flags & IORING_SETUP_R_DISABLED))
7960 ret = io_submit_sqes(ctx, to_submit);
7961 mutex_unlock(&ctx->uring_lock);
7963 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7964 wake_up(&ctx->sqo_sq_wait);
7966 revert_creds(creds);
7972 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7974 struct io_ring_ctx *ctx;
7975 unsigned sq_thread_idle = 0;
7977 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7978 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7979 sqd->sq_thread_idle = sq_thread_idle;
7982 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7984 bool did_sig = false;
7985 struct ksignal ksig;
7987 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7988 signal_pending(current)) {
7989 mutex_unlock(&sqd->lock);
7990 if (signal_pending(current))
7991 did_sig = get_signal(&ksig);
7993 mutex_lock(&sqd->lock);
7995 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7998 static int io_sq_thread(void *data)
8000 struct io_sq_data *sqd = data;
8001 struct io_ring_ctx *ctx;
8002 unsigned long timeout = 0;
8003 char buf[TASK_COMM_LEN];
8006 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8007 set_task_comm(current, buf);
8009 if (sqd->sq_cpu != -1)
8010 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8012 set_cpus_allowed_ptr(current, cpu_online_mask);
8013 current->flags |= PF_NO_SETAFFINITY;
8015 audit_alloc_kernel(current);
8017 mutex_lock(&sqd->lock);
8019 bool cap_entries, sqt_spin = false;
8021 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8022 if (io_sqd_handle_event(sqd))
8024 timeout = jiffies + sqd->sq_thread_idle;
8027 cap_entries = !list_is_singular(&sqd->ctx_list);
8028 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8029 int ret = __io_sq_thread(ctx, cap_entries);
8031 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8034 if (io_run_task_work())
8037 if (sqt_spin || !time_after(jiffies, timeout)) {
8040 timeout = jiffies + sqd->sq_thread_idle;
8044 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8045 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8046 bool needs_sched = true;
8048 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8049 io_ring_set_wakeup_flag(ctx);
8051 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8052 !wq_list_empty(&ctx->iopoll_list)) {
8053 needs_sched = false;
8058 * Ensure the store of the wakeup flag is not
8059 * reordered with the load of the SQ tail
8063 if (io_sqring_entries(ctx)) {
8064 needs_sched = false;
8070 mutex_unlock(&sqd->lock);
8072 mutex_lock(&sqd->lock);
8074 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8075 io_ring_clear_wakeup_flag(ctx);
8078 finish_wait(&sqd->wait, &wait);
8079 timeout = jiffies + sqd->sq_thread_idle;
8082 io_uring_cancel_generic(true, sqd);
8084 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8085 io_ring_set_wakeup_flag(ctx);
8087 mutex_unlock(&sqd->lock);
8089 audit_free(current);
8091 complete(&sqd->exited);
8095 struct io_wait_queue {
8096 struct wait_queue_entry wq;
8097 struct io_ring_ctx *ctx;
8099 unsigned nr_timeouts;
8102 static inline bool io_should_wake(struct io_wait_queue *iowq)
8104 struct io_ring_ctx *ctx = iowq->ctx;
8105 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8108 * Wake up if we have enough events, or if a timeout occurred since we
8109 * started waiting. For timeouts, we always want to return to userspace,
8110 * regardless of event count.
8112 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8115 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8116 int wake_flags, void *key)
8118 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8122 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8123 * the task, and the next invocation will do it.
8125 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8126 return autoremove_wake_function(curr, mode, wake_flags, key);
8130 static int io_run_task_work_sig(void)
8132 if (io_run_task_work())
8134 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8135 return -ERESTARTSYS;
8136 if (task_sigpending(current))
8141 /* when returns >0, the caller should retry */
8142 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8143 struct io_wait_queue *iowq,
8148 /* make sure we run task_work before checking for signals */
8149 ret = io_run_task_work_sig();
8150 if (ret || io_should_wake(iowq))
8152 /* let the caller flush overflows, retry */
8153 if (test_bit(0, &ctx->check_cq_overflow))
8156 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8162 * Wait until events become available, if we don't already have some. The
8163 * application must reap them itself, as they reside on the shared cq ring.
8165 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8166 const sigset_t __user *sig, size_t sigsz,
8167 struct __kernel_timespec __user *uts)
8169 struct io_wait_queue iowq;
8170 struct io_rings *rings = ctx->rings;
8171 ktime_t timeout = KTIME_MAX;
8175 io_cqring_overflow_flush(ctx);
8176 if (io_cqring_events(ctx) >= min_events)
8178 if (!io_run_task_work())
8183 #ifdef CONFIG_COMPAT
8184 if (in_compat_syscall())
8185 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8189 ret = set_user_sigmask(sig, sigsz);
8196 struct timespec64 ts;
8198 if (get_timespec64(&ts, uts))
8200 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8203 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8204 iowq.wq.private = current;
8205 INIT_LIST_HEAD(&iowq.wq.entry);
8207 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8208 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8210 trace_io_uring_cqring_wait(ctx, min_events);
8212 /* if we can't even flush overflow, don't wait for more */
8213 if (!io_cqring_overflow_flush(ctx)) {
8217 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8218 TASK_INTERRUPTIBLE);
8219 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8223 finish_wait(&ctx->cq_wait, &iowq.wq);
8224 restore_saved_sigmask_unless(ret == -EINTR);
8226 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8229 static void io_free_page_table(void **table, size_t size)
8231 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8233 for (i = 0; i < nr_tables; i++)
8238 static __cold void **io_alloc_page_table(size_t size)
8240 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8241 size_t init_size = size;
8244 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8248 for (i = 0; i < nr_tables; i++) {
8249 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8251 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8253 io_free_page_table(table, init_size);
8261 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8263 percpu_ref_exit(&ref_node->refs);
8267 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8269 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8270 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8271 unsigned long flags;
8272 bool first_add = false;
8273 unsigned long delay = HZ;
8275 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8278 /* if we are mid-quiesce then do not delay */
8279 if (node->rsrc_data->quiesce)
8282 while (!list_empty(&ctx->rsrc_ref_list)) {
8283 node = list_first_entry(&ctx->rsrc_ref_list,
8284 struct io_rsrc_node, node);
8285 /* recycle ref nodes in order */
8288 list_del(&node->node);
8289 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8291 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8294 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8297 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8299 struct io_rsrc_node *ref_node;
8301 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8305 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8310 INIT_LIST_HEAD(&ref_node->node);
8311 INIT_LIST_HEAD(&ref_node->rsrc_list);
8312 ref_node->done = false;
8316 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8317 struct io_rsrc_data *data_to_kill)
8318 __must_hold(&ctx->uring_lock)
8320 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8321 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8323 io_rsrc_refs_drop(ctx);
8326 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8328 rsrc_node->rsrc_data = data_to_kill;
8329 spin_lock_irq(&ctx->rsrc_ref_lock);
8330 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8331 spin_unlock_irq(&ctx->rsrc_ref_lock);
8333 atomic_inc(&data_to_kill->refs);
8334 percpu_ref_kill(&rsrc_node->refs);
8335 ctx->rsrc_node = NULL;
8338 if (!ctx->rsrc_node) {
8339 ctx->rsrc_node = ctx->rsrc_backup_node;
8340 ctx->rsrc_backup_node = NULL;
8344 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8346 if (ctx->rsrc_backup_node)
8348 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8349 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8352 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8353 struct io_ring_ctx *ctx)
8357 /* As we may drop ->uring_lock, other task may have started quiesce */
8361 data->quiesce = true;
8363 ret = io_rsrc_node_switch_start(ctx);
8366 io_rsrc_node_switch(ctx, data);
8368 /* kill initial ref, already quiesced if zero */
8369 if (atomic_dec_and_test(&data->refs))
8371 mutex_unlock(&ctx->uring_lock);
8372 flush_delayed_work(&ctx->rsrc_put_work);
8373 ret = wait_for_completion_interruptible(&data->done);
8375 mutex_lock(&ctx->uring_lock);
8376 if (atomic_read(&data->refs) > 0) {
8378 * it has been revived by another thread while
8381 mutex_unlock(&ctx->uring_lock);
8387 atomic_inc(&data->refs);
8388 /* wait for all works potentially completing data->done */
8389 flush_delayed_work(&ctx->rsrc_put_work);
8390 reinit_completion(&data->done);
8392 ret = io_run_task_work_sig();
8393 mutex_lock(&ctx->uring_lock);
8395 data->quiesce = false;
8400 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8402 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8403 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8405 return &data->tags[table_idx][off];
8408 static void io_rsrc_data_free(struct io_rsrc_data *data)
8410 size_t size = data->nr * sizeof(data->tags[0][0]);
8413 io_free_page_table((void **)data->tags, size);
8417 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8418 u64 __user *utags, unsigned nr,
8419 struct io_rsrc_data **pdata)
8421 struct io_rsrc_data *data;
8425 data = kzalloc(sizeof(*data), GFP_KERNEL);
8428 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8436 data->do_put = do_put;
8439 for (i = 0; i < nr; i++) {
8440 u64 *tag_slot = io_get_tag_slot(data, i);
8442 if (copy_from_user(tag_slot, &utags[i],
8448 atomic_set(&data->refs, 1);
8449 init_completion(&data->done);
8453 io_rsrc_data_free(data);
8457 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8459 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8460 GFP_KERNEL_ACCOUNT);
8461 return !!table->files;
8464 static void io_free_file_tables(struct io_file_table *table)
8466 kvfree(table->files);
8467 table->files = NULL;
8470 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8474 for (i = 0; i < ctx->nr_user_files; i++) {
8475 struct file *file = io_file_from_index(ctx, i);
8477 if (!file || io_file_need_scm(file))
8479 io_fixed_file_slot(&ctx->file_table, i)->file_ptr = 0;
8483 #if defined(CONFIG_UNIX)
8484 if (ctx->ring_sock) {
8485 struct sock *sock = ctx->ring_sock->sk;
8486 struct sk_buff *skb;
8488 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8492 io_free_file_tables(&ctx->file_table);
8493 io_rsrc_data_free(ctx->file_data);
8494 ctx->file_data = NULL;
8495 ctx->nr_user_files = 0;
8498 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8502 if (!ctx->file_data)
8504 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8506 __io_sqe_files_unregister(ctx);
8510 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8511 __releases(&sqd->lock)
8513 WARN_ON_ONCE(sqd->thread == current);
8516 * Do the dance but not conditional clear_bit() because it'd race with
8517 * other threads incrementing park_pending and setting the bit.
8519 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8520 if (atomic_dec_return(&sqd->park_pending))
8521 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8522 mutex_unlock(&sqd->lock);
8525 static void io_sq_thread_park(struct io_sq_data *sqd)
8526 __acquires(&sqd->lock)
8528 WARN_ON_ONCE(sqd->thread == current);
8530 atomic_inc(&sqd->park_pending);
8531 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8532 mutex_lock(&sqd->lock);
8534 wake_up_process(sqd->thread);
8537 static void io_sq_thread_stop(struct io_sq_data *sqd)
8539 WARN_ON_ONCE(sqd->thread == current);
8540 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8542 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8543 mutex_lock(&sqd->lock);
8545 wake_up_process(sqd->thread);
8546 mutex_unlock(&sqd->lock);
8547 wait_for_completion(&sqd->exited);
8550 static void io_put_sq_data(struct io_sq_data *sqd)
8552 if (refcount_dec_and_test(&sqd->refs)) {
8553 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8555 io_sq_thread_stop(sqd);
8560 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8562 struct io_sq_data *sqd = ctx->sq_data;
8565 io_sq_thread_park(sqd);
8566 list_del_init(&ctx->sqd_list);
8567 io_sqd_update_thread_idle(sqd);
8568 io_sq_thread_unpark(sqd);
8570 io_put_sq_data(sqd);
8571 ctx->sq_data = NULL;
8575 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8577 struct io_ring_ctx *ctx_attach;
8578 struct io_sq_data *sqd;
8581 f = fdget(p->wq_fd);
8583 return ERR_PTR(-ENXIO);
8584 if (f.file->f_op != &io_uring_fops) {
8586 return ERR_PTR(-EINVAL);
8589 ctx_attach = f.file->private_data;
8590 sqd = ctx_attach->sq_data;
8593 return ERR_PTR(-EINVAL);
8595 if (sqd->task_tgid != current->tgid) {
8597 return ERR_PTR(-EPERM);
8600 refcount_inc(&sqd->refs);
8605 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8608 struct io_sq_data *sqd;
8611 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8612 sqd = io_attach_sq_data(p);
8617 /* fall through for EPERM case, setup new sqd/task */
8618 if (PTR_ERR(sqd) != -EPERM)
8622 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8624 return ERR_PTR(-ENOMEM);
8626 atomic_set(&sqd->park_pending, 0);
8627 refcount_set(&sqd->refs, 1);
8628 INIT_LIST_HEAD(&sqd->ctx_list);
8629 mutex_init(&sqd->lock);
8630 init_waitqueue_head(&sqd->wait);
8631 init_completion(&sqd->exited);
8636 * Ensure the UNIX gc is aware of our file set, so we are certain that
8637 * the io_uring can be safely unregistered on process exit, even if we have
8638 * loops in the file referencing. We account only files that can hold other
8639 * files because otherwise they can't form a loop and so are not interesting
8642 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
8644 #if defined(CONFIG_UNIX)
8645 struct sock *sk = ctx->ring_sock->sk;
8646 struct sk_buff_head *head = &sk->sk_receive_queue;
8647 struct scm_fp_list *fpl;
8648 struct sk_buff *skb;
8650 if (likely(!io_file_need_scm(file)))
8654 * See if we can merge this file into an existing skb SCM_RIGHTS
8655 * file set. If there's no room, fall back to allocating a new skb
8656 * and filling it in.
8658 spin_lock_irq(&head->lock);
8659 skb = skb_peek(head);
8660 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
8661 __skb_unlink(skb, head);
8664 spin_unlock_irq(&head->lock);
8667 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8671 skb = alloc_skb(0, GFP_KERNEL);
8677 fpl->user = get_uid(current_user());
8678 fpl->max = SCM_MAX_FD;
8681 UNIXCB(skb).fp = fpl;
8683 skb->destructor = unix_destruct_scm;
8684 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8687 fpl = UNIXCB(skb).fp;
8688 fpl->fp[fpl->count++] = get_file(file);
8689 unix_inflight(fpl->user, file);
8690 skb_queue_head(head, skb);
8696 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8698 struct file *file = prsrc->file;
8699 #if defined(CONFIG_UNIX)
8700 struct sock *sock = ctx->ring_sock->sk;
8701 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8702 struct sk_buff *skb;
8705 if (!io_file_need_scm(file)) {
8710 __skb_queue_head_init(&list);
8713 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8714 * remove this entry and rearrange the file array.
8716 skb = skb_dequeue(head);
8718 struct scm_fp_list *fp;
8720 fp = UNIXCB(skb).fp;
8721 for (i = 0; i < fp->count; i++) {
8724 if (fp->fp[i] != file)
8727 unix_notinflight(fp->user, fp->fp[i]);
8728 left = fp->count - 1 - i;
8730 memmove(&fp->fp[i], &fp->fp[i + 1],
8731 left * sizeof(struct file *));
8738 __skb_queue_tail(&list, skb);
8748 __skb_queue_tail(&list, skb);
8750 skb = skb_dequeue(head);
8753 if (skb_peek(&list)) {
8754 spin_lock_irq(&head->lock);
8755 while ((skb = __skb_dequeue(&list)) != NULL)
8756 __skb_queue_tail(head, skb);
8757 spin_unlock_irq(&head->lock);
8764 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8766 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8767 struct io_ring_ctx *ctx = rsrc_data->ctx;
8768 struct io_rsrc_put *prsrc, *tmp;
8770 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8771 list_del(&prsrc->list);
8774 if (ctx->flags & IORING_SETUP_IOPOLL)
8775 mutex_lock(&ctx->uring_lock);
8777 spin_lock(&ctx->completion_lock);
8778 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8779 io_commit_cqring(ctx);
8780 spin_unlock(&ctx->completion_lock);
8781 io_cqring_ev_posted(ctx);
8783 if (ctx->flags & IORING_SETUP_IOPOLL)
8784 mutex_unlock(&ctx->uring_lock);
8787 rsrc_data->do_put(ctx, prsrc);
8791 io_rsrc_node_destroy(ref_node);
8792 if (atomic_dec_and_test(&rsrc_data->refs))
8793 complete(&rsrc_data->done);
8796 static void io_rsrc_put_work(struct work_struct *work)
8798 struct io_ring_ctx *ctx;
8799 struct llist_node *node;
8801 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8802 node = llist_del_all(&ctx->rsrc_put_llist);
8805 struct io_rsrc_node *ref_node;
8806 struct llist_node *next = node->next;
8808 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8809 __io_rsrc_put_work(ref_node);
8814 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8815 unsigned nr_args, u64 __user *tags)
8817 __s32 __user *fds = (__s32 __user *) arg;
8826 if (nr_args > IORING_MAX_FIXED_FILES)
8828 if (nr_args > rlimit(RLIMIT_NOFILE))
8830 ret = io_rsrc_node_switch_start(ctx);
8833 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8838 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
8839 io_rsrc_data_free(ctx->file_data);
8840 ctx->file_data = NULL;
8844 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8845 struct io_fixed_file *file_slot;
8847 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8851 /* allow sparse sets */
8854 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8861 if (unlikely(!file))
8865 * Don't allow io_uring instances to be registered. If UNIX
8866 * isn't enabled, then this causes a reference cycle and this
8867 * instance can never get freed. If UNIX is enabled we'll
8868 * handle it just fine, but there's still no point in allowing
8869 * a ring fd as it doesn't support regular read/write anyway.
8871 if (file->f_op == &io_uring_fops) {
8875 ret = io_scm_file_account(ctx, file);
8880 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8881 io_fixed_file_set(file_slot, file);
8884 io_rsrc_node_switch(ctx, NULL);
8887 __io_sqe_files_unregister(ctx);
8891 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8892 struct io_rsrc_node *node, void *rsrc)
8894 u64 *tag_slot = io_get_tag_slot(data, idx);
8895 struct io_rsrc_put *prsrc;
8897 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8901 prsrc->tag = *tag_slot;
8904 list_add(&prsrc->list, &node->rsrc_list);
8908 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8909 unsigned int issue_flags, u32 slot_index)
8911 struct io_ring_ctx *ctx = req->ctx;
8912 bool needs_switch = false;
8913 struct io_fixed_file *file_slot;
8916 io_ring_submit_lock(ctx, issue_flags);
8917 if (file->f_op == &io_uring_fops)
8920 if (!ctx->file_data)
8923 if (slot_index >= ctx->nr_user_files)
8926 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8927 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8929 if (file_slot->file_ptr) {
8930 struct file *old_file;
8932 ret = io_rsrc_node_switch_start(ctx);
8936 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8937 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8938 ctx->rsrc_node, old_file);
8941 file_slot->file_ptr = 0;
8942 needs_switch = true;
8945 ret = io_scm_file_account(ctx, file);
8947 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8948 io_fixed_file_set(file_slot, file);
8952 io_rsrc_node_switch(ctx, ctx->file_data);
8953 io_ring_submit_unlock(ctx, issue_flags);
8959 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8961 unsigned int offset = req->close.file_slot - 1;
8962 struct io_ring_ctx *ctx = req->ctx;
8963 struct io_fixed_file *file_slot;
8967 io_ring_submit_lock(ctx, issue_flags);
8969 if (unlikely(!ctx->file_data))
8972 if (offset >= ctx->nr_user_files)
8974 ret = io_rsrc_node_switch_start(ctx);
8978 offset = array_index_nospec(offset, ctx->nr_user_files);
8979 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8981 if (!file_slot->file_ptr)
8984 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8985 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8989 file_slot->file_ptr = 0;
8990 io_rsrc_node_switch(ctx, ctx->file_data);
8993 io_ring_submit_unlock(ctx, issue_flags);
8997 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8998 struct io_uring_rsrc_update2 *up,
9001 u64 __user *tags = u64_to_user_ptr(up->tags);
9002 __s32 __user *fds = u64_to_user_ptr(up->data);
9003 struct io_rsrc_data *data = ctx->file_data;
9004 struct io_fixed_file *file_slot;
9008 bool needs_switch = false;
9010 if (!ctx->file_data)
9012 if (up->offset + nr_args > ctx->nr_user_files)
9015 for (done = 0; done < nr_args; done++) {
9018 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9019 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9023 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9027 if (fd == IORING_REGISTER_FILES_SKIP)
9030 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9031 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9033 if (file_slot->file_ptr) {
9034 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9035 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9038 file_slot->file_ptr = 0;
9039 needs_switch = true;
9048 * Don't allow io_uring instances to be registered. If
9049 * UNIX isn't enabled, then this causes a reference
9050 * cycle and this instance can never get freed. If UNIX
9051 * is enabled we'll handle it just fine, but there's
9052 * still no point in allowing a ring fd as it doesn't
9053 * support regular read/write anyway.
9055 if (file->f_op == &io_uring_fops) {
9060 err = io_scm_file_account(ctx, file);
9065 *io_get_tag_slot(data, i) = tag;
9066 io_fixed_file_set(file_slot, file);
9071 io_rsrc_node_switch(ctx, data);
9072 return done ? done : err;
9075 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9076 struct task_struct *task)
9078 struct io_wq_hash *hash;
9079 struct io_wq_data data;
9080 unsigned int concurrency;
9082 mutex_lock(&ctx->uring_lock);
9083 hash = ctx->hash_map;
9085 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9087 mutex_unlock(&ctx->uring_lock);
9088 return ERR_PTR(-ENOMEM);
9090 refcount_set(&hash->refs, 1);
9091 init_waitqueue_head(&hash->wait);
9092 ctx->hash_map = hash;
9094 mutex_unlock(&ctx->uring_lock);
9098 data.free_work = io_wq_free_work;
9099 data.do_work = io_wq_submit_work;
9101 /* Do QD, or 4 * CPUS, whatever is smallest */
9102 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9104 return io_wq_create(concurrency, &data);
9107 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9108 struct io_ring_ctx *ctx)
9110 struct io_uring_task *tctx;
9113 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9114 if (unlikely(!tctx))
9117 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9118 sizeof(struct file *), GFP_KERNEL);
9119 if (unlikely(!tctx->registered_rings)) {
9124 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9125 if (unlikely(ret)) {
9126 kfree(tctx->registered_rings);
9131 tctx->io_wq = io_init_wq_offload(ctx, task);
9132 if (IS_ERR(tctx->io_wq)) {
9133 ret = PTR_ERR(tctx->io_wq);
9134 percpu_counter_destroy(&tctx->inflight);
9135 kfree(tctx->registered_rings);
9141 init_waitqueue_head(&tctx->wait);
9142 atomic_set(&tctx->in_idle, 0);
9143 task->io_uring = tctx;
9144 spin_lock_init(&tctx->task_lock);
9145 INIT_WQ_LIST(&tctx->task_list);
9146 INIT_WQ_LIST(&tctx->prior_task_list);
9147 init_task_work(&tctx->task_work, tctx_task_work);
9151 void __io_uring_free(struct task_struct *tsk)
9153 struct io_uring_task *tctx = tsk->io_uring;
9155 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9156 WARN_ON_ONCE(tctx->io_wq);
9157 WARN_ON_ONCE(tctx->cached_refs);
9159 kfree(tctx->registered_rings);
9160 percpu_counter_destroy(&tctx->inflight);
9162 tsk->io_uring = NULL;
9165 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9166 struct io_uring_params *p)
9170 /* Retain compatibility with failing for an invalid attach attempt */
9171 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9172 IORING_SETUP_ATTACH_WQ) {
9175 f = fdget(p->wq_fd);
9178 if (f.file->f_op != &io_uring_fops) {
9184 if (ctx->flags & IORING_SETUP_SQPOLL) {
9185 struct task_struct *tsk;
9186 struct io_sq_data *sqd;
9189 ret = security_uring_sqpoll();
9193 sqd = io_get_sq_data(p, &attached);
9199 ctx->sq_creds = get_current_cred();
9201 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9202 if (!ctx->sq_thread_idle)
9203 ctx->sq_thread_idle = HZ;
9205 io_sq_thread_park(sqd);
9206 list_add(&ctx->sqd_list, &sqd->ctx_list);
9207 io_sqd_update_thread_idle(sqd);
9208 /* don't attach to a dying SQPOLL thread, would be racy */
9209 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9210 io_sq_thread_unpark(sqd);
9217 if (p->flags & IORING_SETUP_SQ_AFF) {
9218 int cpu = p->sq_thread_cpu;
9221 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9228 sqd->task_pid = current->pid;
9229 sqd->task_tgid = current->tgid;
9230 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9237 ret = io_uring_alloc_task_context(tsk, ctx);
9238 wake_up_new_task(tsk);
9241 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9242 /* Can't have SQ_AFF without SQPOLL */
9249 complete(&ctx->sq_data->exited);
9251 io_sq_thread_finish(ctx);
9255 static inline void __io_unaccount_mem(struct user_struct *user,
9256 unsigned long nr_pages)
9258 atomic_long_sub(nr_pages, &user->locked_vm);
9261 static inline int __io_account_mem(struct user_struct *user,
9262 unsigned long nr_pages)
9264 unsigned long page_limit, cur_pages, new_pages;
9266 /* Don't allow more pages than we can safely lock */
9267 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9270 cur_pages = atomic_long_read(&user->locked_vm);
9271 new_pages = cur_pages + nr_pages;
9272 if (new_pages > page_limit)
9274 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9275 new_pages) != cur_pages);
9280 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9283 __io_unaccount_mem(ctx->user, nr_pages);
9285 if (ctx->mm_account)
9286 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9289 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9294 ret = __io_account_mem(ctx->user, nr_pages);
9299 if (ctx->mm_account)
9300 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9305 static void io_mem_free(void *ptr)
9312 page = virt_to_head_page(ptr);
9313 if (put_page_testzero(page))
9314 free_compound_page(page);
9317 static void *io_mem_alloc(size_t size)
9319 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9321 return (void *) __get_free_pages(gfp, get_order(size));
9324 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9327 struct io_rings *rings;
9328 size_t off, sq_array_size;
9330 off = struct_size(rings, cqes, cq_entries);
9331 if (off == SIZE_MAX)
9335 off = ALIGN(off, SMP_CACHE_BYTES);
9343 sq_array_size = array_size(sizeof(u32), sq_entries);
9344 if (sq_array_size == SIZE_MAX)
9347 if (check_add_overflow(off, sq_array_size, &off))
9353 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9355 struct io_mapped_ubuf *imu = *slot;
9358 if (imu != ctx->dummy_ubuf) {
9359 for (i = 0; i < imu->nr_bvecs; i++)
9360 unpin_user_page(imu->bvec[i].bv_page);
9361 if (imu->acct_pages)
9362 io_unaccount_mem(ctx, imu->acct_pages);
9368 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9370 io_buffer_unmap(ctx, &prsrc->buf);
9374 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9378 for (i = 0; i < ctx->nr_user_bufs; i++)
9379 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9380 kfree(ctx->user_bufs);
9381 io_rsrc_data_free(ctx->buf_data);
9382 ctx->user_bufs = NULL;
9383 ctx->buf_data = NULL;
9384 ctx->nr_user_bufs = 0;
9387 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9394 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9396 __io_sqe_buffers_unregister(ctx);
9400 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9401 void __user *arg, unsigned index)
9403 struct iovec __user *src;
9405 #ifdef CONFIG_COMPAT
9407 struct compat_iovec __user *ciovs;
9408 struct compat_iovec ciov;
9410 ciovs = (struct compat_iovec __user *) arg;
9411 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9414 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9415 dst->iov_len = ciov.iov_len;
9419 src = (struct iovec __user *) arg;
9420 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9426 * Not super efficient, but this is just a registration time. And we do cache
9427 * the last compound head, so generally we'll only do a full search if we don't
9430 * We check if the given compound head page has already been accounted, to
9431 * avoid double accounting it. This allows us to account the full size of the
9432 * page, not just the constituent pages of a huge page.
9434 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9435 int nr_pages, struct page *hpage)
9439 /* check current page array */
9440 for (i = 0; i < nr_pages; i++) {
9441 if (!PageCompound(pages[i]))
9443 if (compound_head(pages[i]) == hpage)
9447 /* check previously registered pages */
9448 for (i = 0; i < ctx->nr_user_bufs; i++) {
9449 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9451 for (j = 0; j < imu->nr_bvecs; j++) {
9452 if (!PageCompound(imu->bvec[j].bv_page))
9454 if (compound_head(imu->bvec[j].bv_page) == hpage)
9462 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9463 int nr_pages, struct io_mapped_ubuf *imu,
9464 struct page **last_hpage)
9468 imu->acct_pages = 0;
9469 for (i = 0; i < nr_pages; i++) {
9470 if (!PageCompound(pages[i])) {
9475 hpage = compound_head(pages[i]);
9476 if (hpage == *last_hpage)
9478 *last_hpage = hpage;
9479 if (headpage_already_acct(ctx, pages, i, hpage))
9481 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9485 if (!imu->acct_pages)
9488 ret = io_account_mem(ctx, imu->acct_pages);
9490 imu->acct_pages = 0;
9494 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9495 struct io_mapped_ubuf **pimu,
9496 struct page **last_hpage)
9498 struct io_mapped_ubuf *imu = NULL;
9499 struct vm_area_struct **vmas = NULL;
9500 struct page **pages = NULL;
9501 unsigned long off, start, end, ubuf;
9503 int ret, pret, nr_pages, i;
9505 if (!iov->iov_base) {
9506 *pimu = ctx->dummy_ubuf;
9510 ubuf = (unsigned long) iov->iov_base;
9511 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9512 start = ubuf >> PAGE_SHIFT;
9513 nr_pages = end - start;
9518 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9522 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9527 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9532 mmap_read_lock(current->mm);
9533 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9535 if (pret == nr_pages) {
9536 /* don't support file backed memory */
9537 for (i = 0; i < nr_pages; i++) {
9538 struct vm_area_struct *vma = vmas[i];
9540 if (vma_is_shmem(vma))
9543 !is_file_hugepages(vma->vm_file)) {
9549 ret = pret < 0 ? pret : -EFAULT;
9551 mmap_read_unlock(current->mm);
9554 * if we did partial map, or found file backed vmas,
9555 * release any pages we did get
9558 unpin_user_pages(pages, pret);
9562 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9564 unpin_user_pages(pages, pret);
9568 off = ubuf & ~PAGE_MASK;
9569 size = iov->iov_len;
9570 for (i = 0; i < nr_pages; i++) {
9573 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9574 imu->bvec[i].bv_page = pages[i];
9575 imu->bvec[i].bv_len = vec_len;
9576 imu->bvec[i].bv_offset = off;
9580 /* store original address for later verification */
9582 imu->ubuf_end = ubuf + iov->iov_len;
9583 imu->nr_bvecs = nr_pages;
9594 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9596 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9597 return ctx->user_bufs ? 0 : -ENOMEM;
9600 static int io_buffer_validate(struct iovec *iov)
9602 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9605 * Don't impose further limits on the size and buffer
9606 * constraints here, we'll -EINVAL later when IO is
9607 * submitted if they are wrong.
9610 return iov->iov_len ? -EFAULT : 0;
9614 /* arbitrary limit, but we need something */
9615 if (iov->iov_len > SZ_1G)
9618 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9624 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9625 unsigned int nr_args, u64 __user *tags)
9627 struct page *last_hpage = NULL;
9628 struct io_rsrc_data *data;
9634 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9636 ret = io_rsrc_node_switch_start(ctx);
9639 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9642 ret = io_buffers_map_alloc(ctx, nr_args);
9644 io_rsrc_data_free(data);
9648 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9649 ret = io_copy_iov(ctx, &iov, arg, i);
9652 ret = io_buffer_validate(&iov);
9655 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9660 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9666 WARN_ON_ONCE(ctx->buf_data);
9668 ctx->buf_data = data;
9670 __io_sqe_buffers_unregister(ctx);
9672 io_rsrc_node_switch(ctx, NULL);
9676 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9677 struct io_uring_rsrc_update2 *up,
9678 unsigned int nr_args)
9680 u64 __user *tags = u64_to_user_ptr(up->tags);
9681 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9682 struct page *last_hpage = NULL;
9683 bool needs_switch = false;
9689 if (up->offset + nr_args > ctx->nr_user_bufs)
9692 for (done = 0; done < nr_args; done++) {
9693 struct io_mapped_ubuf *imu;
9694 int offset = up->offset + done;
9697 err = io_copy_iov(ctx, &iov, iovs, done);
9700 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9704 err = io_buffer_validate(&iov);
9707 if (!iov.iov_base && tag) {
9711 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9715 i = array_index_nospec(offset, ctx->nr_user_bufs);
9716 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9717 err = io_queue_rsrc_removal(ctx->buf_data, i,
9718 ctx->rsrc_node, ctx->user_bufs[i]);
9719 if (unlikely(err)) {
9720 io_buffer_unmap(ctx, &imu);
9723 ctx->user_bufs[i] = NULL;
9724 needs_switch = true;
9727 ctx->user_bufs[i] = imu;
9728 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9732 io_rsrc_node_switch(ctx, ctx->buf_data);
9733 return done ? done : err;
9736 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9737 unsigned int eventfd_async)
9739 struct io_ev_fd *ev_fd;
9740 __s32 __user *fds = arg;
9743 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9744 lockdep_is_held(&ctx->uring_lock));
9748 if (copy_from_user(&fd, fds, sizeof(*fds)))
9751 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9755 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9756 if (IS_ERR(ev_fd->cq_ev_fd)) {
9757 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9761 ev_fd->eventfd_async = eventfd_async;
9762 ctx->has_evfd = true;
9763 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9767 static void io_eventfd_put(struct rcu_head *rcu)
9769 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9771 eventfd_ctx_put(ev_fd->cq_ev_fd);
9775 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9777 struct io_ev_fd *ev_fd;
9779 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9780 lockdep_is_held(&ctx->uring_lock));
9782 ctx->has_evfd = false;
9783 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9784 call_rcu(&ev_fd->rcu, io_eventfd_put);
9791 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9795 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9796 struct list_head *list = &ctx->io_buffers[i];
9798 while (!list_empty(list)) {
9799 struct io_buffer_list *bl;
9801 bl = list_first_entry(list, struct io_buffer_list, list);
9802 __io_remove_buffers(ctx, bl, -1U);
9803 list_del(&bl->list);
9808 while (!list_empty(&ctx->io_buffers_pages)) {
9811 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9812 list_del_init(&page->lru);
9817 static void io_req_caches_free(struct io_ring_ctx *ctx)
9819 struct io_submit_state *state = &ctx->submit_state;
9822 mutex_lock(&ctx->uring_lock);
9823 io_flush_cached_locked_reqs(ctx, state);
9825 while (!io_req_cache_empty(ctx)) {
9826 struct io_wq_work_node *node;
9827 struct io_kiocb *req;
9829 node = wq_stack_extract(&state->free_list);
9830 req = container_of(node, struct io_kiocb, comp_list);
9831 kmem_cache_free(req_cachep, req);
9835 percpu_ref_put_many(&ctx->refs, nr);
9836 mutex_unlock(&ctx->uring_lock);
9839 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9841 if (data && !atomic_dec_and_test(&data->refs))
9842 wait_for_completion(&data->done);
9845 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9847 struct async_poll *apoll;
9849 while (!list_empty(&ctx->apoll_cache)) {
9850 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9852 list_del(&apoll->poll.wait.entry);
9857 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9859 io_sq_thread_finish(ctx);
9861 if (ctx->mm_account) {
9862 mmdrop(ctx->mm_account);
9863 ctx->mm_account = NULL;
9866 io_rsrc_refs_drop(ctx);
9867 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9868 io_wait_rsrc_data(ctx->buf_data);
9869 io_wait_rsrc_data(ctx->file_data);
9871 mutex_lock(&ctx->uring_lock);
9873 __io_sqe_buffers_unregister(ctx);
9875 __io_sqe_files_unregister(ctx);
9877 __io_cqring_overflow_flush(ctx, true);
9878 io_eventfd_unregister(ctx);
9879 io_flush_apoll_cache(ctx);
9880 mutex_unlock(&ctx->uring_lock);
9881 io_destroy_buffers(ctx);
9883 put_cred(ctx->sq_creds);
9885 /* there are no registered resources left, nobody uses it */
9887 io_rsrc_node_destroy(ctx->rsrc_node);
9888 if (ctx->rsrc_backup_node)
9889 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9890 flush_delayed_work(&ctx->rsrc_put_work);
9891 flush_delayed_work(&ctx->fallback_work);
9893 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9894 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9896 #if defined(CONFIG_UNIX)
9897 if (ctx->ring_sock) {
9898 ctx->ring_sock->file = NULL; /* so that iput() is called */
9899 sock_release(ctx->ring_sock);
9902 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9904 io_mem_free(ctx->rings);
9905 io_mem_free(ctx->sq_sqes);
9907 percpu_ref_exit(&ctx->refs);
9908 free_uid(ctx->user);
9909 io_req_caches_free(ctx);
9911 io_wq_put_hash(ctx->hash_map);
9912 kfree(ctx->cancel_hash);
9913 kfree(ctx->dummy_ubuf);
9914 kfree(ctx->io_buffers);
9918 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9920 struct io_ring_ctx *ctx = file->private_data;
9923 poll_wait(file, &ctx->cq_wait, wait);
9925 * synchronizes with barrier from wq_has_sleeper call in
9929 if (!io_sqring_full(ctx))
9930 mask |= EPOLLOUT | EPOLLWRNORM;
9933 * Don't flush cqring overflow list here, just do a simple check.
9934 * Otherwise there could possible be ABBA deadlock:
9937 * lock(&ctx->uring_lock);
9939 * lock(&ctx->uring_lock);
9942 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9943 * pushs them to do the flush.
9945 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9946 mask |= EPOLLIN | EPOLLRDNORM;
9951 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9953 const struct cred *creds;
9955 creds = xa_erase(&ctx->personalities, id);
9964 struct io_tctx_exit {
9965 struct callback_head task_work;
9966 struct completion completion;
9967 struct io_ring_ctx *ctx;
9970 static __cold void io_tctx_exit_cb(struct callback_head *cb)
9972 struct io_uring_task *tctx = current->io_uring;
9973 struct io_tctx_exit *work;
9975 work = container_of(cb, struct io_tctx_exit, task_work);
9977 * When @in_idle, we're in cancellation and it's racy to remove the
9978 * node. It'll be removed by the end of cancellation, just ignore it.
9980 if (!atomic_read(&tctx->in_idle))
9981 io_uring_del_tctx_node((unsigned long)work->ctx);
9982 complete(&work->completion);
9985 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9987 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9989 return req->ctx == data;
9992 static __cold void io_ring_exit_work(struct work_struct *work)
9994 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9995 unsigned long timeout = jiffies + HZ * 60 * 5;
9996 unsigned long interval = HZ / 20;
9997 struct io_tctx_exit exit;
9998 struct io_tctx_node *node;
10002 * If we're doing polled IO and end up having requests being
10003 * submitted async (out-of-line), then completions can come in while
10004 * we're waiting for refs to drop. We need to reap these manually,
10005 * as nobody else will be looking for them.
10008 io_uring_try_cancel_requests(ctx, NULL, true);
10009 if (ctx->sq_data) {
10010 struct io_sq_data *sqd = ctx->sq_data;
10011 struct task_struct *tsk;
10013 io_sq_thread_park(sqd);
10015 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10016 io_wq_cancel_cb(tsk->io_uring->io_wq,
10017 io_cancel_ctx_cb, ctx, true);
10018 io_sq_thread_unpark(sqd);
10021 io_req_caches_free(ctx);
10023 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10024 /* there is little hope left, don't run it too often */
10025 interval = HZ * 60;
10027 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10029 init_completion(&exit.completion);
10030 init_task_work(&exit.task_work, io_tctx_exit_cb);
10033 * Some may use context even when all refs and requests have been put,
10034 * and they are free to do so while still holding uring_lock or
10035 * completion_lock, see io_req_task_submit(). Apart from other work,
10036 * this lock/unlock section also waits them to finish.
10038 mutex_lock(&ctx->uring_lock);
10039 while (!list_empty(&ctx->tctx_list)) {
10040 WARN_ON_ONCE(time_after(jiffies, timeout));
10042 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10044 /* don't spin on a single task if cancellation failed */
10045 list_rotate_left(&ctx->tctx_list);
10046 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10047 if (WARN_ON_ONCE(ret))
10050 mutex_unlock(&ctx->uring_lock);
10051 wait_for_completion(&exit.completion);
10052 mutex_lock(&ctx->uring_lock);
10054 mutex_unlock(&ctx->uring_lock);
10055 spin_lock(&ctx->completion_lock);
10056 spin_unlock(&ctx->completion_lock);
10058 io_ring_ctx_free(ctx);
10061 /* Returns true if we found and killed one or more timeouts */
10062 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10063 struct task_struct *tsk, bool cancel_all)
10065 struct io_kiocb *req, *tmp;
10068 spin_lock(&ctx->completion_lock);
10069 spin_lock_irq(&ctx->timeout_lock);
10070 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10071 if (io_match_task(req, tsk, cancel_all)) {
10072 io_kill_timeout(req, -ECANCELED);
10076 spin_unlock_irq(&ctx->timeout_lock);
10077 io_commit_cqring(ctx);
10078 spin_unlock(&ctx->completion_lock);
10080 io_cqring_ev_posted(ctx);
10081 return canceled != 0;
10084 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10086 unsigned long index;
10087 struct creds *creds;
10089 mutex_lock(&ctx->uring_lock);
10090 percpu_ref_kill(&ctx->refs);
10092 __io_cqring_overflow_flush(ctx, true);
10093 xa_for_each(&ctx->personalities, index, creds)
10094 io_unregister_personality(ctx, index);
10095 mutex_unlock(&ctx->uring_lock);
10097 /* failed during ring init, it couldn't have issued any requests */
10099 io_kill_timeouts(ctx, NULL, true);
10100 io_poll_remove_all(ctx, NULL, true);
10101 /* if we failed setting up the ctx, we might not have any rings */
10102 io_iopoll_try_reap_events(ctx);
10105 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10107 * Use system_unbound_wq to avoid spawning tons of event kworkers
10108 * if we're exiting a ton of rings at the same time. It just adds
10109 * noise and overhead, there's no discernable change in runtime
10110 * over using system_wq.
10112 queue_work(system_unbound_wq, &ctx->exit_work);
10115 static int io_uring_release(struct inode *inode, struct file *file)
10117 struct io_ring_ctx *ctx = file->private_data;
10119 file->private_data = NULL;
10120 io_ring_ctx_wait_and_kill(ctx);
10124 struct io_task_cancel {
10125 struct task_struct *task;
10129 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10131 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10132 struct io_task_cancel *cancel = data;
10134 return io_match_task_safe(req, cancel->task, cancel->all);
10137 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10138 struct task_struct *task,
10141 struct io_defer_entry *de;
10144 spin_lock(&ctx->completion_lock);
10145 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10146 if (io_match_task_safe(de->req, task, cancel_all)) {
10147 list_cut_position(&list, &ctx->defer_list, &de->list);
10151 spin_unlock(&ctx->completion_lock);
10152 if (list_empty(&list))
10155 while (!list_empty(&list)) {
10156 de = list_first_entry(&list, struct io_defer_entry, list);
10157 list_del_init(&de->list);
10158 io_req_complete_failed(de->req, -ECANCELED);
10164 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10166 struct io_tctx_node *node;
10167 enum io_wq_cancel cret;
10170 mutex_lock(&ctx->uring_lock);
10171 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10172 struct io_uring_task *tctx = node->task->io_uring;
10175 * io_wq will stay alive while we hold uring_lock, because it's
10176 * killed after ctx nodes, which requires to take the lock.
10178 if (!tctx || !tctx->io_wq)
10180 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10181 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10183 mutex_unlock(&ctx->uring_lock);
10188 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10189 struct task_struct *task,
10192 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10193 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10195 /* failed during ring init, it couldn't have issued any requests */
10200 enum io_wq_cancel cret;
10204 ret |= io_uring_try_cancel_iowq(ctx);
10205 } else if (tctx && tctx->io_wq) {
10207 * Cancels requests of all rings, not only @ctx, but
10208 * it's fine as the task is in exit/exec.
10210 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10212 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10215 /* SQPOLL thread does its own polling */
10216 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10217 (ctx->sq_data && ctx->sq_data->thread == current)) {
10218 while (!wq_list_empty(&ctx->iopoll_list)) {
10219 io_iopoll_try_reap_events(ctx);
10224 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10225 ret |= io_poll_remove_all(ctx, task, cancel_all);
10226 ret |= io_kill_timeouts(ctx, task, cancel_all);
10228 ret |= io_run_task_work();
10235 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10237 struct io_uring_task *tctx = current->io_uring;
10238 struct io_tctx_node *node;
10241 if (unlikely(!tctx)) {
10242 ret = io_uring_alloc_task_context(current, ctx);
10246 tctx = current->io_uring;
10247 if (ctx->iowq_limits_set) {
10248 unsigned int limits[2] = { ctx->iowq_limits[0],
10249 ctx->iowq_limits[1], };
10251 ret = io_wq_max_workers(tctx->io_wq, limits);
10256 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10257 node = kmalloc(sizeof(*node), GFP_KERNEL);
10261 node->task = current;
10263 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10264 node, GFP_KERNEL));
10270 mutex_lock(&ctx->uring_lock);
10271 list_add(&node->ctx_node, &ctx->tctx_list);
10272 mutex_unlock(&ctx->uring_lock);
10279 * Note that this task has used io_uring. We use it for cancelation purposes.
10281 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10283 struct io_uring_task *tctx = current->io_uring;
10285 if (likely(tctx && tctx->last == ctx))
10287 return __io_uring_add_tctx_node(ctx);
10291 * Remove this io_uring_file -> task mapping.
10293 static __cold void io_uring_del_tctx_node(unsigned long index)
10295 struct io_uring_task *tctx = current->io_uring;
10296 struct io_tctx_node *node;
10300 node = xa_erase(&tctx->xa, index);
10304 WARN_ON_ONCE(current != node->task);
10305 WARN_ON_ONCE(list_empty(&node->ctx_node));
10307 mutex_lock(&node->ctx->uring_lock);
10308 list_del(&node->ctx_node);
10309 mutex_unlock(&node->ctx->uring_lock);
10311 if (tctx->last == node->ctx)
10316 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10318 struct io_wq *wq = tctx->io_wq;
10319 struct io_tctx_node *node;
10320 unsigned long index;
10322 xa_for_each(&tctx->xa, index, node) {
10323 io_uring_del_tctx_node(index);
10328 * Must be after io_uring_del_tctx_node() (removes nodes under
10329 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10331 io_wq_put_and_exit(wq);
10332 tctx->io_wq = NULL;
10336 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10340 return percpu_counter_sum(&tctx->inflight);
10344 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10345 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10347 static __cold void io_uring_cancel_generic(bool cancel_all,
10348 struct io_sq_data *sqd)
10350 struct io_uring_task *tctx = current->io_uring;
10351 struct io_ring_ctx *ctx;
10355 WARN_ON_ONCE(sqd && sqd->thread != current);
10357 if (!current->io_uring)
10360 io_wq_exit_start(tctx->io_wq);
10362 atomic_inc(&tctx->in_idle);
10364 io_uring_drop_tctx_refs(current);
10365 /* read completions before cancelations */
10366 inflight = tctx_inflight(tctx, !cancel_all);
10371 struct io_tctx_node *node;
10372 unsigned long index;
10374 xa_for_each(&tctx->xa, index, node) {
10375 /* sqpoll task will cancel all its requests */
10376 if (node->ctx->sq_data)
10378 io_uring_try_cancel_requests(node->ctx, current,
10382 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10383 io_uring_try_cancel_requests(ctx, current,
10387 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10388 io_run_task_work();
10389 io_uring_drop_tctx_refs(current);
10392 * If we've seen completions, retry without waiting. This
10393 * avoids a race where a completion comes in before we did
10394 * prepare_to_wait().
10396 if (inflight == tctx_inflight(tctx, !cancel_all))
10398 finish_wait(&tctx->wait, &wait);
10401 io_uring_clean_tctx(tctx);
10404 * We shouldn't run task_works after cancel, so just leave
10405 * ->in_idle set for normal exit.
10407 atomic_dec(&tctx->in_idle);
10408 /* for exec all current's requests should be gone, kill tctx */
10409 __io_uring_free(current);
10413 void __io_uring_cancel(bool cancel_all)
10415 io_uring_cancel_generic(cancel_all, NULL);
10418 void io_uring_unreg_ringfd(void)
10420 struct io_uring_task *tctx = current->io_uring;
10423 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10424 if (tctx->registered_rings[i]) {
10425 fput(tctx->registered_rings[i]);
10426 tctx->registered_rings[i] = NULL;
10431 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10432 int start, int end)
10437 for (offset = start; offset < end; offset++) {
10438 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10439 if (tctx->registered_rings[offset])
10445 } else if (file->f_op != &io_uring_fops) {
10447 return -EOPNOTSUPP;
10449 tctx->registered_rings[offset] = file;
10457 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10458 * invocation. User passes in an array of struct io_uring_rsrc_update
10459 * with ->data set to the ring_fd, and ->offset given for the desired
10460 * index. If no index is desired, application may set ->offset == -1U
10461 * and we'll find an available index. Returns number of entries
10462 * successfully processed, or < 0 on error if none were processed.
10464 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10467 struct io_uring_rsrc_update __user *arg = __arg;
10468 struct io_uring_rsrc_update reg;
10469 struct io_uring_task *tctx;
10472 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10475 mutex_unlock(&ctx->uring_lock);
10476 ret = io_uring_add_tctx_node(ctx);
10477 mutex_lock(&ctx->uring_lock);
10481 tctx = current->io_uring;
10482 for (i = 0; i < nr_args; i++) {
10485 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10495 if (reg.offset == -1U) {
10497 end = IO_RINGFD_REG_MAX;
10499 if (reg.offset >= IO_RINGFD_REG_MAX) {
10503 start = reg.offset;
10507 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10512 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10513 fput(tctx->registered_rings[reg.offset]);
10514 tctx->registered_rings[reg.offset] = NULL;
10520 return i ? i : ret;
10523 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10526 struct io_uring_rsrc_update __user *arg = __arg;
10527 struct io_uring_task *tctx = current->io_uring;
10528 struct io_uring_rsrc_update reg;
10531 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10536 for (i = 0; i < nr_args; i++) {
10537 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10541 if (reg.resv || reg.offset >= IO_RINGFD_REG_MAX) {
10546 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10547 if (tctx->registered_rings[reg.offset]) {
10548 fput(tctx->registered_rings[reg.offset]);
10549 tctx->registered_rings[reg.offset] = NULL;
10553 return i ? i : ret;
10556 static void *io_uring_validate_mmap_request(struct file *file,
10557 loff_t pgoff, size_t sz)
10559 struct io_ring_ctx *ctx = file->private_data;
10560 loff_t offset = pgoff << PAGE_SHIFT;
10565 case IORING_OFF_SQ_RING:
10566 case IORING_OFF_CQ_RING:
10569 case IORING_OFF_SQES:
10570 ptr = ctx->sq_sqes;
10573 return ERR_PTR(-EINVAL);
10576 page = virt_to_head_page(ptr);
10577 if (sz > page_size(page))
10578 return ERR_PTR(-EINVAL);
10585 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10587 size_t sz = vma->vm_end - vma->vm_start;
10591 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10593 return PTR_ERR(ptr);
10595 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10596 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10599 #else /* !CONFIG_MMU */
10601 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10603 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10606 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10608 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10611 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10612 unsigned long addr, unsigned long len,
10613 unsigned long pgoff, unsigned long flags)
10617 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10619 return PTR_ERR(ptr);
10621 return (unsigned long) ptr;
10624 #endif /* !CONFIG_MMU */
10626 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10631 if (!io_sqring_full(ctx))
10633 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10635 if (!io_sqring_full(ctx))
10638 } while (!signal_pending(current));
10640 finish_wait(&ctx->sqo_sq_wait, &wait);
10644 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
10646 if (flags & IORING_ENTER_EXT_ARG) {
10647 struct io_uring_getevents_arg arg;
10649 if (argsz != sizeof(arg))
10651 if (copy_from_user(&arg, argp, sizeof(arg)))
10657 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10658 struct __kernel_timespec __user **ts,
10659 const sigset_t __user **sig)
10661 struct io_uring_getevents_arg arg;
10664 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10665 * is just a pointer to the sigset_t.
10667 if (!(flags & IORING_ENTER_EXT_ARG)) {
10668 *sig = (const sigset_t __user *) argp;
10674 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10675 * timespec and sigset_t pointers if good.
10677 if (*argsz != sizeof(arg))
10679 if (copy_from_user(&arg, argp, sizeof(arg)))
10683 *sig = u64_to_user_ptr(arg.sigmask);
10684 *argsz = arg.sigmask_sz;
10685 *ts = u64_to_user_ptr(arg.ts);
10689 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10690 u32, min_complete, u32, flags, const void __user *, argp,
10693 struct io_ring_ctx *ctx;
10698 io_run_task_work();
10700 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10701 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10702 IORING_ENTER_REGISTERED_RING)))
10706 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10707 * need only dereference our task private array to find it.
10709 if (flags & IORING_ENTER_REGISTERED_RING) {
10710 struct io_uring_task *tctx = current->io_uring;
10712 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10714 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10715 f.file = tctx->registered_rings[fd];
10716 if (unlikely(!f.file))
10720 if (unlikely(!f.file))
10725 if (unlikely(f.file->f_op != &io_uring_fops))
10729 ctx = f.file->private_data;
10730 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10734 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10738 * For SQ polling, the thread will do all submissions and completions.
10739 * Just return the requested submit count, and wake the thread if
10740 * we were asked to.
10743 if (ctx->flags & IORING_SETUP_SQPOLL) {
10744 io_cqring_overflow_flush(ctx);
10746 if (unlikely(ctx->sq_data->thread == NULL)) {
10750 if (flags & IORING_ENTER_SQ_WAKEUP)
10751 wake_up(&ctx->sq_data->wait);
10752 if (flags & IORING_ENTER_SQ_WAIT) {
10753 ret = io_sqpoll_wait_sq(ctx);
10757 submitted = to_submit;
10758 } else if (to_submit) {
10759 ret = io_uring_add_tctx_node(ctx);
10763 mutex_lock(&ctx->uring_lock);
10764 submitted = io_submit_sqes(ctx, to_submit);
10765 if (submitted != to_submit) {
10766 mutex_unlock(&ctx->uring_lock);
10769 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
10770 goto iopoll_locked;
10771 mutex_unlock(&ctx->uring_lock);
10773 if (flags & IORING_ENTER_GETEVENTS) {
10774 if (ctx->syscall_iopoll) {
10776 * We disallow the app entering submit/complete with
10777 * polling, but we still need to lock the ring to
10778 * prevent racing with polled issue that got punted to
10781 mutex_lock(&ctx->uring_lock);
10783 ret = io_validate_ext_arg(flags, argp, argsz);
10784 if (likely(!ret)) {
10785 min_complete = min(min_complete, ctx->cq_entries);
10786 ret = io_iopoll_check(ctx, min_complete);
10788 mutex_unlock(&ctx->uring_lock);
10790 const sigset_t __user *sig;
10791 struct __kernel_timespec __user *ts;
10793 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10796 min_complete = min(min_complete, ctx->cq_entries);
10797 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10802 percpu_ref_put(&ctx->refs);
10804 if (!(flags & IORING_ENTER_REGISTERED_RING))
10806 return submitted ? submitted : ret;
10809 #ifdef CONFIG_PROC_FS
10810 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10811 const struct cred *cred)
10813 struct user_namespace *uns = seq_user_ns(m);
10814 struct group_info *gi;
10819 seq_printf(m, "%5d\n", id);
10820 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10821 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10822 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10823 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10824 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10825 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10826 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10827 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10828 seq_puts(m, "\n\tGroups:\t");
10829 gi = cred->group_info;
10830 for (g = 0; g < gi->ngroups; g++) {
10831 seq_put_decimal_ull(m, g ? " " : "",
10832 from_kgid_munged(uns, gi->gid[g]));
10834 seq_puts(m, "\n\tCapEff:\t");
10835 cap = cred->cap_effective;
10836 CAP_FOR_EACH_U32(__capi)
10837 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10842 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10843 struct seq_file *m)
10845 struct io_sq_data *sq = NULL;
10846 struct io_overflow_cqe *ocqe;
10847 struct io_rings *r = ctx->rings;
10848 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10849 unsigned int sq_head = READ_ONCE(r->sq.head);
10850 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10851 unsigned int cq_head = READ_ONCE(r->cq.head);
10852 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10853 unsigned int sq_entries, cq_entries;
10858 * we may get imprecise sqe and cqe info if uring is actively running
10859 * since we get cached_sq_head and cached_cq_tail without uring_lock
10860 * and sq_tail and cq_head are changed by userspace. But it's ok since
10861 * we usually use these info when it is stuck.
10863 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10864 seq_printf(m, "SqHead:\t%u\n", sq_head);
10865 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10866 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10867 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10868 seq_printf(m, "CqHead:\t%u\n", cq_head);
10869 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10870 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10871 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10872 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10873 for (i = 0; i < sq_entries; i++) {
10874 unsigned int entry = i + sq_head;
10875 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10876 struct io_uring_sqe *sqe;
10878 if (sq_idx > sq_mask)
10880 sqe = &ctx->sq_sqes[sq_idx];
10881 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10882 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10885 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10886 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10887 for (i = 0; i < cq_entries; i++) {
10888 unsigned int entry = i + cq_head;
10889 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10891 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10892 entry & cq_mask, cqe->user_data, cqe->res,
10897 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10898 * since fdinfo case grabs it in the opposite direction of normal use
10899 * cases. If we fail to get the lock, we just don't iterate any
10900 * structures that could be going away outside the io_uring mutex.
10902 has_lock = mutex_trylock(&ctx->uring_lock);
10904 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10910 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10911 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10912 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10913 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10914 struct file *f = io_file_from_index(ctx, i);
10917 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10919 seq_printf(m, "%5u: <none>\n", i);
10921 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10922 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10923 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10924 unsigned int len = buf->ubuf_end - buf->ubuf;
10926 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10928 if (has_lock && !xa_empty(&ctx->personalities)) {
10929 unsigned long index;
10930 const struct cred *cred;
10932 seq_printf(m, "Personalities:\n");
10933 xa_for_each(&ctx->personalities, index, cred)
10934 io_uring_show_cred(m, index, cred);
10937 mutex_unlock(&ctx->uring_lock);
10939 seq_puts(m, "PollList:\n");
10940 spin_lock(&ctx->completion_lock);
10941 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10942 struct hlist_head *list = &ctx->cancel_hash[i];
10943 struct io_kiocb *req;
10945 hlist_for_each_entry(req, list, hash_node)
10946 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10947 task_work_pending(req->task));
10950 seq_puts(m, "CqOverflowList:\n");
10951 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
10952 struct io_uring_cqe *cqe = &ocqe->cqe;
10954 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
10955 cqe->user_data, cqe->res, cqe->flags);
10959 spin_unlock(&ctx->completion_lock);
10962 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10964 struct io_ring_ctx *ctx = f->private_data;
10966 if (percpu_ref_tryget(&ctx->refs)) {
10967 __io_uring_show_fdinfo(ctx, m);
10968 percpu_ref_put(&ctx->refs);
10973 static const struct file_operations io_uring_fops = {
10974 .release = io_uring_release,
10975 .mmap = io_uring_mmap,
10977 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10978 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10980 .poll = io_uring_poll,
10981 #ifdef CONFIG_PROC_FS
10982 .show_fdinfo = io_uring_show_fdinfo,
10986 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10987 struct io_uring_params *p)
10989 struct io_rings *rings;
10990 size_t size, sq_array_offset;
10992 /* make sure these are sane, as we already accounted them */
10993 ctx->sq_entries = p->sq_entries;
10994 ctx->cq_entries = p->cq_entries;
10996 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10997 if (size == SIZE_MAX)
11000 rings = io_mem_alloc(size);
11004 ctx->rings = rings;
11005 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11006 rings->sq_ring_mask = p->sq_entries - 1;
11007 rings->cq_ring_mask = p->cq_entries - 1;
11008 rings->sq_ring_entries = p->sq_entries;
11009 rings->cq_ring_entries = p->cq_entries;
11011 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11012 if (size == SIZE_MAX) {
11013 io_mem_free(ctx->rings);
11018 ctx->sq_sqes = io_mem_alloc(size);
11019 if (!ctx->sq_sqes) {
11020 io_mem_free(ctx->rings);
11028 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11032 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11036 ret = io_uring_add_tctx_node(ctx);
11041 fd_install(fd, file);
11046 * Allocate an anonymous fd, this is what constitutes the application
11047 * visible backing of an io_uring instance. The application mmaps this
11048 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11049 * we have to tie this fd to a socket for file garbage collection purposes.
11051 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11054 #if defined(CONFIG_UNIX)
11057 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11060 return ERR_PTR(ret);
11063 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11064 O_RDWR | O_CLOEXEC, NULL);
11065 #if defined(CONFIG_UNIX)
11066 if (IS_ERR(file)) {
11067 sock_release(ctx->ring_sock);
11068 ctx->ring_sock = NULL;
11070 ctx->ring_sock->file = file;
11076 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11077 struct io_uring_params __user *params)
11079 struct io_ring_ctx *ctx;
11085 if (entries > IORING_MAX_ENTRIES) {
11086 if (!(p->flags & IORING_SETUP_CLAMP))
11088 entries = IORING_MAX_ENTRIES;
11092 * Use twice as many entries for the CQ ring. It's possible for the
11093 * application to drive a higher depth than the size of the SQ ring,
11094 * since the sqes are only used at submission time. This allows for
11095 * some flexibility in overcommitting a bit. If the application has
11096 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11097 * of CQ ring entries manually.
11099 p->sq_entries = roundup_pow_of_two(entries);
11100 if (p->flags & IORING_SETUP_CQSIZE) {
11102 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11103 * to a power-of-two, if it isn't already. We do NOT impose
11104 * any cq vs sq ring sizing.
11106 if (!p->cq_entries)
11108 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11109 if (!(p->flags & IORING_SETUP_CLAMP))
11111 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11113 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11114 if (p->cq_entries < p->sq_entries)
11117 p->cq_entries = 2 * p->sq_entries;
11120 ctx = io_ring_ctx_alloc(p);
11125 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
11126 * space applications don't need to do io completion events
11127 * polling again, they can rely on io_sq_thread to do polling
11128 * work, which can reduce cpu usage and uring_lock contention.
11130 if (ctx->flags & IORING_SETUP_IOPOLL &&
11131 !(ctx->flags & IORING_SETUP_SQPOLL))
11132 ctx->syscall_iopoll = 1;
11134 ctx->compat = in_compat_syscall();
11135 if (!capable(CAP_IPC_LOCK))
11136 ctx->user = get_uid(current_user());
11139 * This is just grabbed for accounting purposes. When a process exits,
11140 * the mm is exited and dropped before the files, hence we need to hang
11141 * on to this mm purely for the purposes of being able to unaccount
11142 * memory (locked/pinned vm). It's not used for anything else.
11144 mmgrab(current->mm);
11145 ctx->mm_account = current->mm;
11147 ret = io_allocate_scq_urings(ctx, p);
11151 ret = io_sq_offload_create(ctx, p);
11154 /* always set a rsrc node */
11155 ret = io_rsrc_node_switch_start(ctx);
11158 io_rsrc_node_switch(ctx, NULL);
11160 memset(&p->sq_off, 0, sizeof(p->sq_off));
11161 p->sq_off.head = offsetof(struct io_rings, sq.head);
11162 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11163 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11164 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11165 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11166 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11167 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11169 memset(&p->cq_off, 0, sizeof(p->cq_off));
11170 p->cq_off.head = offsetof(struct io_rings, cq.head);
11171 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11172 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11173 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11174 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11175 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11176 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11178 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11179 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11180 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11181 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11182 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11183 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
11184 IORING_FEAT_LINKED_FILE;
11186 if (copy_to_user(params, p, sizeof(*p))) {
11191 file = io_uring_get_file(ctx);
11192 if (IS_ERR(file)) {
11193 ret = PTR_ERR(file);
11198 * Install ring fd as the very last thing, so we don't risk someone
11199 * having closed it before we finish setup
11201 ret = io_uring_install_fd(ctx, file);
11203 /* fput will clean it up */
11208 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11211 io_ring_ctx_wait_and_kill(ctx);
11216 * Sets up an aio uring context, and returns the fd. Applications asks for a
11217 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11218 * params structure passed in.
11220 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11222 struct io_uring_params p;
11225 if (copy_from_user(&p, params, sizeof(p)))
11227 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11232 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11233 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11234 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11235 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11238 return io_uring_create(entries, &p, params);
11241 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11242 struct io_uring_params __user *, params)
11244 return io_uring_setup(entries, params);
11247 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11250 struct io_uring_probe *p;
11254 size = struct_size(p, ops, nr_args);
11255 if (size == SIZE_MAX)
11257 p = kzalloc(size, GFP_KERNEL);
11262 if (copy_from_user(p, arg, size))
11265 if (memchr_inv(p, 0, size))
11268 p->last_op = IORING_OP_LAST - 1;
11269 if (nr_args > IORING_OP_LAST)
11270 nr_args = IORING_OP_LAST;
11272 for (i = 0; i < nr_args; i++) {
11274 if (!io_op_defs[i].not_supported)
11275 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11280 if (copy_to_user(arg, p, size))
11287 static int io_register_personality(struct io_ring_ctx *ctx)
11289 const struct cred *creds;
11293 creds = get_current_cred();
11295 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11296 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11304 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11305 void __user *arg, unsigned int nr_args)
11307 struct io_uring_restriction *res;
11311 /* Restrictions allowed only if rings started disabled */
11312 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11315 /* We allow only a single restrictions registration */
11316 if (ctx->restrictions.registered)
11319 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11322 size = array_size(nr_args, sizeof(*res));
11323 if (size == SIZE_MAX)
11326 res = memdup_user(arg, size);
11328 return PTR_ERR(res);
11332 for (i = 0; i < nr_args; i++) {
11333 switch (res[i].opcode) {
11334 case IORING_RESTRICTION_REGISTER_OP:
11335 if (res[i].register_op >= IORING_REGISTER_LAST) {
11340 __set_bit(res[i].register_op,
11341 ctx->restrictions.register_op);
11343 case IORING_RESTRICTION_SQE_OP:
11344 if (res[i].sqe_op >= IORING_OP_LAST) {
11349 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11351 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11352 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11354 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11355 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11364 /* Reset all restrictions if an error happened */
11366 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11368 ctx->restrictions.registered = true;
11374 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11376 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11379 if (ctx->restrictions.registered)
11380 ctx->restricted = 1;
11382 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11383 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11384 wake_up(&ctx->sq_data->wait);
11388 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11389 struct io_uring_rsrc_update2 *up,
11395 if (check_add_overflow(up->offset, nr_args, &tmp))
11397 err = io_rsrc_node_switch_start(ctx);
11402 case IORING_RSRC_FILE:
11403 return __io_sqe_files_update(ctx, up, nr_args);
11404 case IORING_RSRC_BUFFER:
11405 return __io_sqe_buffers_update(ctx, up, nr_args);
11410 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11413 struct io_uring_rsrc_update2 up;
11417 memset(&up, 0, sizeof(up));
11418 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11420 if (up.resv || up.resv2)
11422 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11425 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11426 unsigned size, unsigned type)
11428 struct io_uring_rsrc_update2 up;
11430 if (size != sizeof(up))
11432 if (copy_from_user(&up, arg, sizeof(up)))
11434 if (!up.nr || up.resv || up.resv2)
11436 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11439 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11440 unsigned int size, unsigned int type)
11442 struct io_uring_rsrc_register rr;
11444 /* keep it extendible */
11445 if (size != sizeof(rr))
11448 memset(&rr, 0, sizeof(rr));
11449 if (copy_from_user(&rr, arg, size))
11451 if (!rr.nr || rr.resv || rr.resv2)
11455 case IORING_RSRC_FILE:
11456 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11457 rr.nr, u64_to_user_ptr(rr.tags));
11458 case IORING_RSRC_BUFFER:
11459 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11460 rr.nr, u64_to_user_ptr(rr.tags));
11465 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11466 void __user *arg, unsigned len)
11468 struct io_uring_task *tctx = current->io_uring;
11469 cpumask_var_t new_mask;
11472 if (!tctx || !tctx->io_wq)
11475 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11478 cpumask_clear(new_mask);
11479 if (len > cpumask_size())
11480 len = cpumask_size();
11482 if (in_compat_syscall()) {
11483 ret = compat_get_bitmap(cpumask_bits(new_mask),
11484 (const compat_ulong_t __user *)arg,
11485 len * 8 /* CHAR_BIT */);
11487 ret = copy_from_user(new_mask, arg, len);
11491 free_cpumask_var(new_mask);
11495 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11496 free_cpumask_var(new_mask);
11500 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11502 struct io_uring_task *tctx = current->io_uring;
11504 if (!tctx || !tctx->io_wq)
11507 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11510 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11512 __must_hold(&ctx->uring_lock)
11514 struct io_tctx_node *node;
11515 struct io_uring_task *tctx = NULL;
11516 struct io_sq_data *sqd = NULL;
11517 __u32 new_count[2];
11520 if (copy_from_user(new_count, arg, sizeof(new_count)))
11522 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11523 if (new_count[i] > INT_MAX)
11526 if (ctx->flags & IORING_SETUP_SQPOLL) {
11527 sqd = ctx->sq_data;
11530 * Observe the correct sqd->lock -> ctx->uring_lock
11531 * ordering. Fine to drop uring_lock here, we hold
11532 * a ref to the ctx.
11534 refcount_inc(&sqd->refs);
11535 mutex_unlock(&ctx->uring_lock);
11536 mutex_lock(&sqd->lock);
11537 mutex_lock(&ctx->uring_lock);
11539 tctx = sqd->thread->io_uring;
11542 tctx = current->io_uring;
11545 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11547 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11549 ctx->iowq_limits[i] = new_count[i];
11550 ctx->iowq_limits_set = true;
11552 if (tctx && tctx->io_wq) {
11553 ret = io_wq_max_workers(tctx->io_wq, new_count);
11557 memset(new_count, 0, sizeof(new_count));
11561 mutex_unlock(&sqd->lock);
11562 io_put_sq_data(sqd);
11565 if (copy_to_user(arg, new_count, sizeof(new_count)))
11568 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11572 /* now propagate the restriction to all registered users */
11573 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11574 struct io_uring_task *tctx = node->task->io_uring;
11576 if (WARN_ON_ONCE(!tctx->io_wq))
11579 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11580 new_count[i] = ctx->iowq_limits[i];
11581 /* ignore errors, it always returns zero anyway */
11582 (void)io_wq_max_workers(tctx->io_wq, new_count);
11587 mutex_unlock(&sqd->lock);
11588 io_put_sq_data(sqd);
11593 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11594 void __user *arg, unsigned nr_args)
11595 __releases(ctx->uring_lock)
11596 __acquires(ctx->uring_lock)
11601 * We're inside the ring mutex, if the ref is already dying, then
11602 * someone else killed the ctx or is already going through
11603 * io_uring_register().
11605 if (percpu_ref_is_dying(&ctx->refs))
11608 if (ctx->restricted) {
11609 if (opcode >= IORING_REGISTER_LAST)
11611 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11612 if (!test_bit(opcode, ctx->restrictions.register_op))
11617 case IORING_REGISTER_BUFFERS:
11618 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11620 case IORING_UNREGISTER_BUFFERS:
11622 if (arg || nr_args)
11624 ret = io_sqe_buffers_unregister(ctx);
11626 case IORING_REGISTER_FILES:
11627 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11629 case IORING_UNREGISTER_FILES:
11631 if (arg || nr_args)
11633 ret = io_sqe_files_unregister(ctx);
11635 case IORING_REGISTER_FILES_UPDATE:
11636 ret = io_register_files_update(ctx, arg, nr_args);
11638 case IORING_REGISTER_EVENTFD:
11642 ret = io_eventfd_register(ctx, arg, 0);
11644 case IORING_REGISTER_EVENTFD_ASYNC:
11648 ret = io_eventfd_register(ctx, arg, 1);
11650 case IORING_UNREGISTER_EVENTFD:
11652 if (arg || nr_args)
11654 ret = io_eventfd_unregister(ctx);
11656 case IORING_REGISTER_PROBE:
11658 if (!arg || nr_args > 256)
11660 ret = io_probe(ctx, arg, nr_args);
11662 case IORING_REGISTER_PERSONALITY:
11664 if (arg || nr_args)
11666 ret = io_register_personality(ctx);
11668 case IORING_UNREGISTER_PERSONALITY:
11672 ret = io_unregister_personality(ctx, nr_args);
11674 case IORING_REGISTER_ENABLE_RINGS:
11676 if (arg || nr_args)
11678 ret = io_register_enable_rings(ctx);
11680 case IORING_REGISTER_RESTRICTIONS:
11681 ret = io_register_restrictions(ctx, arg, nr_args);
11683 case IORING_REGISTER_FILES2:
11684 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11686 case IORING_REGISTER_FILES_UPDATE2:
11687 ret = io_register_rsrc_update(ctx, arg, nr_args,
11690 case IORING_REGISTER_BUFFERS2:
11691 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11693 case IORING_REGISTER_BUFFERS_UPDATE:
11694 ret = io_register_rsrc_update(ctx, arg, nr_args,
11695 IORING_RSRC_BUFFER);
11697 case IORING_REGISTER_IOWQ_AFF:
11699 if (!arg || !nr_args)
11701 ret = io_register_iowq_aff(ctx, arg, nr_args);
11703 case IORING_UNREGISTER_IOWQ_AFF:
11705 if (arg || nr_args)
11707 ret = io_unregister_iowq_aff(ctx);
11709 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11711 if (!arg || nr_args != 2)
11713 ret = io_register_iowq_max_workers(ctx, arg);
11715 case IORING_REGISTER_RING_FDS:
11716 ret = io_ringfd_register(ctx, arg, nr_args);
11718 case IORING_UNREGISTER_RING_FDS:
11719 ret = io_ringfd_unregister(ctx, arg, nr_args);
11729 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11730 void __user *, arg, unsigned int, nr_args)
11732 struct io_ring_ctx *ctx;
11741 if (f.file->f_op != &io_uring_fops)
11744 ctx = f.file->private_data;
11746 io_run_task_work();
11748 mutex_lock(&ctx->uring_lock);
11749 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11750 mutex_unlock(&ctx->uring_lock);
11751 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11757 static int __init io_uring_init(void)
11759 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11760 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11761 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11764 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11765 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11766 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11767 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11768 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11769 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11770 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11771 BUILD_BUG_SQE_ELEM(8, __u64, off);
11772 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11773 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11774 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11775 BUILD_BUG_SQE_ELEM(24, __u32, len);
11776 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11777 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11778 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11779 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11780 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11781 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11782 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11783 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11784 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11785 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11786 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11787 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11788 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11789 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11790 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11791 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11792 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11793 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11794 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11795 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11796 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11798 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11799 sizeof(struct io_uring_rsrc_update));
11800 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11801 sizeof(struct io_uring_rsrc_update2));
11803 /* ->buf_index is u16 */
11804 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11806 /* should fit into one byte */
11807 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11808 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11809 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11811 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11812 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11814 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11818 __initcall(io_uring_init);