1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <net/busy_poll.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/splice.h>
79 #include <linux/task_work.h>
80 #include <linux/pagemap.h>
81 #include <linux/io_uring.h>
82 #include <linux/tracehook.h>
83 #include <linux/audit.h>
84 #include <linux/security.h>
86 #define CREATE_TRACE_POINTS
87 #include <trace/events/io_uring.h>
89 #include <uapi/linux/io_uring.h>
94 #define IORING_MAX_ENTRIES 32768
95 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
96 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
99 #define IORING_MAX_FIXED_FILES (1U << 15)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
104 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
105 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
107 #define IORING_MAX_REG_BUFFERS (1U << 14)
109 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
110 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
112 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
113 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
115 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
116 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
119 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
122 u32 head ____cacheline_aligned_in_smp;
123 u32 tail ____cacheline_aligned_in_smp;
127 * This data is shared with the application through the mmap at offsets
128 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
130 * The offsets to the member fields are published through struct
131 * io_sqring_offsets when calling io_uring_setup.
135 * Head and tail offsets into the ring; the offsets need to be
136 * masked to get valid indices.
138 * The kernel controls head of the sq ring and the tail of the cq ring,
139 * and the application controls tail of the sq ring and the head of the
142 struct io_uring sq, cq;
144 * Bitmasks to apply to head and tail offsets (constant, equals
147 u32 sq_ring_mask, cq_ring_mask;
148 /* Ring sizes (constant, power of 2) */
149 u32 sq_ring_entries, cq_ring_entries;
151 * Number of invalid entries dropped by the kernel due to
152 * invalid index stored in array
154 * Written by the kernel, shouldn't be modified by the
155 * application (i.e. get number of "new events" by comparing to
158 * After a new SQ head value was read by the application this
159 * counter includes all submissions that were dropped reaching
160 * the new SQ head (and possibly more).
166 * Written by the kernel, shouldn't be modified by the
169 * The application needs a full memory barrier before checking
170 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
176 * Written by the application, shouldn't be modified by the
181 * Number of completion events lost because the queue was full;
182 * this should be avoided by the application by making sure
183 * there are not more requests pending than there is space in
184 * the completion queue.
186 * Written by the kernel, shouldn't be modified by the
187 * application (i.e. get number of "new events" by comparing to
190 * As completion events come in out of order this counter is not
191 * ordered with any other data.
195 * Ring buffer of completion events.
197 * The kernel writes completion events fresh every time they are
198 * produced, so the application is allowed to modify pending
201 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
204 enum io_uring_cmd_flags {
205 IO_URING_F_COMPLETE_DEFER = 1,
206 IO_URING_F_UNLOCKED = 2,
207 /* int's last bit, sign checks are usually faster than a bit test */
208 IO_URING_F_NONBLOCK = INT_MIN,
211 struct io_mapped_ubuf {
214 unsigned int nr_bvecs;
215 unsigned long acct_pages;
216 struct bio_vec bvec[];
221 struct io_overflow_cqe {
222 struct io_uring_cqe cqe;
223 struct list_head list;
226 struct io_fixed_file {
227 /* file * with additional FFS_* flags */
228 unsigned long file_ptr;
232 struct list_head list;
237 struct io_mapped_ubuf *buf;
241 struct io_file_table {
242 struct io_fixed_file *files;
245 struct io_rsrc_node {
246 struct percpu_ref refs;
247 struct list_head node;
248 struct list_head rsrc_list;
249 struct io_rsrc_data *rsrc_data;
250 struct llist_node llist;
254 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
256 struct io_rsrc_data {
257 struct io_ring_ctx *ctx;
263 struct completion done;
267 struct io_buffer_list {
268 struct list_head list;
269 struct list_head buf_list;
274 struct list_head list;
281 struct io_restriction {
282 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
283 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
284 u8 sqe_flags_allowed;
285 u8 sqe_flags_required;
290 IO_SQ_THREAD_SHOULD_STOP = 0,
291 IO_SQ_THREAD_SHOULD_PARK,
296 atomic_t park_pending;
299 /* ctx's that are using this sqd */
300 struct list_head ctx_list;
302 struct task_struct *thread;
303 struct wait_queue_head wait;
305 unsigned sq_thread_idle;
311 struct completion exited;
314 #define IO_COMPL_BATCH 32
315 #define IO_REQ_CACHE_SIZE 32
316 #define IO_REQ_ALLOC_BATCH 8
318 struct io_submit_link {
319 struct io_kiocb *head;
320 struct io_kiocb *last;
323 struct io_submit_state {
324 /* inline/task_work completion list, under ->uring_lock */
325 struct io_wq_work_node free_list;
326 /* batch completion logic */
327 struct io_wq_work_list compl_reqs;
328 struct io_submit_link link;
333 unsigned short submit_nr;
334 struct blk_plug plug;
338 struct eventfd_ctx *cq_ev_fd;
339 unsigned int eventfd_async: 1;
343 #define IO_BUFFERS_HASH_BITS 5
346 /* const or read-mostly hot data */
348 struct percpu_ref refs;
350 struct io_rings *rings;
352 unsigned int compat: 1;
353 unsigned int drain_next: 1;
354 unsigned int restricted: 1;
355 unsigned int off_timeout_used: 1;
356 unsigned int drain_active: 1;
357 unsigned int drain_disabled: 1;
358 unsigned int has_evfd: 1;
359 } ____cacheline_aligned_in_smp;
361 /* submission data */
363 struct mutex uring_lock;
366 * Ring buffer of indices into array of io_uring_sqe, which is
367 * mmapped by the application using the IORING_OFF_SQES offset.
369 * This indirection could e.g. be used to assign fixed
370 * io_uring_sqe entries to operations and only submit them to
371 * the queue when needed.
373 * The kernel modifies neither the indices array nor the entries
377 struct io_uring_sqe *sq_sqes;
378 unsigned cached_sq_head;
380 struct list_head defer_list;
383 * Fixed resources fast path, should be accessed only under
384 * uring_lock, and updated through io_uring_register(2)
386 struct io_rsrc_node *rsrc_node;
387 int rsrc_cached_refs;
388 struct io_file_table file_table;
389 unsigned nr_user_files;
390 unsigned nr_user_bufs;
391 struct io_mapped_ubuf **user_bufs;
393 struct io_submit_state submit_state;
394 struct list_head timeout_list;
395 struct list_head ltimeout_list;
396 struct list_head cq_overflow_list;
397 struct list_head *io_buffers;
398 struct list_head io_buffers_cache;
399 struct list_head apoll_cache;
400 struct xarray personalities;
402 unsigned sq_thread_idle;
403 } ____cacheline_aligned_in_smp;
405 /* IRQ completion list, under ->completion_lock */
406 struct io_wq_work_list locked_free_list;
407 unsigned int locked_free_nr;
409 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
410 struct io_sq_data *sq_data; /* if using sq thread polling */
412 struct wait_queue_head sqo_sq_wait;
413 struct list_head sqd_list;
415 unsigned long check_cq_overflow;
416 #ifdef CONFIG_NET_RX_BUSY_POLL
417 /* used to track busy poll napi_id */
418 struct list_head napi_list;
419 spinlock_t napi_lock; /* napi_list lock */
423 unsigned cached_cq_tail;
425 struct io_ev_fd __rcu *io_ev_fd;
426 struct wait_queue_head cq_wait;
428 atomic_t cq_timeouts;
429 unsigned cq_last_tm_flush;
430 } ____cacheline_aligned_in_smp;
433 spinlock_t completion_lock;
435 spinlock_t timeout_lock;
438 * ->iopoll_list is protected by the ctx->uring_lock for
439 * io_uring instances that don't use IORING_SETUP_SQPOLL.
440 * For SQPOLL, only the single threaded io_sq_thread() will
441 * manipulate the list, hence no extra locking is needed there.
443 struct io_wq_work_list iopoll_list;
444 struct hlist_head *cancel_hash;
445 unsigned cancel_hash_bits;
446 bool poll_multi_queue;
448 struct list_head io_buffers_comp;
449 } ____cacheline_aligned_in_smp;
451 struct io_restriction restrictions;
453 /* slow path rsrc auxilary data, used by update/register */
455 struct io_rsrc_node *rsrc_backup_node;
456 struct io_mapped_ubuf *dummy_ubuf;
457 struct io_rsrc_data *file_data;
458 struct io_rsrc_data *buf_data;
460 struct delayed_work rsrc_put_work;
461 struct llist_head rsrc_put_llist;
462 struct list_head rsrc_ref_list;
463 spinlock_t rsrc_ref_lock;
465 struct list_head io_buffers_pages;
468 /* Keep this last, we don't need it for the fast path */
470 #if defined(CONFIG_UNIX)
471 struct socket *ring_sock;
473 /* hashed buffered write serialization */
474 struct io_wq_hash *hash_map;
476 /* Only used for accounting purposes */
477 struct user_struct *user;
478 struct mm_struct *mm_account;
480 /* ctx exit and cancelation */
481 struct llist_head fallback_llist;
482 struct delayed_work fallback_work;
483 struct work_struct exit_work;
484 struct list_head tctx_list;
485 struct completion ref_comp;
487 bool iowq_limits_set;
492 * Arbitrary limit, can be raised if need be
494 #define IO_RINGFD_REG_MAX 16
496 struct io_uring_task {
497 /* submission side */
500 struct wait_queue_head wait;
501 const struct io_ring_ctx *last;
503 struct percpu_counter inflight;
504 atomic_t inflight_tracked;
507 spinlock_t task_lock;
508 struct io_wq_work_list task_list;
509 struct io_wq_work_list prior_task_list;
510 struct callback_head task_work;
511 struct file **registered_rings;
516 * First field must be the file pointer in all the
517 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
519 struct io_poll_iocb {
521 struct wait_queue_head *head;
523 struct wait_queue_entry wait;
526 struct io_poll_update {
532 bool update_user_data;
541 struct io_timeout_data {
542 struct io_kiocb *req;
543 struct hrtimer timer;
544 struct timespec64 ts;
545 enum hrtimer_mode mode;
551 struct sockaddr __user *addr;
552 int __user *addr_len;
555 unsigned long nofile;
575 struct list_head list;
576 /* head of the link, used by linked timeouts only */
577 struct io_kiocb *head;
578 /* for linked completions */
579 struct io_kiocb *prev;
582 struct io_timeout_rem {
587 struct timespec64 ts;
593 /* NOTE: kiocb has the file as the first member, so don't do it here */
601 struct sockaddr __user *addr;
608 struct compat_msghdr __user *umsg_compat;
609 struct user_msghdr __user *umsg;
621 struct filename *filename;
623 unsigned long nofile;
626 struct io_rsrc_update {
652 struct epoll_event event;
656 struct file *file_out;
657 struct file *file_in;
664 struct io_provide_buf {
678 struct filename *filename;
679 struct statx __user *buffer;
691 struct filename *oldpath;
692 struct filename *newpath;
700 struct filename *filename;
707 struct filename *filename;
713 struct filename *oldpath;
714 struct filename *newpath;
721 struct filename *oldpath;
722 struct filename *newpath;
732 struct io_async_connect {
733 struct sockaddr_storage address;
736 struct io_async_msghdr {
737 struct iovec fast_iov[UIO_FASTIOV];
738 /* points to an allocated iov, if NULL we use fast_iov instead */
739 struct iovec *free_iov;
740 struct sockaddr __user *uaddr;
742 struct sockaddr_storage addr;
746 struct iov_iter iter;
747 struct iov_iter_state iter_state;
748 struct iovec fast_iov[UIO_FASTIOV];
752 struct io_rw_state s;
753 const struct iovec *free_iovec;
755 struct wait_page_queue wpq;
759 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
760 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
761 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
762 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
763 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
764 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
765 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
767 /* first byte is taken by user flags, shift it to not overlap */
772 REQ_F_LINK_TIMEOUT_BIT,
773 REQ_F_NEED_CLEANUP_BIT,
775 REQ_F_BUFFER_SELECTED_BIT,
776 REQ_F_COMPLETE_INLINE_BIT,
780 REQ_F_ARM_LTIMEOUT_BIT,
781 REQ_F_ASYNC_DATA_BIT,
782 REQ_F_SKIP_LINK_CQES_BIT,
783 REQ_F_SINGLE_POLL_BIT,
784 REQ_F_DOUBLE_POLL_BIT,
785 /* keep async read/write and isreg together and in order */
786 REQ_F_SUPPORT_NOWAIT_BIT,
789 /* not a real bit, just to check we're not overflowing the space */
795 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
796 /* drain existing IO first */
797 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
799 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
800 /* doesn't sever on completion < 0 */
801 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
803 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
804 /* IOSQE_BUFFER_SELECT */
805 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
806 /* IOSQE_CQE_SKIP_SUCCESS */
807 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
809 /* fail rest of links */
810 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
811 /* on inflight list, should be cancelled and waited on exit reliably */
812 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
813 /* read/write uses file position */
814 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
815 /* must not punt to workers */
816 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
817 /* has or had linked timeout */
818 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
820 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
821 /* already went through poll handler */
822 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
823 /* buffer already selected */
824 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
825 /* completion is deferred through io_comp_state */
826 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
827 /* caller should reissue async */
828 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
829 /* supports async reads/writes */
830 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
832 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
833 /* has creds assigned */
834 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
835 /* skip refcounting if not set */
836 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
837 /* there is a linked timeout that has to be armed */
838 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
839 /* ->async_data allocated */
840 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
841 /* don't post CQEs while failing linked requests */
842 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
843 /* single poll may be active */
844 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
845 /* double poll may active */
846 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
850 struct io_poll_iocb poll;
851 struct io_poll_iocb *double_poll;
854 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
856 struct io_task_work {
858 struct io_wq_work_node node;
859 struct llist_node fallback_node;
861 io_req_tw_func_t func;
865 IORING_RSRC_FILE = 0,
866 IORING_RSRC_BUFFER = 1,
870 * NOTE! Each of the iocb union members has the file pointer
871 * as the first entry in their struct definition. So you can
872 * access the file pointer through any of the sub-structs,
873 * or directly as just 'file' in this struct.
879 struct io_poll_iocb poll;
880 struct io_poll_update poll_update;
881 struct io_accept accept;
883 struct io_cancel cancel;
884 struct io_timeout timeout;
885 struct io_timeout_rem timeout_rem;
886 struct io_connect connect;
887 struct io_sr_msg sr_msg;
889 struct io_close close;
890 struct io_rsrc_update rsrc_update;
891 struct io_fadvise fadvise;
892 struct io_madvise madvise;
893 struct io_epoll epoll;
894 struct io_splice splice;
895 struct io_provide_buf pbuf;
896 struct io_statx statx;
897 struct io_shutdown shutdown;
898 struct io_rename rename;
899 struct io_unlink unlink;
900 struct io_mkdir mkdir;
901 struct io_symlink symlink;
902 struct io_hardlink hardlink;
907 /* polled IO has completed */
916 struct io_ring_ctx *ctx;
917 struct task_struct *task;
919 struct percpu_ref *fixed_rsrc_refs;
920 /* store used ubuf, so we can prevent reloading */
921 struct io_mapped_ubuf *imu;
923 /* used by request caches, completion batching and iopoll */
924 struct io_wq_work_node comp_list;
927 struct io_kiocb *link;
928 struct io_task_work io_task_work;
929 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
930 struct hlist_node hash_node;
931 /* internal polling, see IORING_FEAT_FAST_POLL */
932 struct async_poll *apoll;
933 /* opcode allocated if it needs to store data for async defer */
935 /* custom credentials, valid IFF REQ_F_CREDS is set */
936 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
937 struct io_buffer *kbuf;
938 const struct cred *creds;
939 struct io_wq_work work;
942 struct io_tctx_node {
943 struct list_head ctx_node;
944 struct task_struct *task;
945 struct io_ring_ctx *ctx;
948 struct io_defer_entry {
949 struct list_head list;
950 struct io_kiocb *req;
955 /* needs req->file assigned */
956 unsigned needs_file : 1;
957 /* should block plug */
959 /* hash wq insertion if file is a regular file */
960 unsigned hash_reg_file : 1;
961 /* unbound wq insertion if file is a non-regular file */
962 unsigned unbound_nonreg_file : 1;
963 /* set if opcode supports polled "wait" */
965 unsigned pollout : 1;
966 /* op supports buffer selection */
967 unsigned buffer_select : 1;
968 /* do prep async if is going to be punted */
969 unsigned needs_async_setup : 1;
970 /* opcode is not supported by this kernel */
971 unsigned not_supported : 1;
973 unsigned audit_skip : 1;
974 /* size of async data needed, if any */
975 unsigned short async_size;
978 static const struct io_op_def io_op_defs[] = {
979 [IORING_OP_NOP] = {},
980 [IORING_OP_READV] = {
982 .unbound_nonreg_file = 1,
985 .needs_async_setup = 1,
988 .async_size = sizeof(struct io_async_rw),
990 [IORING_OP_WRITEV] = {
993 .unbound_nonreg_file = 1,
995 .needs_async_setup = 1,
998 .async_size = sizeof(struct io_async_rw),
1000 [IORING_OP_FSYNC] = {
1004 [IORING_OP_READ_FIXED] = {
1006 .unbound_nonreg_file = 1,
1010 .async_size = sizeof(struct io_async_rw),
1012 [IORING_OP_WRITE_FIXED] = {
1015 .unbound_nonreg_file = 1,
1019 .async_size = sizeof(struct io_async_rw),
1021 [IORING_OP_POLL_ADD] = {
1023 .unbound_nonreg_file = 1,
1026 [IORING_OP_POLL_REMOVE] = {
1029 [IORING_OP_SYNC_FILE_RANGE] = {
1033 [IORING_OP_SENDMSG] = {
1035 .unbound_nonreg_file = 1,
1037 .needs_async_setup = 1,
1038 .async_size = sizeof(struct io_async_msghdr),
1040 [IORING_OP_RECVMSG] = {
1042 .unbound_nonreg_file = 1,
1045 .needs_async_setup = 1,
1046 .async_size = sizeof(struct io_async_msghdr),
1048 [IORING_OP_TIMEOUT] = {
1050 .async_size = sizeof(struct io_timeout_data),
1052 [IORING_OP_TIMEOUT_REMOVE] = {
1053 /* used by timeout updates' prep() */
1056 [IORING_OP_ACCEPT] = {
1058 .unbound_nonreg_file = 1,
1061 [IORING_OP_ASYNC_CANCEL] = {
1064 [IORING_OP_LINK_TIMEOUT] = {
1066 .async_size = sizeof(struct io_timeout_data),
1068 [IORING_OP_CONNECT] = {
1070 .unbound_nonreg_file = 1,
1072 .needs_async_setup = 1,
1073 .async_size = sizeof(struct io_async_connect),
1075 [IORING_OP_FALLOCATE] = {
1078 [IORING_OP_OPENAT] = {},
1079 [IORING_OP_CLOSE] = {},
1080 [IORING_OP_FILES_UPDATE] = {
1083 [IORING_OP_STATX] = {
1086 [IORING_OP_READ] = {
1088 .unbound_nonreg_file = 1,
1093 .async_size = sizeof(struct io_async_rw),
1095 [IORING_OP_WRITE] = {
1098 .unbound_nonreg_file = 1,
1102 .async_size = sizeof(struct io_async_rw),
1104 [IORING_OP_FADVISE] = {
1108 [IORING_OP_MADVISE] = {},
1109 [IORING_OP_SEND] = {
1111 .unbound_nonreg_file = 1,
1115 [IORING_OP_RECV] = {
1117 .unbound_nonreg_file = 1,
1122 [IORING_OP_OPENAT2] = {
1124 [IORING_OP_EPOLL_CTL] = {
1125 .unbound_nonreg_file = 1,
1128 [IORING_OP_SPLICE] = {
1131 .unbound_nonreg_file = 1,
1134 [IORING_OP_PROVIDE_BUFFERS] = {
1137 [IORING_OP_REMOVE_BUFFERS] = {
1143 .unbound_nonreg_file = 1,
1146 [IORING_OP_SHUTDOWN] = {
1149 [IORING_OP_RENAMEAT] = {},
1150 [IORING_OP_UNLINKAT] = {},
1151 [IORING_OP_MKDIRAT] = {},
1152 [IORING_OP_SYMLINKAT] = {},
1153 [IORING_OP_LINKAT] = {},
1154 [IORING_OP_MSG_RING] = {
1159 /* requests with any of those set should undergo io_disarm_next() */
1160 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1162 static bool io_disarm_next(struct io_kiocb *req);
1163 static void io_uring_del_tctx_node(unsigned long index);
1164 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1165 struct task_struct *task,
1167 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1169 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1171 static void io_put_req(struct io_kiocb *req);
1172 static void io_put_req_deferred(struct io_kiocb *req);
1173 static void io_dismantle_req(struct io_kiocb *req);
1174 static void io_queue_linked_timeout(struct io_kiocb *req);
1175 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1176 struct io_uring_rsrc_update2 *up,
1178 static void io_clean_op(struct io_kiocb *req);
1179 static struct file *io_file_get(struct io_ring_ctx *ctx,
1180 struct io_kiocb *req, int fd, bool fixed);
1181 static void __io_queue_sqe(struct io_kiocb *req);
1182 static void io_rsrc_put_work(struct work_struct *work);
1184 static void io_req_task_queue(struct io_kiocb *req);
1185 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1186 static int io_req_prep_async(struct io_kiocb *req);
1188 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1189 unsigned int issue_flags, u32 slot_index);
1190 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1192 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1193 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1195 static struct kmem_cache *req_cachep;
1197 static const struct file_operations io_uring_fops;
1199 struct sock *io_uring_get_socket(struct file *file)
1201 #if defined(CONFIG_UNIX)
1202 if (file->f_op == &io_uring_fops) {
1203 struct io_ring_ctx *ctx = file->private_data;
1205 return ctx->ring_sock->sk;
1210 EXPORT_SYMBOL(io_uring_get_socket);
1212 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1215 mutex_lock(&ctx->uring_lock);
1220 #define io_for_each_link(pos, head) \
1221 for (pos = (head); pos; pos = pos->link)
1224 * Shamelessly stolen from the mm implementation of page reference checking,
1225 * see commit f958d7b528b1 for details.
1227 #define req_ref_zero_or_close_to_overflow(req) \
1228 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1230 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1232 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1233 return atomic_inc_not_zero(&req->refs);
1236 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1238 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1241 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1242 return atomic_dec_and_test(&req->refs);
1245 static inline void req_ref_get(struct io_kiocb *req)
1247 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1248 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1249 atomic_inc(&req->refs);
1252 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1254 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1255 __io_submit_flush_completions(ctx);
1258 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1260 if (!(req->flags & REQ_F_REFCOUNT)) {
1261 req->flags |= REQ_F_REFCOUNT;
1262 atomic_set(&req->refs, nr);
1266 static inline void io_req_set_refcount(struct io_kiocb *req)
1268 __io_req_set_refcount(req, 1);
1271 #define IO_RSRC_REF_BATCH 100
1273 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1274 struct io_ring_ctx *ctx)
1275 __must_hold(&ctx->uring_lock)
1277 struct percpu_ref *ref = req->fixed_rsrc_refs;
1280 if (ref == &ctx->rsrc_node->refs)
1281 ctx->rsrc_cached_refs++;
1283 percpu_ref_put(ref);
1287 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1289 if (req->fixed_rsrc_refs)
1290 percpu_ref_put(req->fixed_rsrc_refs);
1293 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1294 __must_hold(&ctx->uring_lock)
1296 if (ctx->rsrc_cached_refs) {
1297 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1298 ctx->rsrc_cached_refs = 0;
1302 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1303 __must_hold(&ctx->uring_lock)
1305 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1306 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1309 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1310 struct io_ring_ctx *ctx)
1312 if (!req->fixed_rsrc_refs) {
1313 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1314 ctx->rsrc_cached_refs--;
1315 if (unlikely(ctx->rsrc_cached_refs < 0))
1316 io_rsrc_refs_refill(ctx);
1320 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1322 struct io_buffer *kbuf = req->kbuf;
1323 unsigned int cflags;
1325 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1326 req->flags &= ~REQ_F_BUFFER_SELECTED;
1327 list_add(&kbuf->list, list);
1332 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1334 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1336 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1339 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1340 unsigned issue_flags)
1342 unsigned int cflags;
1344 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1348 * We can add this buffer back to two lists:
1350 * 1) The io_buffers_cache list. This one is protected by the
1351 * ctx->uring_lock. If we already hold this lock, add back to this
1352 * list as we can grab it from issue as well.
1353 * 2) The io_buffers_comp list. This one is protected by the
1354 * ctx->completion_lock.
1356 * We migrate buffers from the comp_list to the issue cache list
1359 if (issue_flags & IO_URING_F_UNLOCKED) {
1360 struct io_ring_ctx *ctx = req->ctx;
1362 spin_lock(&ctx->completion_lock);
1363 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1364 spin_unlock(&ctx->completion_lock);
1366 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1372 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1375 struct list_head *hash_list;
1376 struct io_buffer_list *bl;
1378 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1379 list_for_each_entry(bl, hash_list, list)
1380 if (bl->bgid == bgid || bgid == -1U)
1386 static void io_kbuf_recycle(struct io_kiocb *req)
1388 struct io_ring_ctx *ctx = req->ctx;
1389 struct io_buffer_list *bl;
1390 struct io_buffer *buf;
1392 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1395 lockdep_assert_held(&ctx->uring_lock);
1398 bl = io_buffer_get_list(ctx, buf->bgid);
1399 list_add(&buf->list, &bl->buf_list);
1400 req->flags &= ~REQ_F_BUFFER_SELECTED;
1404 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1406 __must_hold(&req->ctx->timeout_lock)
1408 struct io_kiocb *req;
1410 if (task && head->task != task)
1415 io_for_each_link(req, head) {
1416 if (req->flags & REQ_F_INFLIGHT)
1422 static bool io_match_linked(struct io_kiocb *head)
1424 struct io_kiocb *req;
1426 io_for_each_link(req, head) {
1427 if (req->flags & REQ_F_INFLIGHT)
1434 * As io_match_task() but protected against racing with linked timeouts.
1435 * User must not hold timeout_lock.
1437 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1442 if (task && head->task != task)
1447 if (head->flags & REQ_F_LINK_TIMEOUT) {
1448 struct io_ring_ctx *ctx = head->ctx;
1450 /* protect against races with linked timeouts */
1451 spin_lock_irq(&ctx->timeout_lock);
1452 matched = io_match_linked(head);
1453 spin_unlock_irq(&ctx->timeout_lock);
1455 matched = io_match_linked(head);
1460 static inline bool req_has_async_data(struct io_kiocb *req)
1462 return req->flags & REQ_F_ASYNC_DATA;
1465 static inline void req_set_fail(struct io_kiocb *req)
1467 req->flags |= REQ_F_FAIL;
1468 if (req->flags & REQ_F_CQE_SKIP) {
1469 req->flags &= ~REQ_F_CQE_SKIP;
1470 req->flags |= REQ_F_SKIP_LINK_CQES;
1474 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1480 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1482 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1484 complete(&ctx->ref_comp);
1487 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1489 return !req->timeout.off;
1492 static __cold void io_fallback_req_func(struct work_struct *work)
1494 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1495 fallback_work.work);
1496 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1497 struct io_kiocb *req, *tmp;
1498 bool locked = false;
1500 percpu_ref_get(&ctx->refs);
1501 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1502 req->io_task_work.func(req, &locked);
1505 io_submit_flush_completions(ctx);
1506 mutex_unlock(&ctx->uring_lock);
1508 percpu_ref_put(&ctx->refs);
1511 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1513 struct io_ring_ctx *ctx;
1516 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1521 * Use 5 bits less than the max cq entries, that should give us around
1522 * 32 entries per hash list if totally full and uniformly spread.
1524 hash_bits = ilog2(p->cq_entries);
1528 ctx->cancel_hash_bits = hash_bits;
1529 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1531 if (!ctx->cancel_hash)
1533 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1535 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1536 if (!ctx->dummy_ubuf)
1538 /* set invalid range, so io_import_fixed() fails meeting it */
1539 ctx->dummy_ubuf->ubuf = -1UL;
1541 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1542 sizeof(struct list_head), GFP_KERNEL);
1543 if (!ctx->io_buffers)
1545 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1546 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1548 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1549 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1552 ctx->flags = p->flags;
1553 init_waitqueue_head(&ctx->sqo_sq_wait);
1554 INIT_LIST_HEAD(&ctx->sqd_list);
1555 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1556 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1557 INIT_LIST_HEAD(&ctx->apoll_cache);
1558 init_completion(&ctx->ref_comp);
1559 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1560 mutex_init(&ctx->uring_lock);
1561 init_waitqueue_head(&ctx->cq_wait);
1562 spin_lock_init(&ctx->completion_lock);
1563 spin_lock_init(&ctx->timeout_lock);
1564 INIT_WQ_LIST(&ctx->iopoll_list);
1565 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1566 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1567 INIT_LIST_HEAD(&ctx->defer_list);
1568 INIT_LIST_HEAD(&ctx->timeout_list);
1569 INIT_LIST_HEAD(&ctx->ltimeout_list);
1570 spin_lock_init(&ctx->rsrc_ref_lock);
1571 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1572 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1573 init_llist_head(&ctx->rsrc_put_llist);
1574 INIT_LIST_HEAD(&ctx->tctx_list);
1575 ctx->submit_state.free_list.next = NULL;
1576 INIT_WQ_LIST(&ctx->locked_free_list);
1577 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1578 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1579 #ifdef CONFIG_NET_RX_BUSY_POLL
1580 INIT_LIST_HEAD(&ctx->napi_list);
1581 spin_lock_init(&ctx->napi_lock);
1585 kfree(ctx->dummy_ubuf);
1586 kfree(ctx->cancel_hash);
1587 kfree(ctx->io_buffers);
1592 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1594 struct io_rings *r = ctx->rings;
1596 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1600 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1602 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1603 struct io_ring_ctx *ctx = req->ctx;
1605 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1611 #define FFS_NOWAIT 0x1UL
1612 #define FFS_ISREG 0x2UL
1613 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1615 static inline bool io_req_ffs_set(struct io_kiocb *req)
1617 return req->flags & REQ_F_FIXED_FILE;
1620 static inline void io_req_track_inflight(struct io_kiocb *req)
1622 if (!(req->flags & REQ_F_INFLIGHT)) {
1623 req->flags |= REQ_F_INFLIGHT;
1624 atomic_inc(¤t->io_uring->inflight_tracked);
1628 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1630 if (WARN_ON_ONCE(!req->link))
1633 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1634 req->flags |= REQ_F_LINK_TIMEOUT;
1636 /* linked timeouts should have two refs once prep'ed */
1637 io_req_set_refcount(req);
1638 __io_req_set_refcount(req->link, 2);
1642 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1644 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1646 return __io_prep_linked_timeout(req);
1649 static void io_prep_async_work(struct io_kiocb *req)
1651 const struct io_op_def *def = &io_op_defs[req->opcode];
1652 struct io_ring_ctx *ctx = req->ctx;
1654 if (!(req->flags & REQ_F_CREDS)) {
1655 req->flags |= REQ_F_CREDS;
1656 req->creds = get_current_cred();
1659 req->work.list.next = NULL;
1660 req->work.flags = 0;
1661 if (req->flags & REQ_F_FORCE_ASYNC)
1662 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1664 if (req->flags & REQ_F_ISREG) {
1665 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1666 io_wq_hash_work(&req->work, file_inode(req->file));
1667 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1668 if (def->unbound_nonreg_file)
1669 req->work.flags |= IO_WQ_WORK_UNBOUND;
1672 switch (req->opcode) {
1673 case IORING_OP_SPLICE:
1675 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1676 req->work.flags |= IO_WQ_WORK_UNBOUND;
1681 static void io_prep_async_link(struct io_kiocb *req)
1683 struct io_kiocb *cur;
1685 if (req->flags & REQ_F_LINK_TIMEOUT) {
1686 struct io_ring_ctx *ctx = req->ctx;
1688 spin_lock_irq(&ctx->timeout_lock);
1689 io_for_each_link(cur, req)
1690 io_prep_async_work(cur);
1691 spin_unlock_irq(&ctx->timeout_lock);
1693 io_for_each_link(cur, req)
1694 io_prep_async_work(cur);
1698 static inline void io_req_add_compl_list(struct io_kiocb *req)
1700 struct io_ring_ctx *ctx = req->ctx;
1701 struct io_submit_state *state = &ctx->submit_state;
1703 if (!(req->flags & REQ_F_CQE_SKIP))
1704 ctx->submit_state.flush_cqes = true;
1705 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1708 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1710 struct io_ring_ctx *ctx = req->ctx;
1711 struct io_kiocb *link = io_prep_linked_timeout(req);
1712 struct io_uring_task *tctx = req->task->io_uring;
1715 BUG_ON(!tctx->io_wq);
1717 /* init ->work of the whole link before punting */
1718 io_prep_async_link(req);
1721 * Not expected to happen, but if we do have a bug where this _can_
1722 * happen, catch it here and ensure the request is marked as
1723 * canceled. That will make io-wq go through the usual work cancel
1724 * procedure rather than attempt to run this request (or create a new
1727 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1728 req->work.flags |= IO_WQ_WORK_CANCEL;
1730 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1731 &req->work, io_wq_is_hashed(&req->work));
1732 io_wq_enqueue(tctx->io_wq, &req->work);
1734 io_queue_linked_timeout(link);
1737 static void io_kill_timeout(struct io_kiocb *req, int status)
1738 __must_hold(&req->ctx->completion_lock)
1739 __must_hold(&req->ctx->timeout_lock)
1741 struct io_timeout_data *io = req->async_data;
1743 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1746 atomic_set(&req->ctx->cq_timeouts,
1747 atomic_read(&req->ctx->cq_timeouts) + 1);
1748 list_del_init(&req->timeout.list);
1749 io_fill_cqe_req(req, status, 0);
1750 io_put_req_deferred(req);
1754 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1756 while (!list_empty(&ctx->defer_list)) {
1757 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1758 struct io_defer_entry, list);
1760 if (req_need_defer(de->req, de->seq))
1762 list_del_init(&de->list);
1763 io_req_task_queue(de->req);
1768 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1769 __must_hold(&ctx->completion_lock)
1771 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1773 spin_lock_irq(&ctx->timeout_lock);
1774 while (!list_empty(&ctx->timeout_list)) {
1775 u32 events_needed, events_got;
1776 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1777 struct io_kiocb, timeout.list);
1779 if (io_is_timeout_noseq(req))
1783 * Since seq can easily wrap around over time, subtract
1784 * the last seq at which timeouts were flushed before comparing.
1785 * Assuming not more than 2^31-1 events have happened since,
1786 * these subtractions won't have wrapped, so we can check if
1787 * target is in [last_seq, current_seq] by comparing the two.
1789 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1790 events_got = seq - ctx->cq_last_tm_flush;
1791 if (events_got < events_needed)
1794 list_del_init(&req->timeout.list);
1795 io_kill_timeout(req, 0);
1797 ctx->cq_last_tm_flush = seq;
1798 spin_unlock_irq(&ctx->timeout_lock);
1801 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1803 /* order cqe stores with ring update */
1804 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1807 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1809 if (ctx->off_timeout_used || ctx->drain_active) {
1810 spin_lock(&ctx->completion_lock);
1811 if (ctx->off_timeout_used)
1812 io_flush_timeouts(ctx);
1813 if (ctx->drain_active)
1814 io_queue_deferred(ctx);
1815 io_commit_cqring(ctx);
1816 spin_unlock(&ctx->completion_lock);
1819 io_eventfd_signal(ctx);
1822 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1824 struct io_rings *r = ctx->rings;
1826 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1829 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1831 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1834 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1836 struct io_rings *rings = ctx->rings;
1837 unsigned tail, mask = ctx->cq_entries - 1;
1840 * writes to the cq entry need to come after reading head; the
1841 * control dependency is enough as we're using WRITE_ONCE to
1844 if (__io_cqring_events(ctx) == ctx->cq_entries)
1847 tail = ctx->cached_cq_tail++;
1848 return &rings->cqes[tail & mask];
1851 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1853 struct io_ev_fd *ev_fd;
1857 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1858 * and eventfd_signal
1860 ev_fd = rcu_dereference(ctx->io_ev_fd);
1863 * Check again if ev_fd exists incase an io_eventfd_unregister call
1864 * completed between the NULL check of ctx->io_ev_fd at the start of
1865 * the function and rcu_read_lock.
1867 if (unlikely(!ev_fd))
1869 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1872 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1873 eventfd_signal(ev_fd->cq_ev_fd, 1);
1878 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1881 * wake_up_all() may seem excessive, but io_wake_function() and
1882 * io_should_wake() handle the termination of the loop and only
1883 * wake as many waiters as we need to.
1885 if (wq_has_sleeper(&ctx->cq_wait))
1886 wake_up_all(&ctx->cq_wait);
1890 * This should only get called when at least one event has been posted.
1891 * Some applications rely on the eventfd notification count only changing
1892 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1893 * 1:1 relationship between how many times this function is called (and
1894 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1896 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1898 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1900 __io_commit_cqring_flush(ctx);
1902 io_cqring_wake(ctx);
1905 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1907 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1909 __io_commit_cqring_flush(ctx);
1911 if (ctx->flags & IORING_SETUP_SQPOLL)
1912 io_cqring_wake(ctx);
1915 /* Returns true if there are no backlogged entries after the flush */
1916 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1918 bool all_flushed, posted;
1920 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1924 spin_lock(&ctx->completion_lock);
1925 while (!list_empty(&ctx->cq_overflow_list)) {
1926 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1927 struct io_overflow_cqe *ocqe;
1931 ocqe = list_first_entry(&ctx->cq_overflow_list,
1932 struct io_overflow_cqe, list);
1934 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1936 io_account_cq_overflow(ctx);
1939 list_del(&ocqe->list);
1943 all_flushed = list_empty(&ctx->cq_overflow_list);
1945 clear_bit(0, &ctx->check_cq_overflow);
1946 WRITE_ONCE(ctx->rings->sq_flags,
1947 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1951 io_commit_cqring(ctx);
1952 spin_unlock(&ctx->completion_lock);
1954 io_cqring_ev_posted(ctx);
1958 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1962 if (test_bit(0, &ctx->check_cq_overflow)) {
1963 /* iopoll syncs against uring_lock, not completion_lock */
1964 if (ctx->flags & IORING_SETUP_IOPOLL)
1965 mutex_lock(&ctx->uring_lock);
1966 ret = __io_cqring_overflow_flush(ctx, false);
1967 if (ctx->flags & IORING_SETUP_IOPOLL)
1968 mutex_unlock(&ctx->uring_lock);
1974 /* must to be called somewhat shortly after putting a request */
1975 static inline void io_put_task(struct task_struct *task, int nr)
1977 struct io_uring_task *tctx = task->io_uring;
1979 if (likely(task == current)) {
1980 tctx->cached_refs += nr;
1982 percpu_counter_sub(&tctx->inflight, nr);
1983 if (unlikely(atomic_read(&tctx->in_idle)))
1984 wake_up(&tctx->wait);
1985 put_task_struct_many(task, nr);
1989 static void io_task_refs_refill(struct io_uring_task *tctx)
1991 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1993 percpu_counter_add(&tctx->inflight, refill);
1994 refcount_add(refill, ¤t->usage);
1995 tctx->cached_refs += refill;
1998 static inline void io_get_task_refs(int nr)
2000 struct io_uring_task *tctx = current->io_uring;
2002 tctx->cached_refs -= nr;
2003 if (unlikely(tctx->cached_refs < 0))
2004 io_task_refs_refill(tctx);
2007 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2009 struct io_uring_task *tctx = task->io_uring;
2010 unsigned int refs = tctx->cached_refs;
2013 tctx->cached_refs = 0;
2014 percpu_counter_sub(&tctx->inflight, refs);
2015 put_task_struct_many(task, refs);
2019 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2020 s32 res, u32 cflags)
2022 struct io_overflow_cqe *ocqe;
2024 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2027 * If we're in ring overflow flush mode, or in task cancel mode,
2028 * or cannot allocate an overflow entry, then we need to drop it
2031 io_account_cq_overflow(ctx);
2034 if (list_empty(&ctx->cq_overflow_list)) {
2035 set_bit(0, &ctx->check_cq_overflow);
2036 WRITE_ONCE(ctx->rings->sq_flags,
2037 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2040 ocqe->cqe.user_data = user_data;
2041 ocqe->cqe.res = res;
2042 ocqe->cqe.flags = cflags;
2043 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2047 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2048 s32 res, u32 cflags)
2050 struct io_uring_cqe *cqe;
2053 * If we can't get a cq entry, userspace overflowed the
2054 * submission (by quite a lot). Increment the overflow count in
2057 cqe = io_get_cqe(ctx);
2059 WRITE_ONCE(cqe->user_data, user_data);
2060 WRITE_ONCE(cqe->res, res);
2061 WRITE_ONCE(cqe->flags, cflags);
2064 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2067 static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2069 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2070 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
2073 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2075 if (!(req->flags & REQ_F_CQE_SKIP))
2076 __io_fill_cqe_req(req, res, cflags);
2079 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2080 s32 res, u32 cflags)
2083 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2084 return __io_fill_cqe(ctx, user_data, res, cflags);
2087 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2090 struct io_ring_ctx *ctx = req->ctx;
2092 if (!(req->flags & REQ_F_CQE_SKIP))
2093 __io_fill_cqe_req(req, res, cflags);
2095 * If we're the last reference to this request, add to our locked
2098 if (req_ref_put_and_test(req)) {
2099 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2100 if (req->flags & IO_DISARM_MASK)
2101 io_disarm_next(req);
2103 io_req_task_queue(req->link);
2107 io_req_put_rsrc(req, ctx);
2108 io_dismantle_req(req);
2109 io_put_task(req->task, 1);
2110 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2111 ctx->locked_free_nr++;
2115 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2118 struct io_ring_ctx *ctx = req->ctx;
2120 spin_lock(&ctx->completion_lock);
2121 __io_req_complete_post(req, res, cflags);
2122 io_commit_cqring(ctx);
2123 spin_unlock(&ctx->completion_lock);
2124 io_cqring_ev_posted(ctx);
2127 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2131 req->cflags = cflags;
2132 req->flags |= REQ_F_COMPLETE_INLINE;
2135 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2136 s32 res, u32 cflags)
2138 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2139 io_req_complete_state(req, res, cflags);
2141 io_req_complete_post(req, res, cflags);
2144 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2146 __io_req_complete(req, 0, res, 0);
2149 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2152 io_req_complete_post(req, res, io_put_kbuf(req, 0));
2155 static void io_req_complete_fail_submit(struct io_kiocb *req)
2158 * We don't submit, fail them all, for that replace hardlinks with
2159 * normal links. Extra REQ_F_LINK is tolerated.
2161 req->flags &= ~REQ_F_HARDLINK;
2162 req->flags |= REQ_F_LINK;
2163 io_req_complete_failed(req, req->result);
2167 * Don't initialise the fields below on every allocation, but do that in
2168 * advance and keep them valid across allocations.
2170 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2174 req->async_data = NULL;
2175 /* not necessary, but safer to zero */
2179 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2180 struct io_submit_state *state)
2182 spin_lock(&ctx->completion_lock);
2183 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2184 ctx->locked_free_nr = 0;
2185 spin_unlock(&ctx->completion_lock);
2188 /* Returns true IFF there are requests in the cache */
2189 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2191 struct io_submit_state *state = &ctx->submit_state;
2194 * If we have more than a batch's worth of requests in our IRQ side
2195 * locked cache, grab the lock and move them over to our submission
2198 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2199 io_flush_cached_locked_reqs(ctx, state);
2200 return !!state->free_list.next;
2204 * A request might get retired back into the request caches even before opcode
2205 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2206 * Because of that, io_alloc_req() should be called only under ->uring_lock
2207 * and with extra caution to not get a request that is still worked on.
2209 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2210 __must_hold(&ctx->uring_lock)
2212 struct io_submit_state *state = &ctx->submit_state;
2213 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2214 void *reqs[IO_REQ_ALLOC_BATCH];
2215 struct io_kiocb *req;
2218 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2221 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2224 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2225 * retry single alloc to be on the safe side.
2227 if (unlikely(ret <= 0)) {
2228 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2234 percpu_ref_get_many(&ctx->refs, ret);
2235 for (i = 0; i < ret; i++) {
2238 io_preinit_req(req, ctx);
2239 wq_stack_add_head(&req->comp_list, &state->free_list);
2244 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2246 if (unlikely(!ctx->submit_state.free_list.next))
2247 return __io_alloc_req_refill(ctx);
2251 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2253 struct io_wq_work_node *node;
2255 node = wq_stack_extract(&ctx->submit_state.free_list);
2256 return container_of(node, struct io_kiocb, comp_list);
2259 static inline void io_put_file(struct file *file)
2265 static inline void io_dismantle_req(struct io_kiocb *req)
2267 unsigned int flags = req->flags;
2269 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2271 if (!(flags & REQ_F_FIXED_FILE))
2272 io_put_file(req->file);
2275 static __cold void __io_free_req(struct io_kiocb *req)
2277 struct io_ring_ctx *ctx = req->ctx;
2279 io_req_put_rsrc(req, ctx);
2280 io_dismantle_req(req);
2281 io_put_task(req->task, 1);
2283 spin_lock(&ctx->completion_lock);
2284 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2285 ctx->locked_free_nr++;
2286 spin_unlock(&ctx->completion_lock);
2289 static inline void io_remove_next_linked(struct io_kiocb *req)
2291 struct io_kiocb *nxt = req->link;
2293 req->link = nxt->link;
2297 static bool io_kill_linked_timeout(struct io_kiocb *req)
2298 __must_hold(&req->ctx->completion_lock)
2299 __must_hold(&req->ctx->timeout_lock)
2301 struct io_kiocb *link = req->link;
2303 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2304 struct io_timeout_data *io = link->async_data;
2306 io_remove_next_linked(req);
2307 link->timeout.head = NULL;
2308 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2309 list_del(&link->timeout.list);
2310 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2311 io_fill_cqe_req(link, -ECANCELED, 0);
2312 io_put_req_deferred(link);
2319 static void io_fail_links(struct io_kiocb *req)
2320 __must_hold(&req->ctx->completion_lock)
2322 struct io_kiocb *nxt, *link = req->link;
2323 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2327 long res = -ECANCELED;
2329 if (link->flags & REQ_F_FAIL)
2335 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2339 link->flags &= ~REQ_F_CQE_SKIP;
2340 io_fill_cqe_req(link, res, 0);
2342 io_put_req_deferred(link);
2347 static bool io_disarm_next(struct io_kiocb *req)
2348 __must_hold(&req->ctx->completion_lock)
2350 bool posted = false;
2352 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2353 struct io_kiocb *link = req->link;
2355 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2356 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2357 io_remove_next_linked(req);
2358 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2359 io_fill_cqe_req(link, -ECANCELED, 0);
2360 io_put_req_deferred(link);
2363 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2364 struct io_ring_ctx *ctx = req->ctx;
2366 spin_lock_irq(&ctx->timeout_lock);
2367 posted = io_kill_linked_timeout(req);
2368 spin_unlock_irq(&ctx->timeout_lock);
2370 if (unlikely((req->flags & REQ_F_FAIL) &&
2371 !(req->flags & REQ_F_HARDLINK))) {
2372 posted |= (req->link != NULL);
2378 static void __io_req_find_next_prep(struct io_kiocb *req)
2380 struct io_ring_ctx *ctx = req->ctx;
2383 spin_lock(&ctx->completion_lock);
2384 posted = io_disarm_next(req);
2386 io_commit_cqring(ctx);
2387 spin_unlock(&ctx->completion_lock);
2389 io_cqring_ev_posted(ctx);
2392 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2394 struct io_kiocb *nxt;
2396 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2399 * If LINK is set, we have dependent requests in this chain. If we
2400 * didn't fail this request, queue the first one up, moving any other
2401 * dependencies to the next request. In case of failure, fail the rest
2404 if (unlikely(req->flags & IO_DISARM_MASK))
2405 __io_req_find_next_prep(req);
2411 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2416 io_submit_flush_completions(ctx);
2417 mutex_unlock(&ctx->uring_lock);
2420 percpu_ref_put(&ctx->refs);
2423 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2425 io_commit_cqring(ctx);
2426 spin_unlock(&ctx->completion_lock);
2427 io_cqring_ev_posted(ctx);
2430 static void handle_prev_tw_list(struct io_wq_work_node *node,
2431 struct io_ring_ctx **ctx, bool *uring_locked)
2433 if (*ctx && !*uring_locked)
2434 spin_lock(&(*ctx)->completion_lock);
2437 struct io_wq_work_node *next = node->next;
2438 struct io_kiocb *req = container_of(node, struct io_kiocb,
2441 if (req->ctx != *ctx) {
2442 if (unlikely(!*uring_locked && *ctx))
2443 ctx_commit_and_unlock(*ctx);
2445 ctx_flush_and_put(*ctx, uring_locked);
2447 /* if not contended, grab and improve batching */
2448 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2449 percpu_ref_get(&(*ctx)->refs);
2450 if (unlikely(!*uring_locked))
2451 spin_lock(&(*ctx)->completion_lock);
2453 if (likely(*uring_locked))
2454 req->io_task_work.func(req, uring_locked);
2456 __io_req_complete_post(req, req->result,
2457 io_put_kbuf_comp(req));
2461 if (unlikely(!*uring_locked))
2462 ctx_commit_and_unlock(*ctx);
2465 static void handle_tw_list(struct io_wq_work_node *node,
2466 struct io_ring_ctx **ctx, bool *locked)
2469 struct io_wq_work_node *next = node->next;
2470 struct io_kiocb *req = container_of(node, struct io_kiocb,
2473 if (req->ctx != *ctx) {
2474 ctx_flush_and_put(*ctx, locked);
2476 /* if not contended, grab and improve batching */
2477 *locked = mutex_trylock(&(*ctx)->uring_lock);
2478 percpu_ref_get(&(*ctx)->refs);
2480 req->io_task_work.func(req, locked);
2485 static void tctx_task_work(struct callback_head *cb)
2487 bool uring_locked = false;
2488 struct io_ring_ctx *ctx = NULL;
2489 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2493 struct io_wq_work_node *node1, *node2;
2495 if (!tctx->task_list.first &&
2496 !tctx->prior_task_list.first && uring_locked)
2497 io_submit_flush_completions(ctx);
2499 spin_lock_irq(&tctx->task_lock);
2500 node1 = tctx->prior_task_list.first;
2501 node2 = tctx->task_list.first;
2502 INIT_WQ_LIST(&tctx->task_list);
2503 INIT_WQ_LIST(&tctx->prior_task_list);
2504 if (!node2 && !node1)
2505 tctx->task_running = false;
2506 spin_unlock_irq(&tctx->task_lock);
2507 if (!node2 && !node1)
2511 handle_prev_tw_list(node1, &ctx, &uring_locked);
2514 handle_tw_list(node2, &ctx, &uring_locked);
2518 ctx_flush_and_put(ctx, &uring_locked);
2520 /* relaxed read is enough as only the task itself sets ->in_idle */
2521 if (unlikely(atomic_read(&tctx->in_idle)))
2522 io_uring_drop_tctx_refs(current);
2525 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2527 struct task_struct *tsk = req->task;
2528 struct io_uring_task *tctx = tsk->io_uring;
2529 enum task_work_notify_mode notify;
2530 struct io_wq_work_node *node;
2531 unsigned long flags;
2534 WARN_ON_ONCE(!tctx);
2536 spin_lock_irqsave(&tctx->task_lock, flags);
2538 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2540 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2541 running = tctx->task_running;
2543 tctx->task_running = true;
2544 spin_unlock_irqrestore(&tctx->task_lock, flags);
2546 /* task_work already pending, we're done */
2551 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2552 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2553 * processing task_work. There's no reliable way to tell if TWA_RESUME
2556 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2557 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2558 if (notify == TWA_NONE)
2559 wake_up_process(tsk);
2563 spin_lock_irqsave(&tctx->task_lock, flags);
2564 tctx->task_running = false;
2565 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2566 spin_unlock_irqrestore(&tctx->task_lock, flags);
2569 req = container_of(node, struct io_kiocb, io_task_work.node);
2571 if (llist_add(&req->io_task_work.fallback_node,
2572 &req->ctx->fallback_llist))
2573 schedule_delayed_work(&req->ctx->fallback_work, 1);
2577 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2579 struct io_ring_ctx *ctx = req->ctx;
2581 /* not needed for normal modes, but SQPOLL depends on it */
2582 io_tw_lock(ctx, locked);
2583 io_req_complete_failed(req, req->result);
2586 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2588 struct io_ring_ctx *ctx = req->ctx;
2590 io_tw_lock(ctx, locked);
2591 /* req->task == current here, checking PF_EXITING is safe */
2592 if (likely(!(req->task->flags & PF_EXITING)))
2593 __io_queue_sqe(req);
2595 io_req_complete_failed(req, -EFAULT);
2598 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2601 req->io_task_work.func = io_req_task_cancel;
2602 io_req_task_work_add(req, false);
2605 static void io_req_task_queue(struct io_kiocb *req)
2607 req->io_task_work.func = io_req_task_submit;
2608 io_req_task_work_add(req, false);
2611 static void io_req_task_queue_reissue(struct io_kiocb *req)
2613 req->io_task_work.func = io_queue_async_work;
2614 io_req_task_work_add(req, false);
2617 static inline void io_queue_next(struct io_kiocb *req)
2619 struct io_kiocb *nxt = io_req_find_next(req);
2622 io_req_task_queue(nxt);
2625 static void io_free_req(struct io_kiocb *req)
2631 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2636 static void io_free_batch_list(struct io_ring_ctx *ctx,
2637 struct io_wq_work_node *node)
2638 __must_hold(&ctx->uring_lock)
2640 struct task_struct *task = NULL;
2644 struct io_kiocb *req = container_of(node, struct io_kiocb,
2647 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2648 node = req->comp_list.next;
2649 if (!req_ref_put_and_test(req))
2653 io_req_put_rsrc_locked(req, ctx);
2655 io_dismantle_req(req);
2657 if (req->task != task) {
2659 io_put_task(task, task_refs);
2664 node = req->comp_list.next;
2665 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2669 io_put_task(task, task_refs);
2672 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2673 __must_hold(&ctx->uring_lock)
2675 struct io_wq_work_node *node, *prev;
2676 struct io_submit_state *state = &ctx->submit_state;
2678 if (state->flush_cqes) {
2679 spin_lock(&ctx->completion_lock);
2680 wq_list_for_each(node, prev, &state->compl_reqs) {
2681 struct io_kiocb *req = container_of(node, struct io_kiocb,
2684 if (!(req->flags & REQ_F_CQE_SKIP))
2685 __io_fill_cqe_req(req, req->result, req->cflags);
2686 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2687 struct async_poll *apoll = req->apoll;
2689 if (apoll->double_poll)
2690 kfree(apoll->double_poll);
2691 list_add(&apoll->poll.wait.entry,
2693 req->flags &= ~REQ_F_POLLED;
2697 io_commit_cqring(ctx);
2698 spin_unlock(&ctx->completion_lock);
2699 io_cqring_ev_posted(ctx);
2700 state->flush_cqes = false;
2703 io_free_batch_list(ctx, state->compl_reqs.first);
2704 INIT_WQ_LIST(&state->compl_reqs);
2708 * Drop reference to request, return next in chain (if there is one) if this
2709 * was the last reference to this request.
2711 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2713 struct io_kiocb *nxt = NULL;
2715 if (req_ref_put_and_test(req)) {
2716 nxt = io_req_find_next(req);
2722 static inline void io_put_req(struct io_kiocb *req)
2724 if (req_ref_put_and_test(req))
2728 static inline void io_put_req_deferred(struct io_kiocb *req)
2730 if (req_ref_put_and_test(req)) {
2731 req->io_task_work.func = io_free_req_work;
2732 io_req_task_work_add(req, false);
2736 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2738 /* See comment at the top of this file */
2740 return __io_cqring_events(ctx);
2743 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2745 struct io_rings *rings = ctx->rings;
2747 /* make sure SQ entry isn't read before tail */
2748 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2751 static inline bool io_run_task_work(void)
2753 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2754 __set_current_state(TASK_RUNNING);
2755 tracehook_notify_signal();
2762 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2764 struct io_wq_work_node *pos, *start, *prev;
2765 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2766 DEFINE_IO_COMP_BATCH(iob);
2770 * Only spin for completions if we don't have multiple devices hanging
2771 * off our complete list.
2773 if (ctx->poll_multi_queue || force_nonspin)
2774 poll_flags |= BLK_POLL_ONESHOT;
2776 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2777 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2778 struct kiocb *kiocb = &req->rw.kiocb;
2782 * Move completed and retryable entries to our local lists.
2783 * If we find a request that requires polling, break out
2784 * and complete those lists first, if we have entries there.
2786 if (READ_ONCE(req->iopoll_completed))
2789 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2790 if (unlikely(ret < 0))
2793 poll_flags |= BLK_POLL_ONESHOT;
2795 /* iopoll may have completed current req */
2796 if (!rq_list_empty(iob.req_list) ||
2797 READ_ONCE(req->iopoll_completed))
2801 if (!rq_list_empty(iob.req_list))
2807 wq_list_for_each_resume(pos, prev) {
2808 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2810 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2811 if (!smp_load_acquire(&req->iopoll_completed))
2813 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2816 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
2820 if (unlikely(!nr_events))
2823 io_commit_cqring(ctx);
2824 io_cqring_ev_posted_iopoll(ctx);
2825 pos = start ? start->next : ctx->iopoll_list.first;
2826 wq_list_cut(&ctx->iopoll_list, prev, start);
2827 io_free_batch_list(ctx, pos);
2832 * We can't just wait for polled events to come to us, we have to actively
2833 * find and complete them.
2835 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2837 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2840 mutex_lock(&ctx->uring_lock);
2841 while (!wq_list_empty(&ctx->iopoll_list)) {
2842 /* let it sleep and repeat later if can't complete a request */
2843 if (io_do_iopoll(ctx, true) == 0)
2846 * Ensure we allow local-to-the-cpu processing to take place,
2847 * in this case we need to ensure that we reap all events.
2848 * Also let task_work, etc. to progress by releasing the mutex
2850 if (need_resched()) {
2851 mutex_unlock(&ctx->uring_lock);
2853 mutex_lock(&ctx->uring_lock);
2856 mutex_unlock(&ctx->uring_lock);
2859 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2861 unsigned int nr_events = 0;
2865 * We disallow the app entering submit/complete with polling, but we
2866 * still need to lock the ring to prevent racing with polled issue
2867 * that got punted to a workqueue.
2869 mutex_lock(&ctx->uring_lock);
2871 * Don't enter poll loop if we already have events pending.
2872 * If we do, we can potentially be spinning for commands that
2873 * already triggered a CQE (eg in error).
2875 if (test_bit(0, &ctx->check_cq_overflow))
2876 __io_cqring_overflow_flush(ctx, false);
2877 if (io_cqring_events(ctx))
2881 * If a submit got punted to a workqueue, we can have the
2882 * application entering polling for a command before it gets
2883 * issued. That app will hold the uring_lock for the duration
2884 * of the poll right here, so we need to take a breather every
2885 * now and then to ensure that the issue has a chance to add
2886 * the poll to the issued list. Otherwise we can spin here
2887 * forever, while the workqueue is stuck trying to acquire the
2890 if (wq_list_empty(&ctx->iopoll_list)) {
2891 u32 tail = ctx->cached_cq_tail;
2893 mutex_unlock(&ctx->uring_lock);
2895 mutex_lock(&ctx->uring_lock);
2897 /* some requests don't go through iopoll_list */
2898 if (tail != ctx->cached_cq_tail ||
2899 wq_list_empty(&ctx->iopoll_list))
2902 ret = io_do_iopoll(ctx, !min);
2907 } while (nr_events < min && !need_resched());
2909 mutex_unlock(&ctx->uring_lock);
2913 static void kiocb_end_write(struct io_kiocb *req)
2916 * Tell lockdep we inherited freeze protection from submission
2919 if (req->flags & REQ_F_ISREG) {
2920 struct super_block *sb = file_inode(req->file)->i_sb;
2922 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2928 static bool io_resubmit_prep(struct io_kiocb *req)
2930 struct io_async_rw *rw = req->async_data;
2932 if (!req_has_async_data(req))
2933 return !io_req_prep_async(req);
2934 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2938 static bool io_rw_should_reissue(struct io_kiocb *req)
2940 umode_t mode = file_inode(req->file)->i_mode;
2941 struct io_ring_ctx *ctx = req->ctx;
2943 if (!S_ISBLK(mode) && !S_ISREG(mode))
2945 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2946 !(ctx->flags & IORING_SETUP_IOPOLL)))
2949 * If ref is dying, we might be running poll reap from the exit work.
2950 * Don't attempt to reissue from that path, just let it fail with
2953 if (percpu_ref_is_dying(&ctx->refs))
2956 * Play it safe and assume not safe to re-import and reissue if we're
2957 * not in the original thread group (or in task context).
2959 if (!same_thread_group(req->task, current) || !in_task())
2964 static bool io_resubmit_prep(struct io_kiocb *req)
2968 static bool io_rw_should_reissue(struct io_kiocb *req)
2974 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2976 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2977 kiocb_end_write(req);
2978 if (unlikely(res != req->result)) {
2979 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2980 io_rw_should_reissue(req)) {
2981 req->flags |= REQ_F_REISSUE;
2990 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2992 int res = req->result;
2995 io_req_complete_state(req, res, io_put_kbuf(req, 0));
2996 io_req_add_compl_list(req);
2998 io_req_complete_post(req, res,
2999 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3003 static void __io_complete_rw(struct io_kiocb *req, long res,
3004 unsigned int issue_flags)
3006 if (__io_complete_rw_common(req, res))
3008 __io_req_complete(req, issue_flags, req->result,
3009 io_put_kbuf(req, issue_flags));
3012 static void io_complete_rw(struct kiocb *kiocb, long res)
3014 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3016 if (__io_complete_rw_common(req, res))
3019 req->io_task_work.func = io_req_task_complete;
3020 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
3023 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3025 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3027 if (kiocb->ki_flags & IOCB_WRITE)
3028 kiocb_end_write(req);
3029 if (unlikely(res != req->result)) {
3030 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3031 req->flags |= REQ_F_REISSUE;
3037 /* order with io_iopoll_complete() checking ->iopoll_completed */
3038 smp_store_release(&req->iopoll_completed, 1);
3042 * After the iocb has been issued, it's safe to be found on the poll list.
3043 * Adding the kiocb to the list AFTER submission ensures that we don't
3044 * find it from a io_do_iopoll() thread before the issuer is done
3045 * accessing the kiocb cookie.
3047 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3049 struct io_ring_ctx *ctx = req->ctx;
3050 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3052 /* workqueue context doesn't hold uring_lock, grab it now */
3053 if (unlikely(needs_lock))
3054 mutex_lock(&ctx->uring_lock);
3057 * Track whether we have multiple files in our lists. This will impact
3058 * how we do polling eventually, not spinning if we're on potentially
3059 * different devices.
3061 if (wq_list_empty(&ctx->iopoll_list)) {
3062 ctx->poll_multi_queue = false;
3063 } else if (!ctx->poll_multi_queue) {
3064 struct io_kiocb *list_req;
3066 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3068 if (list_req->file != req->file)
3069 ctx->poll_multi_queue = true;
3073 * For fast devices, IO may have already completed. If it has, add
3074 * it to the front so we find it first.
3076 if (READ_ONCE(req->iopoll_completed))
3077 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3079 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3081 if (unlikely(needs_lock)) {
3083 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3084 * in sq thread task context or in io worker task context. If
3085 * current task context is sq thread, we don't need to check
3086 * whether should wake up sq thread.
3088 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3089 wq_has_sleeper(&ctx->sq_data->wait))
3090 wake_up(&ctx->sq_data->wait);
3092 mutex_unlock(&ctx->uring_lock);
3096 static bool io_bdev_nowait(struct block_device *bdev)
3098 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3102 * If we tracked the file through the SCM inflight mechanism, we could support
3103 * any file. For now, just ensure that anything potentially problematic is done
3106 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3108 if (S_ISBLK(mode)) {
3109 if (IS_ENABLED(CONFIG_BLOCK) &&
3110 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3116 if (S_ISREG(mode)) {
3117 if (IS_ENABLED(CONFIG_BLOCK) &&
3118 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3119 file->f_op != &io_uring_fops)
3124 /* any ->read/write should understand O_NONBLOCK */
3125 if (file->f_flags & O_NONBLOCK)
3127 return file->f_mode & FMODE_NOWAIT;
3131 * If we tracked the file through the SCM inflight mechanism, we could support
3132 * any file. For now, just ensure that anything potentially problematic is done
3135 static unsigned int io_file_get_flags(struct file *file)
3137 umode_t mode = file_inode(file)->i_mode;
3138 unsigned int res = 0;
3142 if (__io_file_supports_nowait(file, mode))
3147 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3149 return req->flags & REQ_F_SUPPORT_NOWAIT;
3152 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3154 struct io_ring_ctx *ctx = req->ctx;
3155 struct kiocb *kiocb = &req->rw.kiocb;
3156 struct file *file = req->file;
3160 if (!io_req_ffs_set(req))
3161 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3163 kiocb->ki_pos = READ_ONCE(sqe->off);
3164 kiocb->ki_flags = iocb_flags(file);
3165 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3170 * If the file is marked O_NONBLOCK, still allow retry for it if it
3171 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3172 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3174 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3175 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3176 req->flags |= REQ_F_NOWAIT;
3178 if (ctx->flags & IORING_SETUP_IOPOLL) {
3179 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3182 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3183 kiocb->ki_complete = io_complete_rw_iopoll;
3184 req->iopoll_completed = 0;
3186 if (kiocb->ki_flags & IOCB_HIPRI)
3188 kiocb->ki_complete = io_complete_rw;
3191 ioprio = READ_ONCE(sqe->ioprio);
3193 ret = ioprio_check_cap(ioprio);
3197 kiocb->ki_ioprio = ioprio;
3199 kiocb->ki_ioprio = get_current_ioprio();
3203 req->rw.addr = READ_ONCE(sqe->addr);
3204 req->rw.len = READ_ONCE(sqe->len);
3205 req->buf_index = READ_ONCE(sqe->buf_index);
3209 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3215 case -ERESTARTNOINTR:
3216 case -ERESTARTNOHAND:
3217 case -ERESTART_RESTARTBLOCK:
3219 * We can't just restart the syscall, since previously
3220 * submitted sqes may already be in progress. Just fail this
3226 kiocb->ki_complete(kiocb, ret);
3230 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3232 struct kiocb *kiocb = &req->rw.kiocb;
3233 bool is_stream = req->file->f_mode & FMODE_STREAM;
3235 if (kiocb->ki_pos == -1) {
3237 req->flags |= REQ_F_CUR_POS;
3238 kiocb->ki_pos = req->file->f_pos;
3239 return &kiocb->ki_pos;
3245 return is_stream ? NULL : &kiocb->ki_pos;
3248 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3249 unsigned int issue_flags)
3251 struct io_async_rw *io = req->async_data;
3253 /* add previously done IO, if any */
3254 if (req_has_async_data(req) && io->bytes_done > 0) {
3256 ret = io->bytes_done;
3258 ret += io->bytes_done;
3261 if (req->flags & REQ_F_CUR_POS)
3262 req->file->f_pos = req->rw.kiocb.ki_pos;
3263 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3264 __io_complete_rw(req, ret, issue_flags);
3266 io_rw_done(&req->rw.kiocb, ret);
3268 if (req->flags & REQ_F_REISSUE) {
3269 req->flags &= ~REQ_F_REISSUE;
3270 if (io_resubmit_prep(req))
3271 io_req_task_queue_reissue(req);
3273 io_req_task_queue_fail(req, ret);
3277 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3278 struct io_mapped_ubuf *imu)
3280 size_t len = req->rw.len;
3281 u64 buf_end, buf_addr = req->rw.addr;
3284 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3286 /* not inside the mapped region */
3287 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3291 * May not be a start of buffer, set size appropriately
3292 * and advance us to the beginning.
3294 offset = buf_addr - imu->ubuf;
3295 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3299 * Don't use iov_iter_advance() here, as it's really slow for
3300 * using the latter parts of a big fixed buffer - it iterates
3301 * over each segment manually. We can cheat a bit here, because
3304 * 1) it's a BVEC iter, we set it up
3305 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3306 * first and last bvec
3308 * So just find our index, and adjust the iterator afterwards.
3309 * If the offset is within the first bvec (or the whole first
3310 * bvec, just use iov_iter_advance(). This makes it easier
3311 * since we can just skip the first segment, which may not
3312 * be PAGE_SIZE aligned.
3314 const struct bio_vec *bvec = imu->bvec;
3316 if (offset <= bvec->bv_len) {
3317 iov_iter_advance(iter, offset);
3319 unsigned long seg_skip;
3321 /* skip first vec */
3322 offset -= bvec->bv_len;
3323 seg_skip = 1 + (offset >> PAGE_SHIFT);
3325 iter->bvec = bvec + seg_skip;
3326 iter->nr_segs -= seg_skip;
3327 iter->count -= bvec->bv_len + offset;
3328 iter->iov_offset = offset & ~PAGE_MASK;
3335 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3337 struct io_mapped_ubuf *imu = req->imu;
3338 u16 index, buf_index = req->buf_index;
3341 struct io_ring_ctx *ctx = req->ctx;
3343 if (unlikely(buf_index >= ctx->nr_user_bufs))
3345 io_req_set_rsrc_node(req, ctx);
3346 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3347 imu = READ_ONCE(ctx->user_bufs[index]);
3350 return __io_import_fixed(req, rw, iter, imu);
3353 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3356 mutex_unlock(&ctx->uring_lock);
3359 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3362 * "Normal" inline submissions always hold the uring_lock, since we
3363 * grab it from the system call. Same is true for the SQPOLL offload.
3364 * The only exception is when we've detached the request and issue it
3365 * from an async worker thread, grab the lock for that case.
3368 mutex_lock(&ctx->uring_lock);
3371 static void io_buffer_add_list(struct io_ring_ctx *ctx,
3372 struct io_buffer_list *bl, unsigned int bgid)
3374 struct list_head *list;
3376 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3377 INIT_LIST_HEAD(&bl->buf_list);
3379 list_add(&bl->list, list);
3382 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3383 int bgid, unsigned int issue_flags)
3385 struct io_buffer *kbuf = req->kbuf;
3386 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3387 struct io_ring_ctx *ctx = req->ctx;
3388 struct io_buffer_list *bl;
3390 if (req->flags & REQ_F_BUFFER_SELECTED)
3393 io_ring_submit_lock(ctx, needs_lock);
3395 lockdep_assert_held(&ctx->uring_lock);
3397 bl = io_buffer_get_list(ctx, bgid);
3398 if (bl && !list_empty(&bl->buf_list)) {
3399 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3400 list_del(&kbuf->list);
3401 if (*len > kbuf->len)
3403 req->flags |= REQ_F_BUFFER_SELECTED;
3406 kbuf = ERR_PTR(-ENOBUFS);
3409 io_ring_submit_unlock(req->ctx, needs_lock);
3413 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3414 unsigned int issue_flags)
3416 struct io_buffer *kbuf;
3419 bgid = req->buf_index;
3420 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3423 return u64_to_user_ptr(kbuf->addr);
3426 #ifdef CONFIG_COMPAT
3427 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3428 unsigned int issue_flags)
3430 struct compat_iovec __user *uiov;
3431 compat_ssize_t clen;
3435 uiov = u64_to_user_ptr(req->rw.addr);
3436 if (!access_ok(uiov, sizeof(*uiov)))
3438 if (__get_user(clen, &uiov->iov_len))
3444 buf = io_rw_buffer_select(req, &len, issue_flags);
3446 return PTR_ERR(buf);
3447 iov[0].iov_base = buf;
3448 iov[0].iov_len = (compat_size_t) len;
3453 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3454 unsigned int issue_flags)
3456 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3460 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3463 len = iov[0].iov_len;
3466 buf = io_rw_buffer_select(req, &len, issue_flags);
3468 return PTR_ERR(buf);
3469 iov[0].iov_base = buf;
3470 iov[0].iov_len = len;
3474 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3475 unsigned int issue_flags)
3477 if (req->flags & REQ_F_BUFFER_SELECTED) {
3478 struct io_buffer *kbuf = req->kbuf;
3480 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3481 iov[0].iov_len = kbuf->len;
3484 if (req->rw.len != 1)
3487 #ifdef CONFIG_COMPAT
3488 if (req->ctx->compat)
3489 return io_compat_import(req, iov, issue_flags);
3492 return __io_iov_buffer_select(req, iov, issue_flags);
3495 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3496 struct io_rw_state *s,
3497 unsigned int issue_flags)
3499 struct iov_iter *iter = &s->iter;
3500 u8 opcode = req->opcode;
3501 struct iovec *iovec;
3506 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3507 ret = io_import_fixed(req, rw, iter);
3509 return ERR_PTR(ret);
3513 /* buffer index only valid with fixed read/write, or buffer select */
3514 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3515 return ERR_PTR(-EINVAL);
3517 buf = u64_to_user_ptr(req->rw.addr);
3518 sqe_len = req->rw.len;
3520 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3521 if (req->flags & REQ_F_BUFFER_SELECT) {
3522 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3524 return ERR_CAST(buf);
3525 req->rw.len = sqe_len;
3528 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3530 return ERR_PTR(ret);
3534 iovec = s->fast_iov;
3535 if (req->flags & REQ_F_BUFFER_SELECT) {
3536 ret = io_iov_buffer_select(req, iovec, issue_flags);
3538 return ERR_PTR(ret);
3539 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3543 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3545 if (unlikely(ret < 0))
3546 return ERR_PTR(ret);
3550 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3551 struct iovec **iovec, struct io_rw_state *s,
3552 unsigned int issue_flags)
3554 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3555 if (unlikely(IS_ERR(*iovec)))
3556 return PTR_ERR(*iovec);
3558 iov_iter_save_state(&s->iter, &s->iter_state);
3562 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3564 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3568 * For files that don't have ->read_iter() and ->write_iter(), handle them
3569 * by looping over ->read() or ->write() manually.
3571 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3573 struct kiocb *kiocb = &req->rw.kiocb;
3574 struct file *file = req->file;
3579 * Don't support polled IO through this interface, and we can't
3580 * support non-blocking either. For the latter, this just causes
3581 * the kiocb to be handled from an async context.
3583 if (kiocb->ki_flags & IOCB_HIPRI)
3585 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3586 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3589 ppos = io_kiocb_ppos(kiocb);
3591 while (iov_iter_count(iter)) {
3595 if (!iov_iter_is_bvec(iter)) {
3596 iovec = iov_iter_iovec(iter);
3598 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3599 iovec.iov_len = req->rw.len;
3603 nr = file->f_op->read(file, iovec.iov_base,
3604 iovec.iov_len, ppos);
3606 nr = file->f_op->write(file, iovec.iov_base,
3607 iovec.iov_len, ppos);
3616 if (!iov_iter_is_bvec(iter)) {
3617 iov_iter_advance(iter, nr);
3624 if (nr != iovec.iov_len)
3631 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3632 const struct iovec *fast_iov, struct iov_iter *iter)
3634 struct io_async_rw *rw = req->async_data;
3636 memcpy(&rw->s.iter, iter, sizeof(*iter));
3637 rw->free_iovec = iovec;
3639 /* can only be fixed buffers, no need to do anything */
3640 if (iov_iter_is_bvec(iter))
3643 unsigned iov_off = 0;
3645 rw->s.iter.iov = rw->s.fast_iov;
3646 if (iter->iov != fast_iov) {
3647 iov_off = iter->iov - fast_iov;
3648 rw->s.iter.iov += iov_off;
3650 if (rw->s.fast_iov != fast_iov)
3651 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3652 sizeof(struct iovec) * iter->nr_segs);
3654 req->flags |= REQ_F_NEED_CLEANUP;
3658 static inline bool io_alloc_async_data(struct io_kiocb *req)
3660 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3661 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3662 if (req->async_data) {
3663 req->flags |= REQ_F_ASYNC_DATA;
3669 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3670 struct io_rw_state *s, bool force)
3672 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3674 if (!req_has_async_data(req)) {
3675 struct io_async_rw *iorw;
3677 if (io_alloc_async_data(req)) {
3682 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3683 iorw = req->async_data;
3684 /* we've copied and mapped the iter, ensure state is saved */
3685 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3690 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3692 struct io_async_rw *iorw = req->async_data;
3696 /* submission path, ->uring_lock should already be taken */
3697 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3698 if (unlikely(ret < 0))
3701 iorw->bytes_done = 0;
3702 iorw->free_iovec = iov;
3704 req->flags |= REQ_F_NEED_CLEANUP;
3708 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3710 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3712 return io_prep_rw(req, sqe);
3716 * This is our waitqueue callback handler, registered through __folio_lock_async()
3717 * when we initially tried to do the IO with the iocb armed our waitqueue.
3718 * This gets called when the page is unlocked, and we generally expect that to
3719 * happen when the page IO is completed and the page is now uptodate. This will
3720 * queue a task_work based retry of the operation, attempting to copy the data
3721 * again. If the latter fails because the page was NOT uptodate, then we will
3722 * do a thread based blocking retry of the operation. That's the unexpected
3725 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3726 int sync, void *arg)
3728 struct wait_page_queue *wpq;
3729 struct io_kiocb *req = wait->private;
3730 struct wait_page_key *key = arg;
3732 wpq = container_of(wait, struct wait_page_queue, wait);
3734 if (!wake_page_match(wpq, key))
3737 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3738 list_del_init(&wait->entry);
3739 io_req_task_queue(req);
3744 * This controls whether a given IO request should be armed for async page
3745 * based retry. If we return false here, the request is handed to the async
3746 * worker threads for retry. If we're doing buffered reads on a regular file,
3747 * we prepare a private wait_page_queue entry and retry the operation. This
3748 * will either succeed because the page is now uptodate and unlocked, or it
3749 * will register a callback when the page is unlocked at IO completion. Through
3750 * that callback, io_uring uses task_work to setup a retry of the operation.
3751 * That retry will attempt the buffered read again. The retry will generally
3752 * succeed, or in rare cases where it fails, we then fall back to using the
3753 * async worker threads for a blocking retry.
3755 static bool io_rw_should_retry(struct io_kiocb *req)
3757 struct io_async_rw *rw = req->async_data;
3758 struct wait_page_queue *wait = &rw->wpq;
3759 struct kiocb *kiocb = &req->rw.kiocb;
3761 /* never retry for NOWAIT, we just complete with -EAGAIN */
3762 if (req->flags & REQ_F_NOWAIT)
3765 /* Only for buffered IO */
3766 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3770 * just use poll if we can, and don't attempt if the fs doesn't
3771 * support callback based unlocks
3773 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3776 wait->wait.func = io_async_buf_func;
3777 wait->wait.private = req;
3778 wait->wait.flags = 0;
3779 INIT_LIST_HEAD(&wait->wait.entry);
3780 kiocb->ki_flags |= IOCB_WAITQ;
3781 kiocb->ki_flags &= ~IOCB_NOWAIT;
3782 kiocb->ki_waitq = wait;
3786 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3788 if (likely(req->file->f_op->read_iter))
3789 return call_read_iter(req->file, &req->rw.kiocb, iter);
3790 else if (req->file->f_op->read)
3791 return loop_rw_iter(READ, req, iter);
3796 static bool need_read_all(struct io_kiocb *req)
3798 return req->flags & REQ_F_ISREG ||
3799 S_ISBLK(file_inode(req->file)->i_mode);
3802 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3804 struct io_rw_state __s, *s = &__s;
3805 struct iovec *iovec;
3806 struct kiocb *kiocb = &req->rw.kiocb;
3807 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3808 struct io_async_rw *rw;
3812 if (!req_has_async_data(req)) {
3813 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3814 if (unlikely(ret < 0))
3818 * Safe and required to re-import if we're using provided
3819 * buffers, as we dropped the selected one before retry.
3821 if (req->flags & REQ_F_BUFFER_SELECT) {
3822 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3823 if (unlikely(ret < 0))
3827 rw = req->async_data;
3830 * We come here from an earlier attempt, restore our state to
3831 * match in case it doesn't. It's cheap enough that we don't
3832 * need to make this conditional.
3834 iov_iter_restore(&s->iter, &s->iter_state);
3837 req->result = iov_iter_count(&s->iter);
3839 if (force_nonblock) {
3840 /* If the file doesn't support async, just async punt */
3841 if (unlikely(!io_file_supports_nowait(req))) {
3842 ret = io_setup_async_rw(req, iovec, s, true);
3843 return ret ?: -EAGAIN;
3845 kiocb->ki_flags |= IOCB_NOWAIT;
3847 /* Ensure we clear previously set non-block flag */
3848 kiocb->ki_flags &= ~IOCB_NOWAIT;
3851 ppos = io_kiocb_update_pos(req);
3853 ret = rw_verify_area(READ, req->file, ppos, req->result);
3854 if (unlikely(ret)) {
3859 ret = io_iter_do_read(req, &s->iter);
3861 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3862 req->flags &= ~REQ_F_REISSUE;
3863 /* if we can poll, just do that */
3864 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3866 /* IOPOLL retry should happen for io-wq threads */
3867 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3869 /* no retry on NONBLOCK nor RWF_NOWAIT */
3870 if (req->flags & REQ_F_NOWAIT)
3873 } else if (ret == -EIOCBQUEUED) {
3875 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3876 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3877 /* read all, failed, already did sync or don't want to retry */
3882 * Don't depend on the iter state matching what was consumed, or being
3883 * untouched in case of error. Restore it and we'll advance it
3884 * manually if we need to.
3886 iov_iter_restore(&s->iter, &s->iter_state);
3888 ret2 = io_setup_async_rw(req, iovec, s, true);
3893 rw = req->async_data;
3896 * Now use our persistent iterator and state, if we aren't already.
3897 * We've restored and mapped the iter to match.
3902 * We end up here because of a partial read, either from
3903 * above or inside this loop. Advance the iter by the bytes
3904 * that were consumed.
3906 iov_iter_advance(&s->iter, ret);
3907 if (!iov_iter_count(&s->iter))
3909 rw->bytes_done += ret;
3910 iov_iter_save_state(&s->iter, &s->iter_state);
3912 /* if we can retry, do so with the callbacks armed */
3913 if (!io_rw_should_retry(req)) {
3914 kiocb->ki_flags &= ~IOCB_WAITQ;
3919 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3920 * we get -EIOCBQUEUED, then we'll get a notification when the
3921 * desired page gets unlocked. We can also get a partial read
3922 * here, and if we do, then just retry at the new offset.
3924 ret = io_iter_do_read(req, &s->iter);
3925 if (ret == -EIOCBQUEUED)
3927 /* we got some bytes, but not all. retry. */
3928 kiocb->ki_flags &= ~IOCB_WAITQ;
3929 iov_iter_restore(&s->iter, &s->iter_state);
3932 kiocb_done(req, ret, issue_flags);
3934 /* it's faster to check here then delegate to kfree */
3940 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3942 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3944 return io_prep_rw(req, sqe);
3947 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3949 struct io_rw_state __s, *s = &__s;
3950 struct iovec *iovec;
3951 struct kiocb *kiocb = &req->rw.kiocb;
3952 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3956 if (!req_has_async_data(req)) {
3957 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3958 if (unlikely(ret < 0))
3961 struct io_async_rw *rw = req->async_data;
3964 iov_iter_restore(&s->iter, &s->iter_state);
3967 req->result = iov_iter_count(&s->iter);
3969 if (force_nonblock) {
3970 /* If the file doesn't support async, just async punt */
3971 if (unlikely(!io_file_supports_nowait(req)))
3974 /* file path doesn't support NOWAIT for non-direct_IO */
3975 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3976 (req->flags & REQ_F_ISREG))
3979 kiocb->ki_flags |= IOCB_NOWAIT;
3981 /* Ensure we clear previously set non-block flag */
3982 kiocb->ki_flags &= ~IOCB_NOWAIT;
3985 ppos = io_kiocb_update_pos(req);
3987 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3992 * Open-code file_start_write here to grab freeze protection,
3993 * which will be released by another thread in
3994 * io_complete_rw(). Fool lockdep by telling it the lock got
3995 * released so that it doesn't complain about the held lock when
3996 * we return to userspace.
3998 if (req->flags & REQ_F_ISREG) {
3999 sb_start_write(file_inode(req->file)->i_sb);
4000 __sb_writers_release(file_inode(req->file)->i_sb,
4003 kiocb->ki_flags |= IOCB_WRITE;
4005 if (likely(req->file->f_op->write_iter))
4006 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4007 else if (req->file->f_op->write)
4008 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4012 if (req->flags & REQ_F_REISSUE) {
4013 req->flags &= ~REQ_F_REISSUE;
4018 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4019 * retry them without IOCB_NOWAIT.
4021 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4023 /* no retry on NONBLOCK nor RWF_NOWAIT */
4024 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4026 if (!force_nonblock || ret2 != -EAGAIN) {
4027 /* IOPOLL retry should happen for io-wq threads */
4028 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4031 kiocb_done(req, ret2, issue_flags);
4034 iov_iter_restore(&s->iter, &s->iter_state);
4035 ret = io_setup_async_rw(req, iovec, s, false);
4036 return ret ?: -EAGAIN;
4039 /* it's reportedly faster than delegating the null check to kfree() */
4045 static int io_renameat_prep(struct io_kiocb *req,
4046 const struct io_uring_sqe *sqe)
4048 struct io_rename *ren = &req->rename;
4049 const char __user *oldf, *newf;
4051 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4053 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4055 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4058 ren->old_dfd = READ_ONCE(sqe->fd);
4059 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4060 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4061 ren->new_dfd = READ_ONCE(sqe->len);
4062 ren->flags = READ_ONCE(sqe->rename_flags);
4064 ren->oldpath = getname(oldf);
4065 if (IS_ERR(ren->oldpath))
4066 return PTR_ERR(ren->oldpath);
4068 ren->newpath = getname(newf);
4069 if (IS_ERR(ren->newpath)) {
4070 putname(ren->oldpath);
4071 return PTR_ERR(ren->newpath);
4074 req->flags |= REQ_F_NEED_CLEANUP;
4078 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4080 struct io_rename *ren = &req->rename;
4083 if (issue_flags & IO_URING_F_NONBLOCK)
4086 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4087 ren->newpath, ren->flags);
4089 req->flags &= ~REQ_F_NEED_CLEANUP;
4092 io_req_complete(req, ret);
4096 static int io_unlinkat_prep(struct io_kiocb *req,
4097 const struct io_uring_sqe *sqe)
4099 struct io_unlink *un = &req->unlink;
4100 const char __user *fname;
4102 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4104 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4107 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4110 un->dfd = READ_ONCE(sqe->fd);
4112 un->flags = READ_ONCE(sqe->unlink_flags);
4113 if (un->flags & ~AT_REMOVEDIR)
4116 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4117 un->filename = getname(fname);
4118 if (IS_ERR(un->filename))
4119 return PTR_ERR(un->filename);
4121 req->flags |= REQ_F_NEED_CLEANUP;
4125 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4127 struct io_unlink *un = &req->unlink;
4130 if (issue_flags & IO_URING_F_NONBLOCK)
4133 if (un->flags & AT_REMOVEDIR)
4134 ret = do_rmdir(un->dfd, un->filename);
4136 ret = do_unlinkat(un->dfd, un->filename);
4138 req->flags &= ~REQ_F_NEED_CLEANUP;
4141 io_req_complete(req, ret);
4145 static int io_mkdirat_prep(struct io_kiocb *req,
4146 const struct io_uring_sqe *sqe)
4148 struct io_mkdir *mkd = &req->mkdir;
4149 const char __user *fname;
4151 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4153 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4156 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4159 mkd->dfd = READ_ONCE(sqe->fd);
4160 mkd->mode = READ_ONCE(sqe->len);
4162 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4163 mkd->filename = getname(fname);
4164 if (IS_ERR(mkd->filename))
4165 return PTR_ERR(mkd->filename);
4167 req->flags |= REQ_F_NEED_CLEANUP;
4171 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4173 struct io_mkdir *mkd = &req->mkdir;
4176 if (issue_flags & IO_URING_F_NONBLOCK)
4179 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4181 req->flags &= ~REQ_F_NEED_CLEANUP;
4184 io_req_complete(req, ret);
4188 static int io_symlinkat_prep(struct io_kiocb *req,
4189 const struct io_uring_sqe *sqe)
4191 struct io_symlink *sl = &req->symlink;
4192 const char __user *oldpath, *newpath;
4194 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4196 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4199 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4202 sl->new_dfd = READ_ONCE(sqe->fd);
4203 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4204 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4206 sl->oldpath = getname(oldpath);
4207 if (IS_ERR(sl->oldpath))
4208 return PTR_ERR(sl->oldpath);
4210 sl->newpath = getname(newpath);
4211 if (IS_ERR(sl->newpath)) {
4212 putname(sl->oldpath);
4213 return PTR_ERR(sl->newpath);
4216 req->flags |= REQ_F_NEED_CLEANUP;
4220 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4222 struct io_symlink *sl = &req->symlink;
4225 if (issue_flags & IO_URING_F_NONBLOCK)
4228 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4230 req->flags &= ~REQ_F_NEED_CLEANUP;
4233 io_req_complete(req, ret);
4237 static int io_linkat_prep(struct io_kiocb *req,
4238 const struct io_uring_sqe *sqe)
4240 struct io_hardlink *lnk = &req->hardlink;
4241 const char __user *oldf, *newf;
4243 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4245 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4247 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4250 lnk->old_dfd = READ_ONCE(sqe->fd);
4251 lnk->new_dfd = READ_ONCE(sqe->len);
4252 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4253 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4254 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4256 lnk->oldpath = getname(oldf);
4257 if (IS_ERR(lnk->oldpath))
4258 return PTR_ERR(lnk->oldpath);
4260 lnk->newpath = getname(newf);
4261 if (IS_ERR(lnk->newpath)) {
4262 putname(lnk->oldpath);
4263 return PTR_ERR(lnk->newpath);
4266 req->flags |= REQ_F_NEED_CLEANUP;
4270 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4272 struct io_hardlink *lnk = &req->hardlink;
4275 if (issue_flags & IO_URING_F_NONBLOCK)
4278 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4279 lnk->newpath, lnk->flags);
4281 req->flags &= ~REQ_F_NEED_CLEANUP;
4284 io_req_complete(req, ret);
4288 static int io_shutdown_prep(struct io_kiocb *req,
4289 const struct io_uring_sqe *sqe)
4291 #if defined(CONFIG_NET)
4292 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4294 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4295 sqe->buf_index || sqe->splice_fd_in))
4298 req->shutdown.how = READ_ONCE(sqe->len);
4305 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4307 #if defined(CONFIG_NET)
4308 struct socket *sock;
4311 if (issue_flags & IO_URING_F_NONBLOCK)
4314 sock = sock_from_file(req->file);
4315 if (unlikely(!sock))
4318 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4321 io_req_complete(req, ret);
4328 static int __io_splice_prep(struct io_kiocb *req,
4329 const struct io_uring_sqe *sqe)
4331 struct io_splice *sp = &req->splice;
4332 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4334 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4338 sp->len = READ_ONCE(sqe->len);
4339 sp->flags = READ_ONCE(sqe->splice_flags);
4341 if (unlikely(sp->flags & ~valid_flags))
4344 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4345 (sp->flags & SPLICE_F_FD_IN_FIXED));
4348 req->flags |= REQ_F_NEED_CLEANUP;
4352 static int io_tee_prep(struct io_kiocb *req,
4353 const struct io_uring_sqe *sqe)
4355 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4357 return __io_splice_prep(req, sqe);
4360 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4362 struct io_splice *sp = &req->splice;
4363 struct file *in = sp->file_in;
4364 struct file *out = sp->file_out;
4365 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4368 if (issue_flags & IO_URING_F_NONBLOCK)
4371 ret = do_tee(in, out, sp->len, flags);
4373 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4375 req->flags &= ~REQ_F_NEED_CLEANUP;
4379 io_req_complete(req, ret);
4383 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4385 struct io_splice *sp = &req->splice;
4387 sp->off_in = READ_ONCE(sqe->splice_off_in);
4388 sp->off_out = READ_ONCE(sqe->off);
4389 return __io_splice_prep(req, sqe);
4392 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4394 struct io_splice *sp = &req->splice;
4395 struct file *in = sp->file_in;
4396 struct file *out = sp->file_out;
4397 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4398 loff_t *poff_in, *poff_out;
4401 if (issue_flags & IO_URING_F_NONBLOCK)
4404 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4405 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4408 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4410 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4412 req->flags &= ~REQ_F_NEED_CLEANUP;
4416 io_req_complete(req, ret);
4421 * IORING_OP_NOP just posts a completion event, nothing else.
4423 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4425 struct io_ring_ctx *ctx = req->ctx;
4427 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4430 __io_req_complete(req, issue_flags, 0, 0);
4434 static int io_msg_ring_prep(struct io_kiocb *req,
4435 const struct io_uring_sqe *sqe)
4437 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4438 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4441 if (req->file->f_op != &io_uring_fops)
4444 req->msg.user_data = READ_ONCE(sqe->off);
4445 req->msg.len = READ_ONCE(sqe->len);
4449 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4451 struct io_ring_ctx *target_ctx;
4452 struct io_msg *msg = &req->msg;
4453 int ret = -EOVERFLOW;
4456 target_ctx = req->file->private_data;
4458 spin_lock(&target_ctx->completion_lock);
4459 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len,
4461 io_commit_cqring(target_ctx);
4462 spin_unlock(&target_ctx->completion_lock);
4465 io_cqring_ev_posted(target_ctx);
4469 __io_req_complete(req, issue_flags, ret, 0);
4473 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4475 struct io_ring_ctx *ctx = req->ctx;
4480 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4482 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4486 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4487 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4490 req->sync.off = READ_ONCE(sqe->off);
4491 req->sync.len = READ_ONCE(sqe->len);
4495 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4497 loff_t end = req->sync.off + req->sync.len;
4500 /* fsync always requires a blocking context */
4501 if (issue_flags & IO_URING_F_NONBLOCK)
4504 ret = vfs_fsync_range(req->file, req->sync.off,
4505 end > 0 ? end : LLONG_MAX,
4506 req->sync.flags & IORING_FSYNC_DATASYNC);
4509 io_req_complete(req, ret);
4513 static int io_fallocate_prep(struct io_kiocb *req,
4514 const struct io_uring_sqe *sqe)
4516 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4519 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4522 req->sync.off = READ_ONCE(sqe->off);
4523 req->sync.len = READ_ONCE(sqe->addr);
4524 req->sync.mode = READ_ONCE(sqe->len);
4528 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4532 /* fallocate always requiring blocking context */
4533 if (issue_flags & IO_URING_F_NONBLOCK)
4535 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4539 io_req_complete(req, ret);
4543 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4545 const char __user *fname;
4548 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4550 if (unlikely(sqe->ioprio || sqe->buf_index))
4552 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4555 /* open.how should be already initialised */
4556 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4557 req->open.how.flags |= O_LARGEFILE;
4559 req->open.dfd = READ_ONCE(sqe->fd);
4560 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4561 req->open.filename = getname(fname);
4562 if (IS_ERR(req->open.filename)) {
4563 ret = PTR_ERR(req->open.filename);
4564 req->open.filename = NULL;
4568 req->open.file_slot = READ_ONCE(sqe->file_index);
4569 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4572 req->open.nofile = rlimit(RLIMIT_NOFILE);
4573 req->flags |= REQ_F_NEED_CLEANUP;
4577 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4579 u64 mode = READ_ONCE(sqe->len);
4580 u64 flags = READ_ONCE(sqe->open_flags);
4582 req->open.how = build_open_how(flags, mode);
4583 return __io_openat_prep(req, sqe);
4586 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4588 struct open_how __user *how;
4592 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4593 len = READ_ONCE(sqe->len);
4594 if (len < OPEN_HOW_SIZE_VER0)
4597 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4602 return __io_openat_prep(req, sqe);
4605 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4607 struct open_flags op;
4609 bool resolve_nonblock, nonblock_set;
4610 bool fixed = !!req->open.file_slot;
4613 ret = build_open_flags(&req->open.how, &op);
4616 nonblock_set = op.open_flag & O_NONBLOCK;
4617 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4618 if (issue_flags & IO_URING_F_NONBLOCK) {
4620 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4621 * it'll always -EAGAIN
4623 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4625 op.lookup_flags |= LOOKUP_CACHED;
4626 op.open_flag |= O_NONBLOCK;
4630 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4635 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4638 * We could hang on to this 'fd' on retrying, but seems like
4639 * marginal gain for something that is now known to be a slower
4640 * path. So just put it, and we'll get a new one when we retry.
4645 ret = PTR_ERR(file);
4646 /* only retry if RESOLVE_CACHED wasn't already set by application */
4647 if (ret == -EAGAIN &&
4648 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4653 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4654 file->f_flags &= ~O_NONBLOCK;
4655 fsnotify_open(file);
4658 fd_install(ret, file);
4660 ret = io_install_fixed_file(req, file, issue_flags,
4661 req->open.file_slot - 1);
4663 putname(req->open.filename);
4664 req->flags &= ~REQ_F_NEED_CLEANUP;
4667 __io_req_complete(req, issue_flags, ret, 0);
4671 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4673 return io_openat2(req, issue_flags);
4676 static int io_remove_buffers_prep(struct io_kiocb *req,
4677 const struct io_uring_sqe *sqe)
4679 struct io_provide_buf *p = &req->pbuf;
4682 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4686 tmp = READ_ONCE(sqe->fd);
4687 if (!tmp || tmp > USHRT_MAX)
4690 memset(p, 0, sizeof(*p));
4692 p->bgid = READ_ONCE(sqe->buf_group);
4696 static int __io_remove_buffers(struct io_ring_ctx *ctx,
4697 struct io_buffer_list *bl, unsigned nbufs)
4701 /* shouldn't happen */
4705 /* the head kbuf is the list itself */
4706 while (!list_empty(&bl->buf_list)) {
4707 struct io_buffer *nxt;
4709 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
4710 list_del(&nxt->list);
4720 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4722 struct io_provide_buf *p = &req->pbuf;
4723 struct io_ring_ctx *ctx = req->ctx;
4724 struct io_buffer_list *bl;
4726 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4728 io_ring_submit_lock(ctx, needs_lock);
4730 lockdep_assert_held(&ctx->uring_lock);
4733 bl = io_buffer_get_list(ctx, p->bgid);
4735 ret = __io_remove_buffers(ctx, bl, p->nbufs);
4739 /* complete before unlock, IOPOLL may need the lock */
4740 __io_req_complete(req, issue_flags, ret, 0);
4741 io_ring_submit_unlock(ctx, needs_lock);
4745 static int io_provide_buffers_prep(struct io_kiocb *req,
4746 const struct io_uring_sqe *sqe)
4748 unsigned long size, tmp_check;
4749 struct io_provide_buf *p = &req->pbuf;
4752 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4755 tmp = READ_ONCE(sqe->fd);
4756 if (!tmp || tmp > USHRT_MAX)
4759 p->addr = READ_ONCE(sqe->addr);
4760 p->len = READ_ONCE(sqe->len);
4762 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4765 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4768 size = (unsigned long)p->len * p->nbufs;
4769 if (!access_ok(u64_to_user_ptr(p->addr), size))
4772 p->bgid = READ_ONCE(sqe->buf_group);
4773 tmp = READ_ONCE(sqe->off);
4774 if (tmp > USHRT_MAX)
4780 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4782 struct io_buffer *buf;
4787 * Completions that don't happen inline (eg not under uring_lock) will
4788 * add to ->io_buffers_comp. If we don't have any free buffers, check
4789 * the completion list and splice those entries first.
4791 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4792 spin_lock(&ctx->completion_lock);
4793 if (!list_empty(&ctx->io_buffers_comp)) {
4794 list_splice_init(&ctx->io_buffers_comp,
4795 &ctx->io_buffers_cache);
4796 spin_unlock(&ctx->completion_lock);
4799 spin_unlock(&ctx->completion_lock);
4803 * No free buffers and no completion entries either. Allocate a new
4804 * page worth of buffer entries and add those to our freelist.
4806 page = alloc_page(GFP_KERNEL_ACCOUNT);
4810 list_add(&page->lru, &ctx->io_buffers_pages);
4812 buf = page_address(page);
4813 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4814 while (bufs_in_page) {
4815 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4823 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4824 struct io_buffer_list *bl)
4826 struct io_buffer *buf;
4827 u64 addr = pbuf->addr;
4828 int i, bid = pbuf->bid;
4830 for (i = 0; i < pbuf->nbufs; i++) {
4831 if (list_empty(&ctx->io_buffers_cache) &&
4832 io_refill_buffer_cache(ctx))
4834 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4836 list_move_tail(&buf->list, &bl->buf_list);
4838 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4840 buf->bgid = pbuf->bgid;
4846 return i ? 0 : -ENOMEM;
4849 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4851 struct io_provide_buf *p = &req->pbuf;
4852 struct io_ring_ctx *ctx = req->ctx;
4853 struct io_buffer_list *bl;
4855 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4857 io_ring_submit_lock(ctx, needs_lock);
4859 lockdep_assert_held(&ctx->uring_lock);
4861 bl = io_buffer_get_list(ctx, p->bgid);
4862 if (unlikely(!bl)) {
4863 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4868 io_buffer_add_list(ctx, bl, p->bgid);
4871 ret = io_add_buffers(ctx, p, bl);
4875 /* complete before unlock, IOPOLL may need the lock */
4876 __io_req_complete(req, issue_flags, ret, 0);
4877 io_ring_submit_unlock(ctx, needs_lock);
4881 static int io_epoll_ctl_prep(struct io_kiocb *req,
4882 const struct io_uring_sqe *sqe)
4884 #if defined(CONFIG_EPOLL)
4885 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4887 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4890 req->epoll.epfd = READ_ONCE(sqe->fd);
4891 req->epoll.op = READ_ONCE(sqe->len);
4892 req->epoll.fd = READ_ONCE(sqe->off);
4894 if (ep_op_has_event(req->epoll.op)) {
4895 struct epoll_event __user *ev;
4897 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4898 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4908 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4910 #if defined(CONFIG_EPOLL)
4911 struct io_epoll *ie = &req->epoll;
4913 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4915 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4916 if (force_nonblock && ret == -EAGAIN)
4921 __io_req_complete(req, issue_flags, ret, 0);
4928 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4930 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4931 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4933 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4936 req->madvise.addr = READ_ONCE(sqe->addr);
4937 req->madvise.len = READ_ONCE(sqe->len);
4938 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4945 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4947 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4948 struct io_madvise *ma = &req->madvise;
4951 if (issue_flags & IO_URING_F_NONBLOCK)
4954 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4957 io_req_complete(req, ret);
4964 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4966 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4968 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4971 req->fadvise.offset = READ_ONCE(sqe->off);
4972 req->fadvise.len = READ_ONCE(sqe->len);
4973 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4977 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4979 struct io_fadvise *fa = &req->fadvise;
4982 if (issue_flags & IO_URING_F_NONBLOCK) {
4983 switch (fa->advice) {
4984 case POSIX_FADV_NORMAL:
4985 case POSIX_FADV_RANDOM:
4986 case POSIX_FADV_SEQUENTIAL:
4993 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4996 __io_req_complete(req, issue_flags, ret, 0);
5000 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5002 const char __user *path;
5004 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5006 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5008 if (req->flags & REQ_F_FIXED_FILE)
5011 req->statx.dfd = READ_ONCE(sqe->fd);
5012 req->statx.mask = READ_ONCE(sqe->len);
5013 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5014 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5015 req->statx.flags = READ_ONCE(sqe->statx_flags);
5017 req->statx.filename = getname_flags(path,
5018 getname_statx_lookup_flags(req->statx.flags),
5021 if (IS_ERR(req->statx.filename)) {
5022 int ret = PTR_ERR(req->statx.filename);
5024 req->statx.filename = NULL;
5028 req->flags |= REQ_F_NEED_CLEANUP;
5032 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5034 struct io_statx *ctx = &req->statx;
5037 if (issue_flags & IO_URING_F_NONBLOCK)
5040 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5045 io_req_complete(req, ret);
5049 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5051 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5053 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5054 sqe->rw_flags || sqe->buf_index)
5056 if (req->flags & REQ_F_FIXED_FILE)
5059 req->close.fd = READ_ONCE(sqe->fd);
5060 req->close.file_slot = READ_ONCE(sqe->file_index);
5061 if (req->close.file_slot && req->close.fd)
5067 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5069 struct files_struct *files = current->files;
5070 struct io_close *close = &req->close;
5071 struct fdtable *fdt;
5072 struct file *file = NULL;
5075 if (req->close.file_slot) {
5076 ret = io_close_fixed(req, issue_flags);
5080 spin_lock(&files->file_lock);
5081 fdt = files_fdtable(files);
5082 if (close->fd >= fdt->max_fds) {
5083 spin_unlock(&files->file_lock);
5086 file = fdt->fd[close->fd];
5087 if (!file || file->f_op == &io_uring_fops) {
5088 spin_unlock(&files->file_lock);
5093 /* if the file has a flush method, be safe and punt to async */
5094 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5095 spin_unlock(&files->file_lock);
5099 ret = __close_fd_get_file(close->fd, &file);
5100 spin_unlock(&files->file_lock);
5107 /* No ->flush() or already async, safely close from here */
5108 ret = filp_close(file, current->files);
5114 __io_req_complete(req, issue_flags, ret, 0);
5118 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5120 struct io_ring_ctx *ctx = req->ctx;
5122 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5124 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5128 req->sync.off = READ_ONCE(sqe->off);
5129 req->sync.len = READ_ONCE(sqe->len);
5130 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5134 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5138 /* sync_file_range always requires a blocking context */
5139 if (issue_flags & IO_URING_F_NONBLOCK)
5142 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5146 io_req_complete(req, ret);
5150 #if defined(CONFIG_NET)
5151 static int io_setup_async_msg(struct io_kiocb *req,
5152 struct io_async_msghdr *kmsg)
5154 struct io_async_msghdr *async_msg = req->async_data;
5158 if (io_alloc_async_data(req)) {
5159 kfree(kmsg->free_iov);
5162 async_msg = req->async_data;
5163 req->flags |= REQ_F_NEED_CLEANUP;
5164 memcpy(async_msg, kmsg, sizeof(*kmsg));
5165 async_msg->msg.msg_name = &async_msg->addr;
5166 /* if were using fast_iov, set it to the new one */
5167 if (!async_msg->free_iov)
5168 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5173 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5174 struct io_async_msghdr *iomsg)
5176 iomsg->msg.msg_name = &iomsg->addr;
5177 iomsg->free_iov = iomsg->fast_iov;
5178 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5179 req->sr_msg.msg_flags, &iomsg->free_iov);
5182 static int io_sendmsg_prep_async(struct io_kiocb *req)
5186 ret = io_sendmsg_copy_hdr(req, req->async_data);
5188 req->flags |= REQ_F_NEED_CLEANUP;
5192 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5194 struct io_sr_msg *sr = &req->sr_msg;
5196 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5199 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5200 sr->len = READ_ONCE(sqe->len);
5201 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5202 if (sr->msg_flags & MSG_DONTWAIT)
5203 req->flags |= REQ_F_NOWAIT;
5205 #ifdef CONFIG_COMPAT
5206 if (req->ctx->compat)
5207 sr->msg_flags |= MSG_CMSG_COMPAT;
5212 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5214 struct io_async_msghdr iomsg, *kmsg;
5215 struct socket *sock;
5220 sock = sock_from_file(req->file);
5221 if (unlikely(!sock))
5224 if (req_has_async_data(req)) {
5225 kmsg = req->async_data;
5227 ret = io_sendmsg_copy_hdr(req, &iomsg);
5233 flags = req->sr_msg.msg_flags;
5234 if (issue_flags & IO_URING_F_NONBLOCK)
5235 flags |= MSG_DONTWAIT;
5236 if (flags & MSG_WAITALL)
5237 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5239 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5241 if (ret < min_ret) {
5242 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5243 return io_setup_async_msg(req, kmsg);
5244 if (ret == -ERESTARTSYS)
5248 /* fast path, check for non-NULL to avoid function call */
5250 kfree(kmsg->free_iov);
5251 req->flags &= ~REQ_F_NEED_CLEANUP;
5252 __io_req_complete(req, issue_flags, ret, 0);
5256 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5258 struct io_sr_msg *sr = &req->sr_msg;
5261 struct socket *sock;
5266 sock = sock_from_file(req->file);
5267 if (unlikely(!sock))
5270 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5274 msg.msg_name = NULL;
5275 msg.msg_control = NULL;
5276 msg.msg_controllen = 0;
5277 msg.msg_namelen = 0;
5279 flags = req->sr_msg.msg_flags;
5280 if (issue_flags & IO_URING_F_NONBLOCK)
5281 flags |= MSG_DONTWAIT;
5282 if (flags & MSG_WAITALL)
5283 min_ret = iov_iter_count(&msg.msg_iter);
5285 msg.msg_flags = flags;
5286 ret = sock_sendmsg(sock, &msg);
5287 if (ret < min_ret) {
5288 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5290 if (ret == -ERESTARTSYS)
5294 __io_req_complete(req, issue_flags, ret, 0);
5298 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5299 struct io_async_msghdr *iomsg)
5301 struct io_sr_msg *sr = &req->sr_msg;
5302 struct iovec __user *uiov;
5306 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5307 &iomsg->uaddr, &uiov, &iov_len);
5311 if (req->flags & REQ_F_BUFFER_SELECT) {
5314 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5316 sr->len = iomsg->fast_iov[0].iov_len;
5317 iomsg->free_iov = NULL;
5319 iomsg->free_iov = iomsg->fast_iov;
5320 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5321 &iomsg->free_iov, &iomsg->msg.msg_iter,
5330 #ifdef CONFIG_COMPAT
5331 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5332 struct io_async_msghdr *iomsg)
5334 struct io_sr_msg *sr = &req->sr_msg;
5335 struct compat_iovec __user *uiov;
5340 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5345 uiov = compat_ptr(ptr);
5346 if (req->flags & REQ_F_BUFFER_SELECT) {
5347 compat_ssize_t clen;
5351 if (!access_ok(uiov, sizeof(*uiov)))
5353 if (__get_user(clen, &uiov->iov_len))
5358 iomsg->free_iov = NULL;
5360 iomsg->free_iov = iomsg->fast_iov;
5361 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5362 UIO_FASTIOV, &iomsg->free_iov,
5363 &iomsg->msg.msg_iter, true);
5372 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5373 struct io_async_msghdr *iomsg)
5375 iomsg->msg.msg_name = &iomsg->addr;
5377 #ifdef CONFIG_COMPAT
5378 if (req->ctx->compat)
5379 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5382 return __io_recvmsg_copy_hdr(req, iomsg);
5385 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5386 unsigned int issue_flags)
5388 struct io_sr_msg *sr = &req->sr_msg;
5390 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5393 static int io_recvmsg_prep_async(struct io_kiocb *req)
5397 ret = io_recvmsg_copy_hdr(req, req->async_data);
5399 req->flags |= REQ_F_NEED_CLEANUP;
5403 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5405 struct io_sr_msg *sr = &req->sr_msg;
5407 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5410 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5411 sr->len = READ_ONCE(sqe->len);
5412 sr->bgid = READ_ONCE(sqe->buf_group);
5413 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5414 if (sr->msg_flags & MSG_DONTWAIT)
5415 req->flags |= REQ_F_NOWAIT;
5417 #ifdef CONFIG_COMPAT
5418 if (req->ctx->compat)
5419 sr->msg_flags |= MSG_CMSG_COMPAT;
5424 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5426 struct io_async_msghdr iomsg, *kmsg;
5427 struct socket *sock;
5428 struct io_buffer *kbuf;
5430 int ret, min_ret = 0;
5431 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5433 sock = sock_from_file(req->file);
5434 if (unlikely(!sock))
5437 if (req_has_async_data(req)) {
5438 kmsg = req->async_data;
5440 ret = io_recvmsg_copy_hdr(req, &iomsg);
5446 if (req->flags & REQ_F_BUFFER_SELECT) {
5447 kbuf = io_recv_buffer_select(req, issue_flags);
5449 return PTR_ERR(kbuf);
5450 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5451 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5452 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5453 1, req->sr_msg.len);
5456 flags = req->sr_msg.msg_flags;
5458 flags |= MSG_DONTWAIT;
5459 if (flags & MSG_WAITALL)
5460 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5462 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5463 kmsg->uaddr, flags);
5464 if (ret < min_ret) {
5465 if (ret == -EAGAIN && force_nonblock)
5466 return io_setup_async_msg(req, kmsg);
5467 if (ret == -ERESTARTSYS)
5470 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5474 /* fast path, check for non-NULL to avoid function call */
5476 kfree(kmsg->free_iov);
5477 req->flags &= ~REQ_F_NEED_CLEANUP;
5478 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5482 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5484 struct io_buffer *kbuf;
5485 struct io_sr_msg *sr = &req->sr_msg;
5487 void __user *buf = sr->buf;
5488 struct socket *sock;
5491 int ret, min_ret = 0;
5492 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5494 sock = sock_from_file(req->file);
5495 if (unlikely(!sock))
5498 if (req->flags & REQ_F_BUFFER_SELECT) {
5499 kbuf = io_recv_buffer_select(req, issue_flags);
5501 return PTR_ERR(kbuf);
5502 buf = u64_to_user_ptr(kbuf->addr);
5505 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5509 msg.msg_name = NULL;
5510 msg.msg_control = NULL;
5511 msg.msg_controllen = 0;
5512 msg.msg_namelen = 0;
5513 msg.msg_iocb = NULL;
5516 flags = req->sr_msg.msg_flags;
5518 flags |= MSG_DONTWAIT;
5519 if (flags & MSG_WAITALL)
5520 min_ret = iov_iter_count(&msg.msg_iter);
5522 ret = sock_recvmsg(sock, &msg, flags);
5523 if (ret < min_ret) {
5524 if (ret == -EAGAIN && force_nonblock)
5526 if (ret == -ERESTARTSYS)
5529 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5534 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5538 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5540 struct io_accept *accept = &req->accept;
5542 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5544 if (sqe->ioprio || sqe->len || sqe->buf_index)
5547 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5548 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5549 accept->flags = READ_ONCE(sqe->accept_flags);
5550 accept->nofile = rlimit(RLIMIT_NOFILE);
5552 accept->file_slot = READ_ONCE(sqe->file_index);
5553 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5555 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5557 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5558 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5562 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5564 struct io_accept *accept = &req->accept;
5565 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5566 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5567 bool fixed = !!accept->file_slot;
5571 if (req->file->f_flags & O_NONBLOCK)
5572 req->flags |= REQ_F_NOWAIT;
5575 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5576 if (unlikely(fd < 0))
5579 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5584 ret = PTR_ERR(file);
5585 if (ret == -EAGAIN && force_nonblock)
5587 if (ret == -ERESTARTSYS)
5590 } else if (!fixed) {
5591 fd_install(fd, file);
5594 ret = io_install_fixed_file(req, file, issue_flags,
5595 accept->file_slot - 1);
5597 __io_req_complete(req, issue_flags, ret, 0);
5601 static int io_connect_prep_async(struct io_kiocb *req)
5603 struct io_async_connect *io = req->async_data;
5604 struct io_connect *conn = &req->connect;
5606 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5609 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5611 struct io_connect *conn = &req->connect;
5613 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5615 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5619 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5620 conn->addr_len = READ_ONCE(sqe->addr2);
5624 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5626 struct io_async_connect __io, *io;
5627 unsigned file_flags;
5629 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5631 if (req_has_async_data(req)) {
5632 io = req->async_data;
5634 ret = move_addr_to_kernel(req->connect.addr,
5635 req->connect.addr_len,
5642 file_flags = force_nonblock ? O_NONBLOCK : 0;
5644 ret = __sys_connect_file(req->file, &io->address,
5645 req->connect.addr_len, file_flags);
5646 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5647 if (req_has_async_data(req))
5649 if (io_alloc_async_data(req)) {
5653 memcpy(req->async_data, &__io, sizeof(__io));
5656 if (ret == -ERESTARTSYS)
5661 __io_req_complete(req, issue_flags, ret, 0);
5664 #else /* !CONFIG_NET */
5665 #define IO_NETOP_FN(op) \
5666 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5668 return -EOPNOTSUPP; \
5671 #define IO_NETOP_PREP(op) \
5673 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5675 return -EOPNOTSUPP; \
5678 #define IO_NETOP_PREP_ASYNC(op) \
5680 static int io_##op##_prep_async(struct io_kiocb *req) \
5682 return -EOPNOTSUPP; \
5685 IO_NETOP_PREP_ASYNC(sendmsg);
5686 IO_NETOP_PREP_ASYNC(recvmsg);
5687 IO_NETOP_PREP_ASYNC(connect);
5688 IO_NETOP_PREP(accept);
5691 #endif /* CONFIG_NET */
5693 #ifdef CONFIG_NET_RX_BUSY_POLL
5695 #define NAPI_TIMEOUT (60 * SEC_CONVERSION)
5698 struct list_head list;
5699 unsigned int napi_id;
5700 unsigned long timeout;
5704 * Add busy poll NAPI ID from sk.
5706 static void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5708 unsigned int napi_id;
5709 struct socket *sock;
5711 struct napi_entry *ne;
5713 if (!net_busy_loop_on())
5716 sock = sock_from_file(file);
5724 napi_id = READ_ONCE(sk->sk_napi_id);
5726 /* Non-NAPI IDs can be rejected */
5727 if (napi_id < MIN_NAPI_ID)
5730 spin_lock(&ctx->napi_lock);
5731 list_for_each_entry(ne, &ctx->napi_list, list) {
5732 if (ne->napi_id == napi_id) {
5733 ne->timeout = jiffies + NAPI_TIMEOUT;
5738 ne = kmalloc(sizeof(*ne), GFP_NOWAIT);
5742 ne->napi_id = napi_id;
5743 ne->timeout = jiffies + NAPI_TIMEOUT;
5744 list_add_tail(&ne->list, &ctx->napi_list);
5746 spin_unlock(&ctx->napi_lock);
5749 static inline void io_check_napi_entry_timeout(struct napi_entry *ne)
5751 if (time_after(jiffies, ne->timeout)) {
5752 list_del(&ne->list);
5758 * Busy poll if globally on and supporting sockets found
5760 static bool io_napi_busy_loop(struct list_head *napi_list)
5762 struct napi_entry *ne, *n;
5764 list_for_each_entry_safe(ne, n, napi_list, list) {
5765 napi_busy_loop(ne->napi_id, NULL, NULL, true,
5767 io_check_napi_entry_timeout(ne);
5769 return !list_empty(napi_list);
5772 static void io_free_napi_list(struct io_ring_ctx *ctx)
5774 spin_lock(&ctx->napi_lock);
5775 while (!list_empty(&ctx->napi_list)) {
5776 struct napi_entry *ne =
5777 list_first_entry(&ctx->napi_list, struct napi_entry,
5780 list_del(&ne->list);
5783 spin_unlock(&ctx->napi_lock);
5786 static inline void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5790 static inline void io_free_napi_list(struct io_ring_ctx *ctx)
5793 #endif /* CONFIG_NET_RX_BUSY_POLL */
5795 struct io_poll_table {
5796 struct poll_table_struct pt;
5797 struct io_kiocb *req;
5802 #define IO_POLL_CANCEL_FLAG BIT(31)
5803 #define IO_POLL_REF_MASK ((1u << 20)-1)
5806 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5807 * bump it and acquire ownership. It's disallowed to modify requests while not
5808 * owning it, that prevents from races for enqueueing task_work's and b/w
5809 * arming poll and wakeups.
5811 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5813 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5816 static void io_poll_mark_cancelled(struct io_kiocb *req)
5818 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5821 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5823 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5824 if (req->opcode == IORING_OP_POLL_ADD)
5825 return req->async_data;
5826 return req->apoll->double_poll;
5829 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5831 if (req->opcode == IORING_OP_POLL_ADD)
5833 return &req->apoll->poll;
5836 static void io_poll_req_insert(struct io_kiocb *req)
5838 struct io_ring_ctx *ctx = req->ctx;
5839 struct hlist_head *list;
5841 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5842 hlist_add_head(&req->hash_node, list);
5845 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5846 wait_queue_func_t wake_func)
5849 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5850 /* mask in events that we always want/need */
5851 poll->events = events | IO_POLL_UNMASK;
5852 INIT_LIST_HEAD(&poll->wait.entry);
5853 init_waitqueue_func_entry(&poll->wait, wake_func);
5856 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5858 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5861 spin_lock_irq(&head->lock);
5862 list_del_init(&poll->wait.entry);
5864 spin_unlock_irq(&head->lock);
5868 static void io_poll_remove_entries(struct io_kiocb *req)
5871 * Nothing to do if neither of those flags are set. Avoid dipping
5872 * into the poll/apoll/double cachelines if we can.
5874 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5878 * While we hold the waitqueue lock and the waitqueue is nonempty,
5879 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5880 * lock in the first place can race with the waitqueue being freed.
5882 * We solve this as eventpoll does: by taking advantage of the fact that
5883 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5884 * we enter rcu_read_lock() and see that the pointer to the queue is
5885 * non-NULL, we can then lock it without the memory being freed out from
5888 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5889 * case the caller deletes the entry from the queue, leaving it empty.
5890 * In that case, only RCU prevents the queue memory from being freed.
5893 if (req->flags & REQ_F_SINGLE_POLL)
5894 io_poll_remove_entry(io_poll_get_single(req));
5895 if (req->flags & REQ_F_DOUBLE_POLL)
5896 io_poll_remove_entry(io_poll_get_double(req));
5901 * All poll tw should go through this. Checks for poll events, manages
5902 * references, does rewait, etc.
5904 * Returns a negative error on failure. >0 when no action require, which is
5905 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5906 * the request, then the mask is stored in req->result.
5908 static int io_poll_check_events(struct io_kiocb *req)
5910 struct io_ring_ctx *ctx = req->ctx;
5911 struct io_poll_iocb *poll = io_poll_get_single(req);
5914 /* req->task == current here, checking PF_EXITING is safe */
5915 if (unlikely(req->task->flags & PF_EXITING))
5916 io_poll_mark_cancelled(req);
5919 v = atomic_read(&req->poll_refs);
5921 /* tw handler should be the owner, and so have some references */
5922 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5924 if (v & IO_POLL_CANCEL_FLAG)
5928 struct poll_table_struct pt = { ._key = req->cflags };
5930 req->result = vfs_poll(req->file, &pt) & req->cflags;
5933 /* multishot, just fill an CQE and proceed */
5934 if (req->result && !(req->cflags & EPOLLONESHOT)) {
5935 __poll_t mask = mangle_poll(req->result & poll->events);
5938 spin_lock(&ctx->completion_lock);
5939 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5941 io_commit_cqring(ctx);
5942 spin_unlock(&ctx->completion_lock);
5943 if (unlikely(!filled))
5945 io_cqring_ev_posted(ctx);
5946 io_add_napi(req->file, ctx);
5947 } else if (req->result) {
5952 * Release all references, retry if someone tried to restart
5953 * task_work while we were executing it.
5955 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5960 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5962 struct io_ring_ctx *ctx = req->ctx;
5965 ret = io_poll_check_events(req);
5970 req->result = mangle_poll(req->result & req->poll.events);
5976 io_poll_remove_entries(req);
5977 spin_lock(&ctx->completion_lock);
5978 hash_del(&req->hash_node);
5979 __io_req_complete_post(req, req->result, 0);
5980 io_commit_cqring(ctx);
5981 spin_unlock(&ctx->completion_lock);
5982 io_cqring_ev_posted(ctx);
5985 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5987 struct io_ring_ctx *ctx = req->ctx;
5990 ret = io_poll_check_events(req);
5994 io_poll_remove_entries(req);
5995 spin_lock(&ctx->completion_lock);
5996 hash_del(&req->hash_node);
5997 spin_unlock(&ctx->completion_lock);
6000 io_req_task_submit(req, locked);
6002 io_req_complete_failed(req, ret);
6005 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
6009 * This is useful for poll that is armed on behalf of another
6010 * request, and where the wakeup path could be on a different
6011 * CPU. We want to avoid pulling in req->apoll->events for that
6014 req->cflags = events;
6015 if (req->opcode == IORING_OP_POLL_ADD)
6016 req->io_task_work.func = io_poll_task_func;
6018 req->io_task_work.func = io_apoll_task_func;
6020 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
6021 io_req_task_work_add(req, false);
6024 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
6026 if (io_poll_get_ownership(req))
6027 __io_poll_execute(req, res, events);
6030 static void io_poll_cancel_req(struct io_kiocb *req)
6032 io_poll_mark_cancelled(req);
6033 /* kick tw, which should complete the request */
6034 io_poll_execute(req, 0, 0);
6037 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6040 struct io_kiocb *req = wait->private;
6041 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6043 __poll_t mask = key_to_poll(key);
6045 if (unlikely(mask & POLLFREE)) {
6046 io_poll_mark_cancelled(req);
6047 /* we have to kick tw in case it's not already */
6048 io_poll_execute(req, 0, poll->events);
6051 * If the waitqueue is being freed early but someone is already
6052 * holds ownership over it, we have to tear down the request as
6053 * best we can. That means immediately removing the request from
6054 * its waitqueue and preventing all further accesses to the
6055 * waitqueue via the request.
6057 list_del_init(&poll->wait.entry);
6060 * Careful: this *must* be the last step, since as soon
6061 * as req->head is NULL'ed out, the request can be
6062 * completed and freed, since aio_poll_complete_work()
6063 * will no longer need to take the waitqueue lock.
6065 smp_store_release(&poll->head, NULL);
6069 /* for instances that support it check for an event match first */
6070 if (mask && !(mask & poll->events))
6073 if (io_poll_get_ownership(req)) {
6074 /* optional, saves extra locking for removal in tw handler */
6075 if (mask && poll->events & EPOLLONESHOT) {
6076 list_del_init(&poll->wait.entry);
6078 req->flags &= ~REQ_F_SINGLE_POLL;
6080 __io_poll_execute(req, mask, poll->events);
6085 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6086 struct wait_queue_head *head,
6087 struct io_poll_iocb **poll_ptr)
6089 struct io_kiocb *req = pt->req;
6092 * The file being polled uses multiple waitqueues for poll handling
6093 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6096 if (unlikely(pt->nr_entries)) {
6097 struct io_poll_iocb *first = poll;
6099 /* double add on the same waitqueue head, ignore */
6100 if (first->head == head)
6102 /* already have a 2nd entry, fail a third attempt */
6104 if ((*poll_ptr)->head == head)
6106 pt->error = -EINVAL;
6110 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6112 pt->error = -ENOMEM;
6115 req->flags |= REQ_F_DOUBLE_POLL;
6116 io_init_poll_iocb(poll, first->events, first->wait.func);
6118 if (req->opcode == IORING_OP_POLL_ADD)
6119 req->flags |= REQ_F_ASYNC_DATA;
6122 req->flags |= REQ_F_SINGLE_POLL;
6125 poll->wait.private = req;
6127 if (poll->events & EPOLLEXCLUSIVE)
6128 add_wait_queue_exclusive(head, &poll->wait);
6130 add_wait_queue(head, &poll->wait);
6133 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6134 struct poll_table_struct *p)
6136 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6138 __io_queue_proc(&pt->req->poll, pt, head,
6139 (struct io_poll_iocb **) &pt->req->async_data);
6142 static int __io_arm_poll_handler(struct io_kiocb *req,
6143 struct io_poll_iocb *poll,
6144 struct io_poll_table *ipt, __poll_t mask)
6146 struct io_ring_ctx *ctx = req->ctx;
6149 INIT_HLIST_NODE(&req->hash_node);
6150 io_init_poll_iocb(poll, mask, io_poll_wake);
6151 poll->file = req->file;
6152 poll->wait.private = req;
6154 ipt->pt._key = mask;
6157 ipt->nr_entries = 0;
6160 * Take the ownership to delay any tw execution up until we're done
6161 * with poll arming. see io_poll_get_ownership().
6163 atomic_set(&req->poll_refs, 1);
6164 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6166 if (mask && (poll->events & EPOLLONESHOT)) {
6167 io_poll_remove_entries(req);
6168 /* no one else has access to the req, forget about the ref */
6171 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6172 io_poll_remove_entries(req);
6174 ipt->error = -EINVAL;
6178 spin_lock(&ctx->completion_lock);
6179 io_poll_req_insert(req);
6180 spin_unlock(&ctx->completion_lock);
6183 /* can't multishot if failed, just queue the event we've got */
6184 if (unlikely(ipt->error || !ipt->nr_entries))
6185 poll->events |= EPOLLONESHOT;
6186 __io_poll_execute(req, mask, poll->events);
6189 io_add_napi(req->file, req->ctx);
6192 * Release ownership. If someone tried to queue a tw while it was
6193 * locked, kick it off for them.
6195 v = atomic_dec_return(&req->poll_refs);
6196 if (unlikely(v & IO_POLL_REF_MASK))
6197 __io_poll_execute(req, 0, poll->events);
6201 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6202 struct poll_table_struct *p)
6204 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6205 struct async_poll *apoll = pt->req->apoll;
6207 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6216 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6218 const struct io_op_def *def = &io_op_defs[req->opcode];
6219 struct io_ring_ctx *ctx = req->ctx;
6220 struct async_poll *apoll;
6221 struct io_poll_table ipt;
6222 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6225 if (!def->pollin && !def->pollout)
6226 return IO_APOLL_ABORTED;
6227 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6228 return IO_APOLL_ABORTED;
6231 mask |= POLLIN | POLLRDNORM;
6233 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6234 if ((req->opcode == IORING_OP_RECVMSG) &&
6235 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6238 mask |= POLLOUT | POLLWRNORM;
6241 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6242 !list_empty(&ctx->apoll_cache)) {
6243 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6245 list_del_init(&apoll->poll.wait.entry);
6247 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6248 if (unlikely(!apoll))
6249 return IO_APOLL_ABORTED;
6251 apoll->double_poll = NULL;
6253 req->flags |= REQ_F_POLLED;
6254 ipt.pt._qproc = io_async_queue_proc;
6256 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6257 if (ret || ipt.error)
6258 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6260 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6261 mask, apoll->poll.events);
6266 * Returns true if we found and killed one or more poll requests
6268 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6269 struct task_struct *tsk, bool cancel_all)
6271 struct hlist_node *tmp;
6272 struct io_kiocb *req;
6276 spin_lock(&ctx->completion_lock);
6277 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6278 struct hlist_head *list;
6280 list = &ctx->cancel_hash[i];
6281 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6282 if (io_match_task_safe(req, tsk, cancel_all)) {
6283 io_poll_cancel_req(req);
6288 spin_unlock(&ctx->completion_lock);
6292 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6294 __must_hold(&ctx->completion_lock)
6296 struct hlist_head *list;
6297 struct io_kiocb *req;
6299 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6300 hlist_for_each_entry(req, list, hash_node) {
6301 if (sqe_addr != req->user_data)
6303 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6310 static bool io_poll_disarm(struct io_kiocb *req)
6311 __must_hold(&ctx->completion_lock)
6313 if (!io_poll_get_ownership(req))
6315 io_poll_remove_entries(req);
6316 hash_del(&req->hash_node);
6320 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6322 __must_hold(&ctx->completion_lock)
6324 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6328 io_poll_cancel_req(req);
6332 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6337 events = READ_ONCE(sqe->poll32_events);
6339 events = swahw32(events);
6341 if (!(flags & IORING_POLL_ADD_MULTI))
6342 events |= EPOLLONESHOT;
6343 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6346 static int io_poll_update_prep(struct io_kiocb *req,
6347 const struct io_uring_sqe *sqe)
6349 struct io_poll_update *upd = &req->poll_update;
6352 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6354 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6356 flags = READ_ONCE(sqe->len);
6357 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6358 IORING_POLL_ADD_MULTI))
6360 /* meaningless without update */
6361 if (flags == IORING_POLL_ADD_MULTI)
6364 upd->old_user_data = READ_ONCE(sqe->addr);
6365 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6366 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6368 upd->new_user_data = READ_ONCE(sqe->off);
6369 if (!upd->update_user_data && upd->new_user_data)
6371 if (upd->update_events)
6372 upd->events = io_poll_parse_events(sqe, flags);
6373 else if (sqe->poll32_events)
6379 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6381 struct io_poll_iocb *poll = &req->poll;
6384 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6386 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6388 flags = READ_ONCE(sqe->len);
6389 if (flags & ~IORING_POLL_ADD_MULTI)
6391 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6394 io_req_set_refcount(req);
6395 req->cflags = poll->events = io_poll_parse_events(sqe, flags);
6399 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6401 struct io_poll_iocb *poll = &req->poll;
6402 struct io_poll_table ipt;
6405 ipt.pt._qproc = io_poll_queue_proc;
6407 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6408 ret = ret ?: ipt.error;
6410 __io_req_complete(req, issue_flags, ret, 0);
6414 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6416 struct io_ring_ctx *ctx = req->ctx;
6417 struct io_kiocb *preq;
6421 spin_lock(&ctx->completion_lock);
6422 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6423 if (!preq || !io_poll_disarm(preq)) {
6424 spin_unlock(&ctx->completion_lock);
6425 ret = preq ? -EALREADY : -ENOENT;
6428 spin_unlock(&ctx->completion_lock);
6430 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6431 /* only mask one event flags, keep behavior flags */
6432 if (req->poll_update.update_events) {
6433 preq->poll.events &= ~0xffff;
6434 preq->poll.events |= req->poll_update.events & 0xffff;
6435 preq->poll.events |= IO_POLL_UNMASK;
6437 if (req->poll_update.update_user_data)
6438 preq->user_data = req->poll_update.new_user_data;
6440 ret2 = io_poll_add(preq, issue_flags);
6441 /* successfully updated, don't complete poll request */
6447 preq->result = -ECANCELED;
6448 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6449 io_req_task_complete(preq, &locked);
6453 /* complete update request, we're done with it */
6454 __io_req_complete(req, issue_flags, ret, 0);
6458 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6460 struct io_timeout_data *data = container_of(timer,
6461 struct io_timeout_data, timer);
6462 struct io_kiocb *req = data->req;
6463 struct io_ring_ctx *ctx = req->ctx;
6464 unsigned long flags;
6466 spin_lock_irqsave(&ctx->timeout_lock, flags);
6467 list_del_init(&req->timeout.list);
6468 atomic_set(&req->ctx->cq_timeouts,
6469 atomic_read(&req->ctx->cq_timeouts) + 1);
6470 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6472 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6475 req->result = -ETIME;
6476 req->io_task_work.func = io_req_task_complete;
6477 io_req_task_work_add(req, false);
6478 return HRTIMER_NORESTART;
6481 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6483 __must_hold(&ctx->timeout_lock)
6485 struct io_timeout_data *io;
6486 struct io_kiocb *req;
6489 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6490 found = user_data == req->user_data;
6495 return ERR_PTR(-ENOENT);
6497 io = req->async_data;
6498 if (hrtimer_try_to_cancel(&io->timer) == -1)
6499 return ERR_PTR(-EALREADY);
6500 list_del_init(&req->timeout.list);
6504 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6505 __must_hold(&ctx->completion_lock)
6506 __must_hold(&ctx->timeout_lock)
6508 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6511 return PTR_ERR(req);
6512 io_req_task_queue_fail(req, -ECANCELED);
6516 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6518 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6519 case IORING_TIMEOUT_BOOTTIME:
6520 return CLOCK_BOOTTIME;
6521 case IORING_TIMEOUT_REALTIME:
6522 return CLOCK_REALTIME;
6524 /* can't happen, vetted at prep time */
6528 return CLOCK_MONOTONIC;
6532 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6533 struct timespec64 *ts, enum hrtimer_mode mode)
6534 __must_hold(&ctx->timeout_lock)
6536 struct io_timeout_data *io;
6537 struct io_kiocb *req;
6540 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6541 found = user_data == req->user_data;
6548 io = req->async_data;
6549 if (hrtimer_try_to_cancel(&io->timer) == -1)
6551 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6552 io->timer.function = io_link_timeout_fn;
6553 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6557 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6558 struct timespec64 *ts, enum hrtimer_mode mode)
6559 __must_hold(&ctx->timeout_lock)
6561 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6562 struct io_timeout_data *data;
6565 return PTR_ERR(req);
6567 req->timeout.off = 0; /* noseq */
6568 data = req->async_data;
6569 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6570 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6571 data->timer.function = io_timeout_fn;
6572 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6576 static int io_timeout_remove_prep(struct io_kiocb *req,
6577 const struct io_uring_sqe *sqe)
6579 struct io_timeout_rem *tr = &req->timeout_rem;
6581 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6583 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6585 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6588 tr->ltimeout = false;
6589 tr->addr = READ_ONCE(sqe->addr);
6590 tr->flags = READ_ONCE(sqe->timeout_flags);
6591 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6592 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6594 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6595 tr->ltimeout = true;
6596 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6598 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6600 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6602 } else if (tr->flags) {
6603 /* timeout removal doesn't support flags */
6610 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6612 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6617 * Remove or update an existing timeout command
6619 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6621 struct io_timeout_rem *tr = &req->timeout_rem;
6622 struct io_ring_ctx *ctx = req->ctx;
6625 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6626 spin_lock(&ctx->completion_lock);
6627 spin_lock_irq(&ctx->timeout_lock);
6628 ret = io_timeout_cancel(ctx, tr->addr);
6629 spin_unlock_irq(&ctx->timeout_lock);
6630 spin_unlock(&ctx->completion_lock);
6632 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6634 spin_lock_irq(&ctx->timeout_lock);
6636 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6638 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6639 spin_unlock_irq(&ctx->timeout_lock);
6644 io_req_complete_post(req, ret, 0);
6648 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6649 bool is_timeout_link)
6651 struct io_timeout_data *data;
6653 u32 off = READ_ONCE(sqe->off);
6655 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6657 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6660 if (off && is_timeout_link)
6662 flags = READ_ONCE(sqe->timeout_flags);
6663 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6664 IORING_TIMEOUT_ETIME_SUCCESS))
6666 /* more than one clock specified is invalid, obviously */
6667 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6670 INIT_LIST_HEAD(&req->timeout.list);
6671 req->timeout.off = off;
6672 if (unlikely(off && !req->ctx->off_timeout_used))
6673 req->ctx->off_timeout_used = true;
6675 if (WARN_ON_ONCE(req_has_async_data(req)))
6677 if (io_alloc_async_data(req))
6680 data = req->async_data;
6682 data->flags = flags;
6684 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6687 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6690 data->mode = io_translate_timeout_mode(flags);
6691 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6693 if (is_timeout_link) {
6694 struct io_submit_link *link = &req->ctx->submit_state.link;
6698 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6700 req->timeout.head = link->last;
6701 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6706 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6708 struct io_ring_ctx *ctx = req->ctx;
6709 struct io_timeout_data *data = req->async_data;
6710 struct list_head *entry;
6711 u32 tail, off = req->timeout.off;
6713 spin_lock_irq(&ctx->timeout_lock);
6716 * sqe->off holds how many events that need to occur for this
6717 * timeout event to be satisfied. If it isn't set, then this is
6718 * a pure timeout request, sequence isn't used.
6720 if (io_is_timeout_noseq(req)) {
6721 entry = ctx->timeout_list.prev;
6725 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6726 req->timeout.target_seq = tail + off;
6728 /* Update the last seq here in case io_flush_timeouts() hasn't.
6729 * This is safe because ->completion_lock is held, and submissions
6730 * and completions are never mixed in the same ->completion_lock section.
6732 ctx->cq_last_tm_flush = tail;
6735 * Insertion sort, ensuring the first entry in the list is always
6736 * the one we need first.
6738 list_for_each_prev(entry, &ctx->timeout_list) {
6739 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6742 if (io_is_timeout_noseq(nxt))
6744 /* nxt.seq is behind @tail, otherwise would've been completed */
6745 if (off >= nxt->timeout.target_seq - tail)
6749 list_add(&req->timeout.list, entry);
6750 data->timer.function = io_timeout_fn;
6751 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6752 spin_unlock_irq(&ctx->timeout_lock);
6756 struct io_cancel_data {
6757 struct io_ring_ctx *ctx;
6761 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6763 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6764 struct io_cancel_data *cd = data;
6766 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6769 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6770 struct io_ring_ctx *ctx)
6772 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6773 enum io_wq_cancel cancel_ret;
6776 if (!tctx || !tctx->io_wq)
6779 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6780 switch (cancel_ret) {
6781 case IO_WQ_CANCEL_OK:
6784 case IO_WQ_CANCEL_RUNNING:
6787 case IO_WQ_CANCEL_NOTFOUND:
6795 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6797 struct io_ring_ctx *ctx = req->ctx;
6800 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6802 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6804 * Fall-through even for -EALREADY, as we may have poll armed
6805 * that need unarming.
6810 spin_lock(&ctx->completion_lock);
6811 ret = io_poll_cancel(ctx, sqe_addr, false);
6815 spin_lock_irq(&ctx->timeout_lock);
6816 ret = io_timeout_cancel(ctx, sqe_addr);
6817 spin_unlock_irq(&ctx->timeout_lock);
6819 spin_unlock(&ctx->completion_lock);
6823 static int io_async_cancel_prep(struct io_kiocb *req,
6824 const struct io_uring_sqe *sqe)
6826 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6828 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6830 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6834 req->cancel.addr = READ_ONCE(sqe->addr);
6838 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6840 struct io_ring_ctx *ctx = req->ctx;
6841 u64 sqe_addr = req->cancel.addr;
6842 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6843 struct io_tctx_node *node;
6846 ret = io_try_cancel_userdata(req, sqe_addr);
6850 /* slow path, try all io-wq's */
6851 io_ring_submit_lock(ctx, needs_lock);
6853 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6854 struct io_uring_task *tctx = node->task->io_uring;
6856 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6860 io_ring_submit_unlock(ctx, needs_lock);
6864 io_req_complete_post(req, ret, 0);
6868 static int io_rsrc_update_prep(struct io_kiocb *req,
6869 const struct io_uring_sqe *sqe)
6871 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6873 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6876 req->rsrc_update.offset = READ_ONCE(sqe->off);
6877 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6878 if (!req->rsrc_update.nr_args)
6880 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6884 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6886 struct io_ring_ctx *ctx = req->ctx;
6887 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6888 struct io_uring_rsrc_update2 up;
6891 up.offset = req->rsrc_update.offset;
6892 up.data = req->rsrc_update.arg;
6897 io_ring_submit_lock(ctx, needs_lock);
6898 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6899 &up, req->rsrc_update.nr_args);
6900 io_ring_submit_unlock(ctx, needs_lock);
6904 __io_req_complete(req, issue_flags, ret, 0);
6908 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6910 switch (req->opcode) {
6913 case IORING_OP_READV:
6914 case IORING_OP_READ_FIXED:
6915 case IORING_OP_READ:
6916 return io_read_prep(req, sqe);
6917 case IORING_OP_WRITEV:
6918 case IORING_OP_WRITE_FIXED:
6919 case IORING_OP_WRITE:
6920 return io_write_prep(req, sqe);
6921 case IORING_OP_POLL_ADD:
6922 return io_poll_add_prep(req, sqe);
6923 case IORING_OP_POLL_REMOVE:
6924 return io_poll_update_prep(req, sqe);
6925 case IORING_OP_FSYNC:
6926 return io_fsync_prep(req, sqe);
6927 case IORING_OP_SYNC_FILE_RANGE:
6928 return io_sfr_prep(req, sqe);
6929 case IORING_OP_SENDMSG:
6930 case IORING_OP_SEND:
6931 return io_sendmsg_prep(req, sqe);
6932 case IORING_OP_RECVMSG:
6933 case IORING_OP_RECV:
6934 return io_recvmsg_prep(req, sqe);
6935 case IORING_OP_CONNECT:
6936 return io_connect_prep(req, sqe);
6937 case IORING_OP_TIMEOUT:
6938 return io_timeout_prep(req, sqe, false);
6939 case IORING_OP_TIMEOUT_REMOVE:
6940 return io_timeout_remove_prep(req, sqe);
6941 case IORING_OP_ASYNC_CANCEL:
6942 return io_async_cancel_prep(req, sqe);
6943 case IORING_OP_LINK_TIMEOUT:
6944 return io_timeout_prep(req, sqe, true);
6945 case IORING_OP_ACCEPT:
6946 return io_accept_prep(req, sqe);
6947 case IORING_OP_FALLOCATE:
6948 return io_fallocate_prep(req, sqe);
6949 case IORING_OP_OPENAT:
6950 return io_openat_prep(req, sqe);
6951 case IORING_OP_CLOSE:
6952 return io_close_prep(req, sqe);
6953 case IORING_OP_FILES_UPDATE:
6954 return io_rsrc_update_prep(req, sqe);
6955 case IORING_OP_STATX:
6956 return io_statx_prep(req, sqe);
6957 case IORING_OP_FADVISE:
6958 return io_fadvise_prep(req, sqe);
6959 case IORING_OP_MADVISE:
6960 return io_madvise_prep(req, sqe);
6961 case IORING_OP_OPENAT2:
6962 return io_openat2_prep(req, sqe);
6963 case IORING_OP_EPOLL_CTL:
6964 return io_epoll_ctl_prep(req, sqe);
6965 case IORING_OP_SPLICE:
6966 return io_splice_prep(req, sqe);
6967 case IORING_OP_PROVIDE_BUFFERS:
6968 return io_provide_buffers_prep(req, sqe);
6969 case IORING_OP_REMOVE_BUFFERS:
6970 return io_remove_buffers_prep(req, sqe);
6972 return io_tee_prep(req, sqe);
6973 case IORING_OP_SHUTDOWN:
6974 return io_shutdown_prep(req, sqe);
6975 case IORING_OP_RENAMEAT:
6976 return io_renameat_prep(req, sqe);
6977 case IORING_OP_UNLINKAT:
6978 return io_unlinkat_prep(req, sqe);
6979 case IORING_OP_MKDIRAT:
6980 return io_mkdirat_prep(req, sqe);
6981 case IORING_OP_SYMLINKAT:
6982 return io_symlinkat_prep(req, sqe);
6983 case IORING_OP_LINKAT:
6984 return io_linkat_prep(req, sqe);
6985 case IORING_OP_MSG_RING:
6986 return io_msg_ring_prep(req, sqe);
6989 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6994 static int io_req_prep_async(struct io_kiocb *req)
6996 if (!io_op_defs[req->opcode].needs_async_setup)
6998 if (WARN_ON_ONCE(req_has_async_data(req)))
7000 if (io_alloc_async_data(req))
7003 switch (req->opcode) {
7004 case IORING_OP_READV:
7005 return io_rw_prep_async(req, READ);
7006 case IORING_OP_WRITEV:
7007 return io_rw_prep_async(req, WRITE);
7008 case IORING_OP_SENDMSG:
7009 return io_sendmsg_prep_async(req);
7010 case IORING_OP_RECVMSG:
7011 return io_recvmsg_prep_async(req);
7012 case IORING_OP_CONNECT:
7013 return io_connect_prep_async(req);
7015 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7020 static u32 io_get_sequence(struct io_kiocb *req)
7022 u32 seq = req->ctx->cached_sq_head;
7024 /* need original cached_sq_head, but it was increased for each req */
7025 io_for_each_link(req, req)
7030 static __cold void io_drain_req(struct io_kiocb *req)
7032 struct io_ring_ctx *ctx = req->ctx;
7033 struct io_defer_entry *de;
7035 u32 seq = io_get_sequence(req);
7037 /* Still need defer if there is pending req in defer list. */
7038 spin_lock(&ctx->completion_lock);
7039 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7040 spin_unlock(&ctx->completion_lock);
7042 ctx->drain_active = false;
7043 io_req_task_queue(req);
7046 spin_unlock(&ctx->completion_lock);
7048 ret = io_req_prep_async(req);
7051 io_req_complete_failed(req, ret);
7054 io_prep_async_link(req);
7055 de = kmalloc(sizeof(*de), GFP_KERNEL);
7061 spin_lock(&ctx->completion_lock);
7062 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7063 spin_unlock(&ctx->completion_lock);
7068 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7071 list_add_tail(&de->list, &ctx->defer_list);
7072 spin_unlock(&ctx->completion_lock);
7075 static void io_clean_op(struct io_kiocb *req)
7077 if (req->flags & REQ_F_BUFFER_SELECTED)
7078 io_put_kbuf_comp(req);
7080 if (req->flags & REQ_F_NEED_CLEANUP) {
7081 switch (req->opcode) {
7082 case IORING_OP_READV:
7083 case IORING_OP_READ_FIXED:
7084 case IORING_OP_READ:
7085 case IORING_OP_WRITEV:
7086 case IORING_OP_WRITE_FIXED:
7087 case IORING_OP_WRITE: {
7088 struct io_async_rw *io = req->async_data;
7090 kfree(io->free_iovec);
7093 case IORING_OP_RECVMSG:
7094 case IORING_OP_SENDMSG: {
7095 struct io_async_msghdr *io = req->async_data;
7097 kfree(io->free_iov);
7100 case IORING_OP_SPLICE:
7102 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
7103 io_put_file(req->splice.file_in);
7105 case IORING_OP_OPENAT:
7106 case IORING_OP_OPENAT2:
7107 if (req->open.filename)
7108 putname(req->open.filename);
7110 case IORING_OP_RENAMEAT:
7111 putname(req->rename.oldpath);
7112 putname(req->rename.newpath);
7114 case IORING_OP_UNLINKAT:
7115 putname(req->unlink.filename);
7117 case IORING_OP_MKDIRAT:
7118 putname(req->mkdir.filename);
7120 case IORING_OP_SYMLINKAT:
7121 putname(req->symlink.oldpath);
7122 putname(req->symlink.newpath);
7124 case IORING_OP_LINKAT:
7125 putname(req->hardlink.oldpath);
7126 putname(req->hardlink.newpath);
7128 case IORING_OP_STATX:
7129 if (req->statx.filename)
7130 putname(req->statx.filename);
7134 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7135 kfree(req->apoll->double_poll);
7139 if (req->flags & REQ_F_INFLIGHT) {
7140 struct io_uring_task *tctx = req->task->io_uring;
7142 atomic_dec(&tctx->inflight_tracked);
7144 if (req->flags & REQ_F_CREDS)
7145 put_cred(req->creds);
7146 if (req->flags & REQ_F_ASYNC_DATA) {
7147 kfree(req->async_data);
7148 req->async_data = NULL;
7150 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7153 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7155 const struct cred *creds = NULL;
7158 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7159 creds = override_creds(req->creds);
7161 if (!io_op_defs[req->opcode].audit_skip)
7162 audit_uring_entry(req->opcode);
7164 switch (req->opcode) {
7166 ret = io_nop(req, issue_flags);
7168 case IORING_OP_READV:
7169 case IORING_OP_READ_FIXED:
7170 case IORING_OP_READ:
7171 ret = io_read(req, issue_flags);
7173 case IORING_OP_WRITEV:
7174 case IORING_OP_WRITE_FIXED:
7175 case IORING_OP_WRITE:
7176 ret = io_write(req, issue_flags);
7178 case IORING_OP_FSYNC:
7179 ret = io_fsync(req, issue_flags);
7181 case IORING_OP_POLL_ADD:
7182 ret = io_poll_add(req, issue_flags);
7184 case IORING_OP_POLL_REMOVE:
7185 ret = io_poll_update(req, issue_flags);
7187 case IORING_OP_SYNC_FILE_RANGE:
7188 ret = io_sync_file_range(req, issue_flags);
7190 case IORING_OP_SENDMSG:
7191 ret = io_sendmsg(req, issue_flags);
7193 case IORING_OP_SEND:
7194 ret = io_send(req, issue_flags);
7196 case IORING_OP_RECVMSG:
7197 ret = io_recvmsg(req, issue_flags);
7199 case IORING_OP_RECV:
7200 ret = io_recv(req, issue_flags);
7202 case IORING_OP_TIMEOUT:
7203 ret = io_timeout(req, issue_flags);
7205 case IORING_OP_TIMEOUT_REMOVE:
7206 ret = io_timeout_remove(req, issue_flags);
7208 case IORING_OP_ACCEPT:
7209 ret = io_accept(req, issue_flags);
7211 case IORING_OP_CONNECT:
7212 ret = io_connect(req, issue_flags);
7214 case IORING_OP_ASYNC_CANCEL:
7215 ret = io_async_cancel(req, issue_flags);
7217 case IORING_OP_FALLOCATE:
7218 ret = io_fallocate(req, issue_flags);
7220 case IORING_OP_OPENAT:
7221 ret = io_openat(req, issue_flags);
7223 case IORING_OP_CLOSE:
7224 ret = io_close(req, issue_flags);
7226 case IORING_OP_FILES_UPDATE:
7227 ret = io_files_update(req, issue_flags);
7229 case IORING_OP_STATX:
7230 ret = io_statx(req, issue_flags);
7232 case IORING_OP_FADVISE:
7233 ret = io_fadvise(req, issue_flags);
7235 case IORING_OP_MADVISE:
7236 ret = io_madvise(req, issue_flags);
7238 case IORING_OP_OPENAT2:
7239 ret = io_openat2(req, issue_flags);
7241 case IORING_OP_EPOLL_CTL:
7242 ret = io_epoll_ctl(req, issue_flags);
7244 case IORING_OP_SPLICE:
7245 ret = io_splice(req, issue_flags);
7247 case IORING_OP_PROVIDE_BUFFERS:
7248 ret = io_provide_buffers(req, issue_flags);
7250 case IORING_OP_REMOVE_BUFFERS:
7251 ret = io_remove_buffers(req, issue_flags);
7254 ret = io_tee(req, issue_flags);
7256 case IORING_OP_SHUTDOWN:
7257 ret = io_shutdown(req, issue_flags);
7259 case IORING_OP_RENAMEAT:
7260 ret = io_renameat(req, issue_flags);
7262 case IORING_OP_UNLINKAT:
7263 ret = io_unlinkat(req, issue_flags);
7265 case IORING_OP_MKDIRAT:
7266 ret = io_mkdirat(req, issue_flags);
7268 case IORING_OP_SYMLINKAT:
7269 ret = io_symlinkat(req, issue_flags);
7271 case IORING_OP_LINKAT:
7272 ret = io_linkat(req, issue_flags);
7274 case IORING_OP_MSG_RING:
7275 ret = io_msg_ring(req, issue_flags);
7282 if (!io_op_defs[req->opcode].audit_skip)
7283 audit_uring_exit(!ret, ret);
7286 revert_creds(creds);
7289 /* If the op doesn't have a file, we're not polling for it */
7290 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7291 io_iopoll_req_issued(req, issue_flags);
7296 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7298 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7300 req = io_put_req_find_next(req);
7301 return req ? &req->work : NULL;
7304 static void io_wq_submit_work(struct io_wq_work *work)
7306 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7307 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7308 bool needs_poll = false;
7309 struct io_kiocb *timeout;
7312 /* one will be dropped by ->io_free_work() after returning to io-wq */
7313 if (!(req->flags & REQ_F_REFCOUNT))
7314 __io_req_set_refcount(req, 2);
7318 timeout = io_prep_linked_timeout(req);
7320 io_queue_linked_timeout(timeout);
7322 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7323 if (work->flags & IO_WQ_WORK_CANCEL) {
7324 io_req_task_queue_fail(req, -ECANCELED);
7328 if (req->flags & REQ_F_FORCE_ASYNC) {
7329 const struct io_op_def *def = &io_op_defs[req->opcode];
7330 bool opcode_poll = def->pollin || def->pollout;
7332 if (opcode_poll && file_can_poll(req->file)) {
7334 issue_flags |= IO_URING_F_NONBLOCK;
7339 ret = io_issue_sqe(req, issue_flags);
7343 * We can get EAGAIN for iopolled IO even though we're
7344 * forcing a sync submission from here, since we can't
7345 * wait for request slots on the block side.
7352 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7354 /* aborted or ready, in either case retry blocking */
7356 issue_flags &= ~IO_URING_F_NONBLOCK;
7359 /* avoid locking problems by failing it from a clean context */
7361 io_req_task_queue_fail(req, ret);
7364 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7367 return &table->files[i];
7370 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7373 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7375 return (struct file *) (slot->file_ptr & FFS_MASK);
7378 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7380 unsigned long file_ptr = (unsigned long) file;
7382 file_ptr |= io_file_get_flags(file);
7383 file_slot->file_ptr = file_ptr;
7386 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7387 struct io_kiocb *req, int fd)
7390 unsigned long file_ptr;
7392 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7394 fd = array_index_nospec(fd, ctx->nr_user_files);
7395 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7396 file = (struct file *) (file_ptr & FFS_MASK);
7397 file_ptr &= ~FFS_MASK;
7398 /* mask in overlapping REQ_F and FFS bits */
7399 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7400 io_req_set_rsrc_node(req, ctx);
7404 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7405 struct io_kiocb *req, int fd)
7407 struct file *file = fget(fd);
7409 trace_io_uring_file_get(ctx, req, req->user_data, fd);
7411 /* we don't allow fixed io_uring files */
7412 if (file && unlikely(file->f_op == &io_uring_fops))
7413 io_req_track_inflight(req);
7417 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7418 struct io_kiocb *req, int fd, bool fixed)
7421 return io_file_get_fixed(ctx, req, fd);
7423 return io_file_get_normal(ctx, req, fd);
7426 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7428 struct io_kiocb *prev = req->timeout.prev;
7432 if (!(req->task->flags & PF_EXITING))
7433 ret = io_try_cancel_userdata(req, prev->user_data);
7434 io_req_complete_post(req, ret ?: -ETIME, 0);
7437 io_req_complete_post(req, -ETIME, 0);
7441 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7443 struct io_timeout_data *data = container_of(timer,
7444 struct io_timeout_data, timer);
7445 struct io_kiocb *prev, *req = data->req;
7446 struct io_ring_ctx *ctx = req->ctx;
7447 unsigned long flags;
7449 spin_lock_irqsave(&ctx->timeout_lock, flags);
7450 prev = req->timeout.head;
7451 req->timeout.head = NULL;
7454 * We don't expect the list to be empty, that will only happen if we
7455 * race with the completion of the linked work.
7458 io_remove_next_linked(prev);
7459 if (!req_ref_inc_not_zero(prev))
7462 list_del(&req->timeout.list);
7463 req->timeout.prev = prev;
7464 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7466 req->io_task_work.func = io_req_task_link_timeout;
7467 io_req_task_work_add(req, false);
7468 return HRTIMER_NORESTART;
7471 static void io_queue_linked_timeout(struct io_kiocb *req)
7473 struct io_ring_ctx *ctx = req->ctx;
7475 spin_lock_irq(&ctx->timeout_lock);
7477 * If the back reference is NULL, then our linked request finished
7478 * before we got a chance to setup the timer
7480 if (req->timeout.head) {
7481 struct io_timeout_data *data = req->async_data;
7483 data->timer.function = io_link_timeout_fn;
7484 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7486 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7488 spin_unlock_irq(&ctx->timeout_lock);
7489 /* drop submission reference */
7493 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7494 __must_hold(&req->ctx->uring_lock)
7496 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7498 switch (io_arm_poll_handler(req, 0)) {
7499 case IO_APOLL_READY:
7500 io_req_task_queue(req);
7502 case IO_APOLL_ABORTED:
7504 * Queued up for async execution, worker will release
7505 * submit reference when the iocb is actually submitted.
7507 io_kbuf_recycle(req);
7508 io_queue_async_work(req, NULL);
7511 io_kbuf_recycle(req);
7516 io_queue_linked_timeout(linked_timeout);
7519 static inline void __io_queue_sqe(struct io_kiocb *req)
7520 __must_hold(&req->ctx->uring_lock)
7522 struct io_kiocb *linked_timeout;
7525 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7527 if (req->flags & REQ_F_COMPLETE_INLINE) {
7528 io_req_add_compl_list(req);
7532 * We async punt it if the file wasn't marked NOWAIT, or if the file
7533 * doesn't support non-blocking read/write attempts
7536 linked_timeout = io_prep_linked_timeout(req);
7538 io_queue_linked_timeout(linked_timeout);
7539 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7540 io_queue_sqe_arm_apoll(req);
7542 io_req_complete_failed(req, ret);
7546 static void io_queue_sqe_fallback(struct io_kiocb *req)
7547 __must_hold(&req->ctx->uring_lock)
7549 if (req->flags & REQ_F_FAIL) {
7550 io_req_complete_fail_submit(req);
7551 } else if (unlikely(req->ctx->drain_active)) {
7554 int ret = io_req_prep_async(req);
7557 io_req_complete_failed(req, ret);
7559 io_queue_async_work(req, NULL);
7563 static inline void io_queue_sqe(struct io_kiocb *req)
7564 __must_hold(&req->ctx->uring_lock)
7566 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7567 __io_queue_sqe(req);
7569 io_queue_sqe_fallback(req);
7573 * Check SQE restrictions (opcode and flags).
7575 * Returns 'true' if SQE is allowed, 'false' otherwise.
7577 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7578 struct io_kiocb *req,
7579 unsigned int sqe_flags)
7581 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7584 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7585 ctx->restrictions.sqe_flags_required)
7588 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7589 ctx->restrictions.sqe_flags_required))
7595 static void io_init_req_drain(struct io_kiocb *req)
7597 struct io_ring_ctx *ctx = req->ctx;
7598 struct io_kiocb *head = ctx->submit_state.link.head;
7600 ctx->drain_active = true;
7603 * If we need to drain a request in the middle of a link, drain
7604 * the head request and the next request/link after the current
7605 * link. Considering sequential execution of links,
7606 * REQ_F_IO_DRAIN will be maintained for every request of our
7609 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7610 ctx->drain_next = true;
7614 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7615 const struct io_uring_sqe *sqe)
7616 __must_hold(&ctx->uring_lock)
7618 unsigned int sqe_flags;
7622 /* req is partially pre-initialised, see io_preinit_req() */
7623 req->opcode = opcode = READ_ONCE(sqe->opcode);
7624 /* same numerical values with corresponding REQ_F_*, safe to copy */
7625 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7626 req->user_data = READ_ONCE(sqe->user_data);
7628 req->fixed_rsrc_refs = NULL;
7629 req->task = current;
7631 if (unlikely(opcode >= IORING_OP_LAST)) {
7635 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7636 /* enforce forwards compatibility on users */
7637 if (sqe_flags & ~SQE_VALID_FLAGS)
7639 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7640 !io_op_defs[opcode].buffer_select)
7642 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7643 ctx->drain_disabled = true;
7644 if (sqe_flags & IOSQE_IO_DRAIN) {
7645 if (ctx->drain_disabled)
7647 io_init_req_drain(req);
7650 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7651 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7653 /* knock it to the slow queue path, will be drained there */
7654 if (ctx->drain_active)
7655 req->flags |= REQ_F_FORCE_ASYNC;
7656 /* if there is no link, we're at "next" request and need to drain */
7657 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7658 ctx->drain_next = false;
7659 ctx->drain_active = true;
7660 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7664 if (io_op_defs[opcode].needs_file) {
7665 struct io_submit_state *state = &ctx->submit_state;
7668 * Plug now if we have more than 2 IO left after this, and the
7669 * target is potentially a read/write to block based storage.
7671 if (state->need_plug && io_op_defs[opcode].plug) {
7672 state->plug_started = true;
7673 state->need_plug = false;
7674 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7677 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7678 (sqe_flags & IOSQE_FIXED_FILE));
7679 if (unlikely(!req->file))
7683 personality = READ_ONCE(sqe->personality);
7687 req->creds = xa_load(&ctx->personalities, personality);
7690 get_cred(req->creds);
7691 ret = security_uring_override_creds(req->creds);
7693 put_cred(req->creds);
7696 req->flags |= REQ_F_CREDS;
7699 return io_req_prep(req, sqe);
7702 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7703 const struct io_uring_sqe *sqe)
7704 __must_hold(&ctx->uring_lock)
7706 struct io_submit_link *link = &ctx->submit_state.link;
7709 ret = io_init_req(ctx, req, sqe);
7710 if (unlikely(ret)) {
7711 trace_io_uring_req_failed(sqe, ctx, req, ret);
7713 /* fail even hard links since we don't submit */
7716 * we can judge a link req is failed or cancelled by if
7717 * REQ_F_FAIL is set, but the head is an exception since
7718 * it may be set REQ_F_FAIL because of other req's failure
7719 * so let's leverage req->result to distinguish if a head
7720 * is set REQ_F_FAIL because of its failure or other req's
7721 * failure so that we can set the correct ret code for it.
7722 * init result here to avoid affecting the normal path.
7724 if (!(link->head->flags & REQ_F_FAIL))
7725 req_fail_link_node(link->head, -ECANCELED);
7726 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7728 * the current req is a normal req, we should return
7729 * error and thus break the submittion loop.
7731 io_req_complete_failed(req, ret);
7734 req_fail_link_node(req, ret);
7737 /* don't need @sqe from now on */
7738 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7740 ctx->flags & IORING_SETUP_SQPOLL);
7743 * If we already have a head request, queue this one for async
7744 * submittal once the head completes. If we don't have a head but
7745 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7746 * submitted sync once the chain is complete. If none of those
7747 * conditions are true (normal request), then just queue it.
7750 struct io_kiocb *head = link->head;
7752 if (!(req->flags & REQ_F_FAIL)) {
7753 ret = io_req_prep_async(req);
7754 if (unlikely(ret)) {
7755 req_fail_link_node(req, ret);
7756 if (!(head->flags & REQ_F_FAIL))
7757 req_fail_link_node(head, -ECANCELED);
7760 trace_io_uring_link(ctx, req, head);
7761 link->last->link = req;
7764 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7766 /* last request of a link, enqueue the link */
7769 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7780 * Batched submission is done, ensure local IO is flushed out.
7782 static void io_submit_state_end(struct io_ring_ctx *ctx)
7784 struct io_submit_state *state = &ctx->submit_state;
7786 if (state->link.head)
7787 io_queue_sqe(state->link.head);
7788 /* flush only after queuing links as they can generate completions */
7789 io_submit_flush_completions(ctx);
7790 if (state->plug_started)
7791 blk_finish_plug(&state->plug);
7795 * Start submission side cache.
7797 static void io_submit_state_start(struct io_submit_state *state,
7798 unsigned int max_ios)
7800 state->plug_started = false;
7801 state->need_plug = max_ios > 2;
7802 state->submit_nr = max_ios;
7803 /* set only head, no need to init link_last in advance */
7804 state->link.head = NULL;
7807 static void io_commit_sqring(struct io_ring_ctx *ctx)
7809 struct io_rings *rings = ctx->rings;
7812 * Ensure any loads from the SQEs are done at this point,
7813 * since once we write the new head, the application could
7814 * write new data to them.
7816 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7820 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7821 * that is mapped by userspace. This means that care needs to be taken to
7822 * ensure that reads are stable, as we cannot rely on userspace always
7823 * being a good citizen. If members of the sqe are validated and then later
7824 * used, it's important that those reads are done through READ_ONCE() to
7825 * prevent a re-load down the line.
7827 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7829 unsigned head, mask = ctx->sq_entries - 1;
7830 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7833 * The cached sq head (or cq tail) serves two purposes:
7835 * 1) allows us to batch the cost of updating the user visible
7837 * 2) allows the kernel side to track the head on its own, even
7838 * though the application is the one updating it.
7840 head = READ_ONCE(ctx->sq_array[sq_idx]);
7841 if (likely(head < ctx->sq_entries))
7842 return &ctx->sq_sqes[head];
7844 /* drop invalid entries */
7846 WRITE_ONCE(ctx->rings->sq_dropped,
7847 READ_ONCE(ctx->rings->sq_dropped) + 1);
7851 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7852 __must_hold(&ctx->uring_lock)
7854 unsigned int entries = io_sqring_entries(ctx);
7857 if (unlikely(!entries))
7859 /* make sure SQ entry isn't read before tail */
7860 nr = min3(nr, ctx->sq_entries, entries);
7861 io_get_task_refs(nr);
7863 io_submit_state_start(&ctx->submit_state, nr);
7865 const struct io_uring_sqe *sqe;
7866 struct io_kiocb *req;
7868 if (unlikely(!io_alloc_req_refill(ctx))) {
7870 submitted = -EAGAIN;
7873 req = io_alloc_req(ctx);
7874 sqe = io_get_sqe(ctx);
7875 if (unlikely(!sqe)) {
7876 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7879 /* will complete beyond this point, count as submitted */
7881 if (io_submit_sqe(ctx, req, sqe)) {
7883 * Continue submitting even for sqe failure if the
7884 * ring was setup with IORING_SETUP_SUBMIT_ALL
7886 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7889 } while (submitted < nr);
7891 if (unlikely(submitted != nr)) {
7892 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7893 int unused = nr - ref_used;
7895 current->io_uring->cached_refs += unused;
7898 io_submit_state_end(ctx);
7899 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7900 io_commit_sqring(ctx);
7905 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7907 return READ_ONCE(sqd->state);
7910 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7912 /* Tell userspace we may need a wakeup call */
7913 spin_lock(&ctx->completion_lock);
7914 WRITE_ONCE(ctx->rings->sq_flags,
7915 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7916 spin_unlock(&ctx->completion_lock);
7919 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7921 spin_lock(&ctx->completion_lock);
7922 WRITE_ONCE(ctx->rings->sq_flags,
7923 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7924 spin_unlock(&ctx->completion_lock);
7927 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7929 unsigned int to_submit;
7932 to_submit = io_sqring_entries(ctx);
7933 /* if we're handling multiple rings, cap submit size for fairness */
7934 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7935 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7937 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7938 const struct cred *creds = NULL;
7940 if (ctx->sq_creds != current_cred())
7941 creds = override_creds(ctx->sq_creds);
7943 mutex_lock(&ctx->uring_lock);
7944 if (!wq_list_empty(&ctx->iopoll_list))
7945 io_do_iopoll(ctx, true);
7948 * Don't submit if refs are dying, good for io_uring_register(),
7949 * but also it is relied upon by io_ring_exit_work()
7951 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7952 !(ctx->flags & IORING_SETUP_R_DISABLED))
7953 ret = io_submit_sqes(ctx, to_submit);
7954 mutex_unlock(&ctx->uring_lock);
7955 #ifdef CONFIG_NET_RX_BUSY_POLL
7956 spin_lock(&ctx->napi_lock);
7957 if (!list_empty(&ctx->napi_list) &&
7958 io_napi_busy_loop(&ctx->napi_list))
7960 spin_unlock(&ctx->napi_lock);
7962 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7963 wake_up(&ctx->sqo_sq_wait);
7965 revert_creds(creds);
7971 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7973 struct io_ring_ctx *ctx;
7974 unsigned sq_thread_idle = 0;
7976 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7977 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7978 sqd->sq_thread_idle = sq_thread_idle;
7981 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7983 bool did_sig = false;
7984 struct ksignal ksig;
7986 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7987 signal_pending(current)) {
7988 mutex_unlock(&sqd->lock);
7989 if (signal_pending(current))
7990 did_sig = get_signal(&ksig);
7992 mutex_lock(&sqd->lock);
7994 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7997 static int io_sq_thread(void *data)
7999 struct io_sq_data *sqd = data;
8000 struct io_ring_ctx *ctx;
8001 unsigned long timeout = 0;
8002 char buf[TASK_COMM_LEN];
8005 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8006 set_task_comm(current, buf);
8008 if (sqd->sq_cpu != -1)
8009 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8011 set_cpus_allowed_ptr(current, cpu_online_mask);
8012 current->flags |= PF_NO_SETAFFINITY;
8014 audit_alloc_kernel(current);
8016 mutex_lock(&sqd->lock);
8018 bool cap_entries, sqt_spin = false;
8020 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8021 if (io_sqd_handle_event(sqd))
8023 timeout = jiffies + sqd->sq_thread_idle;
8026 cap_entries = !list_is_singular(&sqd->ctx_list);
8027 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8028 int ret = __io_sq_thread(ctx, cap_entries);
8030 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8033 if (io_run_task_work())
8036 if (sqt_spin || !time_after(jiffies, timeout)) {
8039 timeout = jiffies + sqd->sq_thread_idle;
8043 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8044 if (!io_sqd_events_pending(sqd) && !current->task_works) {
8045 bool needs_sched = true;
8047 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8048 io_ring_set_wakeup_flag(ctx);
8050 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8051 !wq_list_empty(&ctx->iopoll_list)) {
8052 needs_sched = false;
8055 if (io_sqring_entries(ctx)) {
8056 needs_sched = false;
8062 mutex_unlock(&sqd->lock);
8064 mutex_lock(&sqd->lock);
8066 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8067 io_ring_clear_wakeup_flag(ctx);
8070 finish_wait(&sqd->wait, &wait);
8071 timeout = jiffies + sqd->sq_thread_idle;
8074 io_uring_cancel_generic(true, sqd);
8076 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8077 io_ring_set_wakeup_flag(ctx);
8079 mutex_unlock(&sqd->lock);
8081 audit_free(current);
8083 complete(&sqd->exited);
8087 struct io_wait_queue {
8088 struct wait_queue_entry wq;
8089 struct io_ring_ctx *ctx;
8091 unsigned nr_timeouts;
8092 #ifdef CONFIG_NET_RX_BUSY_POLL
8093 unsigned busy_poll_to;
8097 static inline bool io_should_wake(struct io_wait_queue *iowq)
8099 struct io_ring_ctx *ctx = iowq->ctx;
8100 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8103 * Wake up if we have enough events, or if a timeout occurred since we
8104 * started waiting. For timeouts, we always want to return to userspace,
8105 * regardless of event count.
8107 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8110 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8111 int wake_flags, void *key)
8113 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8117 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8118 * the task, and the next invocation will do it.
8120 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8121 return autoremove_wake_function(curr, mode, wake_flags, key);
8125 static int io_run_task_work_sig(void)
8127 if (io_run_task_work())
8129 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8130 return -ERESTARTSYS;
8131 if (task_sigpending(current))
8136 /* when returns >0, the caller should retry */
8137 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8138 struct io_wait_queue *iowq,
8143 /* make sure we run task_work before checking for signals */
8144 ret = io_run_task_work_sig();
8145 if (ret || io_should_wake(iowq))
8147 /* let the caller flush overflows, retry */
8148 if (test_bit(0, &ctx->check_cq_overflow))
8151 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8156 #ifdef CONFIG_NET_RX_BUSY_POLL
8157 static void io_adjust_busy_loop_timeout(struct timespec64 *ts,
8158 struct io_wait_queue *iowq)
8160 unsigned busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8161 struct timespec64 pollto = ns_to_timespec64(1000 * (s64)busy_poll_to);
8163 if (timespec64_compare(ts, &pollto) > 0) {
8164 *ts = timespec64_sub(*ts, pollto);
8165 iowq->busy_poll_to = busy_poll_to;
8167 u64 to = timespec64_to_ns(ts);
8170 iowq->busy_poll_to = to;
8176 static inline bool io_busy_loop_timeout(unsigned long start_time,
8177 unsigned long bp_usec)
8180 unsigned long end_time = start_time + bp_usec;
8181 unsigned long now = busy_loop_current_time();
8183 return time_after(now, end_time);
8188 static bool io_busy_loop_end(void *p, unsigned long start_time)
8190 struct io_wait_queue *iowq = p;
8192 return signal_pending(current) ||
8193 io_should_wake(iowq) ||
8194 io_busy_loop_timeout(start_time, iowq->busy_poll_to);
8197 static void io_blocking_napi_busy_loop(struct list_head *napi_list,
8198 struct io_wait_queue *iowq)
8200 unsigned long start_time =
8201 list_is_singular(napi_list) ? 0 :
8202 busy_loop_current_time();
8205 if (list_is_singular(napi_list)) {
8206 struct napi_entry *ne =
8207 list_first_entry(napi_list,
8208 struct napi_entry, list);
8210 napi_busy_loop(ne->napi_id, io_busy_loop_end, iowq,
8211 true, BUSY_POLL_BUDGET);
8212 io_check_napi_entry_timeout(ne);
8215 } while (io_napi_busy_loop(napi_list) &&
8216 !io_busy_loop_end(iowq, start_time));
8219 static void io_putback_napi_list(struct io_ring_ctx *ctx,
8220 struct list_head *napi_list)
8222 struct napi_entry *cne, *lne;
8224 spin_lock(&ctx->napi_lock);
8225 list_for_each_entry(cne, &ctx->napi_list, list)
8226 list_for_each_entry(lne, napi_list, list)
8227 if (cne->napi_id == lne->napi_id) {
8228 list_del(&lne->list);
8232 list_splice(napi_list, &ctx->napi_list);
8233 spin_unlock(&ctx->napi_lock);
8235 #endif /* CONFIG_NET_RX_BUSY_POLL */
8238 * Wait until events become available, if we don't already have some. The
8239 * application must reap them itself, as they reside on the shared cq ring.
8241 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8242 const sigset_t __user *sig, size_t sigsz,
8243 struct __kernel_timespec __user *uts)
8245 struct io_wait_queue iowq;
8246 struct io_rings *rings = ctx->rings;
8247 ktime_t timeout = KTIME_MAX;
8249 #ifdef CONFIG_NET_RX_BUSY_POLL
8250 LIST_HEAD(local_napi_list);
8254 io_cqring_overflow_flush(ctx);
8255 if (io_cqring_events(ctx) >= min_events)
8257 if (!io_run_task_work())
8262 #ifdef CONFIG_COMPAT
8263 if (in_compat_syscall())
8264 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8268 ret = set_user_sigmask(sig, sigsz);
8274 #ifdef CONFIG_NET_RX_BUSY_POLL
8275 iowq.busy_poll_to = 0;
8276 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8277 spin_lock(&ctx->napi_lock);
8278 list_splice_init(&ctx->napi_list, &local_napi_list);
8279 spin_unlock(&ctx->napi_lock);
8283 struct timespec64 ts;
8285 if (get_timespec64(&ts, uts))
8287 #ifdef CONFIG_NET_RX_BUSY_POLL
8288 if (!list_empty(&local_napi_list))
8289 io_adjust_busy_loop_timeout(&ts, &iowq);
8291 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8293 #ifdef CONFIG_NET_RX_BUSY_POLL
8294 else if (!list_empty(&local_napi_list))
8295 iowq.busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8298 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8299 iowq.wq.private = current;
8300 INIT_LIST_HEAD(&iowq.wq.entry);
8302 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8303 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8305 trace_io_uring_cqring_wait(ctx, min_events);
8306 #ifdef CONFIG_NET_RX_BUSY_POLL
8307 if (iowq.busy_poll_to)
8308 io_blocking_napi_busy_loop(&local_napi_list, &iowq);
8309 if (!list_empty(&local_napi_list))
8310 io_putback_napi_list(ctx, &local_napi_list);
8313 /* if we can't even flush overflow, don't wait for more */
8314 if (!io_cqring_overflow_flush(ctx)) {
8318 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8319 TASK_INTERRUPTIBLE);
8320 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8321 finish_wait(&ctx->cq_wait, &iowq.wq);
8325 restore_saved_sigmask_unless(ret == -EINTR);
8327 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8330 static void io_free_page_table(void **table, size_t size)
8332 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8334 for (i = 0; i < nr_tables; i++)
8339 static __cold void **io_alloc_page_table(size_t size)
8341 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8342 size_t init_size = size;
8345 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8349 for (i = 0; i < nr_tables; i++) {
8350 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8352 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8354 io_free_page_table(table, init_size);
8362 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8364 percpu_ref_exit(&ref_node->refs);
8368 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8370 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8371 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8372 unsigned long flags;
8373 bool first_add = false;
8374 unsigned long delay = HZ;
8376 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8379 /* if we are mid-quiesce then do not delay */
8380 if (node->rsrc_data->quiesce)
8383 while (!list_empty(&ctx->rsrc_ref_list)) {
8384 node = list_first_entry(&ctx->rsrc_ref_list,
8385 struct io_rsrc_node, node);
8386 /* recycle ref nodes in order */
8389 list_del(&node->node);
8390 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8392 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8395 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8398 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8400 struct io_rsrc_node *ref_node;
8402 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8406 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8411 INIT_LIST_HEAD(&ref_node->node);
8412 INIT_LIST_HEAD(&ref_node->rsrc_list);
8413 ref_node->done = false;
8417 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8418 struct io_rsrc_data *data_to_kill)
8419 __must_hold(&ctx->uring_lock)
8421 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8422 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8424 io_rsrc_refs_drop(ctx);
8427 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8429 rsrc_node->rsrc_data = data_to_kill;
8430 spin_lock_irq(&ctx->rsrc_ref_lock);
8431 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8432 spin_unlock_irq(&ctx->rsrc_ref_lock);
8434 atomic_inc(&data_to_kill->refs);
8435 percpu_ref_kill(&rsrc_node->refs);
8436 ctx->rsrc_node = NULL;
8439 if (!ctx->rsrc_node) {
8440 ctx->rsrc_node = ctx->rsrc_backup_node;
8441 ctx->rsrc_backup_node = NULL;
8445 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8447 if (ctx->rsrc_backup_node)
8449 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8450 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8453 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8454 struct io_ring_ctx *ctx)
8458 /* As we may drop ->uring_lock, other task may have started quiesce */
8462 data->quiesce = true;
8464 ret = io_rsrc_node_switch_start(ctx);
8467 io_rsrc_node_switch(ctx, data);
8469 /* kill initial ref, already quiesced if zero */
8470 if (atomic_dec_and_test(&data->refs))
8472 mutex_unlock(&ctx->uring_lock);
8473 flush_delayed_work(&ctx->rsrc_put_work);
8474 ret = wait_for_completion_interruptible(&data->done);
8476 mutex_lock(&ctx->uring_lock);
8477 if (atomic_read(&data->refs) > 0) {
8479 * it has been revived by another thread while
8482 mutex_unlock(&ctx->uring_lock);
8488 atomic_inc(&data->refs);
8489 /* wait for all works potentially completing data->done */
8490 flush_delayed_work(&ctx->rsrc_put_work);
8491 reinit_completion(&data->done);
8493 ret = io_run_task_work_sig();
8494 mutex_lock(&ctx->uring_lock);
8496 data->quiesce = false;
8501 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8503 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8504 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8506 return &data->tags[table_idx][off];
8509 static void io_rsrc_data_free(struct io_rsrc_data *data)
8511 size_t size = data->nr * sizeof(data->tags[0][0]);
8514 io_free_page_table((void **)data->tags, size);
8518 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8519 u64 __user *utags, unsigned nr,
8520 struct io_rsrc_data **pdata)
8522 struct io_rsrc_data *data;
8526 data = kzalloc(sizeof(*data), GFP_KERNEL);
8529 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8537 data->do_put = do_put;
8540 for (i = 0; i < nr; i++) {
8541 u64 *tag_slot = io_get_tag_slot(data, i);
8543 if (copy_from_user(tag_slot, &utags[i],
8549 atomic_set(&data->refs, 1);
8550 init_completion(&data->done);
8554 io_rsrc_data_free(data);
8558 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8560 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8561 GFP_KERNEL_ACCOUNT);
8562 return !!table->files;
8565 static void io_free_file_tables(struct io_file_table *table)
8567 kvfree(table->files);
8568 table->files = NULL;
8571 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8573 #if defined(CONFIG_UNIX)
8574 if (ctx->ring_sock) {
8575 struct sock *sock = ctx->ring_sock->sk;
8576 struct sk_buff *skb;
8578 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8584 for (i = 0; i < ctx->nr_user_files; i++) {
8587 file = io_file_from_index(ctx, i);
8592 io_free_file_tables(&ctx->file_table);
8593 io_rsrc_data_free(ctx->file_data);
8594 ctx->file_data = NULL;
8595 ctx->nr_user_files = 0;
8598 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8602 if (!ctx->file_data)
8604 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8606 __io_sqe_files_unregister(ctx);
8610 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8611 __releases(&sqd->lock)
8613 WARN_ON_ONCE(sqd->thread == current);
8616 * Do the dance but not conditional clear_bit() because it'd race with
8617 * other threads incrementing park_pending and setting the bit.
8619 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8620 if (atomic_dec_return(&sqd->park_pending))
8621 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8622 mutex_unlock(&sqd->lock);
8625 static void io_sq_thread_park(struct io_sq_data *sqd)
8626 __acquires(&sqd->lock)
8628 WARN_ON_ONCE(sqd->thread == current);
8630 atomic_inc(&sqd->park_pending);
8631 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8632 mutex_lock(&sqd->lock);
8634 wake_up_process(sqd->thread);
8637 static void io_sq_thread_stop(struct io_sq_data *sqd)
8639 WARN_ON_ONCE(sqd->thread == current);
8640 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8642 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8643 mutex_lock(&sqd->lock);
8645 wake_up_process(sqd->thread);
8646 mutex_unlock(&sqd->lock);
8647 wait_for_completion(&sqd->exited);
8650 static void io_put_sq_data(struct io_sq_data *sqd)
8652 if (refcount_dec_and_test(&sqd->refs)) {
8653 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8655 io_sq_thread_stop(sqd);
8660 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8662 struct io_sq_data *sqd = ctx->sq_data;
8665 io_sq_thread_park(sqd);
8666 list_del_init(&ctx->sqd_list);
8667 io_sqd_update_thread_idle(sqd);
8668 io_sq_thread_unpark(sqd);
8670 io_put_sq_data(sqd);
8671 ctx->sq_data = NULL;
8675 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8677 struct io_ring_ctx *ctx_attach;
8678 struct io_sq_data *sqd;
8681 f = fdget(p->wq_fd);
8683 return ERR_PTR(-ENXIO);
8684 if (f.file->f_op != &io_uring_fops) {
8686 return ERR_PTR(-EINVAL);
8689 ctx_attach = f.file->private_data;
8690 sqd = ctx_attach->sq_data;
8693 return ERR_PTR(-EINVAL);
8695 if (sqd->task_tgid != current->tgid) {
8697 return ERR_PTR(-EPERM);
8700 refcount_inc(&sqd->refs);
8705 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8708 struct io_sq_data *sqd;
8711 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8712 sqd = io_attach_sq_data(p);
8717 /* fall through for EPERM case, setup new sqd/task */
8718 if (PTR_ERR(sqd) != -EPERM)
8722 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8724 return ERR_PTR(-ENOMEM);
8726 atomic_set(&sqd->park_pending, 0);
8727 refcount_set(&sqd->refs, 1);
8728 INIT_LIST_HEAD(&sqd->ctx_list);
8729 mutex_init(&sqd->lock);
8730 init_waitqueue_head(&sqd->wait);
8731 init_completion(&sqd->exited);
8735 #if defined(CONFIG_UNIX)
8737 * Ensure the UNIX gc is aware of our file set, so we are certain that
8738 * the io_uring can be safely unregistered on process exit, even if we have
8739 * loops in the file referencing.
8741 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8743 struct sock *sk = ctx->ring_sock->sk;
8744 struct scm_fp_list *fpl;
8745 struct sk_buff *skb;
8748 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8752 skb = alloc_skb(0, GFP_KERNEL);
8761 fpl->user = get_uid(current_user());
8762 for (i = 0; i < nr; i++) {
8763 struct file *file = io_file_from_index(ctx, i + offset);
8767 fpl->fp[nr_files] = get_file(file);
8768 unix_inflight(fpl->user, fpl->fp[nr_files]);
8773 fpl->max = SCM_MAX_FD;
8774 fpl->count = nr_files;
8775 UNIXCB(skb).fp = fpl;
8776 skb->destructor = unix_destruct_scm;
8777 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8778 skb_queue_head(&sk->sk_receive_queue, skb);
8780 for (i = 0; i < nr_files; i++)
8791 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8792 * causes regular reference counting to break down. We rely on the UNIX
8793 * garbage collection to take care of this problem for us.
8795 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8797 unsigned left, total;
8801 left = ctx->nr_user_files;
8803 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8805 ret = __io_sqe_files_scm(ctx, this_files, total);
8809 total += this_files;
8815 while (total < ctx->nr_user_files) {
8816 struct file *file = io_file_from_index(ctx, total);
8826 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8832 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8834 struct file *file = prsrc->file;
8835 #if defined(CONFIG_UNIX)
8836 struct sock *sock = ctx->ring_sock->sk;
8837 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8838 struct sk_buff *skb;
8841 __skb_queue_head_init(&list);
8844 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8845 * remove this entry and rearrange the file array.
8847 skb = skb_dequeue(head);
8849 struct scm_fp_list *fp;
8851 fp = UNIXCB(skb).fp;
8852 for (i = 0; i < fp->count; i++) {
8855 if (fp->fp[i] != file)
8858 unix_notinflight(fp->user, fp->fp[i]);
8859 left = fp->count - 1 - i;
8861 memmove(&fp->fp[i], &fp->fp[i + 1],
8862 left * sizeof(struct file *));
8869 __skb_queue_tail(&list, skb);
8879 __skb_queue_tail(&list, skb);
8881 skb = skb_dequeue(head);
8884 if (skb_peek(&list)) {
8885 spin_lock_irq(&head->lock);
8886 while ((skb = __skb_dequeue(&list)) != NULL)
8887 __skb_queue_tail(head, skb);
8888 spin_unlock_irq(&head->lock);
8895 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8897 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8898 struct io_ring_ctx *ctx = rsrc_data->ctx;
8899 struct io_rsrc_put *prsrc, *tmp;
8901 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8902 list_del(&prsrc->list);
8905 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8907 io_ring_submit_lock(ctx, lock_ring);
8908 spin_lock(&ctx->completion_lock);
8909 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8910 io_commit_cqring(ctx);
8911 spin_unlock(&ctx->completion_lock);
8912 io_cqring_ev_posted(ctx);
8913 io_ring_submit_unlock(ctx, lock_ring);
8916 rsrc_data->do_put(ctx, prsrc);
8920 io_rsrc_node_destroy(ref_node);
8921 if (atomic_dec_and_test(&rsrc_data->refs))
8922 complete(&rsrc_data->done);
8925 static void io_rsrc_put_work(struct work_struct *work)
8927 struct io_ring_ctx *ctx;
8928 struct llist_node *node;
8930 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8931 node = llist_del_all(&ctx->rsrc_put_llist);
8934 struct io_rsrc_node *ref_node;
8935 struct llist_node *next = node->next;
8937 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8938 __io_rsrc_put_work(ref_node);
8943 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8944 unsigned nr_args, u64 __user *tags)
8946 __s32 __user *fds = (__s32 __user *) arg;
8955 if (nr_args > IORING_MAX_FIXED_FILES)
8957 if (nr_args > rlimit(RLIMIT_NOFILE))
8959 ret = io_rsrc_node_switch_start(ctx);
8962 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8968 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8971 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8972 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8976 /* allow sparse sets */
8979 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8986 if (unlikely(!file))
8990 * Don't allow io_uring instances to be registered. If UNIX
8991 * isn't enabled, then this causes a reference cycle and this
8992 * instance can never get freed. If UNIX is enabled we'll
8993 * handle it just fine, but there's still no point in allowing
8994 * a ring fd as it doesn't support regular read/write anyway.
8996 if (file->f_op == &io_uring_fops) {
9000 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
9003 ret = io_sqe_files_scm(ctx);
9005 __io_sqe_files_unregister(ctx);
9009 io_rsrc_node_switch(ctx, NULL);
9012 for (i = 0; i < ctx->nr_user_files; i++) {
9013 file = io_file_from_index(ctx, i);
9017 io_free_file_tables(&ctx->file_table);
9018 ctx->nr_user_files = 0;
9020 io_rsrc_data_free(ctx->file_data);
9021 ctx->file_data = NULL;
9025 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
9028 #if defined(CONFIG_UNIX)
9029 struct sock *sock = ctx->ring_sock->sk;
9030 struct sk_buff_head *head = &sock->sk_receive_queue;
9031 struct sk_buff *skb;
9034 * See if we can merge this file into an existing skb SCM_RIGHTS
9035 * file set. If there's no room, fall back to allocating a new skb
9036 * and filling it in.
9038 spin_lock_irq(&head->lock);
9039 skb = skb_peek(head);
9041 struct scm_fp_list *fpl = UNIXCB(skb).fp;
9043 if (fpl->count < SCM_MAX_FD) {
9044 __skb_unlink(skb, head);
9045 spin_unlock_irq(&head->lock);
9046 fpl->fp[fpl->count] = get_file(file);
9047 unix_inflight(fpl->user, fpl->fp[fpl->count]);
9049 spin_lock_irq(&head->lock);
9050 __skb_queue_head(head, skb);
9055 spin_unlock_irq(&head->lock);
9062 return __io_sqe_files_scm(ctx, 1, index);
9068 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9069 struct io_rsrc_node *node, void *rsrc)
9071 struct io_rsrc_put *prsrc;
9073 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9077 prsrc->tag = *io_get_tag_slot(data, idx);
9079 list_add(&prsrc->list, &node->rsrc_list);
9083 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9084 unsigned int issue_flags, u32 slot_index)
9086 struct io_ring_ctx *ctx = req->ctx;
9087 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9088 bool needs_switch = false;
9089 struct io_fixed_file *file_slot;
9092 io_ring_submit_lock(ctx, needs_lock);
9093 if (file->f_op == &io_uring_fops)
9096 if (!ctx->file_data)
9099 if (slot_index >= ctx->nr_user_files)
9102 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9103 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9105 if (file_slot->file_ptr) {
9106 struct file *old_file;
9108 ret = io_rsrc_node_switch_start(ctx);
9112 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9113 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9114 ctx->rsrc_node, old_file);
9117 file_slot->file_ptr = 0;
9118 needs_switch = true;
9121 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9122 io_fixed_file_set(file_slot, file);
9123 ret = io_sqe_file_register(ctx, file, slot_index);
9125 file_slot->file_ptr = 0;
9132 io_rsrc_node_switch(ctx, ctx->file_data);
9133 io_ring_submit_unlock(ctx, needs_lock);
9139 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9141 unsigned int offset = req->close.file_slot - 1;
9142 struct io_ring_ctx *ctx = req->ctx;
9143 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9144 struct io_fixed_file *file_slot;
9148 io_ring_submit_lock(ctx, needs_lock);
9150 if (unlikely(!ctx->file_data))
9153 if (offset >= ctx->nr_user_files)
9155 ret = io_rsrc_node_switch_start(ctx);
9159 i = array_index_nospec(offset, ctx->nr_user_files);
9160 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9162 if (!file_slot->file_ptr)
9165 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9166 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9170 file_slot->file_ptr = 0;
9171 io_rsrc_node_switch(ctx, ctx->file_data);
9174 io_ring_submit_unlock(ctx, needs_lock);
9178 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9179 struct io_uring_rsrc_update2 *up,
9182 u64 __user *tags = u64_to_user_ptr(up->tags);
9183 __s32 __user *fds = u64_to_user_ptr(up->data);
9184 struct io_rsrc_data *data = ctx->file_data;
9185 struct io_fixed_file *file_slot;
9189 bool needs_switch = false;
9191 if (!ctx->file_data)
9193 if (up->offset + nr_args > ctx->nr_user_files)
9196 for (done = 0; done < nr_args; done++) {
9199 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9200 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9204 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9208 if (fd == IORING_REGISTER_FILES_SKIP)
9211 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9212 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9214 if (file_slot->file_ptr) {
9215 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9216 err = io_queue_rsrc_removal(data, up->offset + done,
9217 ctx->rsrc_node, file);
9220 file_slot->file_ptr = 0;
9221 needs_switch = true;
9230 * Don't allow io_uring instances to be registered. If
9231 * UNIX isn't enabled, then this causes a reference
9232 * cycle and this instance can never get freed. If UNIX
9233 * is enabled we'll handle it just fine, but there's
9234 * still no point in allowing a ring fd as it doesn't
9235 * support regular read/write anyway.
9237 if (file->f_op == &io_uring_fops) {
9242 *io_get_tag_slot(data, up->offset + done) = tag;
9243 io_fixed_file_set(file_slot, file);
9244 err = io_sqe_file_register(ctx, file, i);
9246 file_slot->file_ptr = 0;
9254 io_rsrc_node_switch(ctx, data);
9255 return done ? done : err;
9258 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9259 struct task_struct *task)
9261 struct io_wq_hash *hash;
9262 struct io_wq_data data;
9263 unsigned int concurrency;
9265 mutex_lock(&ctx->uring_lock);
9266 hash = ctx->hash_map;
9268 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9270 mutex_unlock(&ctx->uring_lock);
9271 return ERR_PTR(-ENOMEM);
9273 refcount_set(&hash->refs, 1);
9274 init_waitqueue_head(&hash->wait);
9275 ctx->hash_map = hash;
9277 mutex_unlock(&ctx->uring_lock);
9281 data.free_work = io_wq_free_work;
9282 data.do_work = io_wq_submit_work;
9284 /* Do QD, or 4 * CPUS, whatever is smallest */
9285 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9287 return io_wq_create(concurrency, &data);
9290 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9291 struct io_ring_ctx *ctx)
9293 struct io_uring_task *tctx;
9296 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9297 if (unlikely(!tctx))
9300 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9301 sizeof(struct file *), GFP_KERNEL);
9302 if (unlikely(!tctx->registered_rings)) {
9307 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9308 if (unlikely(ret)) {
9309 kfree(tctx->registered_rings);
9314 tctx->io_wq = io_init_wq_offload(ctx, task);
9315 if (IS_ERR(tctx->io_wq)) {
9316 ret = PTR_ERR(tctx->io_wq);
9317 percpu_counter_destroy(&tctx->inflight);
9318 kfree(tctx->registered_rings);
9324 init_waitqueue_head(&tctx->wait);
9325 atomic_set(&tctx->in_idle, 0);
9326 atomic_set(&tctx->inflight_tracked, 0);
9327 task->io_uring = tctx;
9328 spin_lock_init(&tctx->task_lock);
9329 INIT_WQ_LIST(&tctx->task_list);
9330 INIT_WQ_LIST(&tctx->prior_task_list);
9331 init_task_work(&tctx->task_work, tctx_task_work);
9335 void __io_uring_free(struct task_struct *tsk)
9337 struct io_uring_task *tctx = tsk->io_uring;
9339 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9340 WARN_ON_ONCE(tctx->io_wq);
9341 WARN_ON_ONCE(tctx->cached_refs);
9343 kfree(tctx->registered_rings);
9344 percpu_counter_destroy(&tctx->inflight);
9346 tsk->io_uring = NULL;
9349 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9350 struct io_uring_params *p)
9354 /* Retain compatibility with failing for an invalid attach attempt */
9355 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9356 IORING_SETUP_ATTACH_WQ) {
9359 f = fdget(p->wq_fd);
9362 if (f.file->f_op != &io_uring_fops) {
9368 if (ctx->flags & IORING_SETUP_SQPOLL) {
9369 struct task_struct *tsk;
9370 struct io_sq_data *sqd;
9373 ret = security_uring_sqpoll();
9377 sqd = io_get_sq_data(p, &attached);
9383 ctx->sq_creds = get_current_cred();
9385 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9386 if (!ctx->sq_thread_idle)
9387 ctx->sq_thread_idle = HZ;
9389 io_sq_thread_park(sqd);
9390 list_add(&ctx->sqd_list, &sqd->ctx_list);
9391 io_sqd_update_thread_idle(sqd);
9392 /* don't attach to a dying SQPOLL thread, would be racy */
9393 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9394 io_sq_thread_unpark(sqd);
9401 if (p->flags & IORING_SETUP_SQ_AFF) {
9402 int cpu = p->sq_thread_cpu;
9405 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9412 sqd->task_pid = current->pid;
9413 sqd->task_tgid = current->tgid;
9414 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9421 ret = io_uring_alloc_task_context(tsk, ctx);
9422 wake_up_new_task(tsk);
9425 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9426 /* Can't have SQ_AFF without SQPOLL */
9433 complete(&ctx->sq_data->exited);
9435 io_sq_thread_finish(ctx);
9439 static inline void __io_unaccount_mem(struct user_struct *user,
9440 unsigned long nr_pages)
9442 atomic_long_sub(nr_pages, &user->locked_vm);
9445 static inline int __io_account_mem(struct user_struct *user,
9446 unsigned long nr_pages)
9448 unsigned long page_limit, cur_pages, new_pages;
9450 /* Don't allow more pages than we can safely lock */
9451 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9454 cur_pages = atomic_long_read(&user->locked_vm);
9455 new_pages = cur_pages + nr_pages;
9456 if (new_pages > page_limit)
9458 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9459 new_pages) != cur_pages);
9464 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9467 __io_unaccount_mem(ctx->user, nr_pages);
9469 if (ctx->mm_account)
9470 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9473 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9478 ret = __io_account_mem(ctx->user, nr_pages);
9483 if (ctx->mm_account)
9484 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9489 static void io_mem_free(void *ptr)
9496 page = virt_to_head_page(ptr);
9497 if (put_page_testzero(page))
9498 free_compound_page(page);
9501 static void *io_mem_alloc(size_t size)
9503 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9505 return (void *) __get_free_pages(gfp, get_order(size));
9508 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9511 struct io_rings *rings;
9512 size_t off, sq_array_size;
9514 off = struct_size(rings, cqes, cq_entries);
9515 if (off == SIZE_MAX)
9519 off = ALIGN(off, SMP_CACHE_BYTES);
9527 sq_array_size = array_size(sizeof(u32), sq_entries);
9528 if (sq_array_size == SIZE_MAX)
9531 if (check_add_overflow(off, sq_array_size, &off))
9537 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9539 struct io_mapped_ubuf *imu = *slot;
9542 if (imu != ctx->dummy_ubuf) {
9543 for (i = 0; i < imu->nr_bvecs; i++)
9544 unpin_user_page(imu->bvec[i].bv_page);
9545 if (imu->acct_pages)
9546 io_unaccount_mem(ctx, imu->acct_pages);
9552 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9554 io_buffer_unmap(ctx, &prsrc->buf);
9558 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9562 for (i = 0; i < ctx->nr_user_bufs; i++)
9563 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9564 kfree(ctx->user_bufs);
9565 io_rsrc_data_free(ctx->buf_data);
9566 ctx->user_bufs = NULL;
9567 ctx->buf_data = NULL;
9568 ctx->nr_user_bufs = 0;
9571 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9578 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9580 __io_sqe_buffers_unregister(ctx);
9584 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9585 void __user *arg, unsigned index)
9587 struct iovec __user *src;
9589 #ifdef CONFIG_COMPAT
9591 struct compat_iovec __user *ciovs;
9592 struct compat_iovec ciov;
9594 ciovs = (struct compat_iovec __user *) arg;
9595 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9598 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9599 dst->iov_len = ciov.iov_len;
9603 src = (struct iovec __user *) arg;
9604 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9610 * Not super efficient, but this is just a registration time. And we do cache
9611 * the last compound head, so generally we'll only do a full search if we don't
9614 * We check if the given compound head page has already been accounted, to
9615 * avoid double accounting it. This allows us to account the full size of the
9616 * page, not just the constituent pages of a huge page.
9618 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9619 int nr_pages, struct page *hpage)
9623 /* check current page array */
9624 for (i = 0; i < nr_pages; i++) {
9625 if (!PageCompound(pages[i]))
9627 if (compound_head(pages[i]) == hpage)
9631 /* check previously registered pages */
9632 for (i = 0; i < ctx->nr_user_bufs; i++) {
9633 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9635 for (j = 0; j < imu->nr_bvecs; j++) {
9636 if (!PageCompound(imu->bvec[j].bv_page))
9638 if (compound_head(imu->bvec[j].bv_page) == hpage)
9646 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9647 int nr_pages, struct io_mapped_ubuf *imu,
9648 struct page **last_hpage)
9652 imu->acct_pages = 0;
9653 for (i = 0; i < nr_pages; i++) {
9654 if (!PageCompound(pages[i])) {
9659 hpage = compound_head(pages[i]);
9660 if (hpage == *last_hpage)
9662 *last_hpage = hpage;
9663 if (headpage_already_acct(ctx, pages, i, hpage))
9665 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9669 if (!imu->acct_pages)
9672 ret = io_account_mem(ctx, imu->acct_pages);
9674 imu->acct_pages = 0;
9678 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9679 struct io_mapped_ubuf **pimu,
9680 struct page **last_hpage)
9682 struct io_mapped_ubuf *imu = NULL;
9683 struct vm_area_struct **vmas = NULL;
9684 struct page **pages = NULL;
9685 unsigned long off, start, end, ubuf;
9687 int ret, pret, nr_pages, i;
9689 if (!iov->iov_base) {
9690 *pimu = ctx->dummy_ubuf;
9694 ubuf = (unsigned long) iov->iov_base;
9695 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9696 start = ubuf >> PAGE_SHIFT;
9697 nr_pages = end - start;
9702 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9706 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9711 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9716 mmap_read_lock(current->mm);
9717 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9719 if (pret == nr_pages) {
9720 /* don't support file backed memory */
9721 for (i = 0; i < nr_pages; i++) {
9722 struct vm_area_struct *vma = vmas[i];
9724 if (vma_is_shmem(vma))
9727 !is_file_hugepages(vma->vm_file)) {
9733 ret = pret < 0 ? pret : -EFAULT;
9735 mmap_read_unlock(current->mm);
9738 * if we did partial map, or found file backed vmas,
9739 * release any pages we did get
9742 unpin_user_pages(pages, pret);
9746 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9748 unpin_user_pages(pages, pret);
9752 off = ubuf & ~PAGE_MASK;
9753 size = iov->iov_len;
9754 for (i = 0; i < nr_pages; i++) {
9757 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9758 imu->bvec[i].bv_page = pages[i];
9759 imu->bvec[i].bv_len = vec_len;
9760 imu->bvec[i].bv_offset = off;
9764 /* store original address for later verification */
9766 imu->ubuf_end = ubuf + iov->iov_len;
9767 imu->nr_bvecs = nr_pages;
9778 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9780 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9781 return ctx->user_bufs ? 0 : -ENOMEM;
9784 static int io_buffer_validate(struct iovec *iov)
9786 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9789 * Don't impose further limits on the size and buffer
9790 * constraints here, we'll -EINVAL later when IO is
9791 * submitted if they are wrong.
9794 return iov->iov_len ? -EFAULT : 0;
9798 /* arbitrary limit, but we need something */
9799 if (iov->iov_len > SZ_1G)
9802 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9808 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9809 unsigned int nr_args, u64 __user *tags)
9811 struct page *last_hpage = NULL;
9812 struct io_rsrc_data *data;
9818 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9820 ret = io_rsrc_node_switch_start(ctx);
9823 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9826 ret = io_buffers_map_alloc(ctx, nr_args);
9828 io_rsrc_data_free(data);
9832 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9833 ret = io_copy_iov(ctx, &iov, arg, i);
9836 ret = io_buffer_validate(&iov);
9839 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9844 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9850 WARN_ON_ONCE(ctx->buf_data);
9852 ctx->buf_data = data;
9854 __io_sqe_buffers_unregister(ctx);
9856 io_rsrc_node_switch(ctx, NULL);
9860 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9861 struct io_uring_rsrc_update2 *up,
9862 unsigned int nr_args)
9864 u64 __user *tags = u64_to_user_ptr(up->tags);
9865 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9866 struct page *last_hpage = NULL;
9867 bool needs_switch = false;
9873 if (up->offset + nr_args > ctx->nr_user_bufs)
9876 for (done = 0; done < nr_args; done++) {
9877 struct io_mapped_ubuf *imu;
9878 int offset = up->offset + done;
9881 err = io_copy_iov(ctx, &iov, iovs, done);
9884 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9888 err = io_buffer_validate(&iov);
9891 if (!iov.iov_base && tag) {
9895 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9899 i = array_index_nospec(offset, ctx->nr_user_bufs);
9900 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9901 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9902 ctx->rsrc_node, ctx->user_bufs[i]);
9903 if (unlikely(err)) {
9904 io_buffer_unmap(ctx, &imu);
9907 ctx->user_bufs[i] = NULL;
9908 needs_switch = true;
9911 ctx->user_bufs[i] = imu;
9912 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9916 io_rsrc_node_switch(ctx, ctx->buf_data);
9917 return done ? done : err;
9920 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9921 unsigned int eventfd_async)
9923 struct io_ev_fd *ev_fd;
9924 __s32 __user *fds = arg;
9927 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9928 lockdep_is_held(&ctx->uring_lock));
9932 if (copy_from_user(&fd, fds, sizeof(*fds)))
9935 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9939 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9940 if (IS_ERR(ev_fd->cq_ev_fd)) {
9941 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9945 ev_fd->eventfd_async = eventfd_async;
9946 ctx->has_evfd = true;
9947 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9951 static void io_eventfd_put(struct rcu_head *rcu)
9953 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9955 eventfd_ctx_put(ev_fd->cq_ev_fd);
9959 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9961 struct io_ev_fd *ev_fd;
9963 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9964 lockdep_is_held(&ctx->uring_lock));
9966 ctx->has_evfd = false;
9967 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9968 call_rcu(&ev_fd->rcu, io_eventfd_put);
9975 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9979 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9980 struct list_head *list = &ctx->io_buffers[i];
9982 while (!list_empty(list)) {
9983 struct io_buffer_list *bl;
9985 bl = list_first_entry(list, struct io_buffer_list, list);
9986 __io_remove_buffers(ctx, bl, -1U);
9987 list_del(&bl->list);
9992 while (!list_empty(&ctx->io_buffers_pages)) {
9995 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9996 list_del_init(&page->lru);
10001 static void io_req_caches_free(struct io_ring_ctx *ctx)
10003 struct io_submit_state *state = &ctx->submit_state;
10006 mutex_lock(&ctx->uring_lock);
10007 io_flush_cached_locked_reqs(ctx, state);
10009 while (state->free_list.next) {
10010 struct io_wq_work_node *node;
10011 struct io_kiocb *req;
10013 node = wq_stack_extract(&state->free_list);
10014 req = container_of(node, struct io_kiocb, comp_list);
10015 kmem_cache_free(req_cachep, req);
10019 percpu_ref_put_many(&ctx->refs, nr);
10020 mutex_unlock(&ctx->uring_lock);
10023 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10025 if (data && !atomic_dec_and_test(&data->refs))
10026 wait_for_completion(&data->done);
10029 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10031 struct async_poll *apoll;
10033 while (!list_empty(&ctx->apoll_cache)) {
10034 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10036 list_del(&apoll->poll.wait.entry);
10041 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10043 io_sq_thread_finish(ctx);
10045 if (ctx->mm_account) {
10046 mmdrop(ctx->mm_account);
10047 ctx->mm_account = NULL;
10050 io_rsrc_refs_drop(ctx);
10051 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10052 io_wait_rsrc_data(ctx->buf_data);
10053 io_wait_rsrc_data(ctx->file_data);
10055 mutex_lock(&ctx->uring_lock);
10057 __io_sqe_buffers_unregister(ctx);
10058 if (ctx->file_data)
10059 __io_sqe_files_unregister(ctx);
10061 __io_cqring_overflow_flush(ctx, true);
10062 io_eventfd_unregister(ctx);
10063 io_flush_apoll_cache(ctx);
10064 mutex_unlock(&ctx->uring_lock);
10065 io_destroy_buffers(ctx);
10067 put_cred(ctx->sq_creds);
10069 /* there are no registered resources left, nobody uses it */
10070 if (ctx->rsrc_node)
10071 io_rsrc_node_destroy(ctx->rsrc_node);
10072 if (ctx->rsrc_backup_node)
10073 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10074 flush_delayed_work(&ctx->rsrc_put_work);
10075 flush_delayed_work(&ctx->fallback_work);
10077 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10078 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10080 #if defined(CONFIG_UNIX)
10081 if (ctx->ring_sock) {
10082 ctx->ring_sock->file = NULL; /* so that iput() is called */
10083 sock_release(ctx->ring_sock);
10086 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10088 io_mem_free(ctx->rings);
10089 io_mem_free(ctx->sq_sqes);
10091 percpu_ref_exit(&ctx->refs);
10092 free_uid(ctx->user);
10093 io_req_caches_free(ctx);
10095 io_wq_put_hash(ctx->hash_map);
10096 io_free_napi_list(ctx);
10097 kfree(ctx->cancel_hash);
10098 kfree(ctx->dummy_ubuf);
10099 kfree(ctx->io_buffers);
10103 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10105 struct io_ring_ctx *ctx = file->private_data;
10108 poll_wait(file, &ctx->cq_wait, wait);
10110 * synchronizes with barrier from wq_has_sleeper call in
10114 if (!io_sqring_full(ctx))
10115 mask |= EPOLLOUT | EPOLLWRNORM;
10118 * Don't flush cqring overflow list here, just do a simple check.
10119 * Otherwise there could possible be ABBA deadlock:
10122 * lock(&ctx->uring_lock);
10124 * lock(&ctx->uring_lock);
10127 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10128 * pushs them to do the flush.
10130 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
10131 mask |= EPOLLIN | EPOLLRDNORM;
10136 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10138 const struct cred *creds;
10140 creds = xa_erase(&ctx->personalities, id);
10149 struct io_tctx_exit {
10150 struct callback_head task_work;
10151 struct completion completion;
10152 struct io_ring_ctx *ctx;
10155 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10157 struct io_uring_task *tctx = current->io_uring;
10158 struct io_tctx_exit *work;
10160 work = container_of(cb, struct io_tctx_exit, task_work);
10162 * When @in_idle, we're in cancellation and it's racy to remove the
10163 * node. It'll be removed by the end of cancellation, just ignore it.
10165 if (!atomic_read(&tctx->in_idle))
10166 io_uring_del_tctx_node((unsigned long)work->ctx);
10167 complete(&work->completion);
10170 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10172 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10174 return req->ctx == data;
10177 static __cold void io_ring_exit_work(struct work_struct *work)
10179 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10180 unsigned long timeout = jiffies + HZ * 60 * 5;
10181 unsigned long interval = HZ / 20;
10182 struct io_tctx_exit exit;
10183 struct io_tctx_node *node;
10187 * If we're doing polled IO and end up having requests being
10188 * submitted async (out-of-line), then completions can come in while
10189 * we're waiting for refs to drop. We need to reap these manually,
10190 * as nobody else will be looking for them.
10193 io_uring_try_cancel_requests(ctx, NULL, true);
10194 if (ctx->sq_data) {
10195 struct io_sq_data *sqd = ctx->sq_data;
10196 struct task_struct *tsk;
10198 io_sq_thread_park(sqd);
10200 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10201 io_wq_cancel_cb(tsk->io_uring->io_wq,
10202 io_cancel_ctx_cb, ctx, true);
10203 io_sq_thread_unpark(sqd);
10206 io_req_caches_free(ctx);
10208 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10209 /* there is little hope left, don't run it too often */
10210 interval = HZ * 60;
10212 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10214 init_completion(&exit.completion);
10215 init_task_work(&exit.task_work, io_tctx_exit_cb);
10218 * Some may use context even when all refs and requests have been put,
10219 * and they are free to do so while still holding uring_lock or
10220 * completion_lock, see io_req_task_submit(). Apart from other work,
10221 * this lock/unlock section also waits them to finish.
10223 mutex_lock(&ctx->uring_lock);
10224 while (!list_empty(&ctx->tctx_list)) {
10225 WARN_ON_ONCE(time_after(jiffies, timeout));
10227 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10229 /* don't spin on a single task if cancellation failed */
10230 list_rotate_left(&ctx->tctx_list);
10231 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10232 if (WARN_ON_ONCE(ret))
10235 mutex_unlock(&ctx->uring_lock);
10236 wait_for_completion(&exit.completion);
10237 mutex_lock(&ctx->uring_lock);
10239 mutex_unlock(&ctx->uring_lock);
10240 spin_lock(&ctx->completion_lock);
10241 spin_unlock(&ctx->completion_lock);
10243 io_ring_ctx_free(ctx);
10246 /* Returns true if we found and killed one or more timeouts */
10247 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10248 struct task_struct *tsk, bool cancel_all)
10250 struct io_kiocb *req, *tmp;
10253 spin_lock(&ctx->completion_lock);
10254 spin_lock_irq(&ctx->timeout_lock);
10255 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10256 if (io_match_task(req, tsk, cancel_all)) {
10257 io_kill_timeout(req, -ECANCELED);
10261 spin_unlock_irq(&ctx->timeout_lock);
10263 io_commit_cqring(ctx);
10264 spin_unlock(&ctx->completion_lock);
10266 io_cqring_ev_posted(ctx);
10267 return canceled != 0;
10270 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10272 unsigned long index;
10273 struct creds *creds;
10275 mutex_lock(&ctx->uring_lock);
10276 percpu_ref_kill(&ctx->refs);
10278 __io_cqring_overflow_flush(ctx, true);
10279 xa_for_each(&ctx->personalities, index, creds)
10280 io_unregister_personality(ctx, index);
10281 mutex_unlock(&ctx->uring_lock);
10283 io_kill_timeouts(ctx, NULL, true);
10284 io_poll_remove_all(ctx, NULL, true);
10286 /* if we failed setting up the ctx, we might not have any rings */
10287 io_iopoll_try_reap_events(ctx);
10289 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10291 * Use system_unbound_wq to avoid spawning tons of event kworkers
10292 * if we're exiting a ton of rings at the same time. It just adds
10293 * noise and overhead, there's no discernable change in runtime
10294 * over using system_wq.
10296 queue_work(system_unbound_wq, &ctx->exit_work);
10299 static int io_uring_release(struct inode *inode, struct file *file)
10301 struct io_ring_ctx *ctx = file->private_data;
10303 file->private_data = NULL;
10304 io_ring_ctx_wait_and_kill(ctx);
10308 struct io_task_cancel {
10309 struct task_struct *task;
10313 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10315 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10316 struct io_task_cancel *cancel = data;
10318 return io_match_task_safe(req, cancel->task, cancel->all);
10321 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10322 struct task_struct *task,
10325 struct io_defer_entry *de;
10328 spin_lock(&ctx->completion_lock);
10329 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10330 if (io_match_task_safe(de->req, task, cancel_all)) {
10331 list_cut_position(&list, &ctx->defer_list, &de->list);
10335 spin_unlock(&ctx->completion_lock);
10336 if (list_empty(&list))
10339 while (!list_empty(&list)) {
10340 de = list_first_entry(&list, struct io_defer_entry, list);
10341 list_del_init(&de->list);
10342 io_req_complete_failed(de->req, -ECANCELED);
10348 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10350 struct io_tctx_node *node;
10351 enum io_wq_cancel cret;
10354 mutex_lock(&ctx->uring_lock);
10355 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10356 struct io_uring_task *tctx = node->task->io_uring;
10359 * io_wq will stay alive while we hold uring_lock, because it's
10360 * killed after ctx nodes, which requires to take the lock.
10362 if (!tctx || !tctx->io_wq)
10364 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10365 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10367 mutex_unlock(&ctx->uring_lock);
10372 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10373 struct task_struct *task,
10376 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10377 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10380 enum io_wq_cancel cret;
10384 ret |= io_uring_try_cancel_iowq(ctx);
10385 } else if (tctx && tctx->io_wq) {
10387 * Cancels requests of all rings, not only @ctx, but
10388 * it's fine as the task is in exit/exec.
10390 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10392 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10395 /* SQPOLL thread does its own polling */
10396 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10397 (ctx->sq_data && ctx->sq_data->thread == current)) {
10398 while (!wq_list_empty(&ctx->iopoll_list)) {
10399 io_iopoll_try_reap_events(ctx);
10404 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10405 ret |= io_poll_remove_all(ctx, task, cancel_all);
10406 ret |= io_kill_timeouts(ctx, task, cancel_all);
10408 ret |= io_run_task_work();
10415 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10417 struct io_uring_task *tctx = current->io_uring;
10418 struct io_tctx_node *node;
10421 if (unlikely(!tctx)) {
10422 ret = io_uring_alloc_task_context(current, ctx);
10426 tctx = current->io_uring;
10427 if (ctx->iowq_limits_set) {
10428 unsigned int limits[2] = { ctx->iowq_limits[0],
10429 ctx->iowq_limits[1], };
10431 ret = io_wq_max_workers(tctx->io_wq, limits);
10436 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10437 node = kmalloc(sizeof(*node), GFP_KERNEL);
10441 node->task = current;
10443 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10444 node, GFP_KERNEL));
10450 mutex_lock(&ctx->uring_lock);
10451 list_add(&node->ctx_node, &ctx->tctx_list);
10452 mutex_unlock(&ctx->uring_lock);
10459 * Note that this task has used io_uring. We use it for cancelation purposes.
10461 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10463 struct io_uring_task *tctx = current->io_uring;
10465 if (likely(tctx && tctx->last == ctx))
10467 return __io_uring_add_tctx_node(ctx);
10471 * Remove this io_uring_file -> task mapping.
10473 static __cold void io_uring_del_tctx_node(unsigned long index)
10475 struct io_uring_task *tctx = current->io_uring;
10476 struct io_tctx_node *node;
10480 node = xa_erase(&tctx->xa, index);
10484 WARN_ON_ONCE(current != node->task);
10485 WARN_ON_ONCE(list_empty(&node->ctx_node));
10487 mutex_lock(&node->ctx->uring_lock);
10488 list_del(&node->ctx_node);
10489 mutex_unlock(&node->ctx->uring_lock);
10491 if (tctx->last == node->ctx)
10496 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10498 struct io_wq *wq = tctx->io_wq;
10499 struct io_tctx_node *node;
10500 unsigned long index;
10502 xa_for_each(&tctx->xa, index, node) {
10503 io_uring_del_tctx_node(index);
10508 * Must be after io_uring_del_tctx_node() (removes nodes under
10509 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10511 io_wq_put_and_exit(wq);
10512 tctx->io_wq = NULL;
10516 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10519 return atomic_read(&tctx->inflight_tracked);
10520 return percpu_counter_sum(&tctx->inflight);
10524 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10525 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10527 static __cold void io_uring_cancel_generic(bool cancel_all,
10528 struct io_sq_data *sqd)
10530 struct io_uring_task *tctx = current->io_uring;
10531 struct io_ring_ctx *ctx;
10535 WARN_ON_ONCE(sqd && sqd->thread != current);
10537 if (!current->io_uring)
10540 io_wq_exit_start(tctx->io_wq);
10542 atomic_inc(&tctx->in_idle);
10544 io_uring_drop_tctx_refs(current);
10545 /* read completions before cancelations */
10546 inflight = tctx_inflight(tctx, !cancel_all);
10551 struct io_tctx_node *node;
10552 unsigned long index;
10554 xa_for_each(&tctx->xa, index, node) {
10555 /* sqpoll task will cancel all its requests */
10556 if (node->ctx->sq_data)
10558 io_uring_try_cancel_requests(node->ctx, current,
10562 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10563 io_uring_try_cancel_requests(ctx, current,
10567 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10568 io_run_task_work();
10569 io_uring_drop_tctx_refs(current);
10572 * If we've seen completions, retry without waiting. This
10573 * avoids a race where a completion comes in before we did
10574 * prepare_to_wait().
10576 if (inflight == tctx_inflight(tctx, !cancel_all))
10578 finish_wait(&tctx->wait, &wait);
10581 io_uring_clean_tctx(tctx);
10584 * We shouldn't run task_works after cancel, so just leave
10585 * ->in_idle set for normal exit.
10587 atomic_dec(&tctx->in_idle);
10588 /* for exec all current's requests should be gone, kill tctx */
10589 __io_uring_free(current);
10593 void __io_uring_cancel(bool cancel_all)
10595 io_uring_cancel_generic(cancel_all, NULL);
10598 void io_uring_unreg_ringfd(void)
10600 struct io_uring_task *tctx = current->io_uring;
10603 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10604 if (tctx->registered_rings[i]) {
10605 fput(tctx->registered_rings[i]);
10606 tctx->registered_rings[i] = NULL;
10611 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10612 int start, int end)
10617 for (offset = start; offset < end; offset++) {
10618 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10619 if (tctx->registered_rings[offset])
10625 } else if (file->f_op != &io_uring_fops) {
10627 return -EOPNOTSUPP;
10629 tctx->registered_rings[offset] = file;
10637 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10638 * invocation. User passes in an array of struct io_uring_rsrc_update
10639 * with ->data set to the ring_fd, and ->offset given for the desired
10640 * index. If no index is desired, application may set ->offset == -1U
10641 * and we'll find an available index. Returns number of entries
10642 * successfully processed, or < 0 on error if none were processed.
10644 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10647 struct io_uring_rsrc_update __user *arg = __arg;
10648 struct io_uring_rsrc_update reg;
10649 struct io_uring_task *tctx;
10652 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10655 mutex_unlock(&ctx->uring_lock);
10656 ret = io_uring_add_tctx_node(ctx);
10657 mutex_lock(&ctx->uring_lock);
10661 tctx = current->io_uring;
10662 for (i = 0; i < nr_args; i++) {
10665 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10670 if (reg.offset == -1U) {
10672 end = IO_RINGFD_REG_MAX;
10674 if (reg.offset >= IO_RINGFD_REG_MAX) {
10678 start = reg.offset;
10682 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10687 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10688 fput(tctx->registered_rings[reg.offset]);
10689 tctx->registered_rings[reg.offset] = NULL;
10695 return i ? i : ret;
10698 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10701 struct io_uring_rsrc_update __user *arg = __arg;
10702 struct io_uring_task *tctx = current->io_uring;
10703 struct io_uring_rsrc_update reg;
10706 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10711 for (i = 0; i < nr_args; i++) {
10712 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10716 if (reg.offset >= IO_RINGFD_REG_MAX) {
10721 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10722 if (tctx->registered_rings[reg.offset]) {
10723 fput(tctx->registered_rings[reg.offset]);
10724 tctx->registered_rings[reg.offset] = NULL;
10728 return i ? i : ret;
10731 static void *io_uring_validate_mmap_request(struct file *file,
10732 loff_t pgoff, size_t sz)
10734 struct io_ring_ctx *ctx = file->private_data;
10735 loff_t offset = pgoff << PAGE_SHIFT;
10740 case IORING_OFF_SQ_RING:
10741 case IORING_OFF_CQ_RING:
10744 case IORING_OFF_SQES:
10745 ptr = ctx->sq_sqes;
10748 return ERR_PTR(-EINVAL);
10751 page = virt_to_head_page(ptr);
10752 if (sz > page_size(page))
10753 return ERR_PTR(-EINVAL);
10760 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10762 size_t sz = vma->vm_end - vma->vm_start;
10766 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10768 return PTR_ERR(ptr);
10770 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10771 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10774 #else /* !CONFIG_MMU */
10776 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10778 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10781 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10783 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10786 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10787 unsigned long addr, unsigned long len,
10788 unsigned long pgoff, unsigned long flags)
10792 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10794 return PTR_ERR(ptr);
10796 return (unsigned long) ptr;
10799 #endif /* !CONFIG_MMU */
10801 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10806 if (!io_sqring_full(ctx))
10808 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10810 if (!io_sqring_full(ctx))
10813 } while (!signal_pending(current));
10815 finish_wait(&ctx->sqo_sq_wait, &wait);
10819 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10820 struct __kernel_timespec __user **ts,
10821 const sigset_t __user **sig)
10823 struct io_uring_getevents_arg arg;
10826 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10827 * is just a pointer to the sigset_t.
10829 if (!(flags & IORING_ENTER_EXT_ARG)) {
10830 *sig = (const sigset_t __user *) argp;
10836 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10837 * timespec and sigset_t pointers if good.
10839 if (*argsz != sizeof(arg))
10841 if (copy_from_user(&arg, argp, sizeof(arg)))
10843 *sig = u64_to_user_ptr(arg.sigmask);
10844 *argsz = arg.sigmask_sz;
10845 *ts = u64_to_user_ptr(arg.ts);
10849 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10850 u32, min_complete, u32, flags, const void __user *, argp,
10853 struct io_ring_ctx *ctx;
10858 io_run_task_work();
10860 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10861 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10862 IORING_ENTER_REGISTERED_RING)))
10866 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10867 * need only dereference our task private array to find it.
10869 if (flags & IORING_ENTER_REGISTERED_RING) {
10870 struct io_uring_task *tctx = current->io_uring;
10872 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10874 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10875 f.file = tctx->registered_rings[fd];
10876 if (unlikely(!f.file))
10880 if (unlikely(!f.file))
10885 if (unlikely(f.file->f_op != &io_uring_fops))
10889 ctx = f.file->private_data;
10890 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10894 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10898 * For SQ polling, the thread will do all submissions and completions.
10899 * Just return the requested submit count, and wake the thread if
10900 * we were asked to.
10903 if (ctx->flags & IORING_SETUP_SQPOLL) {
10904 io_cqring_overflow_flush(ctx);
10906 if (unlikely(ctx->sq_data->thread == NULL)) {
10910 if (flags & IORING_ENTER_SQ_WAKEUP)
10911 wake_up(&ctx->sq_data->wait);
10912 if (flags & IORING_ENTER_SQ_WAIT) {
10913 ret = io_sqpoll_wait_sq(ctx);
10917 submitted = to_submit;
10918 } else if (to_submit) {
10919 ret = io_uring_add_tctx_node(ctx);
10922 mutex_lock(&ctx->uring_lock);
10923 submitted = io_submit_sqes(ctx, to_submit);
10924 mutex_unlock(&ctx->uring_lock);
10926 if (submitted != to_submit)
10929 if (flags & IORING_ENTER_GETEVENTS) {
10930 const sigset_t __user *sig;
10931 struct __kernel_timespec __user *ts;
10933 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10937 min_complete = min(min_complete, ctx->cq_entries);
10940 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10941 * space applications don't need to do io completion events
10942 * polling again, they can rely on io_sq_thread to do polling
10943 * work, which can reduce cpu usage and uring_lock contention.
10945 if (ctx->flags & IORING_SETUP_IOPOLL &&
10946 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10947 ret = io_iopoll_check(ctx, min_complete);
10949 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10954 percpu_ref_put(&ctx->refs);
10956 if (!(flags & IORING_ENTER_REGISTERED_RING))
10958 return submitted ? submitted : ret;
10961 #ifdef CONFIG_PROC_FS
10962 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10963 const struct cred *cred)
10965 struct user_namespace *uns = seq_user_ns(m);
10966 struct group_info *gi;
10971 seq_printf(m, "%5d\n", id);
10972 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10973 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10974 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10975 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10976 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10977 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10978 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10979 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10980 seq_puts(m, "\n\tGroups:\t");
10981 gi = cred->group_info;
10982 for (g = 0; g < gi->ngroups; g++) {
10983 seq_put_decimal_ull(m, g ? " " : "",
10984 from_kgid_munged(uns, gi->gid[g]));
10986 seq_puts(m, "\n\tCapEff:\t");
10987 cap = cred->cap_effective;
10988 CAP_FOR_EACH_U32(__capi)
10989 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10994 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10995 struct seq_file *m)
10997 struct io_sq_data *sq = NULL;
10998 struct io_overflow_cqe *ocqe;
10999 struct io_rings *r = ctx->rings;
11000 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11001 unsigned int sq_head = READ_ONCE(r->sq.head);
11002 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11003 unsigned int cq_head = READ_ONCE(r->cq.head);
11004 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11005 unsigned int sq_entries, cq_entries;
11010 * we may get imprecise sqe and cqe info if uring is actively running
11011 * since we get cached_sq_head and cached_cq_tail without uring_lock
11012 * and sq_tail and cq_head are changed by userspace. But it's ok since
11013 * we usually use these info when it is stuck.
11015 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11016 seq_printf(m, "SqHead:\t%u\n", sq_head);
11017 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11018 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11019 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11020 seq_printf(m, "CqHead:\t%u\n", cq_head);
11021 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11022 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11023 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11024 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11025 for (i = 0; i < sq_entries; i++) {
11026 unsigned int entry = i + sq_head;
11027 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11028 struct io_uring_sqe *sqe;
11030 if (sq_idx > sq_mask)
11032 sqe = &ctx->sq_sqes[sq_idx];
11033 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11034 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11037 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11038 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11039 for (i = 0; i < cq_entries; i++) {
11040 unsigned int entry = i + cq_head;
11041 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
11043 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11044 entry & cq_mask, cqe->user_data, cqe->res,
11049 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11050 * since fdinfo case grabs it in the opposite direction of normal use
11051 * cases. If we fail to get the lock, we just don't iterate any
11052 * structures that could be going away outside the io_uring mutex.
11054 has_lock = mutex_trylock(&ctx->uring_lock);
11056 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11062 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11063 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11064 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11065 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11066 struct file *f = io_file_from_index(ctx, i);
11069 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11071 seq_printf(m, "%5u: <none>\n", i);
11073 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11074 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11075 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11076 unsigned int len = buf->ubuf_end - buf->ubuf;
11078 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11080 if (has_lock && !xa_empty(&ctx->personalities)) {
11081 unsigned long index;
11082 const struct cred *cred;
11084 seq_printf(m, "Personalities:\n");
11085 xa_for_each(&ctx->personalities, index, cred)
11086 io_uring_show_cred(m, index, cred);
11089 mutex_unlock(&ctx->uring_lock);
11091 seq_puts(m, "PollList:\n");
11092 spin_lock(&ctx->completion_lock);
11093 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11094 struct hlist_head *list = &ctx->cancel_hash[i];
11095 struct io_kiocb *req;
11097 hlist_for_each_entry(req, list, hash_node)
11098 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11099 req->task->task_works != NULL);
11102 seq_puts(m, "CqOverflowList:\n");
11103 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11104 struct io_uring_cqe *cqe = &ocqe->cqe;
11106 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11107 cqe->user_data, cqe->res, cqe->flags);
11111 spin_unlock(&ctx->completion_lock);
11114 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11116 struct io_ring_ctx *ctx = f->private_data;
11118 if (percpu_ref_tryget(&ctx->refs)) {
11119 __io_uring_show_fdinfo(ctx, m);
11120 percpu_ref_put(&ctx->refs);
11125 static const struct file_operations io_uring_fops = {
11126 .release = io_uring_release,
11127 .mmap = io_uring_mmap,
11129 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11130 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11132 .poll = io_uring_poll,
11133 #ifdef CONFIG_PROC_FS
11134 .show_fdinfo = io_uring_show_fdinfo,
11138 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11139 struct io_uring_params *p)
11141 struct io_rings *rings;
11142 size_t size, sq_array_offset;
11144 /* make sure these are sane, as we already accounted them */
11145 ctx->sq_entries = p->sq_entries;
11146 ctx->cq_entries = p->cq_entries;
11148 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11149 if (size == SIZE_MAX)
11152 rings = io_mem_alloc(size);
11156 ctx->rings = rings;
11157 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11158 rings->sq_ring_mask = p->sq_entries - 1;
11159 rings->cq_ring_mask = p->cq_entries - 1;
11160 rings->sq_ring_entries = p->sq_entries;
11161 rings->cq_ring_entries = p->cq_entries;
11163 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11164 if (size == SIZE_MAX) {
11165 io_mem_free(ctx->rings);
11170 ctx->sq_sqes = io_mem_alloc(size);
11171 if (!ctx->sq_sqes) {
11172 io_mem_free(ctx->rings);
11180 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11184 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11188 ret = io_uring_add_tctx_node(ctx);
11193 fd_install(fd, file);
11198 * Allocate an anonymous fd, this is what constitutes the application
11199 * visible backing of an io_uring instance. The application mmaps this
11200 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11201 * we have to tie this fd to a socket for file garbage collection purposes.
11203 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11206 #if defined(CONFIG_UNIX)
11209 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11212 return ERR_PTR(ret);
11215 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11216 O_RDWR | O_CLOEXEC, NULL);
11217 #if defined(CONFIG_UNIX)
11218 if (IS_ERR(file)) {
11219 sock_release(ctx->ring_sock);
11220 ctx->ring_sock = NULL;
11222 ctx->ring_sock->file = file;
11228 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11229 struct io_uring_params __user *params)
11231 struct io_ring_ctx *ctx;
11237 if (entries > IORING_MAX_ENTRIES) {
11238 if (!(p->flags & IORING_SETUP_CLAMP))
11240 entries = IORING_MAX_ENTRIES;
11244 * Use twice as many entries for the CQ ring. It's possible for the
11245 * application to drive a higher depth than the size of the SQ ring,
11246 * since the sqes are only used at submission time. This allows for
11247 * some flexibility in overcommitting a bit. If the application has
11248 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11249 * of CQ ring entries manually.
11251 p->sq_entries = roundup_pow_of_two(entries);
11252 if (p->flags & IORING_SETUP_CQSIZE) {
11254 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11255 * to a power-of-two, if it isn't already. We do NOT impose
11256 * any cq vs sq ring sizing.
11258 if (!p->cq_entries)
11260 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11261 if (!(p->flags & IORING_SETUP_CLAMP))
11263 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11265 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11266 if (p->cq_entries < p->sq_entries)
11269 p->cq_entries = 2 * p->sq_entries;
11272 ctx = io_ring_ctx_alloc(p);
11275 ctx->compat = in_compat_syscall();
11276 if (!capable(CAP_IPC_LOCK))
11277 ctx->user = get_uid(current_user());
11280 * This is just grabbed for accounting purposes. When a process exits,
11281 * the mm is exited and dropped before the files, hence we need to hang
11282 * on to this mm purely for the purposes of being able to unaccount
11283 * memory (locked/pinned vm). It's not used for anything else.
11285 mmgrab(current->mm);
11286 ctx->mm_account = current->mm;
11288 ret = io_allocate_scq_urings(ctx, p);
11292 ret = io_sq_offload_create(ctx, p);
11295 /* always set a rsrc node */
11296 ret = io_rsrc_node_switch_start(ctx);
11299 io_rsrc_node_switch(ctx, NULL);
11301 memset(&p->sq_off, 0, sizeof(p->sq_off));
11302 p->sq_off.head = offsetof(struct io_rings, sq.head);
11303 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11304 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11305 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11306 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11307 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11308 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11310 memset(&p->cq_off, 0, sizeof(p->cq_off));
11311 p->cq_off.head = offsetof(struct io_rings, cq.head);
11312 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11313 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11314 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11315 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11316 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11317 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11319 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11320 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11321 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11322 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11323 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11324 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
11326 if (copy_to_user(params, p, sizeof(*p))) {
11331 file = io_uring_get_file(ctx);
11332 if (IS_ERR(file)) {
11333 ret = PTR_ERR(file);
11338 * Install ring fd as the very last thing, so we don't risk someone
11339 * having closed it before we finish setup
11341 ret = io_uring_install_fd(ctx, file);
11343 /* fput will clean it up */
11348 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11351 io_ring_ctx_wait_and_kill(ctx);
11356 * Sets up an aio uring context, and returns the fd. Applications asks for a
11357 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11358 * params structure passed in.
11360 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11362 struct io_uring_params p;
11365 if (copy_from_user(&p, params, sizeof(p)))
11367 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11372 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11373 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11374 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11375 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11378 return io_uring_create(entries, &p, params);
11381 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11382 struct io_uring_params __user *, params)
11384 return io_uring_setup(entries, params);
11387 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11390 struct io_uring_probe *p;
11394 size = struct_size(p, ops, nr_args);
11395 if (size == SIZE_MAX)
11397 p = kzalloc(size, GFP_KERNEL);
11402 if (copy_from_user(p, arg, size))
11405 if (memchr_inv(p, 0, size))
11408 p->last_op = IORING_OP_LAST - 1;
11409 if (nr_args > IORING_OP_LAST)
11410 nr_args = IORING_OP_LAST;
11412 for (i = 0; i < nr_args; i++) {
11414 if (!io_op_defs[i].not_supported)
11415 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11420 if (copy_to_user(arg, p, size))
11427 static int io_register_personality(struct io_ring_ctx *ctx)
11429 const struct cred *creds;
11433 creds = get_current_cred();
11435 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11436 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11444 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11445 void __user *arg, unsigned int nr_args)
11447 struct io_uring_restriction *res;
11451 /* Restrictions allowed only if rings started disabled */
11452 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11455 /* We allow only a single restrictions registration */
11456 if (ctx->restrictions.registered)
11459 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11462 size = array_size(nr_args, sizeof(*res));
11463 if (size == SIZE_MAX)
11466 res = memdup_user(arg, size);
11468 return PTR_ERR(res);
11472 for (i = 0; i < nr_args; i++) {
11473 switch (res[i].opcode) {
11474 case IORING_RESTRICTION_REGISTER_OP:
11475 if (res[i].register_op >= IORING_REGISTER_LAST) {
11480 __set_bit(res[i].register_op,
11481 ctx->restrictions.register_op);
11483 case IORING_RESTRICTION_SQE_OP:
11484 if (res[i].sqe_op >= IORING_OP_LAST) {
11489 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11491 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11492 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11494 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11495 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11504 /* Reset all restrictions if an error happened */
11506 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11508 ctx->restrictions.registered = true;
11514 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11516 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11519 if (ctx->restrictions.registered)
11520 ctx->restricted = 1;
11522 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11523 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11524 wake_up(&ctx->sq_data->wait);
11528 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11529 struct io_uring_rsrc_update2 *up,
11537 if (check_add_overflow(up->offset, nr_args, &tmp))
11539 err = io_rsrc_node_switch_start(ctx);
11544 case IORING_RSRC_FILE:
11545 return __io_sqe_files_update(ctx, up, nr_args);
11546 case IORING_RSRC_BUFFER:
11547 return __io_sqe_buffers_update(ctx, up, nr_args);
11552 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11555 struct io_uring_rsrc_update2 up;
11559 memset(&up, 0, sizeof(up));
11560 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11562 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11565 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11566 unsigned size, unsigned type)
11568 struct io_uring_rsrc_update2 up;
11570 if (size != sizeof(up))
11572 if (copy_from_user(&up, arg, sizeof(up)))
11574 if (!up.nr || up.resv)
11576 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11579 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11580 unsigned int size, unsigned int type)
11582 struct io_uring_rsrc_register rr;
11584 /* keep it extendible */
11585 if (size != sizeof(rr))
11588 memset(&rr, 0, sizeof(rr));
11589 if (copy_from_user(&rr, arg, size))
11591 if (!rr.nr || rr.resv || rr.resv2)
11595 case IORING_RSRC_FILE:
11596 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11597 rr.nr, u64_to_user_ptr(rr.tags));
11598 case IORING_RSRC_BUFFER:
11599 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11600 rr.nr, u64_to_user_ptr(rr.tags));
11605 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11606 void __user *arg, unsigned len)
11608 struct io_uring_task *tctx = current->io_uring;
11609 cpumask_var_t new_mask;
11612 if (!tctx || !tctx->io_wq)
11615 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11618 cpumask_clear(new_mask);
11619 if (len > cpumask_size())
11620 len = cpumask_size();
11622 if (copy_from_user(new_mask, arg, len)) {
11623 free_cpumask_var(new_mask);
11627 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11628 free_cpumask_var(new_mask);
11632 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11634 struct io_uring_task *tctx = current->io_uring;
11636 if (!tctx || !tctx->io_wq)
11639 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11642 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11644 __must_hold(&ctx->uring_lock)
11646 struct io_tctx_node *node;
11647 struct io_uring_task *tctx = NULL;
11648 struct io_sq_data *sqd = NULL;
11649 __u32 new_count[2];
11652 if (copy_from_user(new_count, arg, sizeof(new_count)))
11654 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11655 if (new_count[i] > INT_MAX)
11658 if (ctx->flags & IORING_SETUP_SQPOLL) {
11659 sqd = ctx->sq_data;
11662 * Observe the correct sqd->lock -> ctx->uring_lock
11663 * ordering. Fine to drop uring_lock here, we hold
11664 * a ref to the ctx.
11666 refcount_inc(&sqd->refs);
11667 mutex_unlock(&ctx->uring_lock);
11668 mutex_lock(&sqd->lock);
11669 mutex_lock(&ctx->uring_lock);
11671 tctx = sqd->thread->io_uring;
11674 tctx = current->io_uring;
11677 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11679 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11681 ctx->iowq_limits[i] = new_count[i];
11682 ctx->iowq_limits_set = true;
11684 if (tctx && tctx->io_wq) {
11685 ret = io_wq_max_workers(tctx->io_wq, new_count);
11689 memset(new_count, 0, sizeof(new_count));
11693 mutex_unlock(&sqd->lock);
11694 io_put_sq_data(sqd);
11697 if (copy_to_user(arg, new_count, sizeof(new_count)))
11700 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11704 /* now propagate the restriction to all registered users */
11705 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11706 struct io_uring_task *tctx = node->task->io_uring;
11708 if (WARN_ON_ONCE(!tctx->io_wq))
11711 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11712 new_count[i] = ctx->iowq_limits[i];
11713 /* ignore errors, it always returns zero anyway */
11714 (void)io_wq_max_workers(tctx->io_wq, new_count);
11719 mutex_unlock(&sqd->lock);
11720 io_put_sq_data(sqd);
11725 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11726 void __user *arg, unsigned nr_args)
11727 __releases(ctx->uring_lock)
11728 __acquires(ctx->uring_lock)
11733 * We're inside the ring mutex, if the ref is already dying, then
11734 * someone else killed the ctx or is already going through
11735 * io_uring_register().
11737 if (percpu_ref_is_dying(&ctx->refs))
11740 if (ctx->restricted) {
11741 if (opcode >= IORING_REGISTER_LAST)
11743 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11744 if (!test_bit(opcode, ctx->restrictions.register_op))
11749 case IORING_REGISTER_BUFFERS:
11750 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11752 case IORING_UNREGISTER_BUFFERS:
11754 if (arg || nr_args)
11756 ret = io_sqe_buffers_unregister(ctx);
11758 case IORING_REGISTER_FILES:
11759 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11761 case IORING_UNREGISTER_FILES:
11763 if (arg || nr_args)
11765 ret = io_sqe_files_unregister(ctx);
11767 case IORING_REGISTER_FILES_UPDATE:
11768 ret = io_register_files_update(ctx, arg, nr_args);
11770 case IORING_REGISTER_EVENTFD:
11774 ret = io_eventfd_register(ctx, arg, 0);
11776 case IORING_REGISTER_EVENTFD_ASYNC:
11780 ret = io_eventfd_register(ctx, arg, 1);
11782 case IORING_UNREGISTER_EVENTFD:
11784 if (arg || nr_args)
11786 ret = io_eventfd_unregister(ctx);
11788 case IORING_REGISTER_PROBE:
11790 if (!arg || nr_args > 256)
11792 ret = io_probe(ctx, arg, nr_args);
11794 case IORING_REGISTER_PERSONALITY:
11796 if (arg || nr_args)
11798 ret = io_register_personality(ctx);
11800 case IORING_UNREGISTER_PERSONALITY:
11804 ret = io_unregister_personality(ctx, nr_args);
11806 case IORING_REGISTER_ENABLE_RINGS:
11808 if (arg || nr_args)
11810 ret = io_register_enable_rings(ctx);
11812 case IORING_REGISTER_RESTRICTIONS:
11813 ret = io_register_restrictions(ctx, arg, nr_args);
11815 case IORING_REGISTER_FILES2:
11816 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11818 case IORING_REGISTER_FILES_UPDATE2:
11819 ret = io_register_rsrc_update(ctx, arg, nr_args,
11822 case IORING_REGISTER_BUFFERS2:
11823 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11825 case IORING_REGISTER_BUFFERS_UPDATE:
11826 ret = io_register_rsrc_update(ctx, arg, nr_args,
11827 IORING_RSRC_BUFFER);
11829 case IORING_REGISTER_IOWQ_AFF:
11831 if (!arg || !nr_args)
11833 ret = io_register_iowq_aff(ctx, arg, nr_args);
11835 case IORING_UNREGISTER_IOWQ_AFF:
11837 if (arg || nr_args)
11839 ret = io_unregister_iowq_aff(ctx);
11841 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11843 if (!arg || nr_args != 2)
11845 ret = io_register_iowq_max_workers(ctx, arg);
11847 case IORING_REGISTER_RING_FDS:
11848 ret = io_ringfd_register(ctx, arg, nr_args);
11850 case IORING_UNREGISTER_RING_FDS:
11851 ret = io_ringfd_unregister(ctx, arg, nr_args);
11861 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11862 void __user *, arg, unsigned int, nr_args)
11864 struct io_ring_ctx *ctx;
11873 if (f.file->f_op != &io_uring_fops)
11876 ctx = f.file->private_data;
11878 io_run_task_work();
11880 mutex_lock(&ctx->uring_lock);
11881 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11882 mutex_unlock(&ctx->uring_lock);
11883 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11889 static int __init io_uring_init(void)
11891 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11892 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11893 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11896 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11897 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11898 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11899 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11900 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11901 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11902 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11903 BUILD_BUG_SQE_ELEM(8, __u64, off);
11904 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11905 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11906 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11907 BUILD_BUG_SQE_ELEM(24, __u32, len);
11908 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11909 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11910 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11911 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11912 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11913 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11914 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11915 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11916 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11917 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11918 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11919 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11920 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11921 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11922 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11923 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11924 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11925 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11926 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11927 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11928 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11930 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11931 sizeof(struct io_uring_rsrc_update));
11932 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11933 sizeof(struct io_uring_rsrc_update2));
11935 /* ->buf_index is u16 */
11936 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11938 /* should fit into one byte */
11939 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11940 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11941 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11943 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11944 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11946 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11950 __initcall(io_uring_init);