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;
268 struct list_head list;
275 struct io_restriction {
276 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
277 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
278 u8 sqe_flags_allowed;
279 u8 sqe_flags_required;
284 IO_SQ_THREAD_SHOULD_STOP = 0,
285 IO_SQ_THREAD_SHOULD_PARK,
290 atomic_t park_pending;
293 /* ctx's that are using this sqd */
294 struct list_head ctx_list;
296 struct task_struct *thread;
297 struct wait_queue_head wait;
299 unsigned sq_thread_idle;
305 struct completion exited;
308 #define IO_COMPL_BATCH 32
309 #define IO_REQ_CACHE_SIZE 32
310 #define IO_REQ_ALLOC_BATCH 8
312 struct io_submit_link {
313 struct io_kiocb *head;
314 struct io_kiocb *last;
317 struct io_submit_state {
318 /* inline/task_work completion list, under ->uring_lock */
319 struct io_wq_work_node free_list;
320 /* batch completion logic */
321 struct io_wq_work_list compl_reqs;
322 struct io_submit_link link;
327 unsigned short submit_nr;
328 struct blk_plug plug;
332 struct eventfd_ctx *cq_ev_fd;
333 unsigned int eventfd_async: 1;
338 /* const or read-mostly hot data */
340 struct percpu_ref refs;
342 struct io_rings *rings;
344 unsigned int compat: 1;
345 unsigned int drain_next: 1;
346 unsigned int restricted: 1;
347 unsigned int off_timeout_used: 1;
348 unsigned int drain_active: 1;
349 unsigned int drain_disabled: 1;
350 } ____cacheline_aligned_in_smp;
352 /* submission data */
354 struct mutex uring_lock;
357 * Ring buffer of indices into array of io_uring_sqe, which is
358 * mmapped by the application using the IORING_OFF_SQES offset.
360 * This indirection could e.g. be used to assign fixed
361 * io_uring_sqe entries to operations and only submit them to
362 * the queue when needed.
364 * The kernel modifies neither the indices array nor the entries
368 struct io_uring_sqe *sq_sqes;
369 unsigned cached_sq_head;
371 struct list_head defer_list;
374 * Fixed resources fast path, should be accessed only under
375 * uring_lock, and updated through io_uring_register(2)
377 struct io_rsrc_node *rsrc_node;
378 int rsrc_cached_refs;
379 struct io_file_table file_table;
380 unsigned nr_user_files;
381 unsigned nr_user_bufs;
382 struct io_mapped_ubuf **user_bufs;
384 struct io_submit_state submit_state;
385 struct list_head timeout_list;
386 struct list_head ltimeout_list;
387 struct list_head cq_overflow_list;
388 struct xarray io_buffers;
389 struct list_head io_buffers_cache;
390 struct list_head apoll_cache;
391 struct xarray personalities;
393 unsigned sq_thread_idle;
394 } ____cacheline_aligned_in_smp;
396 /* IRQ completion list, under ->completion_lock */
397 struct io_wq_work_list locked_free_list;
398 unsigned int locked_free_nr;
400 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
401 struct io_sq_data *sq_data; /* if using sq thread polling */
403 struct wait_queue_head sqo_sq_wait;
404 struct list_head sqd_list;
406 unsigned long check_cq_overflow;
407 #ifdef CONFIG_NET_RX_BUSY_POLL
408 /* used to track busy poll napi_id */
409 struct list_head napi_list;
410 spinlock_t napi_lock; /* napi_list lock */
414 unsigned cached_cq_tail;
416 struct io_ev_fd __rcu *io_ev_fd;
417 struct wait_queue_head cq_wait;
419 atomic_t cq_timeouts;
420 unsigned cq_last_tm_flush;
421 } ____cacheline_aligned_in_smp;
424 spinlock_t completion_lock;
426 spinlock_t timeout_lock;
429 * ->iopoll_list is protected by the ctx->uring_lock for
430 * io_uring instances that don't use IORING_SETUP_SQPOLL.
431 * For SQPOLL, only the single threaded io_sq_thread() will
432 * manipulate the list, hence no extra locking is needed there.
434 struct io_wq_work_list iopoll_list;
435 struct hlist_head *cancel_hash;
436 unsigned cancel_hash_bits;
437 bool poll_multi_queue;
439 struct list_head io_buffers_comp;
440 } ____cacheline_aligned_in_smp;
442 struct io_restriction restrictions;
444 /* slow path rsrc auxilary data, used by update/register */
446 struct io_rsrc_node *rsrc_backup_node;
447 struct io_mapped_ubuf *dummy_ubuf;
448 struct io_rsrc_data *file_data;
449 struct io_rsrc_data *buf_data;
451 struct delayed_work rsrc_put_work;
452 struct llist_head rsrc_put_llist;
453 struct list_head rsrc_ref_list;
454 spinlock_t rsrc_ref_lock;
456 struct list_head io_buffers_pages;
459 /* Keep this last, we don't need it for the fast path */
461 #if defined(CONFIG_UNIX)
462 struct socket *ring_sock;
464 /* hashed buffered write serialization */
465 struct io_wq_hash *hash_map;
467 /* Only used for accounting purposes */
468 struct user_struct *user;
469 struct mm_struct *mm_account;
471 /* ctx exit and cancelation */
472 struct llist_head fallback_llist;
473 struct delayed_work fallback_work;
474 struct work_struct exit_work;
475 struct list_head tctx_list;
476 struct completion ref_comp;
478 bool iowq_limits_set;
483 * Arbitrary limit, can be raised if need be
485 #define IO_RINGFD_REG_MAX 16
487 struct io_uring_task {
488 /* submission side */
491 struct wait_queue_head wait;
492 const struct io_ring_ctx *last;
494 struct percpu_counter inflight;
495 atomic_t inflight_tracked;
498 spinlock_t task_lock;
499 struct io_wq_work_list task_list;
500 struct io_wq_work_list prior_task_list;
501 struct callback_head task_work;
502 struct file **registered_rings;
507 * First field must be the file pointer in all the
508 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
510 struct io_poll_iocb {
512 struct wait_queue_head *head;
514 struct wait_queue_entry wait;
517 struct io_poll_update {
523 bool update_user_data;
532 struct io_timeout_data {
533 struct io_kiocb *req;
534 struct hrtimer timer;
535 struct timespec64 ts;
536 enum hrtimer_mode mode;
542 struct sockaddr __user *addr;
543 int __user *addr_len;
546 unsigned long nofile;
566 struct list_head list;
567 /* head of the link, used by linked timeouts only */
568 struct io_kiocb *head;
569 /* for linked completions */
570 struct io_kiocb *prev;
573 struct io_timeout_rem {
578 struct timespec64 ts;
584 /* NOTE: kiocb has the file as the first member, so don't do it here */
592 struct sockaddr __user *addr;
599 struct compat_msghdr __user *umsg_compat;
600 struct user_msghdr __user *umsg;
612 struct filename *filename;
614 unsigned long nofile;
617 struct io_rsrc_update {
643 struct epoll_event event;
647 struct file *file_out;
648 struct file *file_in;
655 struct io_provide_buf {
669 const char __user *filename;
670 struct statx __user *buffer;
682 struct filename *oldpath;
683 struct filename *newpath;
691 struct filename *filename;
698 struct filename *filename;
704 struct filename *oldpath;
705 struct filename *newpath;
712 struct filename *oldpath;
713 struct filename *newpath;
723 struct io_async_connect {
724 struct sockaddr_storage address;
727 struct io_async_msghdr {
728 struct iovec fast_iov[UIO_FASTIOV];
729 /* points to an allocated iov, if NULL we use fast_iov instead */
730 struct iovec *free_iov;
731 struct sockaddr __user *uaddr;
733 struct sockaddr_storage addr;
737 struct iov_iter iter;
738 struct iov_iter_state iter_state;
739 struct iovec fast_iov[UIO_FASTIOV];
743 struct io_rw_state s;
744 const struct iovec *free_iovec;
746 struct wait_page_queue wpq;
750 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
751 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
752 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
753 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
754 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
755 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
756 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
758 /* first byte is taken by user flags, shift it to not overlap */
763 REQ_F_LINK_TIMEOUT_BIT,
764 REQ_F_NEED_CLEANUP_BIT,
766 REQ_F_BUFFER_SELECTED_BIT,
767 REQ_F_COMPLETE_INLINE_BIT,
771 REQ_F_ARM_LTIMEOUT_BIT,
772 REQ_F_ASYNC_DATA_BIT,
773 REQ_F_SKIP_LINK_CQES_BIT,
774 REQ_F_SINGLE_POLL_BIT,
775 REQ_F_DOUBLE_POLL_BIT,
776 /* keep async read/write and isreg together and in order */
777 REQ_F_SUPPORT_NOWAIT_BIT,
780 /* not a real bit, just to check we're not overflowing the space */
786 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
787 /* drain existing IO first */
788 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
790 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
791 /* doesn't sever on completion < 0 */
792 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
794 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
795 /* IOSQE_BUFFER_SELECT */
796 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
797 /* IOSQE_CQE_SKIP_SUCCESS */
798 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
800 /* fail rest of links */
801 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
802 /* on inflight list, should be cancelled and waited on exit reliably */
803 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
804 /* read/write uses file position */
805 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
806 /* must not punt to workers */
807 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
808 /* has or had linked timeout */
809 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
811 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
812 /* already went through poll handler */
813 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
814 /* buffer already selected */
815 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
816 /* completion is deferred through io_comp_state */
817 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
818 /* caller should reissue async */
819 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
820 /* supports async reads/writes */
821 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
823 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
824 /* has creds assigned */
825 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
826 /* skip refcounting if not set */
827 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
828 /* there is a linked timeout that has to be armed */
829 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
830 /* ->async_data allocated */
831 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
832 /* don't post CQEs while failing linked requests */
833 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
834 /* single poll may be active */
835 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
836 /* double poll may active */
837 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
841 struct io_poll_iocb poll;
842 struct io_poll_iocb *double_poll;
845 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
847 struct io_task_work {
849 struct io_wq_work_node node;
850 struct llist_node fallback_node;
852 io_req_tw_func_t func;
856 IORING_RSRC_FILE = 0,
857 IORING_RSRC_BUFFER = 1,
861 * NOTE! Each of the iocb union members has the file pointer
862 * as the first entry in their struct definition. So you can
863 * access the file pointer through any of the sub-structs,
864 * or directly as just 'file' in this struct.
870 struct io_poll_iocb poll;
871 struct io_poll_update poll_update;
872 struct io_accept accept;
874 struct io_cancel cancel;
875 struct io_timeout timeout;
876 struct io_timeout_rem timeout_rem;
877 struct io_connect connect;
878 struct io_sr_msg sr_msg;
880 struct io_close close;
881 struct io_rsrc_update rsrc_update;
882 struct io_fadvise fadvise;
883 struct io_madvise madvise;
884 struct io_epoll epoll;
885 struct io_splice splice;
886 struct io_provide_buf pbuf;
887 struct io_statx statx;
888 struct io_shutdown shutdown;
889 struct io_rename rename;
890 struct io_unlink unlink;
891 struct io_mkdir mkdir;
892 struct io_symlink symlink;
893 struct io_hardlink hardlink;
898 /* polled IO has completed */
907 struct io_ring_ctx *ctx;
908 struct task_struct *task;
910 struct percpu_ref *fixed_rsrc_refs;
911 /* store used ubuf, so we can prevent reloading */
912 struct io_mapped_ubuf *imu;
914 /* used by request caches, completion batching and iopoll */
915 struct io_wq_work_node comp_list;
918 struct io_kiocb *link;
919 struct io_task_work io_task_work;
920 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
921 struct hlist_node hash_node;
922 /* internal polling, see IORING_FEAT_FAST_POLL */
923 struct async_poll *apoll;
924 /* opcode allocated if it needs to store data for async defer */
926 /* custom credentials, valid IFF REQ_F_CREDS is set */
927 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
928 struct io_buffer *kbuf;
929 const struct cred *creds;
930 struct io_wq_work work;
933 struct io_tctx_node {
934 struct list_head ctx_node;
935 struct task_struct *task;
936 struct io_ring_ctx *ctx;
939 struct io_defer_entry {
940 struct list_head list;
941 struct io_kiocb *req;
946 /* needs req->file assigned */
947 unsigned needs_file : 1;
948 /* should block plug */
950 /* hash wq insertion if file is a regular file */
951 unsigned hash_reg_file : 1;
952 /* unbound wq insertion if file is a non-regular file */
953 unsigned unbound_nonreg_file : 1;
954 /* set if opcode supports polled "wait" */
956 unsigned pollout : 1;
957 /* op supports buffer selection */
958 unsigned buffer_select : 1;
959 /* do prep async if is going to be punted */
960 unsigned needs_async_setup : 1;
961 /* opcode is not supported by this kernel */
962 unsigned not_supported : 1;
964 unsigned audit_skip : 1;
965 /* size of async data needed, if any */
966 unsigned short async_size;
969 static const struct io_op_def io_op_defs[] = {
970 [IORING_OP_NOP] = {},
971 [IORING_OP_READV] = {
973 .unbound_nonreg_file = 1,
976 .needs_async_setup = 1,
979 .async_size = sizeof(struct io_async_rw),
981 [IORING_OP_WRITEV] = {
984 .unbound_nonreg_file = 1,
986 .needs_async_setup = 1,
989 .async_size = sizeof(struct io_async_rw),
991 [IORING_OP_FSYNC] = {
995 [IORING_OP_READ_FIXED] = {
997 .unbound_nonreg_file = 1,
1001 .async_size = sizeof(struct io_async_rw),
1003 [IORING_OP_WRITE_FIXED] = {
1006 .unbound_nonreg_file = 1,
1010 .async_size = sizeof(struct io_async_rw),
1012 [IORING_OP_POLL_ADD] = {
1014 .unbound_nonreg_file = 1,
1017 [IORING_OP_POLL_REMOVE] = {
1020 [IORING_OP_SYNC_FILE_RANGE] = {
1024 [IORING_OP_SENDMSG] = {
1026 .unbound_nonreg_file = 1,
1028 .needs_async_setup = 1,
1029 .async_size = sizeof(struct io_async_msghdr),
1031 [IORING_OP_RECVMSG] = {
1033 .unbound_nonreg_file = 1,
1036 .needs_async_setup = 1,
1037 .async_size = sizeof(struct io_async_msghdr),
1039 [IORING_OP_TIMEOUT] = {
1041 .async_size = sizeof(struct io_timeout_data),
1043 [IORING_OP_TIMEOUT_REMOVE] = {
1044 /* used by timeout updates' prep() */
1047 [IORING_OP_ACCEPT] = {
1049 .unbound_nonreg_file = 1,
1052 [IORING_OP_ASYNC_CANCEL] = {
1055 [IORING_OP_LINK_TIMEOUT] = {
1057 .async_size = sizeof(struct io_timeout_data),
1059 [IORING_OP_CONNECT] = {
1061 .unbound_nonreg_file = 1,
1063 .needs_async_setup = 1,
1064 .async_size = sizeof(struct io_async_connect),
1066 [IORING_OP_FALLOCATE] = {
1069 [IORING_OP_OPENAT] = {},
1070 [IORING_OP_CLOSE] = {},
1071 [IORING_OP_FILES_UPDATE] = {
1074 [IORING_OP_STATX] = {
1077 [IORING_OP_READ] = {
1079 .unbound_nonreg_file = 1,
1084 .async_size = sizeof(struct io_async_rw),
1086 [IORING_OP_WRITE] = {
1089 .unbound_nonreg_file = 1,
1093 .async_size = sizeof(struct io_async_rw),
1095 [IORING_OP_FADVISE] = {
1099 [IORING_OP_MADVISE] = {},
1100 [IORING_OP_SEND] = {
1102 .unbound_nonreg_file = 1,
1106 [IORING_OP_RECV] = {
1108 .unbound_nonreg_file = 1,
1113 [IORING_OP_OPENAT2] = {
1115 [IORING_OP_EPOLL_CTL] = {
1116 .unbound_nonreg_file = 1,
1119 [IORING_OP_SPLICE] = {
1122 .unbound_nonreg_file = 1,
1125 [IORING_OP_PROVIDE_BUFFERS] = {
1128 [IORING_OP_REMOVE_BUFFERS] = {
1134 .unbound_nonreg_file = 1,
1137 [IORING_OP_SHUTDOWN] = {
1140 [IORING_OP_RENAMEAT] = {},
1141 [IORING_OP_UNLINKAT] = {},
1142 [IORING_OP_MKDIRAT] = {},
1143 [IORING_OP_SYMLINKAT] = {},
1144 [IORING_OP_LINKAT] = {},
1145 [IORING_OP_MSG_RING] = {
1150 /* requests with any of those set should undergo io_disarm_next() */
1151 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1153 static bool io_disarm_next(struct io_kiocb *req);
1154 static void io_uring_del_tctx_node(unsigned long index);
1155 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1156 struct task_struct *task,
1158 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1160 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1162 static void io_put_req(struct io_kiocb *req);
1163 static void io_put_req_deferred(struct io_kiocb *req);
1164 static void io_dismantle_req(struct io_kiocb *req);
1165 static void io_queue_linked_timeout(struct io_kiocb *req);
1166 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1167 struct io_uring_rsrc_update2 *up,
1169 static void io_clean_op(struct io_kiocb *req);
1170 static struct file *io_file_get(struct io_ring_ctx *ctx,
1171 struct io_kiocb *req, int fd, bool fixed);
1172 static void __io_queue_sqe(struct io_kiocb *req);
1173 static void io_rsrc_put_work(struct work_struct *work);
1175 static void io_req_task_queue(struct io_kiocb *req);
1176 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1177 static int io_req_prep_async(struct io_kiocb *req);
1179 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1180 unsigned int issue_flags, u32 slot_index);
1181 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1183 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1185 static struct kmem_cache *req_cachep;
1187 static const struct file_operations io_uring_fops;
1189 struct sock *io_uring_get_socket(struct file *file)
1191 #if defined(CONFIG_UNIX)
1192 if (file->f_op == &io_uring_fops) {
1193 struct io_ring_ctx *ctx = file->private_data;
1195 return ctx->ring_sock->sk;
1200 EXPORT_SYMBOL(io_uring_get_socket);
1202 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1205 mutex_lock(&ctx->uring_lock);
1210 #define io_for_each_link(pos, head) \
1211 for (pos = (head); pos; pos = pos->link)
1214 * Shamelessly stolen from the mm implementation of page reference checking,
1215 * see commit f958d7b528b1 for details.
1217 #define req_ref_zero_or_close_to_overflow(req) \
1218 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1220 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1222 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1223 return atomic_inc_not_zero(&req->refs);
1226 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1228 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1231 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1232 return atomic_dec_and_test(&req->refs);
1235 static inline void req_ref_get(struct io_kiocb *req)
1237 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1238 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1239 atomic_inc(&req->refs);
1242 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1244 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1245 __io_submit_flush_completions(ctx);
1248 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1250 if (!(req->flags & REQ_F_REFCOUNT)) {
1251 req->flags |= REQ_F_REFCOUNT;
1252 atomic_set(&req->refs, nr);
1256 static inline void io_req_set_refcount(struct io_kiocb *req)
1258 __io_req_set_refcount(req, 1);
1261 #define IO_RSRC_REF_BATCH 100
1263 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1264 struct io_ring_ctx *ctx)
1265 __must_hold(&ctx->uring_lock)
1267 struct percpu_ref *ref = req->fixed_rsrc_refs;
1270 if (ref == &ctx->rsrc_node->refs)
1271 ctx->rsrc_cached_refs++;
1273 percpu_ref_put(ref);
1277 static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1279 if (req->fixed_rsrc_refs)
1280 percpu_ref_put(req->fixed_rsrc_refs);
1283 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1284 __must_hold(&ctx->uring_lock)
1286 if (ctx->rsrc_cached_refs) {
1287 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1288 ctx->rsrc_cached_refs = 0;
1292 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1293 __must_hold(&ctx->uring_lock)
1295 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1296 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1299 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1300 struct io_ring_ctx *ctx)
1302 if (!req->fixed_rsrc_refs) {
1303 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1304 ctx->rsrc_cached_refs--;
1305 if (unlikely(ctx->rsrc_cached_refs < 0))
1306 io_rsrc_refs_refill(ctx);
1310 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1312 struct io_buffer *kbuf = req->kbuf;
1313 unsigned int cflags;
1315 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
1316 req->flags &= ~REQ_F_BUFFER_SELECTED;
1317 list_add(&kbuf->list, list);
1322 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1324 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1326 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1329 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1330 unsigned issue_flags)
1332 unsigned int cflags;
1334 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1338 * We can add this buffer back to two lists:
1340 * 1) The io_buffers_cache list. This one is protected by the
1341 * ctx->uring_lock. If we already hold this lock, add back to this
1342 * list as we can grab it from issue as well.
1343 * 2) The io_buffers_comp list. This one is protected by the
1344 * ctx->completion_lock.
1346 * We migrate buffers from the comp_list to the issue cache list
1349 if (issue_flags & IO_URING_F_UNLOCKED) {
1350 struct io_ring_ctx *ctx = req->ctx;
1352 spin_lock(&ctx->completion_lock);
1353 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1354 spin_unlock(&ctx->completion_lock);
1356 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1362 static void io_kbuf_recycle(struct io_kiocb *req)
1364 struct io_ring_ctx *ctx = req->ctx;
1365 struct io_buffer *head, *buf;
1367 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1370 lockdep_assert_held(&ctx->uring_lock);
1374 head = xa_load(&ctx->io_buffers, buf->bgid);
1376 list_add(&buf->list, &head->list);
1380 INIT_LIST_HEAD(&buf->list);
1382 /* if we fail, just leave buffer attached */
1383 ret = xa_insert(&ctx->io_buffers, buf->bgid, buf, GFP_KERNEL);
1384 if (unlikely(ret < 0))
1388 req->flags &= ~REQ_F_BUFFER_SELECTED;
1392 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1394 __must_hold(&req->ctx->timeout_lock)
1396 struct io_kiocb *req;
1398 if (task && head->task != task)
1403 io_for_each_link(req, head) {
1404 if (req->flags & REQ_F_INFLIGHT)
1410 static bool io_match_linked(struct io_kiocb *head)
1412 struct io_kiocb *req;
1414 io_for_each_link(req, head) {
1415 if (req->flags & REQ_F_INFLIGHT)
1422 * As io_match_task() but protected against racing with linked timeouts.
1423 * User must not hold timeout_lock.
1425 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1430 if (task && head->task != task)
1435 if (head->flags & REQ_F_LINK_TIMEOUT) {
1436 struct io_ring_ctx *ctx = head->ctx;
1438 /* protect against races with linked timeouts */
1439 spin_lock_irq(&ctx->timeout_lock);
1440 matched = io_match_linked(head);
1441 spin_unlock_irq(&ctx->timeout_lock);
1443 matched = io_match_linked(head);
1448 static inline bool req_has_async_data(struct io_kiocb *req)
1450 return req->flags & REQ_F_ASYNC_DATA;
1453 static inline void req_set_fail(struct io_kiocb *req)
1455 req->flags |= REQ_F_FAIL;
1456 if (req->flags & REQ_F_CQE_SKIP) {
1457 req->flags &= ~REQ_F_CQE_SKIP;
1458 req->flags |= REQ_F_SKIP_LINK_CQES;
1462 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1468 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1470 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1472 complete(&ctx->ref_comp);
1475 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1477 return !req->timeout.off;
1480 static __cold void io_fallback_req_func(struct work_struct *work)
1482 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1483 fallback_work.work);
1484 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1485 struct io_kiocb *req, *tmp;
1486 bool locked = false;
1488 percpu_ref_get(&ctx->refs);
1489 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1490 req->io_task_work.func(req, &locked);
1493 io_submit_flush_completions(ctx);
1494 mutex_unlock(&ctx->uring_lock);
1496 percpu_ref_put(&ctx->refs);
1499 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1501 struct io_ring_ctx *ctx;
1504 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1509 * Use 5 bits less than the max cq entries, that should give us around
1510 * 32 entries per hash list if totally full and uniformly spread.
1512 hash_bits = ilog2(p->cq_entries);
1516 ctx->cancel_hash_bits = hash_bits;
1517 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1519 if (!ctx->cancel_hash)
1521 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1523 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1524 if (!ctx->dummy_ubuf)
1526 /* set invalid range, so io_import_fixed() fails meeting it */
1527 ctx->dummy_ubuf->ubuf = -1UL;
1529 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1530 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1533 ctx->flags = p->flags;
1534 init_waitqueue_head(&ctx->sqo_sq_wait);
1535 INIT_LIST_HEAD(&ctx->sqd_list);
1536 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1537 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1538 INIT_LIST_HEAD(&ctx->apoll_cache);
1539 init_completion(&ctx->ref_comp);
1540 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1541 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1542 mutex_init(&ctx->uring_lock);
1543 init_waitqueue_head(&ctx->cq_wait);
1544 spin_lock_init(&ctx->completion_lock);
1545 spin_lock_init(&ctx->timeout_lock);
1546 INIT_WQ_LIST(&ctx->iopoll_list);
1547 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1548 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1549 INIT_LIST_HEAD(&ctx->defer_list);
1550 INIT_LIST_HEAD(&ctx->timeout_list);
1551 INIT_LIST_HEAD(&ctx->ltimeout_list);
1552 spin_lock_init(&ctx->rsrc_ref_lock);
1553 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1554 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1555 init_llist_head(&ctx->rsrc_put_llist);
1556 INIT_LIST_HEAD(&ctx->tctx_list);
1557 ctx->submit_state.free_list.next = NULL;
1558 INIT_WQ_LIST(&ctx->locked_free_list);
1559 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1560 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1561 #ifdef CONFIG_NET_RX_BUSY_POLL
1562 INIT_LIST_HEAD(&ctx->napi_list);
1563 spin_lock_init(&ctx->napi_lock);
1567 kfree(ctx->dummy_ubuf);
1568 kfree(ctx->cancel_hash);
1573 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1575 struct io_rings *r = ctx->rings;
1577 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1581 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1583 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1584 struct io_ring_ctx *ctx = req->ctx;
1586 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1592 #define FFS_NOWAIT 0x1UL
1593 #define FFS_ISREG 0x2UL
1594 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
1596 static inline bool io_req_ffs_set(struct io_kiocb *req)
1598 return req->flags & REQ_F_FIXED_FILE;
1601 static inline void io_req_track_inflight(struct io_kiocb *req)
1603 if (!(req->flags & REQ_F_INFLIGHT)) {
1604 req->flags |= REQ_F_INFLIGHT;
1605 atomic_inc(¤t->io_uring->inflight_tracked);
1609 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1611 if (WARN_ON_ONCE(!req->link))
1614 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1615 req->flags |= REQ_F_LINK_TIMEOUT;
1617 /* linked timeouts should have two refs once prep'ed */
1618 io_req_set_refcount(req);
1619 __io_req_set_refcount(req->link, 2);
1623 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1625 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1627 return __io_prep_linked_timeout(req);
1630 static void io_prep_async_work(struct io_kiocb *req)
1632 const struct io_op_def *def = &io_op_defs[req->opcode];
1633 struct io_ring_ctx *ctx = req->ctx;
1635 if (!(req->flags & REQ_F_CREDS)) {
1636 req->flags |= REQ_F_CREDS;
1637 req->creds = get_current_cred();
1640 req->work.list.next = NULL;
1641 req->work.flags = 0;
1642 if (req->flags & REQ_F_FORCE_ASYNC)
1643 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1645 if (req->flags & REQ_F_ISREG) {
1646 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1647 io_wq_hash_work(&req->work, file_inode(req->file));
1648 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1649 if (def->unbound_nonreg_file)
1650 req->work.flags |= IO_WQ_WORK_UNBOUND;
1653 switch (req->opcode) {
1654 case IORING_OP_SPLICE:
1656 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1657 req->work.flags |= IO_WQ_WORK_UNBOUND;
1662 static void io_prep_async_link(struct io_kiocb *req)
1664 struct io_kiocb *cur;
1666 if (req->flags & REQ_F_LINK_TIMEOUT) {
1667 struct io_ring_ctx *ctx = req->ctx;
1669 spin_lock_irq(&ctx->timeout_lock);
1670 io_for_each_link(cur, req)
1671 io_prep_async_work(cur);
1672 spin_unlock_irq(&ctx->timeout_lock);
1674 io_for_each_link(cur, req)
1675 io_prep_async_work(cur);
1679 static inline void io_req_add_compl_list(struct io_kiocb *req)
1681 struct io_ring_ctx *ctx = req->ctx;
1682 struct io_submit_state *state = &ctx->submit_state;
1684 if (!(req->flags & REQ_F_CQE_SKIP))
1685 ctx->submit_state.flush_cqes = true;
1686 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1689 static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
1691 struct io_ring_ctx *ctx = req->ctx;
1692 struct io_kiocb *link = io_prep_linked_timeout(req);
1693 struct io_uring_task *tctx = req->task->io_uring;
1696 BUG_ON(!tctx->io_wq);
1698 /* init ->work of the whole link before punting */
1699 io_prep_async_link(req);
1702 * Not expected to happen, but if we do have a bug where this _can_
1703 * happen, catch it here and ensure the request is marked as
1704 * canceled. That will make io-wq go through the usual work cancel
1705 * procedure rather than attempt to run this request (or create a new
1708 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1709 req->work.flags |= IO_WQ_WORK_CANCEL;
1711 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1712 &req->work, io_wq_is_hashed(&req->work));
1713 io_wq_enqueue(tctx->io_wq, &req->work);
1715 io_queue_linked_timeout(link);
1718 static void io_kill_timeout(struct io_kiocb *req, int status)
1719 __must_hold(&req->ctx->completion_lock)
1720 __must_hold(&req->ctx->timeout_lock)
1722 struct io_timeout_data *io = req->async_data;
1724 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1727 atomic_set(&req->ctx->cq_timeouts,
1728 atomic_read(&req->ctx->cq_timeouts) + 1);
1729 list_del_init(&req->timeout.list);
1730 io_fill_cqe_req(req, status, 0);
1731 io_put_req_deferred(req);
1735 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1737 while (!list_empty(&ctx->defer_list)) {
1738 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1739 struct io_defer_entry, list);
1741 if (req_need_defer(de->req, de->seq))
1743 list_del_init(&de->list);
1744 io_req_task_queue(de->req);
1749 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1750 __must_hold(&ctx->completion_lock)
1752 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1754 spin_lock_irq(&ctx->timeout_lock);
1755 while (!list_empty(&ctx->timeout_list)) {
1756 u32 events_needed, events_got;
1757 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1758 struct io_kiocb, timeout.list);
1760 if (io_is_timeout_noseq(req))
1764 * Since seq can easily wrap around over time, subtract
1765 * the last seq at which timeouts were flushed before comparing.
1766 * Assuming not more than 2^31-1 events have happened since,
1767 * these subtractions won't have wrapped, so we can check if
1768 * target is in [last_seq, current_seq] by comparing the two.
1770 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1771 events_got = seq - ctx->cq_last_tm_flush;
1772 if (events_got < events_needed)
1775 list_del_init(&req->timeout.list);
1776 io_kill_timeout(req, 0);
1778 ctx->cq_last_tm_flush = seq;
1779 spin_unlock_irq(&ctx->timeout_lock);
1782 static __cold void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1784 if (ctx->off_timeout_used)
1785 io_flush_timeouts(ctx);
1786 if (ctx->drain_active)
1787 io_queue_deferred(ctx);
1790 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1792 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1793 __io_commit_cqring_flush(ctx);
1794 /* order cqe stores with ring update */
1795 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1798 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1800 struct io_rings *r = ctx->rings;
1802 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1805 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1807 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1810 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1812 struct io_rings *rings = ctx->rings;
1813 unsigned tail, mask = ctx->cq_entries - 1;
1816 * writes to the cq entry need to come after reading head; the
1817 * control dependency is enough as we're using WRITE_ONCE to
1820 if (__io_cqring_events(ctx) == ctx->cq_entries)
1823 tail = ctx->cached_cq_tail++;
1824 return &rings->cqes[tail & mask];
1827 static void io_eventfd_signal(struct io_ring_ctx *ctx)
1829 struct io_ev_fd *ev_fd;
1831 /* Return quickly if ctx->io_ev_fd doesn't exist */
1832 if (likely(!rcu_dereference_raw(ctx->io_ev_fd)))
1837 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1838 * and eventfd_signal
1840 ev_fd = rcu_dereference(ctx->io_ev_fd);
1843 * Check again if ev_fd exists incase an io_eventfd_unregister call
1844 * completed between the NULL check of ctx->io_ev_fd at the start of
1845 * the function and rcu_read_lock.
1847 if (unlikely(!ev_fd))
1849 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1852 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
1853 eventfd_signal(ev_fd->cq_ev_fd, 1);
1860 * This should only get called when at least one event has been posted.
1861 * Some applications rely on the eventfd notification count only changing
1862 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1863 * 1:1 relationship between how many times this function is called (and
1864 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1866 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1869 * wake_up_all() may seem excessive, but io_wake_function() and
1870 * io_should_wake() handle the termination of the loop and only
1871 * wake as many waiters as we need to.
1873 if (wq_has_sleeper(&ctx->cq_wait))
1874 wake_up_all(&ctx->cq_wait);
1875 io_eventfd_signal(ctx);
1878 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1880 /* see waitqueue_active() comment */
1883 if (ctx->flags & IORING_SETUP_SQPOLL) {
1884 if (waitqueue_active(&ctx->cq_wait))
1885 wake_up_all(&ctx->cq_wait);
1887 io_eventfd_signal(ctx);
1890 /* Returns true if there are no backlogged entries after the flush */
1891 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1893 bool all_flushed, posted;
1895 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1899 spin_lock(&ctx->completion_lock);
1900 while (!list_empty(&ctx->cq_overflow_list)) {
1901 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1902 struct io_overflow_cqe *ocqe;
1906 ocqe = list_first_entry(&ctx->cq_overflow_list,
1907 struct io_overflow_cqe, list);
1909 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1911 io_account_cq_overflow(ctx);
1914 list_del(&ocqe->list);
1918 all_flushed = list_empty(&ctx->cq_overflow_list);
1920 clear_bit(0, &ctx->check_cq_overflow);
1921 WRITE_ONCE(ctx->rings->sq_flags,
1922 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1926 io_commit_cqring(ctx);
1927 spin_unlock(&ctx->completion_lock);
1929 io_cqring_ev_posted(ctx);
1933 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1937 if (test_bit(0, &ctx->check_cq_overflow)) {
1938 /* iopoll syncs against uring_lock, not completion_lock */
1939 if (ctx->flags & IORING_SETUP_IOPOLL)
1940 mutex_lock(&ctx->uring_lock);
1941 ret = __io_cqring_overflow_flush(ctx, false);
1942 if (ctx->flags & IORING_SETUP_IOPOLL)
1943 mutex_unlock(&ctx->uring_lock);
1949 /* must to be called somewhat shortly after putting a request */
1950 static inline void io_put_task(struct task_struct *task, int nr)
1952 struct io_uring_task *tctx = task->io_uring;
1954 if (likely(task == current)) {
1955 tctx->cached_refs += nr;
1957 percpu_counter_sub(&tctx->inflight, nr);
1958 if (unlikely(atomic_read(&tctx->in_idle)))
1959 wake_up(&tctx->wait);
1960 put_task_struct_many(task, nr);
1964 static void io_task_refs_refill(struct io_uring_task *tctx)
1966 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1968 percpu_counter_add(&tctx->inflight, refill);
1969 refcount_add(refill, ¤t->usage);
1970 tctx->cached_refs += refill;
1973 static inline void io_get_task_refs(int nr)
1975 struct io_uring_task *tctx = current->io_uring;
1977 tctx->cached_refs -= nr;
1978 if (unlikely(tctx->cached_refs < 0))
1979 io_task_refs_refill(tctx);
1982 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1984 struct io_uring_task *tctx = task->io_uring;
1985 unsigned int refs = tctx->cached_refs;
1988 tctx->cached_refs = 0;
1989 percpu_counter_sub(&tctx->inflight, refs);
1990 put_task_struct_many(task, refs);
1994 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1995 s32 res, u32 cflags)
1997 struct io_overflow_cqe *ocqe;
1999 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2002 * If we're in ring overflow flush mode, or in task cancel mode,
2003 * or cannot allocate an overflow entry, then we need to drop it
2006 io_account_cq_overflow(ctx);
2009 if (list_empty(&ctx->cq_overflow_list)) {
2010 set_bit(0, &ctx->check_cq_overflow);
2011 WRITE_ONCE(ctx->rings->sq_flags,
2012 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2015 ocqe->cqe.user_data = user_data;
2016 ocqe->cqe.res = res;
2017 ocqe->cqe.flags = cflags;
2018 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2022 static inline bool __fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
2023 s32 res, u32 cflags)
2025 struct io_uring_cqe *cqe;
2028 * If we can't get a cq entry, userspace overflowed the
2029 * submission (by quite a lot). Increment the overflow count in
2032 cqe = io_get_cqe(ctx);
2034 WRITE_ONCE(cqe->user_data, user_data);
2035 WRITE_ONCE(cqe->res, res);
2036 WRITE_ONCE(cqe->flags, cflags);
2039 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2042 static inline bool __io_fill_cqe(struct io_kiocb *req, s32 res, u32 cflags)
2044 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
2045 return __fill_cqe(req->ctx, req->user_data, res, cflags);
2048 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
2050 if (!(req->flags & REQ_F_CQE_SKIP))
2051 __io_fill_cqe(req, res, cflags);
2054 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2055 s32 res, u32 cflags)
2058 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
2059 return __fill_cqe(ctx, user_data, res, cflags);
2062 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2065 struct io_ring_ctx *ctx = req->ctx;
2067 if (!(req->flags & REQ_F_CQE_SKIP))
2068 __io_fill_cqe(req, res, cflags);
2070 * If we're the last reference to this request, add to our locked
2073 if (req_ref_put_and_test(req)) {
2074 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
2075 if (req->flags & IO_DISARM_MASK)
2076 io_disarm_next(req);
2078 io_req_task_queue(req->link);
2082 io_req_put_rsrc(req, ctx);
2083 io_dismantle_req(req);
2084 io_put_task(req->task, 1);
2085 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2086 ctx->locked_free_nr++;
2090 static void io_req_complete_post(struct io_kiocb *req, s32 res,
2093 struct io_ring_ctx *ctx = req->ctx;
2095 spin_lock(&ctx->completion_lock);
2096 __io_req_complete_post(req, res, cflags);
2097 io_commit_cqring(ctx);
2098 spin_unlock(&ctx->completion_lock);
2099 io_cqring_ev_posted(ctx);
2102 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2106 req->cflags = cflags;
2107 req->flags |= REQ_F_COMPLETE_INLINE;
2110 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2111 s32 res, u32 cflags)
2113 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2114 io_req_complete_state(req, res, cflags);
2116 io_req_complete_post(req, res, cflags);
2119 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2121 __io_req_complete(req, 0, res, 0);
2124 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2127 io_req_complete_post(req, res, 0);
2130 static void io_req_complete_fail_submit(struct io_kiocb *req)
2133 * We don't submit, fail them all, for that replace hardlinks with
2134 * normal links. Extra REQ_F_LINK is tolerated.
2136 req->flags &= ~REQ_F_HARDLINK;
2137 req->flags |= REQ_F_LINK;
2138 io_req_complete_failed(req, req->result);
2142 * Don't initialise the fields below on every allocation, but do that in
2143 * advance and keep them valid across allocations.
2145 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2149 req->async_data = NULL;
2150 /* not necessary, but safer to zero */
2154 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2155 struct io_submit_state *state)
2157 spin_lock(&ctx->completion_lock);
2158 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2159 ctx->locked_free_nr = 0;
2160 spin_unlock(&ctx->completion_lock);
2163 /* Returns true IFF there are requests in the cache */
2164 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
2166 struct io_submit_state *state = &ctx->submit_state;
2169 * If we have more than a batch's worth of requests in our IRQ side
2170 * locked cache, grab the lock and move them over to our submission
2173 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
2174 io_flush_cached_locked_reqs(ctx, state);
2175 return !!state->free_list.next;
2179 * A request might get retired back into the request caches even before opcode
2180 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2181 * Because of that, io_alloc_req() should be called only under ->uring_lock
2182 * and with extra caution to not get a request that is still worked on.
2184 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2185 __must_hold(&ctx->uring_lock)
2187 struct io_submit_state *state = &ctx->submit_state;
2188 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2189 void *reqs[IO_REQ_ALLOC_BATCH];
2190 struct io_kiocb *req;
2193 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
2196 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2199 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2200 * retry single alloc to be on the safe side.
2202 if (unlikely(ret <= 0)) {
2203 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2209 percpu_ref_get_many(&ctx->refs, ret);
2210 for (i = 0; i < ret; i++) {
2213 io_preinit_req(req, ctx);
2214 wq_stack_add_head(&req->comp_list, &state->free_list);
2219 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2221 if (unlikely(!ctx->submit_state.free_list.next))
2222 return __io_alloc_req_refill(ctx);
2226 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2228 struct io_wq_work_node *node;
2230 node = wq_stack_extract(&ctx->submit_state.free_list);
2231 return container_of(node, struct io_kiocb, comp_list);
2234 static inline void io_put_file(struct file *file)
2240 static inline void io_dismantle_req(struct io_kiocb *req)
2242 unsigned int flags = req->flags;
2244 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2246 if (!(flags & REQ_F_FIXED_FILE))
2247 io_put_file(req->file);
2250 static __cold void __io_free_req(struct io_kiocb *req)
2252 struct io_ring_ctx *ctx = req->ctx;
2254 io_req_put_rsrc(req, ctx);
2255 io_dismantle_req(req);
2256 io_put_task(req->task, 1);
2258 spin_lock(&ctx->completion_lock);
2259 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2260 ctx->locked_free_nr++;
2261 spin_unlock(&ctx->completion_lock);
2264 static inline void io_remove_next_linked(struct io_kiocb *req)
2266 struct io_kiocb *nxt = req->link;
2268 req->link = nxt->link;
2272 static bool io_kill_linked_timeout(struct io_kiocb *req)
2273 __must_hold(&req->ctx->completion_lock)
2274 __must_hold(&req->ctx->timeout_lock)
2276 struct io_kiocb *link = req->link;
2278 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2279 struct io_timeout_data *io = link->async_data;
2281 io_remove_next_linked(req);
2282 link->timeout.head = NULL;
2283 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2284 list_del(&link->timeout.list);
2285 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2286 io_fill_cqe_req(link, -ECANCELED, 0);
2287 io_put_req_deferred(link);
2294 static void io_fail_links(struct io_kiocb *req)
2295 __must_hold(&req->ctx->completion_lock)
2297 struct io_kiocb *nxt, *link = req->link;
2298 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2302 long res = -ECANCELED;
2304 if (link->flags & REQ_F_FAIL)
2310 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2314 link->flags &= ~REQ_F_CQE_SKIP;
2315 io_fill_cqe_req(link, res, 0);
2317 io_put_req_deferred(link);
2322 static bool io_disarm_next(struct io_kiocb *req)
2323 __must_hold(&req->ctx->completion_lock)
2325 bool posted = false;
2327 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2328 struct io_kiocb *link = req->link;
2330 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2331 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2332 io_remove_next_linked(req);
2333 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
2334 io_fill_cqe_req(link, -ECANCELED, 0);
2335 io_put_req_deferred(link);
2338 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2339 struct io_ring_ctx *ctx = req->ctx;
2341 spin_lock_irq(&ctx->timeout_lock);
2342 posted = io_kill_linked_timeout(req);
2343 spin_unlock_irq(&ctx->timeout_lock);
2345 if (unlikely((req->flags & REQ_F_FAIL) &&
2346 !(req->flags & REQ_F_HARDLINK))) {
2347 posted |= (req->link != NULL);
2353 static void __io_req_find_next_prep(struct io_kiocb *req)
2355 struct io_ring_ctx *ctx = req->ctx;
2358 spin_lock(&ctx->completion_lock);
2359 posted = io_disarm_next(req);
2361 io_commit_cqring(ctx);
2362 spin_unlock(&ctx->completion_lock);
2364 io_cqring_ev_posted(ctx);
2367 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2369 struct io_kiocb *nxt;
2371 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2374 * If LINK is set, we have dependent requests in this chain. If we
2375 * didn't fail this request, queue the first one up, moving any other
2376 * dependencies to the next request. In case of failure, fail the rest
2379 if (unlikely(req->flags & IO_DISARM_MASK))
2380 __io_req_find_next_prep(req);
2386 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2391 io_submit_flush_completions(ctx);
2392 mutex_unlock(&ctx->uring_lock);
2395 percpu_ref_put(&ctx->refs);
2398 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2400 io_commit_cqring(ctx);
2401 spin_unlock(&ctx->completion_lock);
2402 io_cqring_ev_posted(ctx);
2405 static void handle_prev_tw_list(struct io_wq_work_node *node,
2406 struct io_ring_ctx **ctx, bool *uring_locked)
2408 if (*ctx && !*uring_locked)
2409 spin_lock(&(*ctx)->completion_lock);
2412 struct io_wq_work_node *next = node->next;
2413 struct io_kiocb *req = container_of(node, struct io_kiocb,
2416 if (req->ctx != *ctx) {
2417 if (unlikely(!*uring_locked && *ctx))
2418 ctx_commit_and_unlock(*ctx);
2420 ctx_flush_and_put(*ctx, uring_locked);
2422 /* if not contended, grab and improve batching */
2423 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2424 percpu_ref_get(&(*ctx)->refs);
2425 if (unlikely(!*uring_locked))
2426 spin_lock(&(*ctx)->completion_lock);
2428 if (likely(*uring_locked))
2429 req->io_task_work.func(req, uring_locked);
2431 __io_req_complete_post(req, req->result,
2432 io_put_kbuf_comp(req));
2436 if (unlikely(!*uring_locked))
2437 ctx_commit_and_unlock(*ctx);
2440 static void handle_tw_list(struct io_wq_work_node *node,
2441 struct io_ring_ctx **ctx, bool *locked)
2444 struct io_wq_work_node *next = node->next;
2445 struct io_kiocb *req = container_of(node, struct io_kiocb,
2448 if (req->ctx != *ctx) {
2449 ctx_flush_and_put(*ctx, locked);
2451 /* if not contended, grab and improve batching */
2452 *locked = mutex_trylock(&(*ctx)->uring_lock);
2453 percpu_ref_get(&(*ctx)->refs);
2455 req->io_task_work.func(req, locked);
2460 static void tctx_task_work(struct callback_head *cb)
2462 bool uring_locked = false;
2463 struct io_ring_ctx *ctx = NULL;
2464 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2468 struct io_wq_work_node *node1, *node2;
2470 if (!tctx->task_list.first &&
2471 !tctx->prior_task_list.first && uring_locked)
2472 io_submit_flush_completions(ctx);
2474 spin_lock_irq(&tctx->task_lock);
2475 node1 = tctx->prior_task_list.first;
2476 node2 = tctx->task_list.first;
2477 INIT_WQ_LIST(&tctx->task_list);
2478 INIT_WQ_LIST(&tctx->prior_task_list);
2479 if (!node2 && !node1)
2480 tctx->task_running = false;
2481 spin_unlock_irq(&tctx->task_lock);
2482 if (!node2 && !node1)
2486 handle_prev_tw_list(node1, &ctx, &uring_locked);
2489 handle_tw_list(node2, &ctx, &uring_locked);
2493 ctx_flush_and_put(ctx, &uring_locked);
2495 /* relaxed read is enough as only the task itself sets ->in_idle */
2496 if (unlikely(atomic_read(&tctx->in_idle)))
2497 io_uring_drop_tctx_refs(current);
2500 static void io_req_task_work_add(struct io_kiocb *req, bool priority)
2502 struct task_struct *tsk = req->task;
2503 struct io_uring_task *tctx = tsk->io_uring;
2504 enum task_work_notify_mode notify;
2505 struct io_wq_work_node *node;
2506 unsigned long flags;
2509 WARN_ON_ONCE(!tctx);
2511 spin_lock_irqsave(&tctx->task_lock, flags);
2513 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2515 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2516 running = tctx->task_running;
2518 tctx->task_running = true;
2519 spin_unlock_irqrestore(&tctx->task_lock, flags);
2521 /* task_work already pending, we're done */
2526 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2527 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2528 * processing task_work. There's no reliable way to tell if TWA_RESUME
2531 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2532 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2533 if (notify == TWA_NONE)
2534 wake_up_process(tsk);
2538 spin_lock_irqsave(&tctx->task_lock, flags);
2539 tctx->task_running = false;
2540 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
2541 spin_unlock_irqrestore(&tctx->task_lock, flags);
2544 req = container_of(node, struct io_kiocb, io_task_work.node);
2546 if (llist_add(&req->io_task_work.fallback_node,
2547 &req->ctx->fallback_llist))
2548 schedule_delayed_work(&req->ctx->fallback_work, 1);
2552 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2554 struct io_ring_ctx *ctx = req->ctx;
2556 /* not needed for normal modes, but SQPOLL depends on it */
2557 io_tw_lock(ctx, locked);
2558 io_req_complete_failed(req, req->result);
2561 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2563 struct io_ring_ctx *ctx = req->ctx;
2565 io_tw_lock(ctx, locked);
2566 /* req->task == current here, checking PF_EXITING is safe */
2567 if (likely(!(req->task->flags & PF_EXITING)))
2568 __io_queue_sqe(req);
2570 io_req_complete_failed(req, -EFAULT);
2573 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2576 req->io_task_work.func = io_req_task_cancel;
2577 io_req_task_work_add(req, false);
2580 static void io_req_task_queue(struct io_kiocb *req)
2582 req->io_task_work.func = io_req_task_submit;
2583 io_req_task_work_add(req, false);
2586 static void io_req_task_queue_reissue(struct io_kiocb *req)
2588 req->io_task_work.func = io_queue_async_work;
2589 io_req_task_work_add(req, false);
2592 static inline void io_queue_next(struct io_kiocb *req)
2594 struct io_kiocb *nxt = io_req_find_next(req);
2597 io_req_task_queue(nxt);
2600 static void io_free_req(struct io_kiocb *req)
2606 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2611 static void io_free_batch_list(struct io_ring_ctx *ctx,
2612 struct io_wq_work_node *node)
2613 __must_hold(&ctx->uring_lock)
2615 struct task_struct *task = NULL;
2619 struct io_kiocb *req = container_of(node, struct io_kiocb,
2622 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
2623 node = req->comp_list.next;
2624 if (!req_ref_put_and_test(req))
2628 io_req_put_rsrc_locked(req, ctx);
2630 io_dismantle_req(req);
2632 if (req->task != task) {
2634 io_put_task(task, task_refs);
2639 node = req->comp_list.next;
2640 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
2644 io_put_task(task, task_refs);
2647 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2648 __must_hold(&ctx->uring_lock)
2650 struct io_wq_work_node *node, *prev;
2651 struct io_submit_state *state = &ctx->submit_state;
2653 if (state->flush_cqes) {
2654 spin_lock(&ctx->completion_lock);
2655 wq_list_for_each(node, prev, &state->compl_reqs) {
2656 struct io_kiocb *req = container_of(node, struct io_kiocb,
2659 if (!(req->flags & REQ_F_CQE_SKIP))
2660 __io_fill_cqe(req, req->result, req->cflags);
2661 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2662 struct async_poll *apoll = req->apoll;
2664 if (apoll->double_poll)
2665 kfree(apoll->double_poll);
2666 list_add(&apoll->poll.wait.entry,
2668 req->flags &= ~REQ_F_POLLED;
2672 io_commit_cqring(ctx);
2673 spin_unlock(&ctx->completion_lock);
2674 io_cqring_ev_posted(ctx);
2675 state->flush_cqes = false;
2678 io_free_batch_list(ctx, state->compl_reqs.first);
2679 INIT_WQ_LIST(&state->compl_reqs);
2683 * Drop reference to request, return next in chain (if there is one) if this
2684 * was the last reference to this request.
2686 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2688 struct io_kiocb *nxt = NULL;
2690 if (req_ref_put_and_test(req)) {
2691 nxt = io_req_find_next(req);
2697 static inline void io_put_req(struct io_kiocb *req)
2699 if (req_ref_put_and_test(req))
2703 static inline void io_put_req_deferred(struct io_kiocb *req)
2705 if (req_ref_put_and_test(req)) {
2706 req->io_task_work.func = io_free_req_work;
2707 io_req_task_work_add(req, false);
2711 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2713 /* See comment at the top of this file */
2715 return __io_cqring_events(ctx);
2718 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2720 struct io_rings *rings = ctx->rings;
2722 /* make sure SQ entry isn't read before tail */
2723 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2726 static inline bool io_run_task_work(void)
2728 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2729 __set_current_state(TASK_RUNNING);
2730 tracehook_notify_signal();
2737 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
2739 struct io_wq_work_node *pos, *start, *prev;
2740 unsigned int poll_flags = BLK_POLL_NOSLEEP;
2741 DEFINE_IO_COMP_BATCH(iob);
2745 * Only spin for completions if we don't have multiple devices hanging
2746 * off our complete list.
2748 if (ctx->poll_multi_queue || force_nonspin)
2749 poll_flags |= BLK_POLL_ONESHOT;
2751 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2752 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2753 struct kiocb *kiocb = &req->rw.kiocb;
2757 * Move completed and retryable entries to our local lists.
2758 * If we find a request that requires polling, break out
2759 * and complete those lists first, if we have entries there.
2761 if (READ_ONCE(req->iopoll_completed))
2764 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
2765 if (unlikely(ret < 0))
2768 poll_flags |= BLK_POLL_ONESHOT;
2770 /* iopoll may have completed current req */
2771 if (!rq_list_empty(iob.req_list) ||
2772 READ_ONCE(req->iopoll_completed))
2776 if (!rq_list_empty(iob.req_list))
2782 wq_list_for_each_resume(pos, prev) {
2783 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2785 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2786 if (!smp_load_acquire(&req->iopoll_completed))
2788 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2791 __io_fill_cqe(req, req->result, io_put_kbuf(req, 0));
2795 if (unlikely(!nr_events))
2798 io_commit_cqring(ctx);
2799 io_cqring_ev_posted_iopoll(ctx);
2800 pos = start ? start->next : ctx->iopoll_list.first;
2801 wq_list_cut(&ctx->iopoll_list, prev, start);
2802 io_free_batch_list(ctx, pos);
2807 * We can't just wait for polled events to come to us, we have to actively
2808 * find and complete them.
2810 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2812 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2815 mutex_lock(&ctx->uring_lock);
2816 while (!wq_list_empty(&ctx->iopoll_list)) {
2817 /* let it sleep and repeat later if can't complete a request */
2818 if (io_do_iopoll(ctx, true) == 0)
2821 * Ensure we allow local-to-the-cpu processing to take place,
2822 * in this case we need to ensure that we reap all events.
2823 * Also let task_work, etc. to progress by releasing the mutex
2825 if (need_resched()) {
2826 mutex_unlock(&ctx->uring_lock);
2828 mutex_lock(&ctx->uring_lock);
2831 mutex_unlock(&ctx->uring_lock);
2834 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2836 unsigned int nr_events = 0;
2840 * We disallow the app entering submit/complete with polling, but we
2841 * still need to lock the ring to prevent racing with polled issue
2842 * that got punted to a workqueue.
2844 mutex_lock(&ctx->uring_lock);
2846 * Don't enter poll loop if we already have events pending.
2847 * If we do, we can potentially be spinning for commands that
2848 * already triggered a CQE (eg in error).
2850 if (test_bit(0, &ctx->check_cq_overflow))
2851 __io_cqring_overflow_flush(ctx, false);
2852 if (io_cqring_events(ctx))
2856 * If a submit got punted to a workqueue, we can have the
2857 * application entering polling for a command before it gets
2858 * issued. That app will hold the uring_lock for the duration
2859 * of the poll right here, so we need to take a breather every
2860 * now and then to ensure that the issue has a chance to add
2861 * the poll to the issued list. Otherwise we can spin here
2862 * forever, while the workqueue is stuck trying to acquire the
2865 if (wq_list_empty(&ctx->iopoll_list)) {
2866 u32 tail = ctx->cached_cq_tail;
2868 mutex_unlock(&ctx->uring_lock);
2870 mutex_lock(&ctx->uring_lock);
2872 /* some requests don't go through iopoll_list */
2873 if (tail != ctx->cached_cq_tail ||
2874 wq_list_empty(&ctx->iopoll_list))
2877 ret = io_do_iopoll(ctx, !min);
2882 } while (nr_events < min && !need_resched());
2884 mutex_unlock(&ctx->uring_lock);
2888 static void kiocb_end_write(struct io_kiocb *req)
2891 * Tell lockdep we inherited freeze protection from submission
2894 if (req->flags & REQ_F_ISREG) {
2895 struct super_block *sb = file_inode(req->file)->i_sb;
2897 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2903 static bool io_resubmit_prep(struct io_kiocb *req)
2905 struct io_async_rw *rw = req->async_data;
2907 if (!req_has_async_data(req))
2908 return !io_req_prep_async(req);
2909 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
2913 static bool io_rw_should_reissue(struct io_kiocb *req)
2915 umode_t mode = file_inode(req->file)->i_mode;
2916 struct io_ring_ctx *ctx = req->ctx;
2918 if (!S_ISBLK(mode) && !S_ISREG(mode))
2920 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2921 !(ctx->flags & IORING_SETUP_IOPOLL)))
2924 * If ref is dying, we might be running poll reap from the exit work.
2925 * Don't attempt to reissue from that path, just let it fail with
2928 if (percpu_ref_is_dying(&ctx->refs))
2931 * Play it safe and assume not safe to re-import and reissue if we're
2932 * not in the original thread group (or in task context).
2934 if (!same_thread_group(req->task, current) || !in_task())
2939 static bool io_resubmit_prep(struct io_kiocb *req)
2943 static bool io_rw_should_reissue(struct io_kiocb *req)
2949 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2951 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2952 kiocb_end_write(req);
2953 if (unlikely(res != req->result)) {
2954 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2955 io_rw_should_reissue(req)) {
2956 req->flags |= REQ_F_REISSUE;
2965 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
2967 int res = req->result;
2970 io_req_complete_state(req, res, io_put_kbuf(req, 0));
2971 io_req_add_compl_list(req);
2973 io_req_complete_post(req, res,
2974 io_put_kbuf(req, IO_URING_F_UNLOCKED));
2978 static void __io_complete_rw(struct io_kiocb *req, long res,
2979 unsigned int issue_flags)
2981 if (__io_complete_rw_common(req, res))
2983 __io_req_complete(req, issue_flags, req->result,
2984 io_put_kbuf(req, issue_flags));
2987 static void io_complete_rw(struct kiocb *kiocb, long res)
2989 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2991 if (__io_complete_rw_common(req, res))
2994 req->io_task_work.func = io_req_task_complete;
2995 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
2998 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3000 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3002 if (kiocb->ki_flags & IOCB_WRITE)
3003 kiocb_end_write(req);
3004 if (unlikely(res != req->result)) {
3005 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3006 req->flags |= REQ_F_REISSUE;
3012 /* order with io_iopoll_complete() checking ->iopoll_completed */
3013 smp_store_release(&req->iopoll_completed, 1);
3017 * After the iocb has been issued, it's safe to be found on the poll list.
3018 * Adding the kiocb to the list AFTER submission ensures that we don't
3019 * find it from a io_do_iopoll() thread before the issuer is done
3020 * accessing the kiocb cookie.
3022 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3024 struct io_ring_ctx *ctx = req->ctx;
3025 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3027 /* workqueue context doesn't hold uring_lock, grab it now */
3028 if (unlikely(needs_lock))
3029 mutex_lock(&ctx->uring_lock);
3032 * Track whether we have multiple files in our lists. This will impact
3033 * how we do polling eventually, not spinning if we're on potentially
3034 * different devices.
3036 if (wq_list_empty(&ctx->iopoll_list)) {
3037 ctx->poll_multi_queue = false;
3038 } else if (!ctx->poll_multi_queue) {
3039 struct io_kiocb *list_req;
3041 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3043 if (list_req->file != req->file)
3044 ctx->poll_multi_queue = true;
3048 * For fast devices, IO may have already completed. If it has, add
3049 * it to the front so we find it first.
3051 if (READ_ONCE(req->iopoll_completed))
3052 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3054 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3056 if (unlikely(needs_lock)) {
3058 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3059 * in sq thread task context or in io worker task context. If
3060 * current task context is sq thread, we don't need to check
3061 * whether should wake up sq thread.
3063 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3064 wq_has_sleeper(&ctx->sq_data->wait))
3065 wake_up(&ctx->sq_data->wait);
3067 mutex_unlock(&ctx->uring_lock);
3071 static bool io_bdev_nowait(struct block_device *bdev)
3073 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3077 * If we tracked the file through the SCM inflight mechanism, we could support
3078 * any file. For now, just ensure that anything potentially problematic is done
3081 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3083 if (S_ISBLK(mode)) {
3084 if (IS_ENABLED(CONFIG_BLOCK) &&
3085 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3091 if (S_ISREG(mode)) {
3092 if (IS_ENABLED(CONFIG_BLOCK) &&
3093 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3094 file->f_op != &io_uring_fops)
3099 /* any ->read/write should understand O_NONBLOCK */
3100 if (file->f_flags & O_NONBLOCK)
3102 return file->f_mode & FMODE_NOWAIT;
3106 * If we tracked the file through the SCM inflight mechanism, we could support
3107 * any file. For now, just ensure that anything potentially problematic is done
3110 static unsigned int io_file_get_flags(struct file *file)
3112 umode_t mode = file_inode(file)->i_mode;
3113 unsigned int res = 0;
3117 if (__io_file_supports_nowait(file, mode))
3122 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3124 return req->flags & REQ_F_SUPPORT_NOWAIT;
3127 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3129 struct io_ring_ctx *ctx = req->ctx;
3130 struct kiocb *kiocb = &req->rw.kiocb;
3131 struct file *file = req->file;
3135 if (!io_req_ffs_set(req))
3136 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
3138 kiocb->ki_pos = READ_ONCE(sqe->off);
3139 kiocb->ki_flags = iocb_flags(file);
3140 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3145 * If the file is marked O_NONBLOCK, still allow retry for it if it
3146 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3147 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3149 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
3150 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
3151 req->flags |= REQ_F_NOWAIT;
3153 if (ctx->flags & IORING_SETUP_IOPOLL) {
3154 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
3157 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
3158 kiocb->ki_complete = io_complete_rw_iopoll;
3159 req->iopoll_completed = 0;
3161 if (kiocb->ki_flags & IOCB_HIPRI)
3163 kiocb->ki_complete = io_complete_rw;
3166 ioprio = READ_ONCE(sqe->ioprio);
3168 ret = ioprio_check_cap(ioprio);
3172 kiocb->ki_ioprio = ioprio;
3174 kiocb->ki_ioprio = get_current_ioprio();
3178 req->rw.addr = READ_ONCE(sqe->addr);
3179 req->rw.len = READ_ONCE(sqe->len);
3180 req->buf_index = READ_ONCE(sqe->buf_index);
3184 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3190 case -ERESTARTNOINTR:
3191 case -ERESTARTNOHAND:
3192 case -ERESTART_RESTARTBLOCK:
3194 * We can't just restart the syscall, since previously
3195 * submitted sqes may already be in progress. Just fail this
3201 kiocb->ki_complete(kiocb, ret);
3205 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3207 struct kiocb *kiocb = &req->rw.kiocb;
3208 bool is_stream = req->file->f_mode & FMODE_STREAM;
3210 if (kiocb->ki_pos == -1) {
3212 req->flags |= REQ_F_CUR_POS;
3213 kiocb->ki_pos = req->file->f_pos;
3214 return &kiocb->ki_pos;
3220 return is_stream ? NULL : &kiocb->ki_pos;
3223 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3224 unsigned int issue_flags)
3226 struct io_async_rw *io = req->async_data;
3228 /* add previously done IO, if any */
3229 if (req_has_async_data(req) && io->bytes_done > 0) {
3231 ret = io->bytes_done;
3233 ret += io->bytes_done;
3236 if (req->flags & REQ_F_CUR_POS)
3237 req->file->f_pos = req->rw.kiocb.ki_pos;
3238 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3239 __io_complete_rw(req, ret, issue_flags);
3241 io_rw_done(&req->rw.kiocb, ret);
3243 if (req->flags & REQ_F_REISSUE) {
3244 req->flags &= ~REQ_F_REISSUE;
3245 if (io_resubmit_prep(req)) {
3246 io_req_task_queue_reissue(req);
3250 req->io_task_work.func = io_req_task_complete;
3251 io_req_task_work_add(req, false);
3256 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3257 struct io_mapped_ubuf *imu)
3259 size_t len = req->rw.len;
3260 u64 buf_end, buf_addr = req->rw.addr;
3263 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3265 /* not inside the mapped region */
3266 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3270 * May not be a start of buffer, set size appropriately
3271 * and advance us to the beginning.
3273 offset = buf_addr - imu->ubuf;
3274 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3278 * Don't use iov_iter_advance() here, as it's really slow for
3279 * using the latter parts of a big fixed buffer - it iterates
3280 * over each segment manually. We can cheat a bit here, because
3283 * 1) it's a BVEC iter, we set it up
3284 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3285 * first and last bvec
3287 * So just find our index, and adjust the iterator afterwards.
3288 * If the offset is within the first bvec (or the whole first
3289 * bvec, just use iov_iter_advance(). This makes it easier
3290 * since we can just skip the first segment, which may not
3291 * be PAGE_SIZE aligned.
3293 const struct bio_vec *bvec = imu->bvec;
3295 if (offset <= bvec->bv_len) {
3296 iov_iter_advance(iter, offset);
3298 unsigned long seg_skip;
3300 /* skip first vec */
3301 offset -= bvec->bv_len;
3302 seg_skip = 1 + (offset >> PAGE_SHIFT);
3304 iter->bvec = bvec + seg_skip;
3305 iter->nr_segs -= seg_skip;
3306 iter->count -= bvec->bv_len + offset;
3307 iter->iov_offset = offset & ~PAGE_MASK;
3314 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3316 struct io_mapped_ubuf *imu = req->imu;
3317 u16 index, buf_index = req->buf_index;
3320 struct io_ring_ctx *ctx = req->ctx;
3322 if (unlikely(buf_index >= ctx->nr_user_bufs))
3324 io_req_set_rsrc_node(req, ctx);
3325 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3326 imu = READ_ONCE(ctx->user_bufs[index]);
3329 return __io_import_fixed(req, rw, iter, imu);
3332 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3335 mutex_unlock(&ctx->uring_lock);
3338 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3341 * "Normal" inline submissions always hold the uring_lock, since we
3342 * grab it from the system call. Same is true for the SQPOLL offload.
3343 * The only exception is when we've detached the request and issue it
3344 * from an async worker thread, grab the lock for that case.
3347 mutex_lock(&ctx->uring_lock);
3350 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3351 int bgid, unsigned int issue_flags)
3353 struct io_buffer *kbuf = req->kbuf;
3354 struct io_buffer *head;
3355 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3357 if (req->flags & REQ_F_BUFFER_SELECTED)
3360 io_ring_submit_lock(req->ctx, needs_lock);
3362 lockdep_assert_held(&req->ctx->uring_lock);
3364 head = xa_load(&req->ctx->io_buffers, bgid);
3366 if (!list_empty(&head->list)) {
3367 kbuf = list_last_entry(&head->list, struct io_buffer,
3369 list_del(&kbuf->list);
3372 xa_erase(&req->ctx->io_buffers, bgid);
3374 if (*len > kbuf->len)
3376 req->flags |= REQ_F_BUFFER_SELECTED;
3379 kbuf = ERR_PTR(-ENOBUFS);
3382 io_ring_submit_unlock(req->ctx, needs_lock);
3386 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3387 unsigned int issue_flags)
3389 struct io_buffer *kbuf;
3392 bgid = req->buf_index;
3393 kbuf = io_buffer_select(req, len, bgid, issue_flags);
3396 return u64_to_user_ptr(kbuf->addr);
3399 #ifdef CONFIG_COMPAT
3400 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3401 unsigned int issue_flags)
3403 struct compat_iovec __user *uiov;
3404 compat_ssize_t clen;
3408 uiov = u64_to_user_ptr(req->rw.addr);
3409 if (!access_ok(uiov, sizeof(*uiov)))
3411 if (__get_user(clen, &uiov->iov_len))
3417 buf = io_rw_buffer_select(req, &len, issue_flags);
3419 return PTR_ERR(buf);
3420 iov[0].iov_base = buf;
3421 iov[0].iov_len = (compat_size_t) len;
3426 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3427 unsigned int issue_flags)
3429 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3433 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3436 len = iov[0].iov_len;
3439 buf = io_rw_buffer_select(req, &len, issue_flags);
3441 return PTR_ERR(buf);
3442 iov[0].iov_base = buf;
3443 iov[0].iov_len = len;
3447 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3448 unsigned int issue_flags)
3450 if (req->flags & REQ_F_BUFFER_SELECTED) {
3451 struct io_buffer *kbuf = req->kbuf;
3453 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3454 iov[0].iov_len = kbuf->len;
3457 if (req->rw.len != 1)
3460 #ifdef CONFIG_COMPAT
3461 if (req->ctx->compat)
3462 return io_compat_import(req, iov, issue_flags);
3465 return __io_iov_buffer_select(req, iov, issue_flags);
3468 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3469 struct io_rw_state *s,
3470 unsigned int issue_flags)
3472 struct iov_iter *iter = &s->iter;
3473 u8 opcode = req->opcode;
3474 struct iovec *iovec;
3479 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3480 ret = io_import_fixed(req, rw, iter);
3482 return ERR_PTR(ret);
3486 /* buffer index only valid with fixed read/write, or buffer select */
3487 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
3488 return ERR_PTR(-EINVAL);
3490 buf = u64_to_user_ptr(req->rw.addr);
3491 sqe_len = req->rw.len;
3493 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3494 if (req->flags & REQ_F_BUFFER_SELECT) {
3495 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
3497 return ERR_CAST(buf);
3498 req->rw.len = sqe_len;
3501 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3503 return ERR_PTR(ret);
3507 iovec = s->fast_iov;
3508 if (req->flags & REQ_F_BUFFER_SELECT) {
3509 ret = io_iov_buffer_select(req, iovec, issue_flags);
3511 return ERR_PTR(ret);
3512 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3516 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3518 if (unlikely(ret < 0))
3519 return ERR_PTR(ret);
3523 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3524 struct iovec **iovec, struct io_rw_state *s,
3525 unsigned int issue_flags)
3527 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3528 if (unlikely(IS_ERR(*iovec)))
3529 return PTR_ERR(*iovec);
3531 iov_iter_save_state(&s->iter, &s->iter_state);
3535 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3537 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3541 * For files that don't have ->read_iter() and ->write_iter(), handle them
3542 * by looping over ->read() or ->write() manually.
3544 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3546 struct kiocb *kiocb = &req->rw.kiocb;
3547 struct file *file = req->file;
3552 * Don't support polled IO through this interface, and we can't
3553 * support non-blocking either. For the latter, this just causes
3554 * the kiocb to be handled from an async context.
3556 if (kiocb->ki_flags & IOCB_HIPRI)
3558 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3559 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3562 ppos = io_kiocb_ppos(kiocb);
3564 while (iov_iter_count(iter)) {
3568 if (!iov_iter_is_bvec(iter)) {
3569 iovec = iov_iter_iovec(iter);
3571 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3572 iovec.iov_len = req->rw.len;
3576 nr = file->f_op->read(file, iovec.iov_base,
3577 iovec.iov_len, ppos);
3579 nr = file->f_op->write(file, iovec.iov_base,
3580 iovec.iov_len, ppos);
3588 if (!iov_iter_is_bvec(iter)) {
3589 iov_iter_advance(iter, nr);
3595 if (nr != iovec.iov_len)
3602 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3603 const struct iovec *fast_iov, struct iov_iter *iter)
3605 struct io_async_rw *rw = req->async_data;
3607 memcpy(&rw->s.iter, iter, sizeof(*iter));
3608 rw->free_iovec = iovec;
3610 /* can only be fixed buffers, no need to do anything */
3611 if (iov_iter_is_bvec(iter))
3614 unsigned iov_off = 0;
3616 rw->s.iter.iov = rw->s.fast_iov;
3617 if (iter->iov != fast_iov) {
3618 iov_off = iter->iov - fast_iov;
3619 rw->s.iter.iov += iov_off;
3621 if (rw->s.fast_iov != fast_iov)
3622 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3623 sizeof(struct iovec) * iter->nr_segs);
3625 req->flags |= REQ_F_NEED_CLEANUP;
3629 static inline bool io_alloc_async_data(struct io_kiocb *req)
3631 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3632 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3633 if (req->async_data) {
3634 req->flags |= REQ_F_ASYNC_DATA;
3640 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3641 struct io_rw_state *s, bool force)
3643 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3645 if (!req_has_async_data(req)) {
3646 struct io_async_rw *iorw;
3648 if (io_alloc_async_data(req)) {
3653 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3654 iorw = req->async_data;
3655 /* we've copied and mapped the iter, ensure state is saved */
3656 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3661 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3663 struct io_async_rw *iorw = req->async_data;
3667 /* submission path, ->uring_lock should already be taken */
3668 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3669 if (unlikely(ret < 0))
3672 iorw->bytes_done = 0;
3673 iorw->free_iovec = iov;
3675 req->flags |= REQ_F_NEED_CLEANUP;
3679 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3681 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3683 return io_prep_rw(req, sqe);
3687 * This is our waitqueue callback handler, registered through __folio_lock_async()
3688 * when we initially tried to do the IO with the iocb armed our waitqueue.
3689 * This gets called when the page is unlocked, and we generally expect that to
3690 * happen when the page IO is completed and the page is now uptodate. This will
3691 * queue a task_work based retry of the operation, attempting to copy the data
3692 * again. If the latter fails because the page was NOT uptodate, then we will
3693 * do a thread based blocking retry of the operation. That's the unexpected
3696 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3697 int sync, void *arg)
3699 struct wait_page_queue *wpq;
3700 struct io_kiocb *req = wait->private;
3701 struct wait_page_key *key = arg;
3703 wpq = container_of(wait, struct wait_page_queue, wait);
3705 if (!wake_page_match(wpq, key))
3708 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3709 list_del_init(&wait->entry);
3710 io_req_task_queue(req);
3715 * This controls whether a given IO request should be armed for async page
3716 * based retry. If we return false here, the request is handed to the async
3717 * worker threads for retry. If we're doing buffered reads on a regular file,
3718 * we prepare a private wait_page_queue entry and retry the operation. This
3719 * will either succeed because the page is now uptodate and unlocked, or it
3720 * will register a callback when the page is unlocked at IO completion. Through
3721 * that callback, io_uring uses task_work to setup a retry of the operation.
3722 * That retry will attempt the buffered read again. The retry will generally
3723 * succeed, or in rare cases where it fails, we then fall back to using the
3724 * async worker threads for a blocking retry.
3726 static bool io_rw_should_retry(struct io_kiocb *req)
3728 struct io_async_rw *rw = req->async_data;
3729 struct wait_page_queue *wait = &rw->wpq;
3730 struct kiocb *kiocb = &req->rw.kiocb;
3732 /* never retry for NOWAIT, we just complete with -EAGAIN */
3733 if (req->flags & REQ_F_NOWAIT)
3736 /* Only for buffered IO */
3737 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3741 * just use poll if we can, and don't attempt if the fs doesn't
3742 * support callback based unlocks
3744 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3747 wait->wait.func = io_async_buf_func;
3748 wait->wait.private = req;
3749 wait->wait.flags = 0;
3750 INIT_LIST_HEAD(&wait->wait.entry);
3751 kiocb->ki_flags |= IOCB_WAITQ;
3752 kiocb->ki_flags &= ~IOCB_NOWAIT;
3753 kiocb->ki_waitq = wait;
3757 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3759 if (likely(req->file->f_op->read_iter))
3760 return call_read_iter(req->file, &req->rw.kiocb, iter);
3761 else if (req->file->f_op->read)
3762 return loop_rw_iter(READ, req, iter);
3767 static bool need_read_all(struct io_kiocb *req)
3769 return req->flags & REQ_F_ISREG ||
3770 S_ISBLK(file_inode(req->file)->i_mode);
3773 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3775 struct io_rw_state __s, *s = &__s;
3776 struct iovec *iovec;
3777 struct kiocb *kiocb = &req->rw.kiocb;
3778 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3779 struct io_async_rw *rw;
3783 if (!req_has_async_data(req)) {
3784 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3785 if (unlikely(ret < 0))
3789 * Safe and required to re-import if we're using provided
3790 * buffers, as we dropped the selected one before retry.
3792 if (req->flags & REQ_F_BUFFER_SELECT) {
3793 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3794 if (unlikely(ret < 0))
3798 rw = req->async_data;
3801 * We come here from an earlier attempt, restore our state to
3802 * match in case it doesn't. It's cheap enough that we don't
3803 * need to make this conditional.
3805 iov_iter_restore(&s->iter, &s->iter_state);
3808 req->result = iov_iter_count(&s->iter);
3810 if (force_nonblock) {
3811 /* If the file doesn't support async, just async punt */
3812 if (unlikely(!io_file_supports_nowait(req))) {
3813 ret = io_setup_async_rw(req, iovec, s, true);
3814 return ret ?: -EAGAIN;
3816 kiocb->ki_flags |= IOCB_NOWAIT;
3818 /* Ensure we clear previously set non-block flag */
3819 kiocb->ki_flags &= ~IOCB_NOWAIT;
3822 ppos = io_kiocb_update_pos(req);
3824 ret = rw_verify_area(READ, req->file, ppos, req->result);
3825 if (unlikely(ret)) {
3830 ret = io_iter_do_read(req, &s->iter);
3832 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3833 req->flags &= ~REQ_F_REISSUE;
3834 /* if we can poll, just do that */
3835 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3837 /* IOPOLL retry should happen for io-wq threads */
3838 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3840 /* no retry on NONBLOCK nor RWF_NOWAIT */
3841 if (req->flags & REQ_F_NOWAIT)
3844 } else if (ret == -EIOCBQUEUED) {
3846 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
3847 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3848 /* read all, failed, already did sync or don't want to retry */
3853 * Don't depend on the iter state matching what was consumed, or being
3854 * untouched in case of error. Restore it and we'll advance it
3855 * manually if we need to.
3857 iov_iter_restore(&s->iter, &s->iter_state);
3859 ret2 = io_setup_async_rw(req, iovec, s, true);
3864 rw = req->async_data;
3867 * Now use our persistent iterator and state, if we aren't already.
3868 * We've restored and mapped the iter to match.
3873 * We end up here because of a partial read, either from
3874 * above or inside this loop. Advance the iter by the bytes
3875 * that were consumed.
3877 iov_iter_advance(&s->iter, ret);
3878 if (!iov_iter_count(&s->iter))
3880 rw->bytes_done += ret;
3881 iov_iter_save_state(&s->iter, &s->iter_state);
3883 /* if we can retry, do so with the callbacks armed */
3884 if (!io_rw_should_retry(req)) {
3885 kiocb->ki_flags &= ~IOCB_WAITQ;
3890 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3891 * we get -EIOCBQUEUED, then we'll get a notification when the
3892 * desired page gets unlocked. We can also get a partial read
3893 * here, and if we do, then just retry at the new offset.
3895 ret = io_iter_do_read(req, &s->iter);
3896 if (ret == -EIOCBQUEUED)
3898 /* we got some bytes, but not all. retry. */
3899 kiocb->ki_flags &= ~IOCB_WAITQ;
3900 iov_iter_restore(&s->iter, &s->iter_state);
3903 kiocb_done(req, ret, issue_flags);
3905 /* it's faster to check here then delegate to kfree */
3911 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3913 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3915 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
3916 return io_prep_rw(req, sqe);
3919 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3921 struct io_rw_state __s, *s = &__s;
3922 struct iovec *iovec;
3923 struct kiocb *kiocb = &req->rw.kiocb;
3924 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3928 if (!req_has_async_data(req)) {
3929 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3930 if (unlikely(ret < 0))
3933 struct io_async_rw *rw = req->async_data;
3936 iov_iter_restore(&s->iter, &s->iter_state);
3939 req->result = iov_iter_count(&s->iter);
3941 if (force_nonblock) {
3942 /* If the file doesn't support async, just async punt */
3943 if (unlikely(!io_file_supports_nowait(req)))
3946 /* file path doesn't support NOWAIT for non-direct_IO */
3947 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3948 (req->flags & REQ_F_ISREG))
3951 kiocb->ki_flags |= IOCB_NOWAIT;
3953 /* Ensure we clear previously set non-block flag */
3954 kiocb->ki_flags &= ~IOCB_NOWAIT;
3957 ppos = io_kiocb_update_pos(req);
3959 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
3964 * Open-code file_start_write here to grab freeze protection,
3965 * which will be released by another thread in
3966 * io_complete_rw(). Fool lockdep by telling it the lock got
3967 * released so that it doesn't complain about the held lock when
3968 * we return to userspace.
3970 if (req->flags & REQ_F_ISREG) {
3971 sb_start_write(file_inode(req->file)->i_sb);
3972 __sb_writers_release(file_inode(req->file)->i_sb,
3975 kiocb->ki_flags |= IOCB_WRITE;
3977 if (likely(req->file->f_op->write_iter))
3978 ret2 = call_write_iter(req->file, kiocb, &s->iter);
3979 else if (req->file->f_op->write)
3980 ret2 = loop_rw_iter(WRITE, req, &s->iter);
3984 if (req->flags & REQ_F_REISSUE) {
3985 req->flags &= ~REQ_F_REISSUE;
3990 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3991 * retry them without IOCB_NOWAIT.
3993 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3995 /* no retry on NONBLOCK nor RWF_NOWAIT */
3996 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3998 if (!force_nonblock || ret2 != -EAGAIN) {
3999 /* IOPOLL retry should happen for io-wq threads */
4000 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4003 kiocb_done(req, ret2, issue_flags);
4006 iov_iter_restore(&s->iter, &s->iter_state);
4007 ret = io_setup_async_rw(req, iovec, s, false);
4008 return ret ?: -EAGAIN;
4011 /* it's reportedly faster than delegating the null check to kfree() */
4017 static int io_renameat_prep(struct io_kiocb *req,
4018 const struct io_uring_sqe *sqe)
4020 struct io_rename *ren = &req->rename;
4021 const char __user *oldf, *newf;
4023 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4025 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4027 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4030 ren->old_dfd = READ_ONCE(sqe->fd);
4031 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4032 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4033 ren->new_dfd = READ_ONCE(sqe->len);
4034 ren->flags = READ_ONCE(sqe->rename_flags);
4036 ren->oldpath = getname(oldf);
4037 if (IS_ERR(ren->oldpath))
4038 return PTR_ERR(ren->oldpath);
4040 ren->newpath = getname(newf);
4041 if (IS_ERR(ren->newpath)) {
4042 putname(ren->oldpath);
4043 return PTR_ERR(ren->newpath);
4046 req->flags |= REQ_F_NEED_CLEANUP;
4050 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4052 struct io_rename *ren = &req->rename;
4055 if (issue_flags & IO_URING_F_NONBLOCK)
4058 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4059 ren->newpath, ren->flags);
4061 req->flags &= ~REQ_F_NEED_CLEANUP;
4064 io_req_complete(req, ret);
4068 static int io_unlinkat_prep(struct io_kiocb *req,
4069 const struct io_uring_sqe *sqe)
4071 struct io_unlink *un = &req->unlink;
4072 const char __user *fname;
4074 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4076 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4079 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4082 un->dfd = READ_ONCE(sqe->fd);
4084 un->flags = READ_ONCE(sqe->unlink_flags);
4085 if (un->flags & ~AT_REMOVEDIR)
4088 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4089 un->filename = getname(fname);
4090 if (IS_ERR(un->filename))
4091 return PTR_ERR(un->filename);
4093 req->flags |= REQ_F_NEED_CLEANUP;
4097 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4099 struct io_unlink *un = &req->unlink;
4102 if (issue_flags & IO_URING_F_NONBLOCK)
4105 if (un->flags & AT_REMOVEDIR)
4106 ret = do_rmdir(un->dfd, un->filename);
4108 ret = do_unlinkat(un->dfd, un->filename);
4110 req->flags &= ~REQ_F_NEED_CLEANUP;
4113 io_req_complete(req, ret);
4117 static int io_mkdirat_prep(struct io_kiocb *req,
4118 const struct io_uring_sqe *sqe)
4120 struct io_mkdir *mkd = &req->mkdir;
4121 const char __user *fname;
4123 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4125 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4128 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4131 mkd->dfd = READ_ONCE(sqe->fd);
4132 mkd->mode = READ_ONCE(sqe->len);
4134 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4135 mkd->filename = getname(fname);
4136 if (IS_ERR(mkd->filename))
4137 return PTR_ERR(mkd->filename);
4139 req->flags |= REQ_F_NEED_CLEANUP;
4143 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4145 struct io_mkdir *mkd = &req->mkdir;
4148 if (issue_flags & IO_URING_F_NONBLOCK)
4151 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4153 req->flags &= ~REQ_F_NEED_CLEANUP;
4156 io_req_complete(req, ret);
4160 static int io_symlinkat_prep(struct io_kiocb *req,
4161 const struct io_uring_sqe *sqe)
4163 struct io_symlink *sl = &req->symlink;
4164 const char __user *oldpath, *newpath;
4166 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4168 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4171 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4174 sl->new_dfd = READ_ONCE(sqe->fd);
4175 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4176 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4178 sl->oldpath = getname(oldpath);
4179 if (IS_ERR(sl->oldpath))
4180 return PTR_ERR(sl->oldpath);
4182 sl->newpath = getname(newpath);
4183 if (IS_ERR(sl->newpath)) {
4184 putname(sl->oldpath);
4185 return PTR_ERR(sl->newpath);
4188 req->flags |= REQ_F_NEED_CLEANUP;
4192 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4194 struct io_symlink *sl = &req->symlink;
4197 if (issue_flags & IO_URING_F_NONBLOCK)
4200 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4202 req->flags &= ~REQ_F_NEED_CLEANUP;
4205 io_req_complete(req, ret);
4209 static int io_linkat_prep(struct io_kiocb *req,
4210 const struct io_uring_sqe *sqe)
4212 struct io_hardlink *lnk = &req->hardlink;
4213 const char __user *oldf, *newf;
4215 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4217 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4219 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4222 lnk->old_dfd = READ_ONCE(sqe->fd);
4223 lnk->new_dfd = READ_ONCE(sqe->len);
4224 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4225 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4226 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4228 lnk->oldpath = getname(oldf);
4229 if (IS_ERR(lnk->oldpath))
4230 return PTR_ERR(lnk->oldpath);
4232 lnk->newpath = getname(newf);
4233 if (IS_ERR(lnk->newpath)) {
4234 putname(lnk->oldpath);
4235 return PTR_ERR(lnk->newpath);
4238 req->flags |= REQ_F_NEED_CLEANUP;
4242 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4244 struct io_hardlink *lnk = &req->hardlink;
4247 if (issue_flags & IO_URING_F_NONBLOCK)
4250 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4251 lnk->newpath, lnk->flags);
4253 req->flags &= ~REQ_F_NEED_CLEANUP;
4256 io_req_complete(req, ret);
4260 static int io_shutdown_prep(struct io_kiocb *req,
4261 const struct io_uring_sqe *sqe)
4263 #if defined(CONFIG_NET)
4264 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4266 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4267 sqe->buf_index || sqe->splice_fd_in))
4270 req->shutdown.how = READ_ONCE(sqe->len);
4277 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4279 #if defined(CONFIG_NET)
4280 struct socket *sock;
4283 if (issue_flags & IO_URING_F_NONBLOCK)
4286 sock = sock_from_file(req->file);
4287 if (unlikely(!sock))
4290 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4293 io_req_complete(req, ret);
4300 static int __io_splice_prep(struct io_kiocb *req,
4301 const struct io_uring_sqe *sqe)
4303 struct io_splice *sp = &req->splice;
4304 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4306 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4310 sp->len = READ_ONCE(sqe->len);
4311 sp->flags = READ_ONCE(sqe->splice_flags);
4313 if (unlikely(sp->flags & ~valid_flags))
4316 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
4317 (sp->flags & SPLICE_F_FD_IN_FIXED));
4320 req->flags |= REQ_F_NEED_CLEANUP;
4324 static int io_tee_prep(struct io_kiocb *req,
4325 const struct io_uring_sqe *sqe)
4327 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4329 return __io_splice_prep(req, sqe);
4332 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4334 struct io_splice *sp = &req->splice;
4335 struct file *in = sp->file_in;
4336 struct file *out = sp->file_out;
4337 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4340 if (issue_flags & IO_URING_F_NONBLOCK)
4343 ret = do_tee(in, out, sp->len, flags);
4345 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4347 req->flags &= ~REQ_F_NEED_CLEANUP;
4351 io_req_complete(req, ret);
4355 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4357 struct io_splice *sp = &req->splice;
4359 sp->off_in = READ_ONCE(sqe->splice_off_in);
4360 sp->off_out = READ_ONCE(sqe->off);
4361 return __io_splice_prep(req, sqe);
4364 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4366 struct io_splice *sp = &req->splice;
4367 struct file *in = sp->file_in;
4368 struct file *out = sp->file_out;
4369 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4370 loff_t *poff_in, *poff_out;
4373 if (issue_flags & IO_URING_F_NONBLOCK)
4376 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4377 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4380 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4382 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4384 req->flags &= ~REQ_F_NEED_CLEANUP;
4388 io_req_complete(req, ret);
4393 * IORING_OP_NOP just posts a completion event, nothing else.
4395 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4397 struct io_ring_ctx *ctx = req->ctx;
4399 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4402 __io_req_complete(req, issue_flags, 0, 0);
4406 static int io_msg_ring_prep(struct io_kiocb *req,
4407 const struct io_uring_sqe *sqe)
4409 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4410 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4413 if (req->file->f_op != &io_uring_fops)
4416 req->msg.user_data = READ_ONCE(sqe->off);
4417 req->msg.len = READ_ONCE(sqe->len);
4421 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4423 struct io_ring_ctx *target_ctx;
4424 struct io_msg *msg = &req->msg;
4425 int ret = -EOVERFLOW;
4428 target_ctx = req->file->private_data;
4430 spin_lock(&target_ctx->completion_lock);
4431 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len,
4433 io_commit_cqring(target_ctx);
4434 spin_unlock(&target_ctx->completion_lock);
4437 io_cqring_ev_posted(target_ctx);
4441 __io_req_complete(req, issue_flags, ret, 0);
4445 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4447 struct io_ring_ctx *ctx = req->ctx;
4452 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4454 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4458 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4459 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4462 req->sync.off = READ_ONCE(sqe->off);
4463 req->sync.len = READ_ONCE(sqe->len);
4467 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4469 loff_t end = req->sync.off + req->sync.len;
4472 /* fsync always requires a blocking context */
4473 if (issue_flags & IO_URING_F_NONBLOCK)
4476 ret = vfs_fsync_range(req->file, req->sync.off,
4477 end > 0 ? end : LLONG_MAX,
4478 req->sync.flags & IORING_FSYNC_DATASYNC);
4481 io_req_complete(req, ret);
4485 static int io_fallocate_prep(struct io_kiocb *req,
4486 const struct io_uring_sqe *sqe)
4488 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4491 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4494 req->sync.off = READ_ONCE(sqe->off);
4495 req->sync.len = READ_ONCE(sqe->addr);
4496 req->sync.mode = READ_ONCE(sqe->len);
4500 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4504 /* fallocate always requiring blocking context */
4505 if (issue_flags & IO_URING_F_NONBLOCK)
4507 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4511 io_req_complete(req, ret);
4515 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4517 const char __user *fname;
4520 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4522 if (unlikely(sqe->ioprio || sqe->buf_index))
4524 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4527 /* open.how should be already initialised */
4528 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4529 req->open.how.flags |= O_LARGEFILE;
4531 req->open.dfd = READ_ONCE(sqe->fd);
4532 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4533 req->open.filename = getname(fname);
4534 if (IS_ERR(req->open.filename)) {
4535 ret = PTR_ERR(req->open.filename);
4536 req->open.filename = NULL;
4540 req->open.file_slot = READ_ONCE(sqe->file_index);
4541 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4544 req->open.nofile = rlimit(RLIMIT_NOFILE);
4545 req->flags |= REQ_F_NEED_CLEANUP;
4549 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4551 u64 mode = READ_ONCE(sqe->len);
4552 u64 flags = READ_ONCE(sqe->open_flags);
4554 req->open.how = build_open_how(flags, mode);
4555 return __io_openat_prep(req, sqe);
4558 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4560 struct open_how __user *how;
4564 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4565 len = READ_ONCE(sqe->len);
4566 if (len < OPEN_HOW_SIZE_VER0)
4569 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4574 return __io_openat_prep(req, sqe);
4577 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4579 struct open_flags op;
4581 bool resolve_nonblock, nonblock_set;
4582 bool fixed = !!req->open.file_slot;
4585 ret = build_open_flags(&req->open.how, &op);
4588 nonblock_set = op.open_flag & O_NONBLOCK;
4589 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4590 if (issue_flags & IO_URING_F_NONBLOCK) {
4592 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4593 * it'll always -EAGAIN
4595 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4597 op.lookup_flags |= LOOKUP_CACHED;
4598 op.open_flag |= O_NONBLOCK;
4602 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4607 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4610 * We could hang on to this 'fd' on retrying, but seems like
4611 * marginal gain for something that is now known to be a slower
4612 * path. So just put it, and we'll get a new one when we retry.
4617 ret = PTR_ERR(file);
4618 /* only retry if RESOLVE_CACHED wasn't already set by application */
4619 if (ret == -EAGAIN &&
4620 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4625 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4626 file->f_flags &= ~O_NONBLOCK;
4627 fsnotify_open(file);
4630 fd_install(ret, file);
4632 ret = io_install_fixed_file(req, file, issue_flags,
4633 req->open.file_slot - 1);
4635 putname(req->open.filename);
4636 req->flags &= ~REQ_F_NEED_CLEANUP;
4639 __io_req_complete(req, issue_flags, ret, 0);
4643 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4645 return io_openat2(req, issue_flags);
4648 static int io_remove_buffers_prep(struct io_kiocb *req,
4649 const struct io_uring_sqe *sqe)
4651 struct io_provide_buf *p = &req->pbuf;
4654 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4658 tmp = READ_ONCE(sqe->fd);
4659 if (!tmp || tmp > USHRT_MAX)
4662 memset(p, 0, sizeof(*p));
4664 p->bgid = READ_ONCE(sqe->buf_group);
4668 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4669 int bgid, unsigned nbufs)
4673 /* shouldn't happen */
4677 /* the head kbuf is the list itself */
4678 while (!list_empty(&buf->list)) {
4679 struct io_buffer *nxt;
4681 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4682 list_del(&nxt->list);
4688 xa_erase(&ctx->io_buffers, bgid);
4693 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4695 struct io_provide_buf *p = &req->pbuf;
4696 struct io_ring_ctx *ctx = req->ctx;
4697 struct io_buffer *head;
4699 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4701 io_ring_submit_lock(ctx, needs_lock);
4703 lockdep_assert_held(&ctx->uring_lock);
4706 head = xa_load(&ctx->io_buffers, p->bgid);
4708 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4712 /* complete before unlock, IOPOLL may need the lock */
4713 __io_req_complete(req, issue_flags, ret, 0);
4714 io_ring_submit_unlock(ctx, needs_lock);
4718 static int io_provide_buffers_prep(struct io_kiocb *req,
4719 const struct io_uring_sqe *sqe)
4721 unsigned long size, tmp_check;
4722 struct io_provide_buf *p = &req->pbuf;
4725 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4728 tmp = READ_ONCE(sqe->fd);
4729 if (!tmp || tmp > USHRT_MAX)
4732 p->addr = READ_ONCE(sqe->addr);
4733 p->len = READ_ONCE(sqe->len);
4735 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4738 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4741 size = (unsigned long)p->len * p->nbufs;
4742 if (!access_ok(u64_to_user_ptr(p->addr), size))
4745 p->bgid = READ_ONCE(sqe->buf_group);
4746 tmp = READ_ONCE(sqe->off);
4747 if (tmp > USHRT_MAX)
4753 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4755 struct io_buffer *buf;
4760 * Completions that don't happen inline (eg not under uring_lock) will
4761 * add to ->io_buffers_comp. If we don't have any free buffers, check
4762 * the completion list and splice those entries first.
4764 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4765 spin_lock(&ctx->completion_lock);
4766 if (!list_empty(&ctx->io_buffers_comp)) {
4767 list_splice_init(&ctx->io_buffers_comp,
4768 &ctx->io_buffers_cache);
4769 spin_unlock(&ctx->completion_lock);
4772 spin_unlock(&ctx->completion_lock);
4776 * No free buffers and no completion entries either. Allocate a new
4777 * page worth of buffer entries and add those to our freelist.
4779 page = alloc_page(GFP_KERNEL_ACCOUNT);
4783 list_add(&page->lru, &ctx->io_buffers_pages);
4785 buf = page_address(page);
4786 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4787 while (bufs_in_page) {
4788 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4796 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
4797 struct io_buffer **head)
4799 struct io_buffer *buf;
4800 u64 addr = pbuf->addr;
4801 int i, bid = pbuf->bid;
4803 for (i = 0; i < pbuf->nbufs; i++) {
4804 if (list_empty(&ctx->io_buffers_cache) &&
4805 io_refill_buffer_cache(ctx))
4807 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4809 list_del(&buf->list);
4811 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4813 buf->bgid = pbuf->bgid;
4817 INIT_LIST_HEAD(&buf->list);
4820 list_add_tail(&buf->list, &(*head)->list);
4825 return i ? i : -ENOMEM;
4828 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4830 struct io_provide_buf *p = &req->pbuf;
4831 struct io_ring_ctx *ctx = req->ctx;
4832 struct io_buffer *head, *list;
4834 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
4836 io_ring_submit_lock(ctx, needs_lock);
4838 lockdep_assert_held(&ctx->uring_lock);
4840 list = head = xa_load(&ctx->io_buffers, p->bgid);
4842 ret = io_add_buffers(ctx, p, &head);
4843 if (ret >= 0 && !list) {
4844 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4846 __io_remove_buffers(ctx, head, p->bgid, -1U);
4850 /* complete before unlock, IOPOLL may need the lock */
4851 __io_req_complete(req, issue_flags, ret, 0);
4852 io_ring_submit_unlock(ctx, needs_lock);
4856 static int io_epoll_ctl_prep(struct io_kiocb *req,
4857 const struct io_uring_sqe *sqe)
4859 #if defined(CONFIG_EPOLL)
4860 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4862 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4865 req->epoll.epfd = READ_ONCE(sqe->fd);
4866 req->epoll.op = READ_ONCE(sqe->len);
4867 req->epoll.fd = READ_ONCE(sqe->off);
4869 if (ep_op_has_event(req->epoll.op)) {
4870 struct epoll_event __user *ev;
4872 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4873 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4883 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4885 #if defined(CONFIG_EPOLL)
4886 struct io_epoll *ie = &req->epoll;
4888 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4890 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4891 if (force_nonblock && ret == -EAGAIN)
4896 __io_req_complete(req, issue_flags, ret, 0);
4903 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4905 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4906 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4908 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4911 req->madvise.addr = READ_ONCE(sqe->addr);
4912 req->madvise.len = READ_ONCE(sqe->len);
4913 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4920 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4922 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4923 struct io_madvise *ma = &req->madvise;
4926 if (issue_flags & IO_URING_F_NONBLOCK)
4929 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4932 io_req_complete(req, ret);
4939 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4941 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4943 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4946 req->fadvise.offset = READ_ONCE(sqe->off);
4947 req->fadvise.len = READ_ONCE(sqe->len);
4948 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4952 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4954 struct io_fadvise *fa = &req->fadvise;
4957 if (issue_flags & IO_URING_F_NONBLOCK) {
4958 switch (fa->advice) {
4959 case POSIX_FADV_NORMAL:
4960 case POSIX_FADV_RANDOM:
4961 case POSIX_FADV_SEQUENTIAL:
4968 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4971 __io_req_complete(req, issue_flags, ret, 0);
4975 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4977 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4979 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4981 if (req->flags & REQ_F_FIXED_FILE)
4984 req->statx.dfd = READ_ONCE(sqe->fd);
4985 req->statx.mask = READ_ONCE(sqe->len);
4986 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4987 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4988 req->statx.flags = READ_ONCE(sqe->statx_flags);
4993 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4995 struct io_statx *ctx = &req->statx;
4998 if (issue_flags & IO_URING_F_NONBLOCK)
5001 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5006 io_req_complete(req, ret);
5010 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5012 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5014 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
5015 sqe->rw_flags || sqe->buf_index)
5017 if (req->flags & REQ_F_FIXED_FILE)
5020 req->close.fd = READ_ONCE(sqe->fd);
5021 req->close.file_slot = READ_ONCE(sqe->file_index);
5022 if (req->close.file_slot && req->close.fd)
5028 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5030 struct files_struct *files = current->files;
5031 struct io_close *close = &req->close;
5032 struct fdtable *fdt;
5033 struct file *file = NULL;
5036 if (req->close.file_slot) {
5037 ret = io_close_fixed(req, issue_flags);
5041 spin_lock(&files->file_lock);
5042 fdt = files_fdtable(files);
5043 if (close->fd >= fdt->max_fds) {
5044 spin_unlock(&files->file_lock);
5047 file = fdt->fd[close->fd];
5048 if (!file || file->f_op == &io_uring_fops) {
5049 spin_unlock(&files->file_lock);
5054 /* if the file has a flush method, be safe and punt to async */
5055 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5056 spin_unlock(&files->file_lock);
5060 ret = __close_fd_get_file(close->fd, &file);
5061 spin_unlock(&files->file_lock);
5068 /* No ->flush() or already async, safely close from here */
5069 ret = filp_close(file, current->files);
5075 __io_req_complete(req, issue_flags, ret, 0);
5079 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5081 struct io_ring_ctx *ctx = req->ctx;
5083 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5085 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5089 req->sync.off = READ_ONCE(sqe->off);
5090 req->sync.len = READ_ONCE(sqe->len);
5091 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5095 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5099 /* sync_file_range always requires a blocking context */
5100 if (issue_flags & IO_URING_F_NONBLOCK)
5103 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5107 io_req_complete(req, ret);
5111 #if defined(CONFIG_NET)
5112 static int io_setup_async_msg(struct io_kiocb *req,
5113 struct io_async_msghdr *kmsg)
5115 struct io_async_msghdr *async_msg = req->async_data;
5119 if (io_alloc_async_data(req)) {
5120 kfree(kmsg->free_iov);
5123 async_msg = req->async_data;
5124 req->flags |= REQ_F_NEED_CLEANUP;
5125 memcpy(async_msg, kmsg, sizeof(*kmsg));
5126 async_msg->msg.msg_name = &async_msg->addr;
5127 /* if were using fast_iov, set it to the new one */
5128 if (!async_msg->free_iov)
5129 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5134 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5135 struct io_async_msghdr *iomsg)
5137 iomsg->msg.msg_name = &iomsg->addr;
5138 iomsg->free_iov = iomsg->fast_iov;
5139 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5140 req->sr_msg.msg_flags, &iomsg->free_iov);
5143 static int io_sendmsg_prep_async(struct io_kiocb *req)
5147 ret = io_sendmsg_copy_hdr(req, req->async_data);
5149 req->flags |= REQ_F_NEED_CLEANUP;
5153 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5155 struct io_sr_msg *sr = &req->sr_msg;
5157 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5160 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5161 sr->len = READ_ONCE(sqe->len);
5162 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5163 if (sr->msg_flags & MSG_DONTWAIT)
5164 req->flags |= REQ_F_NOWAIT;
5166 #ifdef CONFIG_COMPAT
5167 if (req->ctx->compat)
5168 sr->msg_flags |= MSG_CMSG_COMPAT;
5173 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5175 struct io_async_msghdr iomsg, *kmsg;
5176 struct socket *sock;
5181 sock = sock_from_file(req->file);
5182 if (unlikely(!sock))
5185 if (req_has_async_data(req)) {
5186 kmsg = req->async_data;
5188 ret = io_sendmsg_copy_hdr(req, &iomsg);
5194 flags = req->sr_msg.msg_flags;
5195 if (issue_flags & IO_URING_F_NONBLOCK)
5196 flags |= MSG_DONTWAIT;
5197 if (flags & MSG_WAITALL)
5198 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5200 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5202 if (ret < min_ret) {
5203 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5204 return io_setup_async_msg(req, kmsg);
5205 if (ret == -ERESTARTSYS)
5209 /* fast path, check for non-NULL to avoid function call */
5211 kfree(kmsg->free_iov);
5212 req->flags &= ~REQ_F_NEED_CLEANUP;
5213 __io_req_complete(req, issue_flags, ret, 0);
5217 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5219 struct io_sr_msg *sr = &req->sr_msg;
5222 struct socket *sock;
5227 sock = sock_from_file(req->file);
5228 if (unlikely(!sock))
5231 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5235 msg.msg_name = NULL;
5236 msg.msg_control = NULL;
5237 msg.msg_controllen = 0;
5238 msg.msg_namelen = 0;
5240 flags = req->sr_msg.msg_flags;
5241 if (issue_flags & IO_URING_F_NONBLOCK)
5242 flags |= MSG_DONTWAIT;
5243 if (flags & MSG_WAITALL)
5244 min_ret = iov_iter_count(&msg.msg_iter);
5246 msg.msg_flags = flags;
5247 ret = sock_sendmsg(sock, &msg);
5248 if (ret < min_ret) {
5249 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5251 if (ret == -ERESTARTSYS)
5255 __io_req_complete(req, issue_flags, ret, 0);
5259 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5260 struct io_async_msghdr *iomsg)
5262 struct io_sr_msg *sr = &req->sr_msg;
5263 struct iovec __user *uiov;
5267 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5268 &iomsg->uaddr, &uiov, &iov_len);
5272 if (req->flags & REQ_F_BUFFER_SELECT) {
5275 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
5277 sr->len = iomsg->fast_iov[0].iov_len;
5278 iomsg->free_iov = NULL;
5280 iomsg->free_iov = iomsg->fast_iov;
5281 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
5282 &iomsg->free_iov, &iomsg->msg.msg_iter,
5291 #ifdef CONFIG_COMPAT
5292 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
5293 struct io_async_msghdr *iomsg)
5295 struct io_sr_msg *sr = &req->sr_msg;
5296 struct compat_iovec __user *uiov;
5301 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5306 uiov = compat_ptr(ptr);
5307 if (req->flags & REQ_F_BUFFER_SELECT) {
5308 compat_ssize_t clen;
5312 if (!access_ok(uiov, sizeof(*uiov)))
5314 if (__get_user(clen, &uiov->iov_len))
5319 iomsg->free_iov = NULL;
5321 iomsg->free_iov = iomsg->fast_iov;
5322 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
5323 UIO_FASTIOV, &iomsg->free_iov,
5324 &iomsg->msg.msg_iter, true);
5333 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5334 struct io_async_msghdr *iomsg)
5336 iomsg->msg.msg_name = &iomsg->addr;
5338 #ifdef CONFIG_COMPAT
5339 if (req->ctx->compat)
5340 return __io_compat_recvmsg_copy_hdr(req, iomsg);
5343 return __io_recvmsg_copy_hdr(req, iomsg);
5346 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
5347 unsigned int issue_flags)
5349 struct io_sr_msg *sr = &req->sr_msg;
5351 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
5354 static int io_recvmsg_prep_async(struct io_kiocb *req)
5358 ret = io_recvmsg_copy_hdr(req, req->async_data);
5360 req->flags |= REQ_F_NEED_CLEANUP;
5364 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5366 struct io_sr_msg *sr = &req->sr_msg;
5368 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5371 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5372 sr->len = READ_ONCE(sqe->len);
5373 sr->bgid = READ_ONCE(sqe->buf_group);
5374 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5375 if (sr->msg_flags & MSG_DONTWAIT)
5376 req->flags |= REQ_F_NOWAIT;
5378 #ifdef CONFIG_COMPAT
5379 if (req->ctx->compat)
5380 sr->msg_flags |= MSG_CMSG_COMPAT;
5385 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5387 struct io_async_msghdr iomsg, *kmsg;
5388 struct socket *sock;
5389 struct io_buffer *kbuf;
5391 int ret, min_ret = 0;
5392 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5394 sock = sock_from_file(req->file);
5395 if (unlikely(!sock))
5398 if (req_has_async_data(req)) {
5399 kmsg = req->async_data;
5401 ret = io_recvmsg_copy_hdr(req, &iomsg);
5407 if (req->flags & REQ_F_BUFFER_SELECT) {
5408 kbuf = io_recv_buffer_select(req, issue_flags);
5410 return PTR_ERR(kbuf);
5411 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5412 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5413 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5414 1, req->sr_msg.len);
5417 flags = req->sr_msg.msg_flags;
5419 flags |= MSG_DONTWAIT;
5420 if (flags & MSG_WAITALL)
5421 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5423 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5424 kmsg->uaddr, flags);
5425 if (ret < min_ret) {
5426 if (ret == -EAGAIN && force_nonblock)
5427 return io_setup_async_msg(req, kmsg);
5428 if (ret == -ERESTARTSYS)
5431 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5435 /* fast path, check for non-NULL to avoid function call */
5437 kfree(kmsg->free_iov);
5438 req->flags &= ~REQ_F_NEED_CLEANUP;
5439 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5443 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5445 struct io_buffer *kbuf;
5446 struct io_sr_msg *sr = &req->sr_msg;
5448 void __user *buf = sr->buf;
5449 struct socket *sock;
5452 int ret, min_ret = 0;
5453 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5455 sock = sock_from_file(req->file);
5456 if (unlikely(!sock))
5459 if (req->flags & REQ_F_BUFFER_SELECT) {
5460 kbuf = io_recv_buffer_select(req, issue_flags);
5462 return PTR_ERR(kbuf);
5463 buf = u64_to_user_ptr(kbuf->addr);
5466 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5470 msg.msg_name = NULL;
5471 msg.msg_control = NULL;
5472 msg.msg_controllen = 0;
5473 msg.msg_namelen = 0;
5474 msg.msg_iocb = NULL;
5477 flags = req->sr_msg.msg_flags;
5479 flags |= MSG_DONTWAIT;
5480 if (flags & MSG_WAITALL)
5481 min_ret = iov_iter_count(&msg.msg_iter);
5483 ret = sock_recvmsg(sock, &msg, flags);
5484 if (ret < min_ret) {
5485 if (ret == -EAGAIN && force_nonblock)
5487 if (ret == -ERESTARTSYS)
5490 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5495 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
5499 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5501 struct io_accept *accept = &req->accept;
5503 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5505 if (sqe->ioprio || sqe->len || sqe->buf_index)
5508 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5509 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5510 accept->flags = READ_ONCE(sqe->accept_flags);
5511 accept->nofile = rlimit(RLIMIT_NOFILE);
5513 accept->file_slot = READ_ONCE(sqe->file_index);
5514 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
5515 (accept->flags & SOCK_CLOEXEC)))
5517 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5519 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5520 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5524 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5526 struct io_accept *accept = &req->accept;
5527 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5528 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5529 bool fixed = !!accept->file_slot;
5533 if (req->file->f_flags & O_NONBLOCK)
5534 req->flags |= REQ_F_NOWAIT;
5537 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5538 if (unlikely(fd < 0))
5541 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5546 ret = PTR_ERR(file);
5547 if (ret == -EAGAIN && force_nonblock)
5549 if (ret == -ERESTARTSYS)
5552 } else if (!fixed) {
5553 fd_install(fd, file);
5556 ret = io_install_fixed_file(req, file, issue_flags,
5557 accept->file_slot - 1);
5559 __io_req_complete(req, issue_flags, ret, 0);
5563 static int io_connect_prep_async(struct io_kiocb *req)
5565 struct io_async_connect *io = req->async_data;
5566 struct io_connect *conn = &req->connect;
5568 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5571 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5573 struct io_connect *conn = &req->connect;
5575 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5577 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5581 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5582 conn->addr_len = READ_ONCE(sqe->addr2);
5586 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5588 struct io_async_connect __io, *io;
5589 unsigned file_flags;
5591 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5593 if (req_has_async_data(req)) {
5594 io = req->async_data;
5596 ret = move_addr_to_kernel(req->connect.addr,
5597 req->connect.addr_len,
5604 file_flags = force_nonblock ? O_NONBLOCK : 0;
5606 ret = __sys_connect_file(req->file, &io->address,
5607 req->connect.addr_len, file_flags);
5608 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5609 if (req_has_async_data(req))
5611 if (io_alloc_async_data(req)) {
5615 memcpy(req->async_data, &__io, sizeof(__io));
5618 if (ret == -ERESTARTSYS)
5623 __io_req_complete(req, issue_flags, ret, 0);
5626 #else /* !CONFIG_NET */
5627 #define IO_NETOP_FN(op) \
5628 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5630 return -EOPNOTSUPP; \
5633 #define IO_NETOP_PREP(op) \
5635 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5637 return -EOPNOTSUPP; \
5640 #define IO_NETOP_PREP_ASYNC(op) \
5642 static int io_##op##_prep_async(struct io_kiocb *req) \
5644 return -EOPNOTSUPP; \
5647 IO_NETOP_PREP_ASYNC(sendmsg);
5648 IO_NETOP_PREP_ASYNC(recvmsg);
5649 IO_NETOP_PREP_ASYNC(connect);
5650 IO_NETOP_PREP(accept);
5653 #endif /* CONFIG_NET */
5655 #ifdef CONFIG_NET_RX_BUSY_POLL
5657 #define NAPI_TIMEOUT (60 * SEC_CONVERSION)
5660 struct list_head list;
5661 unsigned int napi_id;
5662 unsigned long timeout;
5666 * Add busy poll NAPI ID from sk.
5668 static void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5670 unsigned int napi_id;
5671 struct socket *sock;
5673 struct napi_entry *ne;
5675 if (!net_busy_loop_on())
5678 sock = sock_from_file(file);
5686 napi_id = READ_ONCE(sk->sk_napi_id);
5688 /* Non-NAPI IDs can be rejected */
5689 if (napi_id < MIN_NAPI_ID)
5692 spin_lock(&ctx->napi_lock);
5693 list_for_each_entry(ne, &ctx->napi_list, list) {
5694 if (ne->napi_id == napi_id) {
5695 ne->timeout = jiffies + NAPI_TIMEOUT;
5700 ne = kmalloc(sizeof(*ne), GFP_NOWAIT);
5704 ne->napi_id = napi_id;
5705 ne->timeout = jiffies + NAPI_TIMEOUT;
5706 list_add_tail(&ne->list, &ctx->napi_list);
5708 spin_unlock(&ctx->napi_lock);
5711 static inline void io_check_napi_entry_timeout(struct napi_entry *ne)
5713 if (time_after(jiffies, ne->timeout)) {
5714 list_del(&ne->list);
5720 * Busy poll if globally on and supporting sockets found
5722 static bool io_napi_busy_loop(struct list_head *napi_list)
5724 struct napi_entry *ne, *n;
5726 list_for_each_entry_safe(ne, n, napi_list, list) {
5727 napi_busy_loop(ne->napi_id, NULL, NULL, true,
5729 io_check_napi_entry_timeout(ne);
5731 return !list_empty(napi_list);
5734 static void io_free_napi_list(struct io_ring_ctx *ctx)
5736 spin_lock(&ctx->napi_lock);
5737 while (!list_empty(&ctx->napi_list)) {
5738 struct napi_entry *ne =
5739 list_first_entry(&ctx->napi_list, struct napi_entry,
5742 list_del(&ne->list);
5745 spin_unlock(&ctx->napi_lock);
5748 static inline void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5752 static inline void io_free_napi_list(struct io_ring_ctx *ctx)
5755 #endif /* CONFIG_NET_RX_BUSY_POLL */
5757 struct io_poll_table {
5758 struct poll_table_struct pt;
5759 struct io_kiocb *req;
5764 #define IO_POLL_CANCEL_FLAG BIT(31)
5765 #define IO_POLL_REF_MASK ((1u << 20)-1)
5768 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5769 * bump it and acquire ownership. It's disallowed to modify requests while not
5770 * owning it, that prevents from races for enqueueing task_work's and b/w
5771 * arming poll and wakeups.
5773 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5775 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5778 static void io_poll_mark_cancelled(struct io_kiocb *req)
5780 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5783 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5785 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5786 if (req->opcode == IORING_OP_POLL_ADD)
5787 return req->async_data;
5788 return req->apoll->double_poll;
5791 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5793 if (req->opcode == IORING_OP_POLL_ADD)
5795 return &req->apoll->poll;
5798 static void io_poll_req_insert(struct io_kiocb *req)
5800 struct io_ring_ctx *ctx = req->ctx;
5801 struct hlist_head *list;
5803 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5804 hlist_add_head(&req->hash_node, list);
5807 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5808 wait_queue_func_t wake_func)
5811 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5812 /* mask in events that we always want/need */
5813 poll->events = events | IO_POLL_UNMASK;
5814 INIT_LIST_HEAD(&poll->wait.entry);
5815 init_waitqueue_func_entry(&poll->wait, wake_func);
5818 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5820 struct wait_queue_head *head = smp_load_acquire(&poll->head);
5823 spin_lock_irq(&head->lock);
5824 list_del_init(&poll->wait.entry);
5826 spin_unlock_irq(&head->lock);
5830 static void io_poll_remove_entries(struct io_kiocb *req)
5833 * Nothing to do if neither of those flags are set. Avoid dipping
5834 * into the poll/apoll/double cachelines if we can.
5836 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5840 * While we hold the waitqueue lock and the waitqueue is nonempty,
5841 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5842 * lock in the first place can race with the waitqueue being freed.
5844 * We solve this as eventpoll does: by taking advantage of the fact that
5845 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5846 * we enter rcu_read_lock() and see that the pointer to the queue is
5847 * non-NULL, we can then lock it without the memory being freed out from
5850 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5851 * case the caller deletes the entry from the queue, leaving it empty.
5852 * In that case, only RCU prevents the queue memory from being freed.
5855 if (req->flags & REQ_F_SINGLE_POLL)
5856 io_poll_remove_entry(io_poll_get_single(req));
5857 if (req->flags & REQ_F_DOUBLE_POLL)
5858 io_poll_remove_entry(io_poll_get_double(req));
5863 * All poll tw should go through this. Checks for poll events, manages
5864 * references, does rewait, etc.
5866 * Returns a negative error on failure. >0 when no action require, which is
5867 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5868 * the request, then the mask is stored in req->result.
5870 static int io_poll_check_events(struct io_kiocb *req)
5872 struct io_ring_ctx *ctx = req->ctx;
5873 struct io_poll_iocb *poll = io_poll_get_single(req);
5876 /* req->task == current here, checking PF_EXITING is safe */
5877 if (unlikely(req->task->flags & PF_EXITING))
5878 io_poll_mark_cancelled(req);
5881 v = atomic_read(&req->poll_refs);
5883 /* tw handler should be the owner, and so have some references */
5884 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5886 if (v & IO_POLL_CANCEL_FLAG)
5890 struct poll_table_struct pt = { ._key = req->cflags };
5892 req->result = vfs_poll(req->file, &pt) & req->cflags;
5895 /* multishot, just fill an CQE and proceed */
5896 if (req->result && !(req->cflags & EPOLLONESHOT)) {
5897 __poll_t mask = mangle_poll(req->result & poll->events);
5900 spin_lock(&ctx->completion_lock);
5901 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5903 io_commit_cqring(ctx);
5904 spin_unlock(&ctx->completion_lock);
5905 if (unlikely(!filled))
5907 io_cqring_ev_posted(ctx);
5908 io_add_napi(req->file, ctx);
5909 } else if (req->result) {
5914 * Release all references, retry if someone tried to restart
5915 * task_work while we were executing it.
5917 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5922 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5924 struct io_ring_ctx *ctx = req->ctx;
5927 ret = io_poll_check_events(req);
5932 req->result = mangle_poll(req->result & req->poll.events);
5938 io_poll_remove_entries(req);
5939 spin_lock(&ctx->completion_lock);
5940 hash_del(&req->hash_node);
5941 __io_req_complete_post(req, req->result, 0);
5942 io_commit_cqring(ctx);
5943 spin_unlock(&ctx->completion_lock);
5944 io_cqring_ev_posted(ctx);
5947 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5949 struct io_ring_ctx *ctx = req->ctx;
5952 ret = io_poll_check_events(req);
5956 io_poll_remove_entries(req);
5957 spin_lock(&ctx->completion_lock);
5958 hash_del(&req->hash_node);
5959 spin_unlock(&ctx->completion_lock);
5962 io_req_task_submit(req, locked);
5964 io_req_complete_failed(req, ret);
5967 static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
5971 * This is useful for poll that is armed on behalf of another
5972 * request, and where the wakeup path could be on a different
5973 * CPU. We want to avoid pulling in req->apoll->events for that
5976 req->cflags = events;
5977 if (req->opcode == IORING_OP_POLL_ADD)
5978 req->io_task_work.func = io_poll_task_func;
5980 req->io_task_work.func = io_apoll_task_func;
5982 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
5983 io_req_task_work_add(req, false);
5986 static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
5988 if (io_poll_get_ownership(req))
5989 __io_poll_execute(req, res, events);
5992 static void io_poll_cancel_req(struct io_kiocb *req)
5994 io_poll_mark_cancelled(req);
5995 /* kick tw, which should complete the request */
5996 io_poll_execute(req, 0, 0);
5999 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6002 struct io_kiocb *req = wait->private;
6003 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6005 __poll_t mask = key_to_poll(key);
6007 if (unlikely(mask & POLLFREE)) {
6008 io_poll_mark_cancelled(req);
6009 /* we have to kick tw in case it's not already */
6010 io_poll_execute(req, 0, poll->events);
6013 * If the waitqueue is being freed early but someone is already
6014 * holds ownership over it, we have to tear down the request as
6015 * best we can. That means immediately removing the request from
6016 * its waitqueue and preventing all further accesses to the
6017 * waitqueue via the request.
6019 list_del_init(&poll->wait.entry);
6022 * Careful: this *must* be the last step, since as soon
6023 * as req->head is NULL'ed out, the request can be
6024 * completed and freed, since aio_poll_complete_work()
6025 * will no longer need to take the waitqueue lock.
6027 smp_store_release(&poll->head, NULL);
6031 /* for instances that support it check for an event match first */
6032 if (mask && !(mask & poll->events))
6035 if (io_poll_get_ownership(req)) {
6036 /* optional, saves extra locking for removal in tw handler */
6037 if (mask && poll->events & EPOLLONESHOT) {
6038 list_del_init(&poll->wait.entry);
6040 req->flags &= ~REQ_F_SINGLE_POLL;
6042 __io_poll_execute(req, mask, poll->events);
6047 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6048 struct wait_queue_head *head,
6049 struct io_poll_iocb **poll_ptr)
6051 struct io_kiocb *req = pt->req;
6054 * The file being polled uses multiple waitqueues for poll handling
6055 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6058 if (unlikely(pt->nr_entries)) {
6059 struct io_poll_iocb *first = poll;
6061 /* double add on the same waitqueue head, ignore */
6062 if (first->head == head)
6064 /* already have a 2nd entry, fail a third attempt */
6066 if ((*poll_ptr)->head == head)
6068 pt->error = -EINVAL;
6072 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6074 pt->error = -ENOMEM;
6077 req->flags |= REQ_F_DOUBLE_POLL;
6078 io_init_poll_iocb(poll, first->events, first->wait.func);
6080 if (req->opcode == IORING_OP_POLL_ADD)
6081 req->flags |= REQ_F_ASYNC_DATA;
6084 req->flags |= REQ_F_SINGLE_POLL;
6087 poll->wait.private = req;
6089 if (poll->events & EPOLLEXCLUSIVE)
6090 add_wait_queue_exclusive(head, &poll->wait);
6092 add_wait_queue(head, &poll->wait);
6095 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6096 struct poll_table_struct *p)
6098 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6100 __io_queue_proc(&pt->req->poll, pt, head,
6101 (struct io_poll_iocb **) &pt->req->async_data);
6104 static int __io_arm_poll_handler(struct io_kiocb *req,
6105 struct io_poll_iocb *poll,
6106 struct io_poll_table *ipt, __poll_t mask)
6108 struct io_ring_ctx *ctx = req->ctx;
6111 INIT_HLIST_NODE(&req->hash_node);
6112 io_init_poll_iocb(poll, mask, io_poll_wake);
6113 poll->file = req->file;
6114 poll->wait.private = req;
6116 ipt->pt._key = mask;
6119 ipt->nr_entries = 0;
6122 * Take the ownership to delay any tw execution up until we're done
6123 * with poll arming. see io_poll_get_ownership().
6125 atomic_set(&req->poll_refs, 1);
6126 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6128 if (mask && (poll->events & EPOLLONESHOT)) {
6129 io_poll_remove_entries(req);
6130 /* no one else has access to the req, forget about the ref */
6133 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6134 io_poll_remove_entries(req);
6136 ipt->error = -EINVAL;
6140 spin_lock(&ctx->completion_lock);
6141 io_poll_req_insert(req);
6142 spin_unlock(&ctx->completion_lock);
6145 /* can't multishot if failed, just queue the event we've got */
6146 if (unlikely(ipt->error || !ipt->nr_entries))
6147 poll->events |= EPOLLONESHOT;
6148 __io_poll_execute(req, mask, poll->events);
6151 io_add_napi(req->file, req->ctx);
6154 * Release ownership. If someone tried to queue a tw while it was
6155 * locked, kick it off for them.
6157 v = atomic_dec_return(&req->poll_refs);
6158 if (unlikely(v & IO_POLL_REF_MASK))
6159 __io_poll_execute(req, 0, poll->events);
6163 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6164 struct poll_table_struct *p)
6166 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6167 struct async_poll *apoll = pt->req->apoll;
6169 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6178 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6180 const struct io_op_def *def = &io_op_defs[req->opcode];
6181 struct io_ring_ctx *ctx = req->ctx;
6182 struct async_poll *apoll;
6183 struct io_poll_table ipt;
6184 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6187 if (!def->pollin && !def->pollout)
6188 return IO_APOLL_ABORTED;
6189 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6190 return IO_APOLL_ABORTED;
6193 mask |= POLLIN | POLLRDNORM;
6195 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6196 if ((req->opcode == IORING_OP_RECVMSG) &&
6197 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6200 mask |= POLLOUT | POLLWRNORM;
6203 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6204 !list_empty(&ctx->apoll_cache)) {
6205 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6207 list_del_init(&apoll->poll.wait.entry);
6209 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6210 if (unlikely(!apoll))
6211 return IO_APOLL_ABORTED;
6213 apoll->double_poll = NULL;
6215 req->flags |= REQ_F_POLLED;
6216 ipt.pt._qproc = io_async_queue_proc;
6218 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
6219 if (ret || ipt.error)
6220 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6222 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
6223 mask, apoll->poll.events);
6228 * Returns true if we found and killed one or more poll requests
6230 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6231 struct task_struct *tsk, bool cancel_all)
6233 struct hlist_node *tmp;
6234 struct io_kiocb *req;
6238 spin_lock(&ctx->completion_lock);
6239 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6240 struct hlist_head *list;
6242 list = &ctx->cancel_hash[i];
6243 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
6244 if (io_match_task_safe(req, tsk, cancel_all)) {
6245 io_poll_cancel_req(req);
6250 spin_unlock(&ctx->completion_lock);
6254 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6256 __must_hold(&ctx->completion_lock)
6258 struct hlist_head *list;
6259 struct io_kiocb *req;
6261 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6262 hlist_for_each_entry(req, list, hash_node) {
6263 if (sqe_addr != req->user_data)
6265 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6272 static bool io_poll_disarm(struct io_kiocb *req)
6273 __must_hold(&ctx->completion_lock)
6275 if (!io_poll_get_ownership(req))
6277 io_poll_remove_entries(req);
6278 hash_del(&req->hash_node);
6282 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6284 __must_hold(&ctx->completion_lock)
6286 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
6290 io_poll_cancel_req(req);
6294 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6299 events = READ_ONCE(sqe->poll32_events);
6301 events = swahw32(events);
6303 if (!(flags & IORING_POLL_ADD_MULTI))
6304 events |= EPOLLONESHOT;
6305 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
6308 static int io_poll_update_prep(struct io_kiocb *req,
6309 const struct io_uring_sqe *sqe)
6311 struct io_poll_update *upd = &req->poll_update;
6314 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6316 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
6318 flags = READ_ONCE(sqe->len);
6319 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6320 IORING_POLL_ADD_MULTI))
6322 /* meaningless without update */
6323 if (flags == IORING_POLL_ADD_MULTI)
6326 upd->old_user_data = READ_ONCE(sqe->addr);
6327 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6328 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
6330 upd->new_user_data = READ_ONCE(sqe->off);
6331 if (!upd->update_user_data && upd->new_user_data)
6333 if (upd->update_events)
6334 upd->events = io_poll_parse_events(sqe, flags);
6335 else if (sqe->poll32_events)
6341 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6343 struct io_poll_iocb *poll = &req->poll;
6346 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6348 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
6350 flags = READ_ONCE(sqe->len);
6351 if (flags & ~IORING_POLL_ADD_MULTI)
6353 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6356 io_req_set_refcount(req);
6357 req->cflags = poll->events = io_poll_parse_events(sqe, flags);
6361 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
6363 struct io_poll_iocb *poll = &req->poll;
6364 struct io_poll_table ipt;
6367 ipt.pt._qproc = io_poll_queue_proc;
6369 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6370 ret = ret ?: ipt.error;
6372 __io_req_complete(req, issue_flags, ret, 0);
6376 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
6378 struct io_ring_ctx *ctx = req->ctx;
6379 struct io_kiocb *preq;
6383 spin_lock(&ctx->completion_lock);
6384 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
6385 if (!preq || !io_poll_disarm(preq)) {
6386 spin_unlock(&ctx->completion_lock);
6387 ret = preq ? -EALREADY : -ENOENT;
6390 spin_unlock(&ctx->completion_lock);
6392 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6393 /* only mask one event flags, keep behavior flags */
6394 if (req->poll_update.update_events) {
6395 preq->poll.events &= ~0xffff;
6396 preq->poll.events |= req->poll_update.events & 0xffff;
6397 preq->poll.events |= IO_POLL_UNMASK;
6399 if (req->poll_update.update_user_data)
6400 preq->user_data = req->poll_update.new_user_data;
6402 ret2 = io_poll_add(preq, issue_flags);
6403 /* successfully updated, don't complete poll request */
6409 preq->result = -ECANCELED;
6410 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6411 io_req_task_complete(preq, &locked);
6415 /* complete update request, we're done with it */
6416 __io_req_complete(req, issue_flags, ret, 0);
6420 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6422 struct io_timeout_data *data = container_of(timer,
6423 struct io_timeout_data, timer);
6424 struct io_kiocb *req = data->req;
6425 struct io_ring_ctx *ctx = req->ctx;
6426 unsigned long flags;
6428 spin_lock_irqsave(&ctx->timeout_lock, flags);
6429 list_del_init(&req->timeout.list);
6430 atomic_set(&req->ctx->cq_timeouts,
6431 atomic_read(&req->ctx->cq_timeouts) + 1);
6432 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6434 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6437 req->result = -ETIME;
6438 req->io_task_work.func = io_req_task_complete;
6439 io_req_task_work_add(req, false);
6440 return HRTIMER_NORESTART;
6443 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6445 __must_hold(&ctx->timeout_lock)
6447 struct io_timeout_data *io;
6448 struct io_kiocb *req;
6451 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
6452 found = user_data == req->user_data;
6457 return ERR_PTR(-ENOENT);
6459 io = req->async_data;
6460 if (hrtimer_try_to_cancel(&io->timer) == -1)
6461 return ERR_PTR(-EALREADY);
6462 list_del_init(&req->timeout.list);
6466 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
6467 __must_hold(&ctx->completion_lock)
6468 __must_hold(&ctx->timeout_lock)
6470 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6473 return PTR_ERR(req);
6476 io_fill_cqe_req(req, -ECANCELED, 0);
6477 io_put_req_deferred(req);
6481 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6483 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6484 case IORING_TIMEOUT_BOOTTIME:
6485 return CLOCK_BOOTTIME;
6486 case IORING_TIMEOUT_REALTIME:
6487 return CLOCK_REALTIME;
6489 /* can't happen, vetted at prep time */
6493 return CLOCK_MONOTONIC;
6497 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6498 struct timespec64 *ts, enum hrtimer_mode mode)
6499 __must_hold(&ctx->timeout_lock)
6501 struct io_timeout_data *io;
6502 struct io_kiocb *req;
6505 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6506 found = user_data == req->user_data;
6513 io = req->async_data;
6514 if (hrtimer_try_to_cancel(&io->timer) == -1)
6516 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6517 io->timer.function = io_link_timeout_fn;
6518 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6522 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6523 struct timespec64 *ts, enum hrtimer_mode mode)
6524 __must_hold(&ctx->timeout_lock)
6526 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6527 struct io_timeout_data *data;
6530 return PTR_ERR(req);
6532 req->timeout.off = 0; /* noseq */
6533 data = req->async_data;
6534 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6535 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6536 data->timer.function = io_timeout_fn;
6537 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6541 static int io_timeout_remove_prep(struct io_kiocb *req,
6542 const struct io_uring_sqe *sqe)
6544 struct io_timeout_rem *tr = &req->timeout_rem;
6546 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6548 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6550 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6553 tr->ltimeout = false;
6554 tr->addr = READ_ONCE(sqe->addr);
6555 tr->flags = READ_ONCE(sqe->timeout_flags);
6556 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6557 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6559 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6560 tr->ltimeout = true;
6561 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6563 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6565 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6567 } else if (tr->flags) {
6568 /* timeout removal doesn't support flags */
6575 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6577 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6582 * Remove or update an existing timeout command
6584 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6586 struct io_timeout_rem *tr = &req->timeout_rem;
6587 struct io_ring_ctx *ctx = req->ctx;
6590 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6591 spin_lock(&ctx->completion_lock);
6592 spin_lock_irq(&ctx->timeout_lock);
6593 ret = io_timeout_cancel(ctx, tr->addr);
6594 spin_unlock_irq(&ctx->timeout_lock);
6595 spin_unlock(&ctx->completion_lock);
6597 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6599 spin_lock_irq(&ctx->timeout_lock);
6601 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6603 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6604 spin_unlock_irq(&ctx->timeout_lock);
6609 io_req_complete_post(req, ret, 0);
6613 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6614 bool is_timeout_link)
6616 struct io_timeout_data *data;
6618 u32 off = READ_ONCE(sqe->off);
6620 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6622 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6625 if (off && is_timeout_link)
6627 flags = READ_ONCE(sqe->timeout_flags);
6628 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6629 IORING_TIMEOUT_ETIME_SUCCESS))
6631 /* more than one clock specified is invalid, obviously */
6632 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6635 INIT_LIST_HEAD(&req->timeout.list);
6636 req->timeout.off = off;
6637 if (unlikely(off && !req->ctx->off_timeout_used))
6638 req->ctx->off_timeout_used = true;
6640 if (WARN_ON_ONCE(req_has_async_data(req)))
6642 if (io_alloc_async_data(req))
6645 data = req->async_data;
6647 data->flags = flags;
6649 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6652 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6655 data->mode = io_translate_timeout_mode(flags);
6656 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6658 if (is_timeout_link) {
6659 struct io_submit_link *link = &req->ctx->submit_state.link;
6663 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6665 req->timeout.head = link->last;
6666 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6671 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6673 struct io_ring_ctx *ctx = req->ctx;
6674 struct io_timeout_data *data = req->async_data;
6675 struct list_head *entry;
6676 u32 tail, off = req->timeout.off;
6678 spin_lock_irq(&ctx->timeout_lock);
6681 * sqe->off holds how many events that need to occur for this
6682 * timeout event to be satisfied. If it isn't set, then this is
6683 * a pure timeout request, sequence isn't used.
6685 if (io_is_timeout_noseq(req)) {
6686 entry = ctx->timeout_list.prev;
6690 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6691 req->timeout.target_seq = tail + off;
6693 /* Update the last seq here in case io_flush_timeouts() hasn't.
6694 * This is safe because ->completion_lock is held, and submissions
6695 * and completions are never mixed in the same ->completion_lock section.
6697 ctx->cq_last_tm_flush = tail;
6700 * Insertion sort, ensuring the first entry in the list is always
6701 * the one we need first.
6703 list_for_each_prev(entry, &ctx->timeout_list) {
6704 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6707 if (io_is_timeout_noseq(nxt))
6709 /* nxt.seq is behind @tail, otherwise would've been completed */
6710 if (off >= nxt->timeout.target_seq - tail)
6714 list_add(&req->timeout.list, entry);
6715 data->timer.function = io_timeout_fn;
6716 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6717 spin_unlock_irq(&ctx->timeout_lock);
6721 struct io_cancel_data {
6722 struct io_ring_ctx *ctx;
6726 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6728 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6729 struct io_cancel_data *cd = data;
6731 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6734 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6735 struct io_ring_ctx *ctx)
6737 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6738 enum io_wq_cancel cancel_ret;
6741 if (!tctx || !tctx->io_wq)
6744 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6745 switch (cancel_ret) {
6746 case IO_WQ_CANCEL_OK:
6749 case IO_WQ_CANCEL_RUNNING:
6752 case IO_WQ_CANCEL_NOTFOUND:
6760 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6762 struct io_ring_ctx *ctx = req->ctx;
6765 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6767 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6769 * Fall-through even for -EALREADY, as we may have poll armed
6770 * that need unarming.
6775 spin_lock(&ctx->completion_lock);
6776 ret = io_poll_cancel(ctx, sqe_addr, false);
6780 spin_lock_irq(&ctx->timeout_lock);
6781 ret = io_timeout_cancel(ctx, sqe_addr);
6782 spin_unlock_irq(&ctx->timeout_lock);
6784 spin_unlock(&ctx->completion_lock);
6788 static int io_async_cancel_prep(struct io_kiocb *req,
6789 const struct io_uring_sqe *sqe)
6791 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6793 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6795 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6799 req->cancel.addr = READ_ONCE(sqe->addr);
6803 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6805 struct io_ring_ctx *ctx = req->ctx;
6806 u64 sqe_addr = req->cancel.addr;
6807 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6808 struct io_tctx_node *node;
6811 ret = io_try_cancel_userdata(req, sqe_addr);
6815 /* slow path, try all io-wq's */
6816 io_ring_submit_lock(ctx, needs_lock);
6818 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6819 struct io_uring_task *tctx = node->task->io_uring;
6821 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6825 io_ring_submit_unlock(ctx, needs_lock);
6829 io_req_complete_post(req, ret, 0);
6833 static int io_rsrc_update_prep(struct io_kiocb *req,
6834 const struct io_uring_sqe *sqe)
6836 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6838 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6841 req->rsrc_update.offset = READ_ONCE(sqe->off);
6842 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6843 if (!req->rsrc_update.nr_args)
6845 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6849 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6851 struct io_ring_ctx *ctx = req->ctx;
6852 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
6853 struct io_uring_rsrc_update2 up;
6856 up.offset = req->rsrc_update.offset;
6857 up.data = req->rsrc_update.arg;
6862 io_ring_submit_lock(ctx, needs_lock);
6863 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6864 &up, req->rsrc_update.nr_args);
6865 io_ring_submit_unlock(ctx, needs_lock);
6869 __io_req_complete(req, issue_flags, ret, 0);
6873 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6875 switch (req->opcode) {
6878 case IORING_OP_READV:
6879 case IORING_OP_READ_FIXED:
6880 case IORING_OP_READ:
6881 return io_read_prep(req, sqe);
6882 case IORING_OP_WRITEV:
6883 case IORING_OP_WRITE_FIXED:
6884 case IORING_OP_WRITE:
6885 return io_write_prep(req, sqe);
6886 case IORING_OP_POLL_ADD:
6887 return io_poll_add_prep(req, sqe);
6888 case IORING_OP_POLL_REMOVE:
6889 return io_poll_update_prep(req, sqe);
6890 case IORING_OP_FSYNC:
6891 return io_fsync_prep(req, sqe);
6892 case IORING_OP_SYNC_FILE_RANGE:
6893 return io_sfr_prep(req, sqe);
6894 case IORING_OP_SENDMSG:
6895 case IORING_OP_SEND:
6896 return io_sendmsg_prep(req, sqe);
6897 case IORING_OP_RECVMSG:
6898 case IORING_OP_RECV:
6899 return io_recvmsg_prep(req, sqe);
6900 case IORING_OP_CONNECT:
6901 return io_connect_prep(req, sqe);
6902 case IORING_OP_TIMEOUT:
6903 return io_timeout_prep(req, sqe, false);
6904 case IORING_OP_TIMEOUT_REMOVE:
6905 return io_timeout_remove_prep(req, sqe);
6906 case IORING_OP_ASYNC_CANCEL:
6907 return io_async_cancel_prep(req, sqe);
6908 case IORING_OP_LINK_TIMEOUT:
6909 return io_timeout_prep(req, sqe, true);
6910 case IORING_OP_ACCEPT:
6911 return io_accept_prep(req, sqe);
6912 case IORING_OP_FALLOCATE:
6913 return io_fallocate_prep(req, sqe);
6914 case IORING_OP_OPENAT:
6915 return io_openat_prep(req, sqe);
6916 case IORING_OP_CLOSE:
6917 return io_close_prep(req, sqe);
6918 case IORING_OP_FILES_UPDATE:
6919 return io_rsrc_update_prep(req, sqe);
6920 case IORING_OP_STATX:
6921 return io_statx_prep(req, sqe);
6922 case IORING_OP_FADVISE:
6923 return io_fadvise_prep(req, sqe);
6924 case IORING_OP_MADVISE:
6925 return io_madvise_prep(req, sqe);
6926 case IORING_OP_OPENAT2:
6927 return io_openat2_prep(req, sqe);
6928 case IORING_OP_EPOLL_CTL:
6929 return io_epoll_ctl_prep(req, sqe);
6930 case IORING_OP_SPLICE:
6931 return io_splice_prep(req, sqe);
6932 case IORING_OP_PROVIDE_BUFFERS:
6933 return io_provide_buffers_prep(req, sqe);
6934 case IORING_OP_REMOVE_BUFFERS:
6935 return io_remove_buffers_prep(req, sqe);
6937 return io_tee_prep(req, sqe);
6938 case IORING_OP_SHUTDOWN:
6939 return io_shutdown_prep(req, sqe);
6940 case IORING_OP_RENAMEAT:
6941 return io_renameat_prep(req, sqe);
6942 case IORING_OP_UNLINKAT:
6943 return io_unlinkat_prep(req, sqe);
6944 case IORING_OP_MKDIRAT:
6945 return io_mkdirat_prep(req, sqe);
6946 case IORING_OP_SYMLINKAT:
6947 return io_symlinkat_prep(req, sqe);
6948 case IORING_OP_LINKAT:
6949 return io_linkat_prep(req, sqe);
6950 case IORING_OP_MSG_RING:
6951 return io_msg_ring_prep(req, sqe);
6954 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6959 static int io_req_prep_async(struct io_kiocb *req)
6961 if (!io_op_defs[req->opcode].needs_async_setup)
6963 if (WARN_ON_ONCE(req_has_async_data(req)))
6965 if (io_alloc_async_data(req))
6968 switch (req->opcode) {
6969 case IORING_OP_READV:
6970 return io_rw_prep_async(req, READ);
6971 case IORING_OP_WRITEV:
6972 return io_rw_prep_async(req, WRITE);
6973 case IORING_OP_SENDMSG:
6974 return io_sendmsg_prep_async(req);
6975 case IORING_OP_RECVMSG:
6976 return io_recvmsg_prep_async(req);
6977 case IORING_OP_CONNECT:
6978 return io_connect_prep_async(req);
6980 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6985 static u32 io_get_sequence(struct io_kiocb *req)
6987 u32 seq = req->ctx->cached_sq_head;
6989 /* need original cached_sq_head, but it was increased for each req */
6990 io_for_each_link(req, req)
6995 static __cold void io_drain_req(struct io_kiocb *req)
6997 struct io_ring_ctx *ctx = req->ctx;
6998 struct io_defer_entry *de;
7000 u32 seq = io_get_sequence(req);
7002 /* Still need defer if there is pending req in defer list. */
7003 spin_lock(&ctx->completion_lock);
7004 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7005 spin_unlock(&ctx->completion_lock);
7007 ctx->drain_active = false;
7008 io_req_task_queue(req);
7011 spin_unlock(&ctx->completion_lock);
7013 ret = io_req_prep_async(req);
7016 io_req_complete_failed(req, ret);
7019 io_prep_async_link(req);
7020 de = kmalloc(sizeof(*de), GFP_KERNEL);
7026 spin_lock(&ctx->completion_lock);
7027 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7028 spin_unlock(&ctx->completion_lock);
7033 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
7036 list_add_tail(&de->list, &ctx->defer_list);
7037 spin_unlock(&ctx->completion_lock);
7040 static void io_clean_op(struct io_kiocb *req)
7042 if (req->flags & REQ_F_BUFFER_SELECTED)
7043 io_put_kbuf_comp(req);
7045 if (req->flags & REQ_F_NEED_CLEANUP) {
7046 switch (req->opcode) {
7047 case IORING_OP_READV:
7048 case IORING_OP_READ_FIXED:
7049 case IORING_OP_READ:
7050 case IORING_OP_WRITEV:
7051 case IORING_OP_WRITE_FIXED:
7052 case IORING_OP_WRITE: {
7053 struct io_async_rw *io = req->async_data;
7055 kfree(io->free_iovec);
7058 case IORING_OP_RECVMSG:
7059 case IORING_OP_SENDMSG: {
7060 struct io_async_msghdr *io = req->async_data;
7062 kfree(io->free_iov);
7065 case IORING_OP_SPLICE:
7067 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
7068 io_put_file(req->splice.file_in);
7070 case IORING_OP_OPENAT:
7071 case IORING_OP_OPENAT2:
7072 if (req->open.filename)
7073 putname(req->open.filename);
7075 case IORING_OP_RENAMEAT:
7076 putname(req->rename.oldpath);
7077 putname(req->rename.newpath);
7079 case IORING_OP_UNLINKAT:
7080 putname(req->unlink.filename);
7082 case IORING_OP_MKDIRAT:
7083 putname(req->mkdir.filename);
7085 case IORING_OP_SYMLINKAT:
7086 putname(req->symlink.oldpath);
7087 putname(req->symlink.newpath);
7089 case IORING_OP_LINKAT:
7090 putname(req->hardlink.oldpath);
7091 putname(req->hardlink.newpath);
7095 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7096 kfree(req->apoll->double_poll);
7100 if (req->flags & REQ_F_INFLIGHT) {
7101 struct io_uring_task *tctx = req->task->io_uring;
7103 atomic_dec(&tctx->inflight_tracked);
7105 if (req->flags & REQ_F_CREDS)
7106 put_cred(req->creds);
7107 if (req->flags & REQ_F_ASYNC_DATA) {
7108 kfree(req->async_data);
7109 req->async_data = NULL;
7111 req->flags &= ~IO_REQ_CLEAN_FLAGS;
7114 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
7116 const struct cred *creds = NULL;
7119 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
7120 creds = override_creds(req->creds);
7122 if (!io_op_defs[req->opcode].audit_skip)
7123 audit_uring_entry(req->opcode);
7125 switch (req->opcode) {
7127 ret = io_nop(req, issue_flags);
7129 case IORING_OP_READV:
7130 case IORING_OP_READ_FIXED:
7131 case IORING_OP_READ:
7132 ret = io_read(req, issue_flags);
7134 case IORING_OP_WRITEV:
7135 case IORING_OP_WRITE_FIXED:
7136 case IORING_OP_WRITE:
7137 ret = io_write(req, issue_flags);
7139 case IORING_OP_FSYNC:
7140 ret = io_fsync(req, issue_flags);
7142 case IORING_OP_POLL_ADD:
7143 ret = io_poll_add(req, issue_flags);
7145 case IORING_OP_POLL_REMOVE:
7146 ret = io_poll_update(req, issue_flags);
7148 case IORING_OP_SYNC_FILE_RANGE:
7149 ret = io_sync_file_range(req, issue_flags);
7151 case IORING_OP_SENDMSG:
7152 ret = io_sendmsg(req, issue_flags);
7154 case IORING_OP_SEND:
7155 ret = io_send(req, issue_flags);
7157 case IORING_OP_RECVMSG:
7158 ret = io_recvmsg(req, issue_flags);
7160 case IORING_OP_RECV:
7161 ret = io_recv(req, issue_flags);
7163 case IORING_OP_TIMEOUT:
7164 ret = io_timeout(req, issue_flags);
7166 case IORING_OP_TIMEOUT_REMOVE:
7167 ret = io_timeout_remove(req, issue_flags);
7169 case IORING_OP_ACCEPT:
7170 ret = io_accept(req, issue_flags);
7172 case IORING_OP_CONNECT:
7173 ret = io_connect(req, issue_flags);
7175 case IORING_OP_ASYNC_CANCEL:
7176 ret = io_async_cancel(req, issue_flags);
7178 case IORING_OP_FALLOCATE:
7179 ret = io_fallocate(req, issue_flags);
7181 case IORING_OP_OPENAT:
7182 ret = io_openat(req, issue_flags);
7184 case IORING_OP_CLOSE:
7185 ret = io_close(req, issue_flags);
7187 case IORING_OP_FILES_UPDATE:
7188 ret = io_files_update(req, issue_flags);
7190 case IORING_OP_STATX:
7191 ret = io_statx(req, issue_flags);
7193 case IORING_OP_FADVISE:
7194 ret = io_fadvise(req, issue_flags);
7196 case IORING_OP_MADVISE:
7197 ret = io_madvise(req, issue_flags);
7199 case IORING_OP_OPENAT2:
7200 ret = io_openat2(req, issue_flags);
7202 case IORING_OP_EPOLL_CTL:
7203 ret = io_epoll_ctl(req, issue_flags);
7205 case IORING_OP_SPLICE:
7206 ret = io_splice(req, issue_flags);
7208 case IORING_OP_PROVIDE_BUFFERS:
7209 ret = io_provide_buffers(req, issue_flags);
7211 case IORING_OP_REMOVE_BUFFERS:
7212 ret = io_remove_buffers(req, issue_flags);
7215 ret = io_tee(req, issue_flags);
7217 case IORING_OP_SHUTDOWN:
7218 ret = io_shutdown(req, issue_flags);
7220 case IORING_OP_RENAMEAT:
7221 ret = io_renameat(req, issue_flags);
7223 case IORING_OP_UNLINKAT:
7224 ret = io_unlinkat(req, issue_flags);
7226 case IORING_OP_MKDIRAT:
7227 ret = io_mkdirat(req, issue_flags);
7229 case IORING_OP_SYMLINKAT:
7230 ret = io_symlinkat(req, issue_flags);
7232 case IORING_OP_LINKAT:
7233 ret = io_linkat(req, issue_flags);
7235 case IORING_OP_MSG_RING:
7236 ret = io_msg_ring(req, issue_flags);
7243 if (!io_op_defs[req->opcode].audit_skip)
7244 audit_uring_exit(!ret, ret);
7247 revert_creds(creds);
7250 /* If the op doesn't have a file, we're not polling for it */
7251 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
7252 io_iopoll_req_issued(req, issue_flags);
7257 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7259 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7261 req = io_put_req_find_next(req);
7262 return req ? &req->work : NULL;
7265 static void io_wq_submit_work(struct io_wq_work *work)
7267 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7268 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7269 bool needs_poll = false;
7270 struct io_kiocb *timeout;
7273 /* one will be dropped by ->io_free_work() after returning to io-wq */
7274 if (!(req->flags & REQ_F_REFCOUNT))
7275 __io_req_set_refcount(req, 2);
7279 timeout = io_prep_linked_timeout(req);
7281 io_queue_linked_timeout(timeout);
7283 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
7284 if (work->flags & IO_WQ_WORK_CANCEL) {
7285 io_req_task_queue_fail(req, -ECANCELED);
7289 if (req->flags & REQ_F_FORCE_ASYNC) {
7290 const struct io_op_def *def = &io_op_defs[req->opcode];
7291 bool opcode_poll = def->pollin || def->pollout;
7293 if (opcode_poll && file_can_poll(req->file)) {
7295 issue_flags |= IO_URING_F_NONBLOCK;
7300 ret = io_issue_sqe(req, issue_flags);
7304 * We can get EAGAIN for iopolled IO even though we're
7305 * forcing a sync submission from here, since we can't
7306 * wait for request slots on the block side.
7313 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
7315 /* aborted or ready, in either case retry blocking */
7317 issue_flags &= ~IO_URING_F_NONBLOCK;
7320 /* avoid locking problems by failing it from a clean context */
7322 io_req_task_queue_fail(req, ret);
7325 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
7328 return &table->files[i];
7331 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7334 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
7336 return (struct file *) (slot->file_ptr & FFS_MASK);
7339 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
7341 unsigned long file_ptr = (unsigned long) file;
7343 file_ptr |= io_file_get_flags(file);
7344 file_slot->file_ptr = file_ptr;
7347 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7348 struct io_kiocb *req, int fd)
7351 unsigned long file_ptr;
7353 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7355 fd = array_index_nospec(fd, ctx->nr_user_files);
7356 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7357 file = (struct file *) (file_ptr & FFS_MASK);
7358 file_ptr &= ~FFS_MASK;
7359 /* mask in overlapping REQ_F and FFS bits */
7360 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
7361 io_req_set_rsrc_node(req, ctx);
7365 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
7366 struct io_kiocb *req, int fd)
7368 struct file *file = fget(fd);
7370 trace_io_uring_file_get(ctx, req, req->user_data, fd);
7372 /* we don't allow fixed io_uring files */
7373 if (file && unlikely(file->f_op == &io_uring_fops))
7374 io_req_track_inflight(req);
7378 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
7379 struct io_kiocb *req, int fd, bool fixed)
7382 return io_file_get_fixed(ctx, req, fd);
7384 return io_file_get_normal(ctx, req, fd);
7387 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
7389 struct io_kiocb *prev = req->timeout.prev;
7393 if (!(req->task->flags & PF_EXITING))
7394 ret = io_try_cancel_userdata(req, prev->user_data);
7395 io_req_complete_post(req, ret ?: -ETIME, 0);
7398 io_req_complete_post(req, -ETIME, 0);
7402 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
7404 struct io_timeout_data *data = container_of(timer,
7405 struct io_timeout_data, timer);
7406 struct io_kiocb *prev, *req = data->req;
7407 struct io_ring_ctx *ctx = req->ctx;
7408 unsigned long flags;
7410 spin_lock_irqsave(&ctx->timeout_lock, flags);
7411 prev = req->timeout.head;
7412 req->timeout.head = NULL;
7415 * We don't expect the list to be empty, that will only happen if we
7416 * race with the completion of the linked work.
7419 io_remove_next_linked(prev);
7420 if (!req_ref_inc_not_zero(prev))
7423 list_del(&req->timeout.list);
7424 req->timeout.prev = prev;
7425 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7427 req->io_task_work.func = io_req_task_link_timeout;
7428 io_req_task_work_add(req, false);
7429 return HRTIMER_NORESTART;
7432 static void io_queue_linked_timeout(struct io_kiocb *req)
7434 struct io_ring_ctx *ctx = req->ctx;
7436 spin_lock_irq(&ctx->timeout_lock);
7438 * If the back reference is NULL, then our linked request finished
7439 * before we got a chance to setup the timer
7441 if (req->timeout.head) {
7442 struct io_timeout_data *data = req->async_data;
7444 data->timer.function = io_link_timeout_fn;
7445 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7447 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
7449 spin_unlock_irq(&ctx->timeout_lock);
7450 /* drop submission reference */
7454 static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7455 __must_hold(&req->ctx->uring_lock)
7457 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7459 switch (io_arm_poll_handler(req, 0)) {
7460 case IO_APOLL_READY:
7461 io_req_task_queue(req);
7463 case IO_APOLL_ABORTED:
7465 * Queued up for async execution, worker will release
7466 * submit reference when the iocb is actually submitted.
7468 io_kbuf_recycle(req);
7469 io_queue_async_work(req, NULL);
7472 io_kbuf_recycle(req);
7477 io_queue_linked_timeout(linked_timeout);
7480 static inline void __io_queue_sqe(struct io_kiocb *req)
7481 __must_hold(&req->ctx->uring_lock)
7483 struct io_kiocb *linked_timeout;
7486 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
7488 if (req->flags & REQ_F_COMPLETE_INLINE) {
7489 io_req_add_compl_list(req);
7493 * We async punt it if the file wasn't marked NOWAIT, or if the file
7494 * doesn't support non-blocking read/write attempts
7497 linked_timeout = io_prep_linked_timeout(req);
7499 io_queue_linked_timeout(linked_timeout);
7500 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
7501 io_queue_sqe_arm_apoll(req);
7503 io_req_complete_failed(req, ret);
7507 static void io_queue_sqe_fallback(struct io_kiocb *req)
7508 __must_hold(&req->ctx->uring_lock)
7510 if (req->flags & REQ_F_FAIL) {
7511 io_req_complete_fail_submit(req);
7512 } else if (unlikely(req->ctx->drain_active)) {
7515 int ret = io_req_prep_async(req);
7518 io_req_complete_failed(req, ret);
7520 io_queue_async_work(req, NULL);
7524 static inline void io_queue_sqe(struct io_kiocb *req)
7525 __must_hold(&req->ctx->uring_lock)
7527 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7528 __io_queue_sqe(req);
7530 io_queue_sqe_fallback(req);
7534 * Check SQE restrictions (opcode and flags).
7536 * Returns 'true' if SQE is allowed, 'false' otherwise.
7538 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7539 struct io_kiocb *req,
7540 unsigned int sqe_flags)
7542 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7545 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7546 ctx->restrictions.sqe_flags_required)
7549 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7550 ctx->restrictions.sqe_flags_required))
7556 static void io_init_req_drain(struct io_kiocb *req)
7558 struct io_ring_ctx *ctx = req->ctx;
7559 struct io_kiocb *head = ctx->submit_state.link.head;
7561 ctx->drain_active = true;
7564 * If we need to drain a request in the middle of a link, drain
7565 * the head request and the next request/link after the current
7566 * link. Considering sequential execution of links,
7567 * REQ_F_IO_DRAIN will be maintained for every request of our
7570 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7571 ctx->drain_next = true;
7575 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7576 const struct io_uring_sqe *sqe)
7577 __must_hold(&ctx->uring_lock)
7579 unsigned int sqe_flags;
7583 /* req is partially pre-initialised, see io_preinit_req() */
7584 req->opcode = opcode = READ_ONCE(sqe->opcode);
7585 /* same numerical values with corresponding REQ_F_*, safe to copy */
7586 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7587 req->user_data = READ_ONCE(sqe->user_data);
7589 req->fixed_rsrc_refs = NULL;
7590 req->task = current;
7592 if (unlikely(opcode >= IORING_OP_LAST)) {
7596 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7597 /* enforce forwards compatibility on users */
7598 if (sqe_flags & ~SQE_VALID_FLAGS)
7600 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7601 !io_op_defs[opcode].buffer_select)
7603 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7604 ctx->drain_disabled = true;
7605 if (sqe_flags & IOSQE_IO_DRAIN) {
7606 if (ctx->drain_disabled)
7608 io_init_req_drain(req);
7611 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7612 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7614 /* knock it to the slow queue path, will be drained there */
7615 if (ctx->drain_active)
7616 req->flags |= REQ_F_FORCE_ASYNC;
7617 /* if there is no link, we're at "next" request and need to drain */
7618 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7619 ctx->drain_next = false;
7620 ctx->drain_active = true;
7621 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
7625 if (io_op_defs[opcode].needs_file) {
7626 struct io_submit_state *state = &ctx->submit_state;
7629 * Plug now if we have more than 2 IO left after this, and the
7630 * target is potentially a read/write to block based storage.
7632 if (state->need_plug && io_op_defs[opcode].plug) {
7633 state->plug_started = true;
7634 state->need_plug = false;
7635 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
7638 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7639 (sqe_flags & IOSQE_FIXED_FILE));
7640 if (unlikely(!req->file))
7644 personality = READ_ONCE(sqe->personality);
7648 req->creds = xa_load(&ctx->personalities, personality);
7651 get_cred(req->creds);
7652 ret = security_uring_override_creds(req->creds);
7654 put_cred(req->creds);
7657 req->flags |= REQ_F_CREDS;
7660 return io_req_prep(req, sqe);
7663 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7664 const struct io_uring_sqe *sqe)
7665 __must_hold(&ctx->uring_lock)
7667 struct io_submit_link *link = &ctx->submit_state.link;
7670 ret = io_init_req(ctx, req, sqe);
7671 if (unlikely(ret)) {
7672 trace_io_uring_req_failed(sqe, ctx, req, ret);
7674 /* fail even hard links since we don't submit */
7677 * we can judge a link req is failed or cancelled by if
7678 * REQ_F_FAIL is set, but the head is an exception since
7679 * it may be set REQ_F_FAIL because of other req's failure
7680 * so let's leverage req->result to distinguish if a head
7681 * is set REQ_F_FAIL because of its failure or other req's
7682 * failure so that we can set the correct ret code for it.
7683 * init result here to avoid affecting the normal path.
7685 if (!(link->head->flags & REQ_F_FAIL))
7686 req_fail_link_node(link->head, -ECANCELED);
7687 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7689 * the current req is a normal req, we should return
7690 * error and thus break the submittion loop.
7692 io_req_complete_failed(req, ret);
7695 req_fail_link_node(req, ret);
7698 /* don't need @sqe from now on */
7699 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
7701 ctx->flags & IORING_SETUP_SQPOLL);
7704 * If we already have a head request, queue this one for async
7705 * submittal once the head completes. If we don't have a head but
7706 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7707 * submitted sync once the chain is complete. If none of those
7708 * conditions are true (normal request), then just queue it.
7711 struct io_kiocb *head = link->head;
7713 if (!(req->flags & REQ_F_FAIL)) {
7714 ret = io_req_prep_async(req);
7715 if (unlikely(ret)) {
7716 req_fail_link_node(req, ret);
7717 if (!(head->flags & REQ_F_FAIL))
7718 req_fail_link_node(head, -ECANCELED);
7721 trace_io_uring_link(ctx, req, head);
7722 link->last->link = req;
7725 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7727 /* last request of a link, enqueue the link */
7730 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7741 * Batched submission is done, ensure local IO is flushed out.
7743 static void io_submit_state_end(struct io_ring_ctx *ctx)
7745 struct io_submit_state *state = &ctx->submit_state;
7747 if (state->link.head)
7748 io_queue_sqe(state->link.head);
7749 /* flush only after queuing links as they can generate completions */
7750 io_submit_flush_completions(ctx);
7751 if (state->plug_started)
7752 blk_finish_plug(&state->plug);
7756 * Start submission side cache.
7758 static void io_submit_state_start(struct io_submit_state *state,
7759 unsigned int max_ios)
7761 state->plug_started = false;
7762 state->need_plug = max_ios > 2;
7763 state->submit_nr = max_ios;
7764 /* set only head, no need to init link_last in advance */
7765 state->link.head = NULL;
7768 static void io_commit_sqring(struct io_ring_ctx *ctx)
7770 struct io_rings *rings = ctx->rings;
7773 * Ensure any loads from the SQEs are done at this point,
7774 * since once we write the new head, the application could
7775 * write new data to them.
7777 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7781 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7782 * that is mapped by userspace. This means that care needs to be taken to
7783 * ensure that reads are stable, as we cannot rely on userspace always
7784 * being a good citizen. If members of the sqe are validated and then later
7785 * used, it's important that those reads are done through READ_ONCE() to
7786 * prevent a re-load down the line.
7788 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7790 unsigned head, mask = ctx->sq_entries - 1;
7791 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7794 * The cached sq head (or cq tail) serves two purposes:
7796 * 1) allows us to batch the cost of updating the user visible
7798 * 2) allows the kernel side to track the head on its own, even
7799 * though the application is the one updating it.
7801 head = READ_ONCE(ctx->sq_array[sq_idx]);
7802 if (likely(head < ctx->sq_entries))
7803 return &ctx->sq_sqes[head];
7805 /* drop invalid entries */
7807 WRITE_ONCE(ctx->rings->sq_dropped,
7808 READ_ONCE(ctx->rings->sq_dropped) + 1);
7812 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7813 __must_hold(&ctx->uring_lock)
7815 unsigned int entries = io_sqring_entries(ctx);
7818 if (unlikely(!entries))
7820 /* make sure SQ entry isn't read before tail */
7821 nr = min3(nr, ctx->sq_entries, entries);
7822 io_get_task_refs(nr);
7824 io_submit_state_start(&ctx->submit_state, nr);
7826 const struct io_uring_sqe *sqe;
7827 struct io_kiocb *req;
7829 if (unlikely(!io_alloc_req_refill(ctx))) {
7831 submitted = -EAGAIN;
7834 req = io_alloc_req(ctx);
7835 sqe = io_get_sqe(ctx);
7836 if (unlikely(!sqe)) {
7837 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
7840 /* will complete beyond this point, count as submitted */
7842 if (io_submit_sqe(ctx, req, sqe)) {
7844 * Continue submitting even for sqe failure if the
7845 * ring was setup with IORING_SETUP_SUBMIT_ALL
7847 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7850 } while (submitted < nr);
7852 if (unlikely(submitted != nr)) {
7853 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7854 int unused = nr - ref_used;
7856 current->io_uring->cached_refs += unused;
7859 io_submit_state_end(ctx);
7860 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7861 io_commit_sqring(ctx);
7866 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7868 return READ_ONCE(sqd->state);
7871 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7873 /* Tell userspace we may need a wakeup call */
7874 spin_lock(&ctx->completion_lock);
7875 WRITE_ONCE(ctx->rings->sq_flags,
7876 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7877 spin_unlock(&ctx->completion_lock);
7880 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7882 spin_lock(&ctx->completion_lock);
7883 WRITE_ONCE(ctx->rings->sq_flags,
7884 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7885 spin_unlock(&ctx->completion_lock);
7888 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7890 unsigned int to_submit;
7893 to_submit = io_sqring_entries(ctx);
7894 /* if we're handling multiple rings, cap submit size for fairness */
7895 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7896 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7898 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
7899 const struct cred *creds = NULL;
7901 if (ctx->sq_creds != current_cred())
7902 creds = override_creds(ctx->sq_creds);
7904 mutex_lock(&ctx->uring_lock);
7905 if (!wq_list_empty(&ctx->iopoll_list))
7906 io_do_iopoll(ctx, true);
7909 * Don't submit if refs are dying, good for io_uring_register(),
7910 * but also it is relied upon by io_ring_exit_work()
7912 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7913 !(ctx->flags & IORING_SETUP_R_DISABLED))
7914 ret = io_submit_sqes(ctx, to_submit);
7915 mutex_unlock(&ctx->uring_lock);
7916 #ifdef CONFIG_NET_RX_BUSY_POLL
7917 spin_lock(&ctx->napi_lock);
7918 if (!list_empty(&ctx->napi_list) &&
7919 io_napi_busy_loop(&ctx->napi_list))
7921 spin_unlock(&ctx->napi_lock);
7923 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7924 wake_up(&ctx->sqo_sq_wait);
7926 revert_creds(creds);
7932 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7934 struct io_ring_ctx *ctx;
7935 unsigned sq_thread_idle = 0;
7937 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7938 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7939 sqd->sq_thread_idle = sq_thread_idle;
7942 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7944 bool did_sig = false;
7945 struct ksignal ksig;
7947 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7948 signal_pending(current)) {
7949 mutex_unlock(&sqd->lock);
7950 if (signal_pending(current))
7951 did_sig = get_signal(&ksig);
7953 mutex_lock(&sqd->lock);
7955 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7958 static int io_sq_thread(void *data)
7960 struct io_sq_data *sqd = data;
7961 struct io_ring_ctx *ctx;
7962 unsigned long timeout = 0;
7963 char buf[TASK_COMM_LEN];
7966 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7967 set_task_comm(current, buf);
7969 if (sqd->sq_cpu != -1)
7970 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7972 set_cpus_allowed_ptr(current, cpu_online_mask);
7973 current->flags |= PF_NO_SETAFFINITY;
7975 audit_alloc_kernel(current);
7977 mutex_lock(&sqd->lock);
7979 bool cap_entries, sqt_spin = false;
7981 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7982 if (io_sqd_handle_event(sqd))
7984 timeout = jiffies + sqd->sq_thread_idle;
7987 cap_entries = !list_is_singular(&sqd->ctx_list);
7988 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7989 int ret = __io_sq_thread(ctx, cap_entries);
7991 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
7994 if (io_run_task_work())
7997 if (sqt_spin || !time_after(jiffies, timeout)) {
8000 timeout = jiffies + sqd->sq_thread_idle;
8004 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8005 if (!io_sqd_events_pending(sqd) && !current->task_works) {
8006 bool needs_sched = true;
8008 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8009 io_ring_set_wakeup_flag(ctx);
8011 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8012 !wq_list_empty(&ctx->iopoll_list)) {
8013 needs_sched = false;
8016 if (io_sqring_entries(ctx)) {
8017 needs_sched = false;
8023 mutex_unlock(&sqd->lock);
8025 mutex_lock(&sqd->lock);
8027 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8028 io_ring_clear_wakeup_flag(ctx);
8031 finish_wait(&sqd->wait, &wait);
8032 timeout = jiffies + sqd->sq_thread_idle;
8035 io_uring_cancel_generic(true, sqd);
8037 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8038 io_ring_set_wakeup_flag(ctx);
8040 mutex_unlock(&sqd->lock);
8042 audit_free(current);
8044 complete(&sqd->exited);
8048 struct io_wait_queue {
8049 struct wait_queue_entry wq;
8050 struct io_ring_ctx *ctx;
8052 unsigned nr_timeouts;
8053 #ifdef CONFIG_NET_RX_BUSY_POLL
8054 unsigned busy_poll_to;
8058 static inline bool io_should_wake(struct io_wait_queue *iowq)
8060 struct io_ring_ctx *ctx = iowq->ctx;
8061 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8064 * Wake up if we have enough events, or if a timeout occurred since we
8065 * started waiting. For timeouts, we always want to return to userspace,
8066 * regardless of event count.
8068 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8071 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8072 int wake_flags, void *key)
8074 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8078 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8079 * the task, and the next invocation will do it.
8081 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
8082 return autoremove_wake_function(curr, mode, wake_flags, key);
8086 static int io_run_task_work_sig(void)
8088 if (io_run_task_work())
8090 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8091 return -ERESTARTSYS;
8092 if (task_sigpending(current))
8097 /* when returns >0, the caller should retry */
8098 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8099 struct io_wait_queue *iowq,
8104 /* make sure we run task_work before checking for signals */
8105 ret = io_run_task_work_sig();
8106 if (ret || io_should_wake(iowq))
8108 /* let the caller flush overflows, retry */
8109 if (test_bit(0, &ctx->check_cq_overflow))
8112 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8117 #ifdef CONFIG_NET_RX_BUSY_POLL
8118 static void io_adjust_busy_loop_timeout(struct timespec64 *ts,
8119 struct io_wait_queue *iowq)
8121 unsigned busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8122 struct timespec64 pollto = ns_to_timespec64(1000 * (s64)busy_poll_to);
8124 if (timespec64_compare(ts, &pollto) > 0) {
8125 *ts = timespec64_sub(*ts, pollto);
8126 iowq->busy_poll_to = busy_poll_to;
8128 u64 to = timespec64_to_ns(ts);
8131 iowq->busy_poll_to = to;
8137 static inline bool io_busy_loop_timeout(unsigned long start_time,
8138 unsigned long bp_usec)
8141 unsigned long end_time = start_time + bp_usec;
8142 unsigned long now = busy_loop_current_time();
8144 return time_after(now, end_time);
8149 static bool io_busy_loop_end(void *p, unsigned long start_time)
8151 struct io_wait_queue *iowq = p;
8153 return signal_pending(current) ||
8154 io_should_wake(iowq) ||
8155 io_busy_loop_timeout(start_time, iowq->busy_poll_to);
8158 static void io_blocking_napi_busy_loop(struct list_head *napi_list,
8159 struct io_wait_queue *iowq)
8161 unsigned long start_time =
8162 list_is_singular(napi_list) ? 0 :
8163 busy_loop_current_time();
8166 if (list_is_singular(napi_list)) {
8167 struct napi_entry *ne =
8168 list_first_entry(napi_list,
8169 struct napi_entry, list);
8171 napi_busy_loop(ne->napi_id, io_busy_loop_end, iowq,
8172 true, BUSY_POLL_BUDGET);
8173 io_check_napi_entry_timeout(ne);
8176 } while (io_napi_busy_loop(napi_list) &&
8177 !io_busy_loop_end(iowq, start_time));
8180 static void io_putback_napi_list(struct io_ring_ctx *ctx,
8181 struct list_head *napi_list)
8183 struct napi_entry *cne, *lne;
8185 spin_lock(&ctx->napi_lock);
8186 list_for_each_entry(cne, &ctx->napi_list, list)
8187 list_for_each_entry(lne, napi_list, list)
8188 if (cne->napi_id == lne->napi_id) {
8189 list_del(&lne->list);
8193 list_splice(napi_list, &ctx->napi_list);
8194 spin_unlock(&ctx->napi_lock);
8196 #endif /* CONFIG_NET_RX_BUSY_POLL */
8199 * Wait until events become available, if we don't already have some. The
8200 * application must reap them itself, as they reside on the shared cq ring.
8202 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8203 const sigset_t __user *sig, size_t sigsz,
8204 struct __kernel_timespec __user *uts)
8206 struct io_wait_queue iowq;
8207 struct io_rings *rings = ctx->rings;
8208 ktime_t timeout = KTIME_MAX;
8210 #ifdef CONFIG_NET_RX_BUSY_POLL
8211 LIST_HEAD(local_napi_list);
8215 io_cqring_overflow_flush(ctx);
8216 if (io_cqring_events(ctx) >= min_events)
8218 if (!io_run_task_work())
8223 #ifdef CONFIG_COMPAT
8224 if (in_compat_syscall())
8225 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8229 ret = set_user_sigmask(sig, sigsz);
8235 #ifdef CONFIG_NET_RX_BUSY_POLL
8236 iowq.busy_poll_to = 0;
8237 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8238 spin_lock(&ctx->napi_lock);
8239 list_splice_init(&ctx->napi_list, &local_napi_list);
8240 spin_unlock(&ctx->napi_lock);
8244 struct timespec64 ts;
8246 if (get_timespec64(&ts, uts))
8248 #ifdef CONFIG_NET_RX_BUSY_POLL
8249 if (!list_empty(&local_napi_list))
8250 io_adjust_busy_loop_timeout(&ts, &iowq);
8252 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8254 #ifdef CONFIG_NET_RX_BUSY_POLL
8255 else if (!list_empty(&local_napi_list))
8256 iowq.busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8259 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8260 iowq.wq.private = current;
8261 INIT_LIST_HEAD(&iowq.wq.entry);
8263 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8264 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8266 trace_io_uring_cqring_wait(ctx, min_events);
8267 #ifdef CONFIG_NET_RX_BUSY_POLL
8268 if (iowq.busy_poll_to)
8269 io_blocking_napi_busy_loop(&local_napi_list, &iowq);
8270 if (!list_empty(&local_napi_list))
8271 io_putback_napi_list(ctx, &local_napi_list);
8274 /* if we can't even flush overflow, don't wait for more */
8275 if (!io_cqring_overflow_flush(ctx)) {
8279 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8280 TASK_INTERRUPTIBLE);
8281 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8282 finish_wait(&ctx->cq_wait, &iowq.wq);
8286 restore_saved_sigmask_unless(ret == -EINTR);
8288 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8291 static void io_free_page_table(void **table, size_t size)
8293 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8295 for (i = 0; i < nr_tables; i++)
8300 static __cold void **io_alloc_page_table(size_t size)
8302 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8303 size_t init_size = size;
8306 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
8310 for (i = 0; i < nr_tables; i++) {
8311 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
8313 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
8315 io_free_page_table(table, init_size);
8323 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
8325 percpu_ref_exit(&ref_node->refs);
8329 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
8331 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8332 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8333 unsigned long flags;
8334 bool first_add = false;
8335 unsigned long delay = HZ;
8337 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8340 /* if we are mid-quiesce then do not delay */
8341 if (node->rsrc_data->quiesce)
8344 while (!list_empty(&ctx->rsrc_ref_list)) {
8345 node = list_first_entry(&ctx->rsrc_ref_list,
8346 struct io_rsrc_node, node);
8347 /* recycle ref nodes in order */
8350 list_del(&node->node);
8351 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8353 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8356 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
8359 static struct io_rsrc_node *io_rsrc_node_alloc(void)
8361 struct io_rsrc_node *ref_node;
8363 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8367 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8372 INIT_LIST_HEAD(&ref_node->node);
8373 INIT_LIST_HEAD(&ref_node->rsrc_list);
8374 ref_node->done = false;
8378 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8379 struct io_rsrc_data *data_to_kill)
8380 __must_hold(&ctx->uring_lock)
8382 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8383 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
8385 io_rsrc_refs_drop(ctx);
8388 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
8390 rsrc_node->rsrc_data = data_to_kill;
8391 spin_lock_irq(&ctx->rsrc_ref_lock);
8392 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
8393 spin_unlock_irq(&ctx->rsrc_ref_lock);
8395 atomic_inc(&data_to_kill->refs);
8396 percpu_ref_kill(&rsrc_node->refs);
8397 ctx->rsrc_node = NULL;
8400 if (!ctx->rsrc_node) {
8401 ctx->rsrc_node = ctx->rsrc_backup_node;
8402 ctx->rsrc_backup_node = NULL;
8406 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8408 if (ctx->rsrc_backup_node)
8410 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8411 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8414 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8415 struct io_ring_ctx *ctx)
8419 /* As we may drop ->uring_lock, other task may have started quiesce */
8423 data->quiesce = true;
8425 ret = io_rsrc_node_switch_start(ctx);
8428 io_rsrc_node_switch(ctx, data);
8430 /* kill initial ref, already quiesced if zero */
8431 if (atomic_dec_and_test(&data->refs))
8433 mutex_unlock(&ctx->uring_lock);
8434 flush_delayed_work(&ctx->rsrc_put_work);
8435 ret = wait_for_completion_interruptible(&data->done);
8437 mutex_lock(&ctx->uring_lock);
8438 if (atomic_read(&data->refs) > 0) {
8440 * it has been revived by another thread while
8443 mutex_unlock(&ctx->uring_lock);
8449 atomic_inc(&data->refs);
8450 /* wait for all works potentially completing data->done */
8451 flush_delayed_work(&ctx->rsrc_put_work);
8452 reinit_completion(&data->done);
8454 ret = io_run_task_work_sig();
8455 mutex_lock(&ctx->uring_lock);
8457 data->quiesce = false;
8462 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8464 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8465 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8467 return &data->tags[table_idx][off];
8470 static void io_rsrc_data_free(struct io_rsrc_data *data)
8472 size_t size = data->nr * sizeof(data->tags[0][0]);
8475 io_free_page_table((void **)data->tags, size);
8479 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8480 u64 __user *utags, unsigned nr,
8481 struct io_rsrc_data **pdata)
8483 struct io_rsrc_data *data;
8487 data = kzalloc(sizeof(*data), GFP_KERNEL);
8490 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
8498 data->do_put = do_put;
8501 for (i = 0; i < nr; i++) {
8502 u64 *tag_slot = io_get_tag_slot(data, i);
8504 if (copy_from_user(tag_slot, &utags[i],
8510 atomic_set(&data->refs, 1);
8511 init_completion(&data->done);
8515 io_rsrc_data_free(data);
8519 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8521 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8522 GFP_KERNEL_ACCOUNT);
8523 return !!table->files;
8526 static void io_free_file_tables(struct io_file_table *table)
8528 kvfree(table->files);
8529 table->files = NULL;
8532 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
8534 #if defined(CONFIG_UNIX)
8535 if (ctx->ring_sock) {
8536 struct sock *sock = ctx->ring_sock->sk;
8537 struct sk_buff *skb;
8539 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8545 for (i = 0; i < ctx->nr_user_files; i++) {
8548 file = io_file_from_index(ctx, i);
8553 io_free_file_tables(&ctx->file_table);
8554 io_rsrc_data_free(ctx->file_data);
8555 ctx->file_data = NULL;
8556 ctx->nr_user_files = 0;
8559 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8563 if (!ctx->file_data)
8565 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8567 __io_sqe_files_unregister(ctx);
8571 static void io_sq_thread_unpark(struct io_sq_data *sqd)
8572 __releases(&sqd->lock)
8574 WARN_ON_ONCE(sqd->thread == current);
8577 * Do the dance but not conditional clear_bit() because it'd race with
8578 * other threads incrementing park_pending and setting the bit.
8580 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8581 if (atomic_dec_return(&sqd->park_pending))
8582 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8583 mutex_unlock(&sqd->lock);
8586 static void io_sq_thread_park(struct io_sq_data *sqd)
8587 __acquires(&sqd->lock)
8589 WARN_ON_ONCE(sqd->thread == current);
8591 atomic_inc(&sqd->park_pending);
8592 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
8593 mutex_lock(&sqd->lock);
8595 wake_up_process(sqd->thread);
8598 static void io_sq_thread_stop(struct io_sq_data *sqd)
8600 WARN_ON_ONCE(sqd->thread == current);
8601 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
8603 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8604 mutex_lock(&sqd->lock);
8606 wake_up_process(sqd->thread);
8607 mutex_unlock(&sqd->lock);
8608 wait_for_completion(&sqd->exited);
8611 static void io_put_sq_data(struct io_sq_data *sqd)
8613 if (refcount_dec_and_test(&sqd->refs)) {
8614 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8616 io_sq_thread_stop(sqd);
8621 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8623 struct io_sq_data *sqd = ctx->sq_data;
8626 io_sq_thread_park(sqd);
8627 list_del_init(&ctx->sqd_list);
8628 io_sqd_update_thread_idle(sqd);
8629 io_sq_thread_unpark(sqd);
8631 io_put_sq_data(sqd);
8632 ctx->sq_data = NULL;
8636 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8638 struct io_ring_ctx *ctx_attach;
8639 struct io_sq_data *sqd;
8642 f = fdget(p->wq_fd);
8644 return ERR_PTR(-ENXIO);
8645 if (f.file->f_op != &io_uring_fops) {
8647 return ERR_PTR(-EINVAL);
8650 ctx_attach = f.file->private_data;
8651 sqd = ctx_attach->sq_data;
8654 return ERR_PTR(-EINVAL);
8656 if (sqd->task_tgid != current->tgid) {
8658 return ERR_PTR(-EPERM);
8661 refcount_inc(&sqd->refs);
8666 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8669 struct io_sq_data *sqd;
8672 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8673 sqd = io_attach_sq_data(p);
8678 /* fall through for EPERM case, setup new sqd/task */
8679 if (PTR_ERR(sqd) != -EPERM)
8683 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8685 return ERR_PTR(-ENOMEM);
8687 atomic_set(&sqd->park_pending, 0);
8688 refcount_set(&sqd->refs, 1);
8689 INIT_LIST_HEAD(&sqd->ctx_list);
8690 mutex_init(&sqd->lock);
8691 init_waitqueue_head(&sqd->wait);
8692 init_completion(&sqd->exited);
8696 #if defined(CONFIG_UNIX)
8698 * Ensure the UNIX gc is aware of our file set, so we are certain that
8699 * the io_uring can be safely unregistered on process exit, even if we have
8700 * loops in the file referencing.
8702 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8704 struct sock *sk = ctx->ring_sock->sk;
8705 struct scm_fp_list *fpl;
8706 struct sk_buff *skb;
8709 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8713 skb = alloc_skb(0, GFP_KERNEL);
8722 fpl->user = get_uid(current_user());
8723 for (i = 0; i < nr; i++) {
8724 struct file *file = io_file_from_index(ctx, i + offset);
8728 fpl->fp[nr_files] = get_file(file);
8729 unix_inflight(fpl->user, fpl->fp[nr_files]);
8734 fpl->max = SCM_MAX_FD;
8735 fpl->count = nr_files;
8736 UNIXCB(skb).fp = fpl;
8737 skb->destructor = unix_destruct_scm;
8738 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8739 skb_queue_head(&sk->sk_receive_queue, skb);
8741 for (i = 0; i < nr_files; i++)
8752 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8753 * causes regular reference counting to break down. We rely on the UNIX
8754 * garbage collection to take care of this problem for us.
8756 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8758 unsigned left, total;
8762 left = ctx->nr_user_files;
8764 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8766 ret = __io_sqe_files_scm(ctx, this_files, total);
8770 total += this_files;
8776 while (total < ctx->nr_user_files) {
8777 struct file *file = io_file_from_index(ctx, total);
8787 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8793 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8795 struct file *file = prsrc->file;
8796 #if defined(CONFIG_UNIX)
8797 struct sock *sock = ctx->ring_sock->sk;
8798 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8799 struct sk_buff *skb;
8802 __skb_queue_head_init(&list);
8805 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8806 * remove this entry and rearrange the file array.
8808 skb = skb_dequeue(head);
8810 struct scm_fp_list *fp;
8812 fp = UNIXCB(skb).fp;
8813 for (i = 0; i < fp->count; i++) {
8816 if (fp->fp[i] != file)
8819 unix_notinflight(fp->user, fp->fp[i]);
8820 left = fp->count - 1 - i;
8822 memmove(&fp->fp[i], &fp->fp[i + 1],
8823 left * sizeof(struct file *));
8830 __skb_queue_tail(&list, skb);
8840 __skb_queue_tail(&list, skb);
8842 skb = skb_dequeue(head);
8845 if (skb_peek(&list)) {
8846 spin_lock_irq(&head->lock);
8847 while ((skb = __skb_dequeue(&list)) != NULL)
8848 __skb_queue_tail(head, skb);
8849 spin_unlock_irq(&head->lock);
8856 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8858 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8859 struct io_ring_ctx *ctx = rsrc_data->ctx;
8860 struct io_rsrc_put *prsrc, *tmp;
8862 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8863 list_del(&prsrc->list);
8866 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8868 io_ring_submit_lock(ctx, lock_ring);
8869 spin_lock(&ctx->completion_lock);
8870 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8871 io_commit_cqring(ctx);
8872 spin_unlock(&ctx->completion_lock);
8873 io_cqring_ev_posted(ctx);
8874 io_ring_submit_unlock(ctx, lock_ring);
8877 rsrc_data->do_put(ctx, prsrc);
8881 io_rsrc_node_destroy(ref_node);
8882 if (atomic_dec_and_test(&rsrc_data->refs))
8883 complete(&rsrc_data->done);
8886 static void io_rsrc_put_work(struct work_struct *work)
8888 struct io_ring_ctx *ctx;
8889 struct llist_node *node;
8891 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8892 node = llist_del_all(&ctx->rsrc_put_llist);
8895 struct io_rsrc_node *ref_node;
8896 struct llist_node *next = node->next;
8898 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8899 __io_rsrc_put_work(ref_node);
8904 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8905 unsigned nr_args, u64 __user *tags)
8907 __s32 __user *fds = (__s32 __user *) arg;
8916 if (nr_args > IORING_MAX_FIXED_FILES)
8918 if (nr_args > rlimit(RLIMIT_NOFILE))
8920 ret = io_rsrc_node_switch_start(ctx);
8923 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8929 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8932 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8933 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8937 /* allow sparse sets */
8940 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8947 if (unlikely(!file))
8951 * Don't allow io_uring instances to be registered. If UNIX
8952 * isn't enabled, then this causes a reference cycle and this
8953 * instance can never get freed. If UNIX is enabled we'll
8954 * handle it just fine, but there's still no point in allowing
8955 * a ring fd as it doesn't support regular read/write anyway.
8957 if (file->f_op == &io_uring_fops) {
8961 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8964 ret = io_sqe_files_scm(ctx);
8966 __io_sqe_files_unregister(ctx);
8970 io_rsrc_node_switch(ctx, NULL);
8973 for (i = 0; i < ctx->nr_user_files; i++) {
8974 file = io_file_from_index(ctx, i);
8978 io_free_file_tables(&ctx->file_table);
8979 ctx->nr_user_files = 0;
8981 io_rsrc_data_free(ctx->file_data);
8982 ctx->file_data = NULL;
8986 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8989 #if defined(CONFIG_UNIX)
8990 struct sock *sock = ctx->ring_sock->sk;
8991 struct sk_buff_head *head = &sock->sk_receive_queue;
8992 struct sk_buff *skb;
8995 * See if we can merge this file into an existing skb SCM_RIGHTS
8996 * file set. If there's no room, fall back to allocating a new skb
8997 * and filling it in.
8999 spin_lock_irq(&head->lock);
9000 skb = skb_peek(head);
9002 struct scm_fp_list *fpl = UNIXCB(skb).fp;
9004 if (fpl->count < SCM_MAX_FD) {
9005 __skb_unlink(skb, head);
9006 spin_unlock_irq(&head->lock);
9007 fpl->fp[fpl->count] = get_file(file);
9008 unix_inflight(fpl->user, fpl->fp[fpl->count]);
9010 spin_lock_irq(&head->lock);
9011 __skb_queue_head(head, skb);
9016 spin_unlock_irq(&head->lock);
9023 return __io_sqe_files_scm(ctx, 1, index);
9029 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9030 struct io_rsrc_node *node, void *rsrc)
9032 struct io_rsrc_put *prsrc;
9034 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9038 prsrc->tag = *io_get_tag_slot(data, idx);
9040 list_add(&prsrc->list, &node->rsrc_list);
9044 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9045 unsigned int issue_flags, u32 slot_index)
9047 struct io_ring_ctx *ctx = req->ctx;
9048 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9049 bool needs_switch = false;
9050 struct io_fixed_file *file_slot;
9053 io_ring_submit_lock(ctx, needs_lock);
9054 if (file->f_op == &io_uring_fops)
9057 if (!ctx->file_data)
9060 if (slot_index >= ctx->nr_user_files)
9063 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9064 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9066 if (file_slot->file_ptr) {
9067 struct file *old_file;
9069 ret = io_rsrc_node_switch_start(ctx);
9073 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9074 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9075 ctx->rsrc_node, old_file);
9078 file_slot->file_ptr = 0;
9079 needs_switch = true;
9082 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9083 io_fixed_file_set(file_slot, file);
9084 ret = io_sqe_file_register(ctx, file, slot_index);
9086 file_slot->file_ptr = 0;
9093 io_rsrc_node_switch(ctx, ctx->file_data);
9094 io_ring_submit_unlock(ctx, needs_lock);
9100 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9102 unsigned int offset = req->close.file_slot - 1;
9103 struct io_ring_ctx *ctx = req->ctx;
9104 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9105 struct io_fixed_file *file_slot;
9109 io_ring_submit_lock(ctx, needs_lock);
9111 if (unlikely(!ctx->file_data))
9114 if (offset >= ctx->nr_user_files)
9116 ret = io_rsrc_node_switch_start(ctx);
9120 i = array_index_nospec(offset, ctx->nr_user_files);
9121 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9123 if (!file_slot->file_ptr)
9126 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9127 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9131 file_slot->file_ptr = 0;
9132 io_rsrc_node_switch(ctx, ctx->file_data);
9135 io_ring_submit_unlock(ctx, needs_lock);
9139 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9140 struct io_uring_rsrc_update2 *up,
9143 u64 __user *tags = u64_to_user_ptr(up->tags);
9144 __s32 __user *fds = u64_to_user_ptr(up->data);
9145 struct io_rsrc_data *data = ctx->file_data;
9146 struct io_fixed_file *file_slot;
9150 bool needs_switch = false;
9152 if (!ctx->file_data)
9154 if (up->offset + nr_args > ctx->nr_user_files)
9157 for (done = 0; done < nr_args; done++) {
9160 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9161 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9165 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9169 if (fd == IORING_REGISTER_FILES_SKIP)
9172 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9173 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9175 if (file_slot->file_ptr) {
9176 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9177 err = io_queue_rsrc_removal(data, up->offset + done,
9178 ctx->rsrc_node, file);
9181 file_slot->file_ptr = 0;
9182 needs_switch = true;
9191 * Don't allow io_uring instances to be registered. If
9192 * UNIX isn't enabled, then this causes a reference
9193 * cycle and this instance can never get freed. If UNIX
9194 * is enabled we'll handle it just fine, but there's
9195 * still no point in allowing a ring fd as it doesn't
9196 * support regular read/write anyway.
9198 if (file->f_op == &io_uring_fops) {
9203 *io_get_tag_slot(data, up->offset + done) = tag;
9204 io_fixed_file_set(file_slot, file);
9205 err = io_sqe_file_register(ctx, file, i);
9207 file_slot->file_ptr = 0;
9215 io_rsrc_node_switch(ctx, data);
9216 return done ? done : err;
9219 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9220 struct task_struct *task)
9222 struct io_wq_hash *hash;
9223 struct io_wq_data data;
9224 unsigned int concurrency;
9226 mutex_lock(&ctx->uring_lock);
9227 hash = ctx->hash_map;
9229 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9231 mutex_unlock(&ctx->uring_lock);
9232 return ERR_PTR(-ENOMEM);
9234 refcount_set(&hash->refs, 1);
9235 init_waitqueue_head(&hash->wait);
9236 ctx->hash_map = hash;
9238 mutex_unlock(&ctx->uring_lock);
9242 data.free_work = io_wq_free_work;
9243 data.do_work = io_wq_submit_work;
9245 /* Do QD, or 4 * CPUS, whatever is smallest */
9246 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9248 return io_wq_create(concurrency, &data);
9251 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9252 struct io_ring_ctx *ctx)
9254 struct io_uring_task *tctx;
9257 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9258 if (unlikely(!tctx))
9261 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9262 sizeof(struct file *), GFP_KERNEL);
9263 if (unlikely(!tctx->registered_rings)) {
9268 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9269 if (unlikely(ret)) {
9270 kfree(tctx->registered_rings);
9275 tctx->io_wq = io_init_wq_offload(ctx, task);
9276 if (IS_ERR(tctx->io_wq)) {
9277 ret = PTR_ERR(tctx->io_wq);
9278 percpu_counter_destroy(&tctx->inflight);
9279 kfree(tctx->registered_rings);
9285 init_waitqueue_head(&tctx->wait);
9286 atomic_set(&tctx->in_idle, 0);
9287 atomic_set(&tctx->inflight_tracked, 0);
9288 task->io_uring = tctx;
9289 spin_lock_init(&tctx->task_lock);
9290 INIT_WQ_LIST(&tctx->task_list);
9291 INIT_WQ_LIST(&tctx->prior_task_list);
9292 init_task_work(&tctx->task_work, tctx_task_work);
9296 void __io_uring_free(struct task_struct *tsk)
9298 struct io_uring_task *tctx = tsk->io_uring;
9300 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9301 WARN_ON_ONCE(tctx->io_wq);
9302 WARN_ON_ONCE(tctx->cached_refs);
9304 kfree(tctx->registered_rings);
9305 percpu_counter_destroy(&tctx->inflight);
9307 tsk->io_uring = NULL;
9310 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9311 struct io_uring_params *p)
9315 /* Retain compatibility with failing for an invalid attach attempt */
9316 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9317 IORING_SETUP_ATTACH_WQ) {
9320 f = fdget(p->wq_fd);
9323 if (f.file->f_op != &io_uring_fops) {
9329 if (ctx->flags & IORING_SETUP_SQPOLL) {
9330 struct task_struct *tsk;
9331 struct io_sq_data *sqd;
9334 ret = security_uring_sqpoll();
9338 sqd = io_get_sq_data(p, &attached);
9344 ctx->sq_creds = get_current_cred();
9346 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9347 if (!ctx->sq_thread_idle)
9348 ctx->sq_thread_idle = HZ;
9350 io_sq_thread_park(sqd);
9351 list_add(&ctx->sqd_list, &sqd->ctx_list);
9352 io_sqd_update_thread_idle(sqd);
9353 /* don't attach to a dying SQPOLL thread, would be racy */
9354 ret = (attached && !sqd->thread) ? -ENXIO : 0;
9355 io_sq_thread_unpark(sqd);
9362 if (p->flags & IORING_SETUP_SQ_AFF) {
9363 int cpu = p->sq_thread_cpu;
9366 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
9373 sqd->task_pid = current->pid;
9374 sqd->task_tgid = current->tgid;
9375 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9382 ret = io_uring_alloc_task_context(tsk, ctx);
9383 wake_up_new_task(tsk);
9386 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9387 /* Can't have SQ_AFF without SQPOLL */
9394 complete(&ctx->sq_data->exited);
9396 io_sq_thread_finish(ctx);
9400 static inline void __io_unaccount_mem(struct user_struct *user,
9401 unsigned long nr_pages)
9403 atomic_long_sub(nr_pages, &user->locked_vm);
9406 static inline int __io_account_mem(struct user_struct *user,
9407 unsigned long nr_pages)
9409 unsigned long page_limit, cur_pages, new_pages;
9411 /* Don't allow more pages than we can safely lock */
9412 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9415 cur_pages = atomic_long_read(&user->locked_vm);
9416 new_pages = cur_pages + nr_pages;
9417 if (new_pages > page_limit)
9419 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9420 new_pages) != cur_pages);
9425 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9428 __io_unaccount_mem(ctx->user, nr_pages);
9430 if (ctx->mm_account)
9431 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
9434 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
9439 ret = __io_account_mem(ctx->user, nr_pages);
9444 if (ctx->mm_account)
9445 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
9450 static void io_mem_free(void *ptr)
9457 page = virt_to_head_page(ptr);
9458 if (put_page_testzero(page))
9459 free_compound_page(page);
9462 static void *io_mem_alloc(size_t size)
9464 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
9466 return (void *) __get_free_pages(gfp, get_order(size));
9469 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9472 struct io_rings *rings;
9473 size_t off, sq_array_size;
9475 off = struct_size(rings, cqes, cq_entries);
9476 if (off == SIZE_MAX)
9480 off = ALIGN(off, SMP_CACHE_BYTES);
9488 sq_array_size = array_size(sizeof(u32), sq_entries);
9489 if (sq_array_size == SIZE_MAX)
9492 if (check_add_overflow(off, sq_array_size, &off))
9498 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
9500 struct io_mapped_ubuf *imu = *slot;
9503 if (imu != ctx->dummy_ubuf) {
9504 for (i = 0; i < imu->nr_bvecs; i++)
9505 unpin_user_page(imu->bvec[i].bv_page);
9506 if (imu->acct_pages)
9507 io_unaccount_mem(ctx, imu->acct_pages);
9513 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9515 io_buffer_unmap(ctx, &prsrc->buf);
9519 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9523 for (i = 0; i < ctx->nr_user_bufs; i++)
9524 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
9525 kfree(ctx->user_bufs);
9526 io_rsrc_data_free(ctx->buf_data);
9527 ctx->user_bufs = NULL;
9528 ctx->buf_data = NULL;
9529 ctx->nr_user_bufs = 0;
9532 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9539 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9541 __io_sqe_buffers_unregister(ctx);
9545 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9546 void __user *arg, unsigned index)
9548 struct iovec __user *src;
9550 #ifdef CONFIG_COMPAT
9552 struct compat_iovec __user *ciovs;
9553 struct compat_iovec ciov;
9555 ciovs = (struct compat_iovec __user *) arg;
9556 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9559 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
9560 dst->iov_len = ciov.iov_len;
9564 src = (struct iovec __user *) arg;
9565 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9571 * Not super efficient, but this is just a registration time. And we do cache
9572 * the last compound head, so generally we'll only do a full search if we don't
9575 * We check if the given compound head page has already been accounted, to
9576 * avoid double accounting it. This allows us to account the full size of the
9577 * page, not just the constituent pages of a huge page.
9579 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9580 int nr_pages, struct page *hpage)
9584 /* check current page array */
9585 for (i = 0; i < nr_pages; i++) {
9586 if (!PageCompound(pages[i]))
9588 if (compound_head(pages[i]) == hpage)
9592 /* check previously registered pages */
9593 for (i = 0; i < ctx->nr_user_bufs; i++) {
9594 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
9596 for (j = 0; j < imu->nr_bvecs; j++) {
9597 if (!PageCompound(imu->bvec[j].bv_page))
9599 if (compound_head(imu->bvec[j].bv_page) == hpage)
9607 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9608 int nr_pages, struct io_mapped_ubuf *imu,
9609 struct page **last_hpage)
9613 imu->acct_pages = 0;
9614 for (i = 0; i < nr_pages; i++) {
9615 if (!PageCompound(pages[i])) {
9620 hpage = compound_head(pages[i]);
9621 if (hpage == *last_hpage)
9623 *last_hpage = hpage;
9624 if (headpage_already_acct(ctx, pages, i, hpage))
9626 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9630 if (!imu->acct_pages)
9633 ret = io_account_mem(ctx, imu->acct_pages);
9635 imu->acct_pages = 0;
9639 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
9640 struct io_mapped_ubuf **pimu,
9641 struct page **last_hpage)
9643 struct io_mapped_ubuf *imu = NULL;
9644 struct vm_area_struct **vmas = NULL;
9645 struct page **pages = NULL;
9646 unsigned long off, start, end, ubuf;
9648 int ret, pret, nr_pages, i;
9650 if (!iov->iov_base) {
9651 *pimu = ctx->dummy_ubuf;
9655 ubuf = (unsigned long) iov->iov_base;
9656 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9657 start = ubuf >> PAGE_SHIFT;
9658 nr_pages = end - start;
9663 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9667 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9672 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
9677 mmap_read_lock(current->mm);
9678 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9680 if (pret == nr_pages) {
9681 /* don't support file backed memory */
9682 for (i = 0; i < nr_pages; i++) {
9683 struct vm_area_struct *vma = vmas[i];
9685 if (vma_is_shmem(vma))
9688 !is_file_hugepages(vma->vm_file)) {
9694 ret = pret < 0 ? pret : -EFAULT;
9696 mmap_read_unlock(current->mm);
9699 * if we did partial map, or found file backed vmas,
9700 * release any pages we did get
9703 unpin_user_pages(pages, pret);
9707 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9709 unpin_user_pages(pages, pret);
9713 off = ubuf & ~PAGE_MASK;
9714 size = iov->iov_len;
9715 for (i = 0; i < nr_pages; i++) {
9718 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9719 imu->bvec[i].bv_page = pages[i];
9720 imu->bvec[i].bv_len = vec_len;
9721 imu->bvec[i].bv_offset = off;
9725 /* store original address for later verification */
9727 imu->ubuf_end = ubuf + iov->iov_len;
9728 imu->nr_bvecs = nr_pages;
9739 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9741 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9742 return ctx->user_bufs ? 0 : -ENOMEM;
9745 static int io_buffer_validate(struct iovec *iov)
9747 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9750 * Don't impose further limits on the size and buffer
9751 * constraints here, we'll -EINVAL later when IO is
9752 * submitted if they are wrong.
9755 return iov->iov_len ? -EFAULT : 0;
9759 /* arbitrary limit, but we need something */
9760 if (iov->iov_len > SZ_1G)
9763 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9769 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9770 unsigned int nr_args, u64 __user *tags)
9772 struct page *last_hpage = NULL;
9773 struct io_rsrc_data *data;
9779 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9781 ret = io_rsrc_node_switch_start(ctx);
9784 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9787 ret = io_buffers_map_alloc(ctx, nr_args);
9789 io_rsrc_data_free(data);
9793 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9794 ret = io_copy_iov(ctx, &iov, arg, i);
9797 ret = io_buffer_validate(&iov);
9800 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9805 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9811 WARN_ON_ONCE(ctx->buf_data);
9813 ctx->buf_data = data;
9815 __io_sqe_buffers_unregister(ctx);
9817 io_rsrc_node_switch(ctx, NULL);
9821 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9822 struct io_uring_rsrc_update2 *up,
9823 unsigned int nr_args)
9825 u64 __user *tags = u64_to_user_ptr(up->tags);
9826 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9827 struct page *last_hpage = NULL;
9828 bool needs_switch = false;
9834 if (up->offset + nr_args > ctx->nr_user_bufs)
9837 for (done = 0; done < nr_args; done++) {
9838 struct io_mapped_ubuf *imu;
9839 int offset = up->offset + done;
9842 err = io_copy_iov(ctx, &iov, iovs, done);
9845 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9849 err = io_buffer_validate(&iov);
9852 if (!iov.iov_base && tag) {
9856 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9860 i = array_index_nospec(offset, ctx->nr_user_bufs);
9861 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9862 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9863 ctx->rsrc_node, ctx->user_bufs[i]);
9864 if (unlikely(err)) {
9865 io_buffer_unmap(ctx, &imu);
9868 ctx->user_bufs[i] = NULL;
9869 needs_switch = true;
9872 ctx->user_bufs[i] = imu;
9873 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9877 io_rsrc_node_switch(ctx, ctx->buf_data);
9878 return done ? done : err;
9881 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9882 unsigned int eventfd_async)
9884 struct io_ev_fd *ev_fd;
9885 __s32 __user *fds = arg;
9888 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9889 lockdep_is_held(&ctx->uring_lock));
9893 if (copy_from_user(&fd, fds, sizeof(*fds)))
9896 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9900 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9901 if (IS_ERR(ev_fd->cq_ev_fd)) {
9902 int ret = PTR_ERR(ev_fd->cq_ev_fd);
9906 ev_fd->eventfd_async = eventfd_async;
9908 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
9912 static void io_eventfd_put(struct rcu_head *rcu)
9914 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9916 eventfd_ctx_put(ev_fd->cq_ev_fd);
9920 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9922 struct io_ev_fd *ev_fd;
9924 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9925 lockdep_is_held(&ctx->uring_lock));
9927 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9928 call_rcu(&ev_fd->rcu, io_eventfd_put);
9935 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9937 struct io_buffer *buf;
9938 unsigned long index;
9940 xa_for_each(&ctx->io_buffers, index, buf)
9941 __io_remove_buffers(ctx, buf, index, -1U);
9943 while (!list_empty(&ctx->io_buffers_pages)) {
9946 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9947 list_del_init(&page->lru);
9952 static void io_req_caches_free(struct io_ring_ctx *ctx)
9954 struct io_submit_state *state = &ctx->submit_state;
9957 mutex_lock(&ctx->uring_lock);
9958 io_flush_cached_locked_reqs(ctx, state);
9960 while (state->free_list.next) {
9961 struct io_wq_work_node *node;
9962 struct io_kiocb *req;
9964 node = wq_stack_extract(&state->free_list);
9965 req = container_of(node, struct io_kiocb, comp_list);
9966 kmem_cache_free(req_cachep, req);
9970 percpu_ref_put_many(&ctx->refs, nr);
9971 mutex_unlock(&ctx->uring_lock);
9974 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9976 if (data && !atomic_dec_and_test(&data->refs))
9977 wait_for_completion(&data->done);
9980 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
9982 struct async_poll *apoll;
9984 while (!list_empty(&ctx->apoll_cache)) {
9985 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
9987 list_del(&apoll->poll.wait.entry);
9992 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
9994 io_sq_thread_finish(ctx);
9996 if (ctx->mm_account) {
9997 mmdrop(ctx->mm_account);
9998 ctx->mm_account = NULL;
10001 io_rsrc_refs_drop(ctx);
10002 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10003 io_wait_rsrc_data(ctx->buf_data);
10004 io_wait_rsrc_data(ctx->file_data);
10006 mutex_lock(&ctx->uring_lock);
10008 __io_sqe_buffers_unregister(ctx);
10009 if (ctx->file_data)
10010 __io_sqe_files_unregister(ctx);
10012 __io_cqring_overflow_flush(ctx, true);
10013 io_eventfd_unregister(ctx);
10014 io_flush_apoll_cache(ctx);
10015 mutex_unlock(&ctx->uring_lock);
10016 io_destroy_buffers(ctx);
10018 put_cred(ctx->sq_creds);
10020 /* there are no registered resources left, nobody uses it */
10021 if (ctx->rsrc_node)
10022 io_rsrc_node_destroy(ctx->rsrc_node);
10023 if (ctx->rsrc_backup_node)
10024 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10025 flush_delayed_work(&ctx->rsrc_put_work);
10026 flush_delayed_work(&ctx->fallback_work);
10028 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10029 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10031 #if defined(CONFIG_UNIX)
10032 if (ctx->ring_sock) {
10033 ctx->ring_sock->file = NULL; /* so that iput() is called */
10034 sock_release(ctx->ring_sock);
10037 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10039 io_mem_free(ctx->rings);
10040 io_mem_free(ctx->sq_sqes);
10042 percpu_ref_exit(&ctx->refs);
10043 free_uid(ctx->user);
10044 io_req_caches_free(ctx);
10046 io_wq_put_hash(ctx->hash_map);
10047 io_free_napi_list(ctx);
10048 kfree(ctx->cancel_hash);
10049 kfree(ctx->dummy_ubuf);
10053 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10055 struct io_ring_ctx *ctx = file->private_data;
10058 poll_wait(file, &ctx->cq_wait, wait);
10060 * synchronizes with barrier from wq_has_sleeper call in
10064 if (!io_sqring_full(ctx))
10065 mask |= EPOLLOUT | EPOLLWRNORM;
10068 * Don't flush cqring overflow list here, just do a simple check.
10069 * Otherwise there could possible be ABBA deadlock:
10072 * lock(&ctx->uring_lock);
10074 * lock(&ctx->uring_lock);
10077 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10078 * pushs them to do the flush.
10080 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
10081 mask |= EPOLLIN | EPOLLRDNORM;
10086 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10088 const struct cred *creds;
10090 creds = xa_erase(&ctx->personalities, id);
10099 struct io_tctx_exit {
10100 struct callback_head task_work;
10101 struct completion completion;
10102 struct io_ring_ctx *ctx;
10105 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10107 struct io_uring_task *tctx = current->io_uring;
10108 struct io_tctx_exit *work;
10110 work = container_of(cb, struct io_tctx_exit, task_work);
10112 * When @in_idle, we're in cancellation and it's racy to remove the
10113 * node. It'll be removed by the end of cancellation, just ignore it.
10115 if (!atomic_read(&tctx->in_idle))
10116 io_uring_del_tctx_node((unsigned long)work->ctx);
10117 complete(&work->completion);
10120 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10122 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10124 return req->ctx == data;
10127 static __cold void io_ring_exit_work(struct work_struct *work)
10129 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10130 unsigned long timeout = jiffies + HZ * 60 * 5;
10131 unsigned long interval = HZ / 20;
10132 struct io_tctx_exit exit;
10133 struct io_tctx_node *node;
10137 * If we're doing polled IO and end up having requests being
10138 * submitted async (out-of-line), then completions can come in while
10139 * we're waiting for refs to drop. We need to reap these manually,
10140 * as nobody else will be looking for them.
10143 io_uring_try_cancel_requests(ctx, NULL, true);
10144 if (ctx->sq_data) {
10145 struct io_sq_data *sqd = ctx->sq_data;
10146 struct task_struct *tsk;
10148 io_sq_thread_park(sqd);
10150 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10151 io_wq_cancel_cb(tsk->io_uring->io_wq,
10152 io_cancel_ctx_cb, ctx, true);
10153 io_sq_thread_unpark(sqd);
10156 io_req_caches_free(ctx);
10158 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10159 /* there is little hope left, don't run it too often */
10160 interval = HZ * 60;
10162 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10164 init_completion(&exit.completion);
10165 init_task_work(&exit.task_work, io_tctx_exit_cb);
10168 * Some may use context even when all refs and requests have been put,
10169 * and they are free to do so while still holding uring_lock or
10170 * completion_lock, see io_req_task_submit(). Apart from other work,
10171 * this lock/unlock section also waits them to finish.
10173 mutex_lock(&ctx->uring_lock);
10174 while (!list_empty(&ctx->tctx_list)) {
10175 WARN_ON_ONCE(time_after(jiffies, timeout));
10177 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10179 /* don't spin on a single task if cancellation failed */
10180 list_rotate_left(&ctx->tctx_list);
10181 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10182 if (WARN_ON_ONCE(ret))
10185 mutex_unlock(&ctx->uring_lock);
10186 wait_for_completion(&exit.completion);
10187 mutex_lock(&ctx->uring_lock);
10189 mutex_unlock(&ctx->uring_lock);
10190 spin_lock(&ctx->completion_lock);
10191 spin_unlock(&ctx->completion_lock);
10193 io_ring_ctx_free(ctx);
10196 /* Returns true if we found and killed one or more timeouts */
10197 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10198 struct task_struct *tsk, bool cancel_all)
10200 struct io_kiocb *req, *tmp;
10203 spin_lock(&ctx->completion_lock);
10204 spin_lock_irq(&ctx->timeout_lock);
10205 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10206 if (io_match_task(req, tsk, cancel_all)) {
10207 io_kill_timeout(req, -ECANCELED);
10211 spin_unlock_irq(&ctx->timeout_lock);
10213 io_commit_cqring(ctx);
10214 spin_unlock(&ctx->completion_lock);
10216 io_cqring_ev_posted(ctx);
10217 return canceled != 0;
10220 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10222 unsigned long index;
10223 struct creds *creds;
10225 mutex_lock(&ctx->uring_lock);
10226 percpu_ref_kill(&ctx->refs);
10228 __io_cqring_overflow_flush(ctx, true);
10229 xa_for_each(&ctx->personalities, index, creds)
10230 io_unregister_personality(ctx, index);
10231 mutex_unlock(&ctx->uring_lock);
10233 io_kill_timeouts(ctx, NULL, true);
10234 io_poll_remove_all(ctx, NULL, true);
10236 /* if we failed setting up the ctx, we might not have any rings */
10237 io_iopoll_try_reap_events(ctx);
10239 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10241 * Use system_unbound_wq to avoid spawning tons of event kworkers
10242 * if we're exiting a ton of rings at the same time. It just adds
10243 * noise and overhead, there's no discernable change in runtime
10244 * over using system_wq.
10246 queue_work(system_unbound_wq, &ctx->exit_work);
10249 static int io_uring_release(struct inode *inode, struct file *file)
10251 struct io_ring_ctx *ctx = file->private_data;
10253 file->private_data = NULL;
10254 io_ring_ctx_wait_and_kill(ctx);
10258 struct io_task_cancel {
10259 struct task_struct *task;
10263 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10265 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10266 struct io_task_cancel *cancel = data;
10268 return io_match_task_safe(req, cancel->task, cancel->all);
10271 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10272 struct task_struct *task,
10275 struct io_defer_entry *de;
10278 spin_lock(&ctx->completion_lock);
10279 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10280 if (io_match_task_safe(de->req, task, cancel_all)) {
10281 list_cut_position(&list, &ctx->defer_list, &de->list);
10285 spin_unlock(&ctx->completion_lock);
10286 if (list_empty(&list))
10289 while (!list_empty(&list)) {
10290 de = list_first_entry(&list, struct io_defer_entry, list);
10291 list_del_init(&de->list);
10292 io_req_complete_failed(de->req, -ECANCELED);
10298 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
10300 struct io_tctx_node *node;
10301 enum io_wq_cancel cret;
10304 mutex_lock(&ctx->uring_lock);
10305 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10306 struct io_uring_task *tctx = node->task->io_uring;
10309 * io_wq will stay alive while we hold uring_lock, because it's
10310 * killed after ctx nodes, which requires to take the lock.
10312 if (!tctx || !tctx->io_wq)
10314 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10315 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10317 mutex_unlock(&ctx->uring_lock);
10322 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10323 struct task_struct *task,
10326 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
10327 struct io_uring_task *tctx = task ? task->io_uring : NULL;
10330 enum io_wq_cancel cret;
10334 ret |= io_uring_try_cancel_iowq(ctx);
10335 } else if (tctx && tctx->io_wq) {
10337 * Cancels requests of all rings, not only @ctx, but
10338 * it's fine as the task is in exit/exec.
10340 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
10342 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10345 /* SQPOLL thread does its own polling */
10346 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
10347 (ctx->sq_data && ctx->sq_data->thread == current)) {
10348 while (!wq_list_empty(&ctx->iopoll_list)) {
10349 io_iopoll_try_reap_events(ctx);
10354 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10355 ret |= io_poll_remove_all(ctx, task, cancel_all);
10356 ret |= io_kill_timeouts(ctx, task, cancel_all);
10358 ret |= io_run_task_work();
10365 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10367 struct io_uring_task *tctx = current->io_uring;
10368 struct io_tctx_node *node;
10371 if (unlikely(!tctx)) {
10372 ret = io_uring_alloc_task_context(current, ctx);
10376 tctx = current->io_uring;
10377 if (ctx->iowq_limits_set) {
10378 unsigned int limits[2] = { ctx->iowq_limits[0],
10379 ctx->iowq_limits[1], };
10381 ret = io_wq_max_workers(tctx->io_wq, limits);
10386 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10387 node = kmalloc(sizeof(*node), GFP_KERNEL);
10391 node->task = current;
10393 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10394 node, GFP_KERNEL));
10400 mutex_lock(&ctx->uring_lock);
10401 list_add(&node->ctx_node, &ctx->tctx_list);
10402 mutex_unlock(&ctx->uring_lock);
10409 * Note that this task has used io_uring. We use it for cancelation purposes.
10411 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
10413 struct io_uring_task *tctx = current->io_uring;
10415 if (likely(tctx && tctx->last == ctx))
10417 return __io_uring_add_tctx_node(ctx);
10421 * Remove this io_uring_file -> task mapping.
10423 static __cold void io_uring_del_tctx_node(unsigned long index)
10425 struct io_uring_task *tctx = current->io_uring;
10426 struct io_tctx_node *node;
10430 node = xa_erase(&tctx->xa, index);
10434 WARN_ON_ONCE(current != node->task);
10435 WARN_ON_ONCE(list_empty(&node->ctx_node));
10437 mutex_lock(&node->ctx->uring_lock);
10438 list_del(&node->ctx_node);
10439 mutex_unlock(&node->ctx->uring_lock);
10441 if (tctx->last == node->ctx)
10446 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
10448 struct io_wq *wq = tctx->io_wq;
10449 struct io_tctx_node *node;
10450 unsigned long index;
10452 xa_for_each(&tctx->xa, index, node) {
10453 io_uring_del_tctx_node(index);
10458 * Must be after io_uring_del_tctx_node() (removes nodes under
10459 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10461 io_wq_put_and_exit(wq);
10462 tctx->io_wq = NULL;
10466 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
10469 return atomic_read(&tctx->inflight_tracked);
10470 return percpu_counter_sum(&tctx->inflight);
10474 * Find any io_uring ctx that this task has registered or done IO on, and cancel
10475 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
10477 static __cold void io_uring_cancel_generic(bool cancel_all,
10478 struct io_sq_data *sqd)
10480 struct io_uring_task *tctx = current->io_uring;
10481 struct io_ring_ctx *ctx;
10485 WARN_ON_ONCE(sqd && sqd->thread != current);
10487 if (!current->io_uring)
10490 io_wq_exit_start(tctx->io_wq);
10492 atomic_inc(&tctx->in_idle);
10494 io_uring_drop_tctx_refs(current);
10495 /* read completions before cancelations */
10496 inflight = tctx_inflight(tctx, !cancel_all);
10501 struct io_tctx_node *node;
10502 unsigned long index;
10504 xa_for_each(&tctx->xa, index, node) {
10505 /* sqpoll task will cancel all its requests */
10506 if (node->ctx->sq_data)
10508 io_uring_try_cancel_requests(node->ctx, current,
10512 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10513 io_uring_try_cancel_requests(ctx, current,
10517 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10518 io_run_task_work();
10519 io_uring_drop_tctx_refs(current);
10522 * If we've seen completions, retry without waiting. This
10523 * avoids a race where a completion comes in before we did
10524 * prepare_to_wait().
10526 if (inflight == tctx_inflight(tctx, !cancel_all))
10528 finish_wait(&tctx->wait, &wait);
10531 io_uring_clean_tctx(tctx);
10534 * We shouldn't run task_works after cancel, so just leave
10535 * ->in_idle set for normal exit.
10537 atomic_dec(&tctx->in_idle);
10538 /* for exec all current's requests should be gone, kill tctx */
10539 __io_uring_free(current);
10543 void __io_uring_cancel(bool cancel_all)
10545 io_uring_cancel_generic(cancel_all, NULL);
10548 void io_uring_unreg_ringfd(void)
10550 struct io_uring_task *tctx = current->io_uring;
10553 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10554 if (tctx->registered_rings[i]) {
10555 fput(tctx->registered_rings[i]);
10556 tctx->registered_rings[i] = NULL;
10561 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10562 int start, int end)
10567 for (offset = start; offset < end; offset++) {
10568 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10569 if (tctx->registered_rings[offset])
10575 } else if (file->f_op != &io_uring_fops) {
10577 return -EOPNOTSUPP;
10579 tctx->registered_rings[offset] = file;
10587 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10588 * invocation. User passes in an array of struct io_uring_rsrc_update
10589 * with ->data set to the ring_fd, and ->offset given for the desired
10590 * index. If no index is desired, application may set ->offset == -1U
10591 * and we'll find an available index. Returns number of entries
10592 * successfully processed, or < 0 on error if none were processed.
10594 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10597 struct io_uring_rsrc_update __user *arg = __arg;
10598 struct io_uring_rsrc_update reg;
10599 struct io_uring_task *tctx;
10602 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10605 mutex_unlock(&ctx->uring_lock);
10606 ret = io_uring_add_tctx_node(ctx);
10607 mutex_lock(&ctx->uring_lock);
10611 tctx = current->io_uring;
10612 for (i = 0; i < nr_args; i++) {
10615 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10620 if (reg.offset == -1U) {
10622 end = IO_RINGFD_REG_MAX;
10624 if (reg.offset >= IO_RINGFD_REG_MAX) {
10628 start = reg.offset;
10632 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10637 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
10638 fput(tctx->registered_rings[reg.offset]);
10639 tctx->registered_rings[reg.offset] = NULL;
10645 return i ? i : ret;
10648 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10651 struct io_uring_rsrc_update __user *arg = __arg;
10652 struct io_uring_task *tctx = current->io_uring;
10653 struct io_uring_rsrc_update reg;
10656 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10661 for (i = 0; i < nr_args; i++) {
10662 if (copy_from_user(®, &arg[i], sizeof(reg))) {
10666 if (reg.offset >= IO_RINGFD_REG_MAX) {
10671 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10672 if (tctx->registered_rings[reg.offset]) {
10673 fput(tctx->registered_rings[reg.offset]);
10674 tctx->registered_rings[reg.offset] = NULL;
10678 return i ? i : ret;
10681 static void *io_uring_validate_mmap_request(struct file *file,
10682 loff_t pgoff, size_t sz)
10684 struct io_ring_ctx *ctx = file->private_data;
10685 loff_t offset = pgoff << PAGE_SHIFT;
10690 case IORING_OFF_SQ_RING:
10691 case IORING_OFF_CQ_RING:
10694 case IORING_OFF_SQES:
10695 ptr = ctx->sq_sqes;
10698 return ERR_PTR(-EINVAL);
10701 page = virt_to_head_page(ptr);
10702 if (sz > page_size(page))
10703 return ERR_PTR(-EINVAL);
10710 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10712 size_t sz = vma->vm_end - vma->vm_start;
10716 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10718 return PTR_ERR(ptr);
10720 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10721 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10724 #else /* !CONFIG_MMU */
10726 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10728 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10731 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10733 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10736 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10737 unsigned long addr, unsigned long len,
10738 unsigned long pgoff, unsigned long flags)
10742 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10744 return PTR_ERR(ptr);
10746 return (unsigned long) ptr;
10749 #endif /* !CONFIG_MMU */
10751 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
10756 if (!io_sqring_full(ctx))
10758 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10760 if (!io_sqring_full(ctx))
10763 } while (!signal_pending(current));
10765 finish_wait(&ctx->sqo_sq_wait, &wait);
10769 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10770 struct __kernel_timespec __user **ts,
10771 const sigset_t __user **sig)
10773 struct io_uring_getevents_arg arg;
10776 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10777 * is just a pointer to the sigset_t.
10779 if (!(flags & IORING_ENTER_EXT_ARG)) {
10780 *sig = (const sigset_t __user *) argp;
10786 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10787 * timespec and sigset_t pointers if good.
10789 if (*argsz != sizeof(arg))
10791 if (copy_from_user(&arg, argp, sizeof(arg)))
10793 *sig = u64_to_user_ptr(arg.sigmask);
10794 *argsz = arg.sigmask_sz;
10795 *ts = u64_to_user_ptr(arg.ts);
10799 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
10800 u32, min_complete, u32, flags, const void __user *, argp,
10803 struct io_ring_ctx *ctx;
10808 io_run_task_work();
10810 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
10811 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10812 IORING_ENTER_REGISTERED_RING)))
10816 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10817 * need only dereference our task private array to find it.
10819 if (flags & IORING_ENTER_REGISTERED_RING) {
10820 struct io_uring_task *tctx = current->io_uring;
10822 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10824 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10825 f.file = tctx->registered_rings[fd];
10826 if (unlikely(!f.file))
10830 if (unlikely(!f.file))
10835 if (unlikely(f.file->f_op != &io_uring_fops))
10839 ctx = f.file->private_data;
10840 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
10844 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
10848 * For SQ polling, the thread will do all submissions and completions.
10849 * Just return the requested submit count, and wake the thread if
10850 * we were asked to.
10853 if (ctx->flags & IORING_SETUP_SQPOLL) {
10854 io_cqring_overflow_flush(ctx);
10856 if (unlikely(ctx->sq_data->thread == NULL)) {
10860 if (flags & IORING_ENTER_SQ_WAKEUP)
10861 wake_up(&ctx->sq_data->wait);
10862 if (flags & IORING_ENTER_SQ_WAIT) {
10863 ret = io_sqpoll_wait_sq(ctx);
10867 submitted = to_submit;
10868 } else if (to_submit) {
10869 ret = io_uring_add_tctx_node(ctx);
10872 mutex_lock(&ctx->uring_lock);
10873 submitted = io_submit_sqes(ctx, to_submit);
10874 mutex_unlock(&ctx->uring_lock);
10876 if (submitted != to_submit)
10879 if (flags & IORING_ENTER_GETEVENTS) {
10880 const sigset_t __user *sig;
10881 struct __kernel_timespec __user *ts;
10883 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10887 min_complete = min(min_complete, ctx->cq_entries);
10890 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10891 * space applications don't need to do io completion events
10892 * polling again, they can rely on io_sq_thread to do polling
10893 * work, which can reduce cpu usage and uring_lock contention.
10895 if (ctx->flags & IORING_SETUP_IOPOLL &&
10896 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10897 ret = io_iopoll_check(ctx, min_complete);
10899 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10904 percpu_ref_put(&ctx->refs);
10906 if (!(flags & IORING_ENTER_REGISTERED_RING))
10908 return submitted ? submitted : ret;
10911 #ifdef CONFIG_PROC_FS
10912 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
10913 const struct cred *cred)
10915 struct user_namespace *uns = seq_user_ns(m);
10916 struct group_info *gi;
10921 seq_printf(m, "%5d\n", id);
10922 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10923 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10924 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10925 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10926 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10927 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10928 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10929 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10930 seq_puts(m, "\n\tGroups:\t");
10931 gi = cred->group_info;
10932 for (g = 0; g < gi->ngroups; g++) {
10933 seq_put_decimal_ull(m, g ? " " : "",
10934 from_kgid_munged(uns, gi->gid[g]));
10936 seq_puts(m, "\n\tCapEff:\t");
10937 cap = cred->cap_effective;
10938 CAP_FOR_EACH_U32(__capi)
10939 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10944 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10945 struct seq_file *m)
10947 struct io_sq_data *sq = NULL;
10948 struct io_overflow_cqe *ocqe;
10949 struct io_rings *r = ctx->rings;
10950 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
10951 unsigned int sq_head = READ_ONCE(r->sq.head);
10952 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10953 unsigned int cq_head = READ_ONCE(r->cq.head);
10954 unsigned int cq_tail = READ_ONCE(r->cq.tail);
10955 unsigned int sq_entries, cq_entries;
10960 * we may get imprecise sqe and cqe info if uring is actively running
10961 * since we get cached_sq_head and cached_cq_tail without uring_lock
10962 * and sq_tail and cq_head are changed by userspace. But it's ok since
10963 * we usually use these info when it is stuck.
10965 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
10966 seq_printf(m, "SqHead:\t%u\n", sq_head);
10967 seq_printf(m, "SqTail:\t%u\n", sq_tail);
10968 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
10969 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
10970 seq_printf(m, "CqHead:\t%u\n", cq_head);
10971 seq_printf(m, "CqTail:\t%u\n", cq_tail);
10972 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
10973 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
10974 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
10975 for (i = 0; i < sq_entries; i++) {
10976 unsigned int entry = i + sq_head;
10977 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
10978 struct io_uring_sqe *sqe;
10980 if (sq_idx > sq_mask)
10982 sqe = &ctx->sq_sqes[sq_idx];
10983 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
10984 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
10987 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
10988 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
10989 for (i = 0; i < cq_entries; i++) {
10990 unsigned int entry = i + cq_head;
10991 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
10993 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
10994 entry & cq_mask, cqe->user_data, cqe->res,
10999 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11000 * since fdinfo case grabs it in the opposite direction of normal use
11001 * cases. If we fail to get the lock, we just don't iterate any
11002 * structures that could be going away outside the io_uring mutex.
11004 has_lock = mutex_trylock(&ctx->uring_lock);
11006 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11012 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11013 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11014 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11015 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11016 struct file *f = io_file_from_index(ctx, i);
11019 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11021 seq_printf(m, "%5u: <none>\n", i);
11023 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11024 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11025 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11026 unsigned int len = buf->ubuf_end - buf->ubuf;
11028 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11030 if (has_lock && !xa_empty(&ctx->personalities)) {
11031 unsigned long index;
11032 const struct cred *cred;
11034 seq_printf(m, "Personalities:\n");
11035 xa_for_each(&ctx->personalities, index, cred)
11036 io_uring_show_cred(m, index, cred);
11039 mutex_unlock(&ctx->uring_lock);
11041 seq_puts(m, "PollList:\n");
11042 spin_lock(&ctx->completion_lock);
11043 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11044 struct hlist_head *list = &ctx->cancel_hash[i];
11045 struct io_kiocb *req;
11047 hlist_for_each_entry(req, list, hash_node)
11048 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11049 req->task->task_works != NULL);
11052 seq_puts(m, "CqOverflowList:\n");
11053 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11054 struct io_uring_cqe *cqe = &ocqe->cqe;
11056 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11057 cqe->user_data, cqe->res, cqe->flags);
11061 spin_unlock(&ctx->completion_lock);
11064 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11066 struct io_ring_ctx *ctx = f->private_data;
11068 if (percpu_ref_tryget(&ctx->refs)) {
11069 __io_uring_show_fdinfo(ctx, m);
11070 percpu_ref_put(&ctx->refs);
11075 static const struct file_operations io_uring_fops = {
11076 .release = io_uring_release,
11077 .mmap = io_uring_mmap,
11079 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11080 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11082 .poll = io_uring_poll,
11083 #ifdef CONFIG_PROC_FS
11084 .show_fdinfo = io_uring_show_fdinfo,
11088 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11089 struct io_uring_params *p)
11091 struct io_rings *rings;
11092 size_t size, sq_array_offset;
11094 /* make sure these are sane, as we already accounted them */
11095 ctx->sq_entries = p->sq_entries;
11096 ctx->cq_entries = p->cq_entries;
11098 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11099 if (size == SIZE_MAX)
11102 rings = io_mem_alloc(size);
11106 ctx->rings = rings;
11107 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11108 rings->sq_ring_mask = p->sq_entries - 1;
11109 rings->cq_ring_mask = p->cq_entries - 1;
11110 rings->sq_ring_entries = p->sq_entries;
11111 rings->cq_ring_entries = p->cq_entries;
11113 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11114 if (size == SIZE_MAX) {
11115 io_mem_free(ctx->rings);
11120 ctx->sq_sqes = io_mem_alloc(size);
11121 if (!ctx->sq_sqes) {
11122 io_mem_free(ctx->rings);
11130 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11134 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11138 ret = io_uring_add_tctx_node(ctx);
11143 fd_install(fd, file);
11148 * Allocate an anonymous fd, this is what constitutes the application
11149 * visible backing of an io_uring instance. The application mmaps this
11150 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11151 * we have to tie this fd to a socket for file garbage collection purposes.
11153 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11156 #if defined(CONFIG_UNIX)
11159 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11162 return ERR_PTR(ret);
11165 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11166 O_RDWR | O_CLOEXEC, NULL);
11167 #if defined(CONFIG_UNIX)
11168 if (IS_ERR(file)) {
11169 sock_release(ctx->ring_sock);
11170 ctx->ring_sock = NULL;
11172 ctx->ring_sock->file = file;
11178 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11179 struct io_uring_params __user *params)
11181 struct io_ring_ctx *ctx;
11187 if (entries > IORING_MAX_ENTRIES) {
11188 if (!(p->flags & IORING_SETUP_CLAMP))
11190 entries = IORING_MAX_ENTRIES;
11194 * Use twice as many entries for the CQ ring. It's possible for the
11195 * application to drive a higher depth than the size of the SQ ring,
11196 * since the sqes are only used at submission time. This allows for
11197 * some flexibility in overcommitting a bit. If the application has
11198 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11199 * of CQ ring entries manually.
11201 p->sq_entries = roundup_pow_of_two(entries);
11202 if (p->flags & IORING_SETUP_CQSIZE) {
11204 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11205 * to a power-of-two, if it isn't already. We do NOT impose
11206 * any cq vs sq ring sizing.
11208 if (!p->cq_entries)
11210 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11211 if (!(p->flags & IORING_SETUP_CLAMP))
11213 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11215 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11216 if (p->cq_entries < p->sq_entries)
11219 p->cq_entries = 2 * p->sq_entries;
11222 ctx = io_ring_ctx_alloc(p);
11225 ctx->compat = in_compat_syscall();
11226 if (!capable(CAP_IPC_LOCK))
11227 ctx->user = get_uid(current_user());
11230 * This is just grabbed for accounting purposes. When a process exits,
11231 * the mm is exited and dropped before the files, hence we need to hang
11232 * on to this mm purely for the purposes of being able to unaccount
11233 * memory (locked/pinned vm). It's not used for anything else.
11235 mmgrab(current->mm);
11236 ctx->mm_account = current->mm;
11238 ret = io_allocate_scq_urings(ctx, p);
11242 ret = io_sq_offload_create(ctx, p);
11245 /* always set a rsrc node */
11246 ret = io_rsrc_node_switch_start(ctx);
11249 io_rsrc_node_switch(ctx, NULL);
11251 memset(&p->sq_off, 0, sizeof(p->sq_off));
11252 p->sq_off.head = offsetof(struct io_rings, sq.head);
11253 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11254 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11255 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11256 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11257 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11258 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
11260 memset(&p->cq_off, 0, sizeof(p->cq_off));
11261 p->cq_off.head = offsetof(struct io_rings, cq.head);
11262 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11263 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11264 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11265 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11266 p->cq_off.cqes = offsetof(struct io_rings, cqes);
11267 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
11269 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11270 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
11271 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
11272 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
11273 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
11274 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
11276 if (copy_to_user(params, p, sizeof(*p))) {
11281 file = io_uring_get_file(ctx);
11282 if (IS_ERR(file)) {
11283 ret = PTR_ERR(file);
11288 * Install ring fd as the very last thing, so we don't risk someone
11289 * having closed it before we finish setup
11291 ret = io_uring_install_fd(ctx, file);
11293 /* fput will clean it up */
11298 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
11301 io_ring_ctx_wait_and_kill(ctx);
11306 * Sets up an aio uring context, and returns the fd. Applications asks for a
11307 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11308 * params structure passed in.
11310 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11312 struct io_uring_params p;
11315 if (copy_from_user(&p, params, sizeof(p)))
11317 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11322 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
11323 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
11324 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
11325 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
11328 return io_uring_create(entries, &p, params);
11331 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11332 struct io_uring_params __user *, params)
11334 return io_uring_setup(entries, params);
11337 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11340 struct io_uring_probe *p;
11344 size = struct_size(p, ops, nr_args);
11345 if (size == SIZE_MAX)
11347 p = kzalloc(size, GFP_KERNEL);
11352 if (copy_from_user(p, arg, size))
11355 if (memchr_inv(p, 0, size))
11358 p->last_op = IORING_OP_LAST - 1;
11359 if (nr_args > IORING_OP_LAST)
11360 nr_args = IORING_OP_LAST;
11362 for (i = 0; i < nr_args; i++) {
11364 if (!io_op_defs[i].not_supported)
11365 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11370 if (copy_to_user(arg, p, size))
11377 static int io_register_personality(struct io_ring_ctx *ctx)
11379 const struct cred *creds;
11383 creds = get_current_cred();
11385 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11386 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
11394 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11395 void __user *arg, unsigned int nr_args)
11397 struct io_uring_restriction *res;
11401 /* Restrictions allowed only if rings started disabled */
11402 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11405 /* We allow only a single restrictions registration */
11406 if (ctx->restrictions.registered)
11409 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11412 size = array_size(nr_args, sizeof(*res));
11413 if (size == SIZE_MAX)
11416 res = memdup_user(arg, size);
11418 return PTR_ERR(res);
11422 for (i = 0; i < nr_args; i++) {
11423 switch (res[i].opcode) {
11424 case IORING_RESTRICTION_REGISTER_OP:
11425 if (res[i].register_op >= IORING_REGISTER_LAST) {
11430 __set_bit(res[i].register_op,
11431 ctx->restrictions.register_op);
11433 case IORING_RESTRICTION_SQE_OP:
11434 if (res[i].sqe_op >= IORING_OP_LAST) {
11439 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11441 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11442 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11444 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11445 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11454 /* Reset all restrictions if an error happened */
11456 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11458 ctx->restrictions.registered = true;
11464 static int io_register_enable_rings(struct io_ring_ctx *ctx)
11466 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11469 if (ctx->restrictions.registered)
11470 ctx->restricted = 1;
11472 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11473 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11474 wake_up(&ctx->sq_data->wait);
11478 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
11479 struct io_uring_rsrc_update2 *up,
11487 if (check_add_overflow(up->offset, nr_args, &tmp))
11489 err = io_rsrc_node_switch_start(ctx);
11494 case IORING_RSRC_FILE:
11495 return __io_sqe_files_update(ctx, up, nr_args);
11496 case IORING_RSRC_BUFFER:
11497 return __io_sqe_buffers_update(ctx, up, nr_args);
11502 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11505 struct io_uring_rsrc_update2 up;
11509 memset(&up, 0, sizeof(up));
11510 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11512 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11515 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
11516 unsigned size, unsigned type)
11518 struct io_uring_rsrc_update2 up;
11520 if (size != sizeof(up))
11522 if (copy_from_user(&up, arg, sizeof(up)))
11524 if (!up.nr || up.resv)
11526 return __io_register_rsrc_update(ctx, type, &up, up.nr);
11529 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
11530 unsigned int size, unsigned int type)
11532 struct io_uring_rsrc_register rr;
11534 /* keep it extendible */
11535 if (size != sizeof(rr))
11538 memset(&rr, 0, sizeof(rr));
11539 if (copy_from_user(&rr, arg, size))
11541 if (!rr.nr || rr.resv || rr.resv2)
11545 case IORING_RSRC_FILE:
11546 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11547 rr.nr, u64_to_user_ptr(rr.tags));
11548 case IORING_RSRC_BUFFER:
11549 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11550 rr.nr, u64_to_user_ptr(rr.tags));
11555 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11556 void __user *arg, unsigned len)
11558 struct io_uring_task *tctx = current->io_uring;
11559 cpumask_var_t new_mask;
11562 if (!tctx || !tctx->io_wq)
11565 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11568 cpumask_clear(new_mask);
11569 if (len > cpumask_size())
11570 len = cpumask_size();
11572 if (copy_from_user(new_mask, arg, len)) {
11573 free_cpumask_var(new_mask);
11577 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11578 free_cpumask_var(new_mask);
11582 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
11584 struct io_uring_task *tctx = current->io_uring;
11586 if (!tctx || !tctx->io_wq)
11589 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11592 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11594 __must_hold(&ctx->uring_lock)
11596 struct io_tctx_node *node;
11597 struct io_uring_task *tctx = NULL;
11598 struct io_sq_data *sqd = NULL;
11599 __u32 new_count[2];
11602 if (copy_from_user(new_count, arg, sizeof(new_count)))
11604 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11605 if (new_count[i] > INT_MAX)
11608 if (ctx->flags & IORING_SETUP_SQPOLL) {
11609 sqd = ctx->sq_data;
11612 * Observe the correct sqd->lock -> ctx->uring_lock
11613 * ordering. Fine to drop uring_lock here, we hold
11614 * a ref to the ctx.
11616 refcount_inc(&sqd->refs);
11617 mutex_unlock(&ctx->uring_lock);
11618 mutex_lock(&sqd->lock);
11619 mutex_lock(&ctx->uring_lock);
11621 tctx = sqd->thread->io_uring;
11624 tctx = current->io_uring;
11627 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
11629 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11631 ctx->iowq_limits[i] = new_count[i];
11632 ctx->iowq_limits_set = true;
11634 if (tctx && tctx->io_wq) {
11635 ret = io_wq_max_workers(tctx->io_wq, new_count);
11639 memset(new_count, 0, sizeof(new_count));
11643 mutex_unlock(&sqd->lock);
11644 io_put_sq_data(sqd);
11647 if (copy_to_user(arg, new_count, sizeof(new_count)))
11650 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11654 /* now propagate the restriction to all registered users */
11655 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11656 struct io_uring_task *tctx = node->task->io_uring;
11658 if (WARN_ON_ONCE(!tctx->io_wq))
11661 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11662 new_count[i] = ctx->iowq_limits[i];
11663 /* ignore errors, it always returns zero anyway */
11664 (void)io_wq_max_workers(tctx->io_wq, new_count);
11669 mutex_unlock(&sqd->lock);
11670 io_put_sq_data(sqd);
11675 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11676 void __user *arg, unsigned nr_args)
11677 __releases(ctx->uring_lock)
11678 __acquires(ctx->uring_lock)
11683 * We're inside the ring mutex, if the ref is already dying, then
11684 * someone else killed the ctx or is already going through
11685 * io_uring_register().
11687 if (percpu_ref_is_dying(&ctx->refs))
11690 if (ctx->restricted) {
11691 if (opcode >= IORING_REGISTER_LAST)
11693 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11694 if (!test_bit(opcode, ctx->restrictions.register_op))
11699 case IORING_REGISTER_BUFFERS:
11700 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
11702 case IORING_UNREGISTER_BUFFERS:
11704 if (arg || nr_args)
11706 ret = io_sqe_buffers_unregister(ctx);
11708 case IORING_REGISTER_FILES:
11709 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
11711 case IORING_UNREGISTER_FILES:
11713 if (arg || nr_args)
11715 ret = io_sqe_files_unregister(ctx);
11717 case IORING_REGISTER_FILES_UPDATE:
11718 ret = io_register_files_update(ctx, arg, nr_args);
11720 case IORING_REGISTER_EVENTFD:
11724 ret = io_eventfd_register(ctx, arg, 0);
11726 case IORING_REGISTER_EVENTFD_ASYNC:
11730 ret = io_eventfd_register(ctx, arg, 1);
11732 case IORING_UNREGISTER_EVENTFD:
11734 if (arg || nr_args)
11736 ret = io_eventfd_unregister(ctx);
11738 case IORING_REGISTER_PROBE:
11740 if (!arg || nr_args > 256)
11742 ret = io_probe(ctx, arg, nr_args);
11744 case IORING_REGISTER_PERSONALITY:
11746 if (arg || nr_args)
11748 ret = io_register_personality(ctx);
11750 case IORING_UNREGISTER_PERSONALITY:
11754 ret = io_unregister_personality(ctx, nr_args);
11756 case IORING_REGISTER_ENABLE_RINGS:
11758 if (arg || nr_args)
11760 ret = io_register_enable_rings(ctx);
11762 case IORING_REGISTER_RESTRICTIONS:
11763 ret = io_register_restrictions(ctx, arg, nr_args);
11765 case IORING_REGISTER_FILES2:
11766 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11768 case IORING_REGISTER_FILES_UPDATE2:
11769 ret = io_register_rsrc_update(ctx, arg, nr_args,
11772 case IORING_REGISTER_BUFFERS2:
11773 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
11775 case IORING_REGISTER_BUFFERS_UPDATE:
11776 ret = io_register_rsrc_update(ctx, arg, nr_args,
11777 IORING_RSRC_BUFFER);
11779 case IORING_REGISTER_IOWQ_AFF:
11781 if (!arg || !nr_args)
11783 ret = io_register_iowq_aff(ctx, arg, nr_args);
11785 case IORING_UNREGISTER_IOWQ_AFF:
11787 if (arg || nr_args)
11789 ret = io_unregister_iowq_aff(ctx);
11791 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11793 if (!arg || nr_args != 2)
11795 ret = io_register_iowq_max_workers(ctx, arg);
11797 case IORING_REGISTER_RING_FDS:
11798 ret = io_ringfd_register(ctx, arg, nr_args);
11800 case IORING_UNREGISTER_RING_FDS:
11801 ret = io_ringfd_unregister(ctx, arg, nr_args);
11811 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11812 void __user *, arg, unsigned int, nr_args)
11814 struct io_ring_ctx *ctx;
11823 if (f.file->f_op != &io_uring_fops)
11826 ctx = f.file->private_data;
11828 io_run_task_work();
11830 mutex_lock(&ctx->uring_lock);
11831 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11832 mutex_unlock(&ctx->uring_lock);
11833 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
11839 static int __init io_uring_init(void)
11841 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11842 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11843 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11846 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11847 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11848 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11849 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11850 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11851 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11852 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11853 BUILD_BUG_SQE_ELEM(8, __u64, off);
11854 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11855 BUILD_BUG_SQE_ELEM(16, __u64, addr);
11856 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
11857 BUILD_BUG_SQE_ELEM(24, __u32, len);
11858 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11859 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11860 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11861 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
11862 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11863 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
11864 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11865 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11866 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11867 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11868 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11869 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11870 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11871 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
11872 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
11873 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11874 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
11875 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
11876 BUILD_BUG_SQE_ELEM(42, __u16, personality);
11877 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
11878 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
11880 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11881 sizeof(struct io_uring_rsrc_update));
11882 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11883 sizeof(struct io_uring_rsrc_update2));
11885 /* ->buf_index is u16 */
11886 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11888 /* should fit into one byte */
11889 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11890 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11891 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
11893 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11894 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11896 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11900 __initcall(io_uring_init);