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_cqring (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/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 #define IORING_FILE_TABLE_SHIFT 9
97 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define IORING_MAX_REG_BUFFERS (1U << 14)
105 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
106 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
110 u32 head ____cacheline_aligned_in_smp;
111 u32 tail ____cacheline_aligned_in_smp;
115 * This data is shared with the application through the mmap at offsets
116 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
118 * The offsets to the member fields are published through struct
119 * io_sqring_offsets when calling io_uring_setup.
123 * Head and tail offsets into the ring; the offsets need to be
124 * masked to get valid indices.
126 * The kernel controls head of the sq ring and the tail of the cq ring,
127 * and the application controls tail of the sq ring and the head of the
130 struct io_uring sq, cq;
132 * Bitmasks to apply to head and tail offsets (constant, equals
135 u32 sq_ring_mask, cq_ring_mask;
136 /* Ring sizes (constant, power of 2) */
137 u32 sq_ring_entries, cq_ring_entries;
139 * Number of invalid entries dropped by the kernel due to
140 * invalid index stored in array
142 * Written by the kernel, shouldn't be modified by the
143 * application (i.e. get number of "new events" by comparing to
146 * After a new SQ head value was read by the application this
147 * counter includes all submissions that were dropped reaching
148 * the new SQ head (and possibly more).
154 * Written by the kernel, shouldn't be modified by the
157 * The application needs a full memory barrier before checking
158 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
164 * Written by the application, shouldn't be modified by the
169 * Number of completion events lost because the queue was full;
170 * this should be avoided by the application by making sure
171 * there are not more requests pending than there is space in
172 * the completion queue.
174 * Written by the kernel, shouldn't be modified by the
175 * application (i.e. get number of "new events" by comparing to
178 * As completion events come in out of order this counter is not
179 * ordered with any other data.
183 * Ring buffer of completion events.
185 * The kernel writes completion events fresh every time they are
186 * produced, so the application is allowed to modify pending
189 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
192 enum io_uring_cmd_flags {
193 IO_URING_F_NONBLOCK = 1,
194 IO_URING_F_COMPLETE_DEFER = 2,
197 struct io_mapped_ubuf {
200 unsigned int nr_bvecs;
201 unsigned long acct_pages;
202 struct bio_vec bvec[];
207 struct io_overflow_cqe {
208 struct io_uring_cqe cqe;
209 struct list_head list;
212 struct io_fixed_file {
213 /* file * with additional FFS_* flags */
214 unsigned long file_ptr;
218 struct list_head list;
223 struct io_mapped_ubuf *buf;
227 struct io_file_table {
228 /* two level table */
229 struct io_fixed_file **files;
232 struct io_rsrc_node {
233 struct percpu_ref refs;
234 struct list_head node;
235 struct list_head rsrc_list;
236 struct io_rsrc_data *rsrc_data;
237 struct llist_node llist;
241 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
243 struct io_rsrc_data {
244 struct io_ring_ctx *ctx;
249 struct completion done;
254 struct list_head list;
260 struct io_restriction {
261 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
262 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
263 u8 sqe_flags_allowed;
264 u8 sqe_flags_required;
269 IO_SQ_THREAD_SHOULD_STOP = 0,
270 IO_SQ_THREAD_SHOULD_PARK,
275 atomic_t park_pending;
278 /* ctx's that are using this sqd */
279 struct list_head ctx_list;
281 struct task_struct *thread;
282 struct wait_queue_head wait;
284 unsigned sq_thread_idle;
290 struct completion exited;
291 struct callback_head *park_task_work;
294 #define IO_IOPOLL_BATCH 8
295 #define IO_COMPL_BATCH 32
296 #define IO_REQ_CACHE_SIZE 32
297 #define IO_REQ_ALLOC_BATCH 8
299 struct io_comp_state {
300 struct io_kiocb *reqs[IO_COMPL_BATCH];
302 unsigned int locked_free_nr;
303 /* inline/task_work completion list, under ->uring_lock */
304 struct list_head free_list;
305 /* IRQ completion list, under ->completion_lock */
306 struct list_head locked_free_list;
309 struct io_submit_link {
310 struct io_kiocb *head;
311 struct io_kiocb *last;
314 struct io_submit_state {
315 struct blk_plug plug;
316 struct io_submit_link link;
319 * io_kiocb alloc cache
321 void *reqs[IO_REQ_CACHE_SIZE];
322 unsigned int free_reqs;
327 * Batch completion logic
329 struct io_comp_state comp;
332 * File reference cache
336 unsigned int file_refs;
337 unsigned int ios_left;
342 struct percpu_ref refs;
343 } ____cacheline_aligned_in_smp;
347 unsigned int compat: 1;
348 unsigned int drain_next: 1;
349 unsigned int eventfd_async: 1;
350 unsigned int restricted: 1;
353 * Ring buffer of indices into array of io_uring_sqe, which is
354 * mmapped by the application using the IORING_OFF_SQES offset.
356 * This indirection could e.g. be used to assign fixed
357 * io_uring_sqe entries to operations and only submit them to
358 * the queue when needed.
360 * The kernel modifies neither the indices array nor the entries
364 unsigned cached_sq_head;
367 unsigned sq_thread_idle;
368 unsigned cached_sq_dropped;
369 unsigned cached_cq_overflow;
370 unsigned long sq_check_overflow;
372 /* hashed buffered write serialization */
373 struct io_wq_hash *hash_map;
375 struct list_head defer_list;
376 struct list_head timeout_list;
377 struct list_head cq_overflow_list;
379 struct io_uring_sqe *sq_sqes;
380 } ____cacheline_aligned_in_smp;
383 struct mutex uring_lock;
384 wait_queue_head_t wait;
385 } ____cacheline_aligned_in_smp;
387 struct io_submit_state submit_state;
389 struct io_rings *rings;
391 /* Only used for accounting purposes */
392 struct mm_struct *mm_account;
394 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
395 struct io_sq_data *sq_data; /* if using sq thread polling */
397 struct wait_queue_head sqo_sq_wait;
398 struct list_head sqd_list;
401 * If used, fixed file set. Writers must ensure that ->refs is dead,
402 * readers must ensure that ->refs is alive as long as the file* is
403 * used. Only updated through io_uring_register(2).
405 struct io_rsrc_data *file_data;
406 struct io_file_table file_table;
407 unsigned nr_user_files;
409 /* if used, fixed mapped user buffers */
410 struct io_rsrc_data *buf_data;
411 unsigned nr_user_bufs;
412 struct io_mapped_ubuf **user_bufs;
414 struct user_struct *user;
416 struct completion ref_comp;
418 #if defined(CONFIG_UNIX)
419 struct socket *ring_sock;
422 struct xarray io_buffers;
424 struct xarray personalities;
428 unsigned cached_cq_tail;
431 atomic_t cq_timeouts;
432 unsigned cq_last_tm_flush;
434 unsigned long cq_check_overflow;
435 struct wait_queue_head cq_wait;
436 struct fasync_struct *cq_fasync;
437 struct eventfd_ctx *cq_ev_fd;
438 } ____cacheline_aligned_in_smp;
441 spinlock_t completion_lock;
444 * ->iopoll_list is protected by the ctx->uring_lock for
445 * io_uring instances that don't use IORING_SETUP_SQPOLL.
446 * For SQPOLL, only the single threaded io_sq_thread() will
447 * manipulate the list, hence no extra locking is needed there.
449 struct list_head iopoll_list;
450 struct hlist_head *cancel_hash;
451 unsigned cancel_hash_bits;
452 bool poll_multi_file;
453 } ____cacheline_aligned_in_smp;
455 struct delayed_work rsrc_put_work;
456 struct llist_head rsrc_put_llist;
457 struct list_head rsrc_ref_list;
458 spinlock_t rsrc_ref_lock;
459 struct io_rsrc_node *rsrc_node;
460 struct io_rsrc_node *rsrc_backup_node;
461 struct io_mapped_ubuf *dummy_ubuf;
463 struct io_restriction restrictions;
466 struct callback_head *exit_task_work;
468 /* Keep this last, we don't need it for the fast path */
469 struct work_struct exit_work;
470 struct list_head tctx_list;
473 struct io_uring_task {
474 /* submission side */
476 struct wait_queue_head wait;
477 const struct io_ring_ctx *last;
479 struct percpu_counter inflight;
480 atomic_t inflight_tracked;
483 spinlock_t task_lock;
484 struct io_wq_work_list task_list;
485 unsigned long task_state;
486 struct callback_head task_work;
490 * First field must be the file pointer in all the
491 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
493 struct io_poll_iocb {
495 struct wait_queue_head *head;
499 struct wait_queue_entry wait;
502 struct io_poll_update {
508 bool update_user_data;
516 struct io_timeout_data {
517 struct io_kiocb *req;
518 struct hrtimer timer;
519 struct timespec64 ts;
520 enum hrtimer_mode mode;
525 struct sockaddr __user *addr;
526 int __user *addr_len;
528 unsigned long nofile;
548 struct list_head list;
549 /* head of the link, used by linked timeouts only */
550 struct io_kiocb *head;
553 struct io_timeout_rem {
558 struct timespec64 ts;
563 /* NOTE: kiocb has the file as the first member, so don't do it here */
571 struct sockaddr __user *addr;
578 struct compat_msghdr __user *umsg_compat;
579 struct user_msghdr __user *umsg;
585 struct io_buffer *kbuf;
591 struct filename *filename;
593 unsigned long nofile;
596 struct io_rsrc_update {
622 struct epoll_event event;
626 struct file *file_out;
627 struct file *file_in;
634 struct io_provide_buf {
648 const char __user *filename;
649 struct statx __user *buffer;
661 struct filename *oldpath;
662 struct filename *newpath;
670 struct filename *filename;
673 struct io_completion {
675 struct list_head list;
679 struct io_async_connect {
680 struct sockaddr_storage address;
683 struct io_async_msghdr {
684 struct iovec fast_iov[UIO_FASTIOV];
685 /* points to an allocated iov, if NULL we use fast_iov instead */
686 struct iovec *free_iov;
687 struct sockaddr __user *uaddr;
689 struct sockaddr_storage addr;
693 struct iovec fast_iov[UIO_FASTIOV];
694 const struct iovec *free_iovec;
695 struct iov_iter iter;
697 struct wait_page_queue wpq;
701 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
702 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
703 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
704 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
705 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
706 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
708 /* first byte is taken by user flags, shift it to not overlap */
709 REQ_F_FAIL_LINK_BIT = 8,
713 REQ_F_LINK_TIMEOUT_BIT,
714 REQ_F_NEED_CLEANUP_BIT,
716 REQ_F_BUFFER_SELECTED_BIT,
717 REQ_F_LTIMEOUT_ACTIVE_BIT,
718 REQ_F_COMPLETE_INLINE_BIT,
720 REQ_F_DONT_REISSUE_BIT,
721 /* keep async read/write and isreg together and in order */
722 REQ_F_ASYNC_READ_BIT,
723 REQ_F_ASYNC_WRITE_BIT,
726 /* not a real bit, just to check we're not overflowing the space */
732 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
733 /* drain existing IO first */
734 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
736 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
737 /* doesn't sever on completion < 0 */
738 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
740 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
741 /* IOSQE_BUFFER_SELECT */
742 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
744 /* fail rest of links */
745 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
746 /* on inflight list, should be cancelled and waited on exit reliably */
747 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
748 /* read/write uses file position */
749 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
750 /* must not punt to workers */
751 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
752 /* has or had linked timeout */
753 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
755 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
756 /* already went through poll handler */
757 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
758 /* buffer already selected */
759 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
760 /* linked timeout is active, i.e. prepared by link's head */
761 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
762 /* completion is deferred through io_comp_state */
763 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
764 /* caller should reissue async */
765 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
766 /* don't attempt request reissue, see io_rw_reissue() */
767 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
768 /* supports async reads */
769 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
770 /* supports async writes */
771 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
773 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
777 struct io_poll_iocb poll;
778 struct io_poll_iocb *double_poll;
781 struct io_task_work {
782 struct io_wq_work_node node;
783 task_work_func_t func;
787 * NOTE! Each of the iocb union members has the file pointer
788 * as the first entry in their struct definition. So you can
789 * access the file pointer through any of the sub-structs,
790 * or directly as just 'ki_filp' in this struct.
796 struct io_poll_iocb poll;
797 struct io_poll_update poll_update;
798 struct io_accept accept;
800 struct io_cancel cancel;
801 struct io_timeout timeout;
802 struct io_timeout_rem timeout_rem;
803 struct io_connect connect;
804 struct io_sr_msg sr_msg;
806 struct io_close close;
807 struct io_rsrc_update rsrc_update;
808 struct io_fadvise fadvise;
809 struct io_madvise madvise;
810 struct io_epoll epoll;
811 struct io_splice splice;
812 struct io_provide_buf pbuf;
813 struct io_statx statx;
814 struct io_shutdown shutdown;
815 struct io_rename rename;
816 struct io_unlink unlink;
817 /* use only after cleaning per-op data, see io_clean_op() */
818 struct io_completion compl;
821 /* opcode allocated if it needs to store data for async defer */
824 /* polled IO has completed */
830 struct io_ring_ctx *ctx;
833 struct task_struct *task;
836 struct io_kiocb *link;
837 struct percpu_ref *fixed_rsrc_refs;
839 /* used with ctx->iopoll_list with reads/writes */
840 struct list_head inflight_entry;
842 struct io_task_work io_task_work;
843 struct callback_head task_work;
845 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
846 struct hlist_node hash_node;
847 struct async_poll *apoll;
848 struct io_wq_work work;
849 /* store used ubuf, so we can prevent reloading */
850 struct io_mapped_ubuf *imu;
853 struct io_tctx_node {
854 struct list_head ctx_node;
855 struct task_struct *task;
856 struct io_ring_ctx *ctx;
859 struct io_defer_entry {
860 struct list_head list;
861 struct io_kiocb *req;
866 /* needs req->file assigned */
867 unsigned needs_file : 1;
868 /* hash wq insertion if file is a regular file */
869 unsigned hash_reg_file : 1;
870 /* unbound wq insertion if file is a non-regular file */
871 unsigned unbound_nonreg_file : 1;
872 /* opcode is not supported by this kernel */
873 unsigned not_supported : 1;
874 /* set if opcode supports polled "wait" */
876 unsigned pollout : 1;
877 /* op supports buffer selection */
878 unsigned buffer_select : 1;
879 /* do prep async if is going to be punted */
880 unsigned needs_async_setup : 1;
881 /* should block plug */
883 /* size of async data needed, if any */
884 unsigned short async_size;
887 static const struct io_op_def io_op_defs[] = {
888 [IORING_OP_NOP] = {},
889 [IORING_OP_READV] = {
891 .unbound_nonreg_file = 1,
894 .needs_async_setup = 1,
896 .async_size = sizeof(struct io_async_rw),
898 [IORING_OP_WRITEV] = {
901 .unbound_nonreg_file = 1,
903 .needs_async_setup = 1,
905 .async_size = sizeof(struct io_async_rw),
907 [IORING_OP_FSYNC] = {
910 [IORING_OP_READ_FIXED] = {
912 .unbound_nonreg_file = 1,
915 .async_size = sizeof(struct io_async_rw),
917 [IORING_OP_WRITE_FIXED] = {
920 .unbound_nonreg_file = 1,
923 .async_size = sizeof(struct io_async_rw),
925 [IORING_OP_POLL_ADD] = {
927 .unbound_nonreg_file = 1,
929 [IORING_OP_POLL_REMOVE] = {},
930 [IORING_OP_SYNC_FILE_RANGE] = {
933 [IORING_OP_SENDMSG] = {
935 .unbound_nonreg_file = 1,
937 .needs_async_setup = 1,
938 .async_size = sizeof(struct io_async_msghdr),
940 [IORING_OP_RECVMSG] = {
942 .unbound_nonreg_file = 1,
945 .needs_async_setup = 1,
946 .async_size = sizeof(struct io_async_msghdr),
948 [IORING_OP_TIMEOUT] = {
949 .async_size = sizeof(struct io_timeout_data),
951 [IORING_OP_TIMEOUT_REMOVE] = {
952 /* used by timeout updates' prep() */
954 [IORING_OP_ACCEPT] = {
956 .unbound_nonreg_file = 1,
959 [IORING_OP_ASYNC_CANCEL] = {},
960 [IORING_OP_LINK_TIMEOUT] = {
961 .async_size = sizeof(struct io_timeout_data),
963 [IORING_OP_CONNECT] = {
965 .unbound_nonreg_file = 1,
967 .needs_async_setup = 1,
968 .async_size = sizeof(struct io_async_connect),
970 [IORING_OP_FALLOCATE] = {
973 [IORING_OP_OPENAT] = {},
974 [IORING_OP_CLOSE] = {},
975 [IORING_OP_FILES_UPDATE] = {},
976 [IORING_OP_STATX] = {},
979 .unbound_nonreg_file = 1,
983 .async_size = sizeof(struct io_async_rw),
985 [IORING_OP_WRITE] = {
987 .unbound_nonreg_file = 1,
990 .async_size = sizeof(struct io_async_rw),
992 [IORING_OP_FADVISE] = {
995 [IORING_OP_MADVISE] = {},
998 .unbound_nonreg_file = 1,
1001 [IORING_OP_RECV] = {
1003 .unbound_nonreg_file = 1,
1007 [IORING_OP_OPENAT2] = {
1009 [IORING_OP_EPOLL_CTL] = {
1010 .unbound_nonreg_file = 1,
1012 [IORING_OP_SPLICE] = {
1015 .unbound_nonreg_file = 1,
1017 [IORING_OP_PROVIDE_BUFFERS] = {},
1018 [IORING_OP_REMOVE_BUFFERS] = {},
1022 .unbound_nonreg_file = 1,
1024 [IORING_OP_SHUTDOWN] = {
1027 [IORING_OP_RENAMEAT] = {},
1028 [IORING_OP_UNLINKAT] = {},
1031 static bool io_disarm_next(struct io_kiocb *req);
1032 static void io_uring_del_task_file(unsigned long index);
1033 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1034 struct task_struct *task,
1035 struct files_struct *files);
1036 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd);
1037 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1039 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1040 long res, unsigned int cflags);
1041 static void io_put_req(struct io_kiocb *req);
1042 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1043 static void io_dismantle_req(struct io_kiocb *req);
1044 static void io_put_task(struct task_struct *task, int nr);
1045 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1046 static void io_queue_linked_timeout(struct io_kiocb *req);
1047 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1048 struct io_uring_rsrc_update2 *up,
1050 static void io_clean_op(struct io_kiocb *req);
1051 static struct file *io_file_get(struct io_submit_state *state,
1052 struct io_kiocb *req, int fd, bool fixed);
1053 static void __io_queue_sqe(struct io_kiocb *req);
1054 static void io_rsrc_put_work(struct work_struct *work);
1056 static void io_req_task_queue(struct io_kiocb *req);
1057 static void io_submit_flush_completions(struct io_comp_state *cs,
1058 struct io_ring_ctx *ctx);
1059 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1060 static int io_req_prep_async(struct io_kiocb *req);
1062 static struct kmem_cache *req_cachep;
1064 static const struct file_operations io_uring_fops;
1066 struct sock *io_uring_get_socket(struct file *file)
1068 #if defined(CONFIG_UNIX)
1069 if (file->f_op == &io_uring_fops) {
1070 struct io_ring_ctx *ctx = file->private_data;
1072 return ctx->ring_sock->sk;
1077 EXPORT_SYMBOL(io_uring_get_socket);
1079 #define io_for_each_link(pos, head) \
1080 for (pos = (head); pos; pos = pos->link)
1082 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1084 struct io_ring_ctx *ctx = req->ctx;
1086 if (!req->fixed_rsrc_refs) {
1087 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1088 percpu_ref_get(req->fixed_rsrc_refs);
1092 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1094 bool got = percpu_ref_tryget(ref);
1096 /* already at zero, wait for ->release() */
1098 wait_for_completion(compl);
1099 percpu_ref_resurrect(ref);
1101 percpu_ref_put(ref);
1104 static bool io_match_task(struct io_kiocb *head,
1105 struct task_struct *task,
1106 struct files_struct *files)
1108 struct io_kiocb *req;
1110 if (task && head->task != task)
1115 io_for_each_link(req, head) {
1116 if (req->flags & REQ_F_INFLIGHT)
1122 static inline void req_set_fail_links(struct io_kiocb *req)
1124 if (req->flags & REQ_F_LINK)
1125 req->flags |= REQ_F_FAIL_LINK;
1128 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1130 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1132 complete(&ctx->ref_comp);
1135 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1137 return !req->timeout.off;
1140 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1142 struct io_ring_ctx *ctx;
1145 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1150 * Use 5 bits less than the max cq entries, that should give us around
1151 * 32 entries per hash list if totally full and uniformly spread.
1153 hash_bits = ilog2(p->cq_entries);
1157 ctx->cancel_hash_bits = hash_bits;
1158 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1160 if (!ctx->cancel_hash)
1162 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1164 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1165 if (!ctx->dummy_ubuf)
1167 /* set invalid range, so io_import_fixed() fails meeting it */
1168 ctx->dummy_ubuf->ubuf = -1UL;
1170 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1171 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1174 ctx->flags = p->flags;
1175 init_waitqueue_head(&ctx->sqo_sq_wait);
1176 INIT_LIST_HEAD(&ctx->sqd_list);
1177 init_waitqueue_head(&ctx->cq_wait);
1178 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1179 init_completion(&ctx->ref_comp);
1180 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1181 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1182 mutex_init(&ctx->uring_lock);
1183 init_waitqueue_head(&ctx->wait);
1184 spin_lock_init(&ctx->completion_lock);
1185 INIT_LIST_HEAD(&ctx->iopoll_list);
1186 INIT_LIST_HEAD(&ctx->defer_list);
1187 INIT_LIST_HEAD(&ctx->timeout_list);
1188 spin_lock_init(&ctx->rsrc_ref_lock);
1189 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1190 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1191 init_llist_head(&ctx->rsrc_put_llist);
1192 INIT_LIST_HEAD(&ctx->tctx_list);
1193 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1194 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1197 kfree(ctx->dummy_ubuf);
1198 kfree(ctx->cancel_hash);
1203 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1205 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1206 struct io_ring_ctx *ctx = req->ctx;
1208 return seq + ctx->cq_extra != ctx->cached_cq_tail
1209 + READ_ONCE(ctx->cached_cq_overflow);
1215 static void io_req_track_inflight(struct io_kiocb *req)
1217 if (!(req->flags & REQ_F_INFLIGHT)) {
1218 req->flags |= REQ_F_INFLIGHT;
1219 atomic_inc(¤t->io_uring->inflight_tracked);
1223 static void io_prep_async_work(struct io_kiocb *req)
1225 const struct io_op_def *def = &io_op_defs[req->opcode];
1226 struct io_ring_ctx *ctx = req->ctx;
1228 if (!req->work.creds)
1229 req->work.creds = get_current_cred();
1231 req->work.list.next = NULL;
1232 req->work.flags = 0;
1233 if (req->flags & REQ_F_FORCE_ASYNC)
1234 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1236 if (req->flags & REQ_F_ISREG) {
1237 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1238 io_wq_hash_work(&req->work, file_inode(req->file));
1239 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1240 if (def->unbound_nonreg_file)
1241 req->work.flags |= IO_WQ_WORK_UNBOUND;
1244 switch (req->opcode) {
1245 case IORING_OP_SPLICE:
1247 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1248 req->work.flags |= IO_WQ_WORK_UNBOUND;
1253 static void io_prep_async_link(struct io_kiocb *req)
1255 struct io_kiocb *cur;
1257 io_for_each_link(cur, req)
1258 io_prep_async_work(cur);
1261 static void io_queue_async_work(struct io_kiocb *req)
1263 struct io_ring_ctx *ctx = req->ctx;
1264 struct io_kiocb *link = io_prep_linked_timeout(req);
1265 struct io_uring_task *tctx = req->task->io_uring;
1268 BUG_ON(!tctx->io_wq);
1270 /* init ->work of the whole link before punting */
1271 io_prep_async_link(req);
1272 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1273 &req->work, req->flags);
1274 io_wq_enqueue(tctx->io_wq, &req->work);
1276 io_queue_linked_timeout(link);
1279 static void io_kill_timeout(struct io_kiocb *req, int status)
1280 __must_hold(&req->ctx->completion_lock)
1282 struct io_timeout_data *io = req->async_data;
1284 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1285 atomic_set(&req->ctx->cq_timeouts,
1286 atomic_read(&req->ctx->cq_timeouts) + 1);
1287 list_del_init(&req->timeout.list);
1288 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1289 io_put_req_deferred(req, 1);
1293 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1296 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1297 struct io_defer_entry, list);
1299 if (req_need_defer(de->req, de->seq))
1301 list_del_init(&de->list);
1302 io_req_task_queue(de->req);
1304 } while (!list_empty(&ctx->defer_list));
1307 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1311 if (list_empty(&ctx->timeout_list))
1314 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1317 u32 events_needed, events_got;
1318 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1319 struct io_kiocb, timeout.list);
1321 if (io_is_timeout_noseq(req))
1325 * Since seq can easily wrap around over time, subtract
1326 * the last seq at which timeouts were flushed before comparing.
1327 * Assuming not more than 2^31-1 events have happened since,
1328 * these subtractions won't have wrapped, so we can check if
1329 * target is in [last_seq, current_seq] by comparing the two.
1331 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1332 events_got = seq - ctx->cq_last_tm_flush;
1333 if (events_got < events_needed)
1336 list_del_init(&req->timeout.list);
1337 io_kill_timeout(req, 0);
1338 } while (!list_empty(&ctx->timeout_list));
1340 ctx->cq_last_tm_flush = seq;
1343 static void io_commit_cqring(struct io_ring_ctx *ctx)
1345 io_flush_timeouts(ctx);
1347 /* order cqe stores with ring update */
1348 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1350 if (unlikely(!list_empty(&ctx->defer_list)))
1351 __io_queue_deferred(ctx);
1354 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1356 struct io_rings *r = ctx->rings;
1358 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1361 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1363 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1366 static inline struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1368 struct io_rings *rings = ctx->rings;
1372 * writes to the cq entry need to come after reading head; the
1373 * control dependency is enough as we're using WRITE_ONCE to
1376 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1379 tail = ctx->cached_cq_tail++;
1380 return &rings->cqes[tail & ctx->cq_mask];
1383 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1385 if (likely(!ctx->cq_ev_fd))
1387 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1389 return !ctx->eventfd_async || io_wq_current_is_worker();
1392 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1394 /* see waitqueue_active() comment */
1397 if (waitqueue_active(&ctx->wait))
1398 wake_up(&ctx->wait);
1399 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1400 wake_up(&ctx->sq_data->wait);
1401 if (io_should_trigger_evfd(ctx))
1402 eventfd_signal(ctx->cq_ev_fd, 1);
1403 if (waitqueue_active(&ctx->cq_wait)) {
1404 wake_up_interruptible(&ctx->cq_wait);
1405 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1409 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1411 /* see waitqueue_active() comment */
1414 if (ctx->flags & IORING_SETUP_SQPOLL) {
1415 if (waitqueue_active(&ctx->wait))
1416 wake_up(&ctx->wait);
1418 if (io_should_trigger_evfd(ctx))
1419 eventfd_signal(ctx->cq_ev_fd, 1);
1420 if (waitqueue_active(&ctx->cq_wait)) {
1421 wake_up_interruptible(&ctx->cq_wait);
1422 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1426 /* Returns true if there are no backlogged entries after the flush */
1427 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1429 struct io_rings *rings = ctx->rings;
1430 unsigned long flags;
1431 bool all_flushed, posted;
1433 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1437 spin_lock_irqsave(&ctx->completion_lock, flags);
1438 while (!list_empty(&ctx->cq_overflow_list)) {
1439 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1440 struct io_overflow_cqe *ocqe;
1444 ocqe = list_first_entry(&ctx->cq_overflow_list,
1445 struct io_overflow_cqe, list);
1447 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1449 WRITE_ONCE(ctx->rings->cq_overflow,
1450 ++ctx->cached_cq_overflow);
1452 list_del(&ocqe->list);
1456 all_flushed = list_empty(&ctx->cq_overflow_list);
1458 clear_bit(0, &ctx->sq_check_overflow);
1459 clear_bit(0, &ctx->cq_check_overflow);
1460 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1464 io_commit_cqring(ctx);
1465 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1467 io_cqring_ev_posted(ctx);
1471 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1475 if (test_bit(0, &ctx->cq_check_overflow)) {
1476 /* iopoll syncs against uring_lock, not completion_lock */
1477 if (ctx->flags & IORING_SETUP_IOPOLL)
1478 mutex_lock(&ctx->uring_lock);
1479 ret = __io_cqring_overflow_flush(ctx, force);
1480 if (ctx->flags & IORING_SETUP_IOPOLL)
1481 mutex_unlock(&ctx->uring_lock);
1488 * Shamelessly stolen from the mm implementation of page reference checking,
1489 * see commit f958d7b528b1 for details.
1491 #define req_ref_zero_or_close_to_overflow(req) \
1492 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1494 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1496 return atomic_inc_not_zero(&req->refs);
1499 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1501 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1502 return atomic_sub_and_test(refs, &req->refs);
1505 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1507 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1508 return atomic_dec_and_test(&req->refs);
1511 static inline void req_ref_put(struct io_kiocb *req)
1513 WARN_ON_ONCE(req_ref_put_and_test(req));
1516 static inline void req_ref_get(struct io_kiocb *req)
1518 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1519 atomic_inc(&req->refs);
1522 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1523 long res, unsigned int cflags)
1525 struct io_overflow_cqe *ocqe;
1527 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1530 * If we're in ring overflow flush mode, or in task cancel mode,
1531 * or cannot allocate an overflow entry, then we need to drop it
1534 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1537 if (list_empty(&ctx->cq_overflow_list)) {
1538 set_bit(0, &ctx->sq_check_overflow);
1539 set_bit(0, &ctx->cq_check_overflow);
1540 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1542 ocqe->cqe.user_data = user_data;
1543 ocqe->cqe.res = res;
1544 ocqe->cqe.flags = cflags;
1545 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1549 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1550 long res, unsigned int cflags)
1552 struct io_uring_cqe *cqe;
1554 trace_io_uring_complete(ctx, user_data, res, cflags);
1557 * If we can't get a cq entry, userspace overflowed the
1558 * submission (by quite a lot). Increment the overflow count in
1561 cqe = io_get_cqring(ctx);
1563 WRITE_ONCE(cqe->user_data, user_data);
1564 WRITE_ONCE(cqe->res, res);
1565 WRITE_ONCE(cqe->flags, cflags);
1568 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1571 /* not as hot to bloat with inlining */
1572 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1573 long res, unsigned int cflags)
1575 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1578 static void io_req_complete_post(struct io_kiocb *req, long res,
1579 unsigned int cflags)
1581 struct io_ring_ctx *ctx = req->ctx;
1582 unsigned long flags;
1584 spin_lock_irqsave(&ctx->completion_lock, flags);
1585 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1587 * If we're the last reference to this request, add to our locked
1590 if (req_ref_put_and_test(req)) {
1591 struct io_comp_state *cs = &ctx->submit_state.comp;
1593 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1594 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1595 io_disarm_next(req);
1597 io_req_task_queue(req->link);
1601 io_dismantle_req(req);
1602 io_put_task(req->task, 1);
1603 list_add(&req->compl.list, &cs->locked_free_list);
1604 cs->locked_free_nr++;
1606 if (!percpu_ref_tryget(&ctx->refs))
1609 io_commit_cqring(ctx);
1610 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1613 io_cqring_ev_posted(ctx);
1614 percpu_ref_put(&ctx->refs);
1618 static inline bool io_req_needs_clean(struct io_kiocb *req)
1620 return req->flags & (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP |
1621 REQ_F_POLLED | REQ_F_INFLIGHT);
1624 static void io_req_complete_state(struct io_kiocb *req, long res,
1625 unsigned int cflags)
1627 if (io_req_needs_clean(req))
1630 req->compl.cflags = cflags;
1631 req->flags |= REQ_F_COMPLETE_INLINE;
1634 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1635 long res, unsigned cflags)
1637 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1638 io_req_complete_state(req, res, cflags);
1640 io_req_complete_post(req, res, cflags);
1643 static inline void io_req_complete(struct io_kiocb *req, long res)
1645 __io_req_complete(req, 0, res, 0);
1648 static void io_req_complete_failed(struct io_kiocb *req, long res)
1650 req_set_fail_links(req);
1652 io_req_complete_post(req, res, 0);
1655 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1656 struct io_comp_state *cs)
1658 spin_lock_irq(&ctx->completion_lock);
1659 list_splice_init(&cs->locked_free_list, &cs->free_list);
1660 cs->locked_free_nr = 0;
1661 spin_unlock_irq(&ctx->completion_lock);
1664 /* Returns true IFF there are requests in the cache */
1665 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1667 struct io_submit_state *state = &ctx->submit_state;
1668 struct io_comp_state *cs = &state->comp;
1672 * If we have more than a batch's worth of requests in our IRQ side
1673 * locked cache, grab the lock and move them over to our submission
1676 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
1677 io_flush_cached_locked_reqs(ctx, cs);
1679 nr = state->free_reqs;
1680 while (!list_empty(&cs->free_list)) {
1681 struct io_kiocb *req = list_first_entry(&cs->free_list,
1682 struct io_kiocb, compl.list);
1684 list_del(&req->compl.list);
1685 state->reqs[nr++] = req;
1686 if (nr == ARRAY_SIZE(state->reqs))
1690 state->free_reqs = nr;
1694 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1696 struct io_submit_state *state = &ctx->submit_state;
1698 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1700 if (!state->free_reqs) {
1701 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1704 if (io_flush_cached_reqs(ctx))
1707 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1711 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1712 * retry single alloc to be on the safe side.
1714 if (unlikely(ret <= 0)) {
1715 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1716 if (!state->reqs[0])
1720 state->free_reqs = ret;
1724 return state->reqs[state->free_reqs];
1727 static inline void io_put_file(struct file *file)
1733 static void io_dismantle_req(struct io_kiocb *req)
1735 unsigned int flags = req->flags;
1737 if (io_req_needs_clean(req))
1739 if (!(flags & REQ_F_FIXED_FILE))
1740 io_put_file(req->file);
1741 if (req->fixed_rsrc_refs)
1742 percpu_ref_put(req->fixed_rsrc_refs);
1743 if (req->async_data)
1744 kfree(req->async_data);
1745 if (req->work.creds) {
1746 put_cred(req->work.creds);
1747 req->work.creds = NULL;
1751 /* must to be called somewhat shortly after putting a request */
1752 static inline void io_put_task(struct task_struct *task, int nr)
1754 struct io_uring_task *tctx = task->io_uring;
1756 percpu_counter_sub(&tctx->inflight, nr);
1757 if (unlikely(atomic_read(&tctx->in_idle)))
1758 wake_up(&tctx->wait);
1759 put_task_struct_many(task, nr);
1762 static void __io_free_req(struct io_kiocb *req)
1764 struct io_ring_ctx *ctx = req->ctx;
1766 io_dismantle_req(req);
1767 io_put_task(req->task, 1);
1769 kmem_cache_free(req_cachep, req);
1770 percpu_ref_put(&ctx->refs);
1773 static inline void io_remove_next_linked(struct io_kiocb *req)
1775 struct io_kiocb *nxt = req->link;
1777 req->link = nxt->link;
1781 static bool io_kill_linked_timeout(struct io_kiocb *req)
1782 __must_hold(&req->ctx->completion_lock)
1784 struct io_kiocb *link = req->link;
1787 * Can happen if a linked timeout fired and link had been like
1788 * req -> link t-out -> link t-out [-> ...]
1790 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1791 struct io_timeout_data *io = link->async_data;
1793 io_remove_next_linked(req);
1794 link->timeout.head = NULL;
1795 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1796 io_cqring_fill_event(link->ctx, link->user_data,
1798 io_put_req_deferred(link, 1);
1805 static void io_fail_links(struct io_kiocb *req)
1806 __must_hold(&req->ctx->completion_lock)
1808 struct io_kiocb *nxt, *link = req->link;
1815 trace_io_uring_fail_link(req, link);
1816 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1817 io_put_req_deferred(link, 2);
1822 static bool io_disarm_next(struct io_kiocb *req)
1823 __must_hold(&req->ctx->completion_lock)
1825 bool posted = false;
1827 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1828 posted = io_kill_linked_timeout(req);
1829 if (unlikely((req->flags & REQ_F_FAIL_LINK) &&
1830 !(req->flags & REQ_F_HARDLINK))) {
1831 posted |= (req->link != NULL);
1837 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1839 struct io_kiocb *nxt;
1842 * If LINK is set, we have dependent requests in this chain. If we
1843 * didn't fail this request, queue the first one up, moving any other
1844 * dependencies to the next request. In case of failure, fail the rest
1847 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1848 struct io_ring_ctx *ctx = req->ctx;
1849 unsigned long flags;
1852 spin_lock_irqsave(&ctx->completion_lock, flags);
1853 posted = io_disarm_next(req);
1855 io_commit_cqring(req->ctx);
1856 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1858 io_cqring_ev_posted(ctx);
1865 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1867 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1869 return __io_req_find_next(req);
1872 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1876 if (ctx->submit_state.comp.nr) {
1877 mutex_lock(&ctx->uring_lock);
1878 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1879 mutex_unlock(&ctx->uring_lock);
1881 percpu_ref_put(&ctx->refs);
1884 static bool __tctx_task_work(struct io_uring_task *tctx)
1886 struct io_ring_ctx *ctx = NULL;
1887 struct io_wq_work_list list;
1888 struct io_wq_work_node *node;
1890 if (wq_list_empty(&tctx->task_list))
1893 spin_lock_irq(&tctx->task_lock);
1894 list = tctx->task_list;
1895 INIT_WQ_LIST(&tctx->task_list);
1896 spin_unlock_irq(&tctx->task_lock);
1900 struct io_wq_work_node *next = node->next;
1901 struct io_kiocb *req;
1903 req = container_of(node, struct io_kiocb, io_task_work.node);
1904 if (req->ctx != ctx) {
1905 ctx_flush_and_put(ctx);
1907 percpu_ref_get(&ctx->refs);
1910 req->task_work.func(&req->task_work);
1914 ctx_flush_and_put(ctx);
1915 return list.first != NULL;
1918 static void tctx_task_work(struct callback_head *cb)
1920 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1922 clear_bit(0, &tctx->task_state);
1924 while (__tctx_task_work(tctx))
1928 static int io_req_task_work_add(struct io_kiocb *req)
1930 struct task_struct *tsk = req->task;
1931 struct io_uring_task *tctx = tsk->io_uring;
1932 enum task_work_notify_mode notify;
1933 struct io_wq_work_node *node, *prev;
1934 unsigned long flags;
1937 if (unlikely(tsk->flags & PF_EXITING))
1940 WARN_ON_ONCE(!tctx);
1942 spin_lock_irqsave(&tctx->task_lock, flags);
1943 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1944 spin_unlock_irqrestore(&tctx->task_lock, flags);
1946 /* task_work already pending, we're done */
1947 if (test_bit(0, &tctx->task_state) ||
1948 test_and_set_bit(0, &tctx->task_state))
1952 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1953 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1954 * processing task_work. There's no reliable way to tell if TWA_RESUME
1957 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1959 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1960 wake_up_process(tsk);
1965 * Slow path - we failed, find and delete work. if the work is not
1966 * in the list, it got run and we're fine.
1968 spin_lock_irqsave(&tctx->task_lock, flags);
1969 wq_list_for_each(node, prev, &tctx->task_list) {
1970 if (&req->io_task_work.node == node) {
1971 wq_list_del(&tctx->task_list, node, prev);
1976 spin_unlock_irqrestore(&tctx->task_lock, flags);
1977 clear_bit(0, &tctx->task_state);
1981 static bool io_run_task_work_head(struct callback_head **work_head)
1983 struct callback_head *work, *next;
1984 bool executed = false;
1987 work = xchg(work_head, NULL);
2003 static void io_task_work_add_head(struct callback_head **work_head,
2004 struct callback_head *task_work)
2006 struct callback_head *head;
2009 head = READ_ONCE(*work_head);
2010 task_work->next = head;
2011 } while (cmpxchg(work_head, head, task_work) != head);
2014 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2015 task_work_func_t cb)
2017 init_task_work(&req->task_work, cb);
2018 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2021 static void io_req_task_cancel(struct callback_head *cb)
2023 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2024 struct io_ring_ctx *ctx = req->ctx;
2026 /* ctx is guaranteed to stay alive while we hold uring_lock */
2027 mutex_lock(&ctx->uring_lock);
2028 io_req_complete_failed(req, req->result);
2029 mutex_unlock(&ctx->uring_lock);
2032 static void __io_req_task_submit(struct io_kiocb *req)
2034 struct io_ring_ctx *ctx = req->ctx;
2036 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2037 mutex_lock(&ctx->uring_lock);
2038 if (!(current->flags & PF_EXITING) && !current->in_execve)
2039 __io_queue_sqe(req);
2041 io_req_complete_failed(req, -EFAULT);
2042 mutex_unlock(&ctx->uring_lock);
2045 static void io_req_task_submit(struct callback_head *cb)
2047 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2049 __io_req_task_submit(req);
2052 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2055 req->task_work.func = io_req_task_cancel;
2057 if (unlikely(io_req_task_work_add(req)))
2058 io_req_task_work_add_fallback(req, io_req_task_cancel);
2061 static void io_req_task_queue(struct io_kiocb *req)
2063 req->task_work.func = io_req_task_submit;
2065 if (unlikely(io_req_task_work_add(req)))
2066 io_req_task_queue_fail(req, -ECANCELED);
2069 static inline void io_queue_next(struct io_kiocb *req)
2071 struct io_kiocb *nxt = io_req_find_next(req);
2074 io_req_task_queue(nxt);
2077 static void io_free_req(struct io_kiocb *req)
2084 struct task_struct *task;
2089 static inline void io_init_req_batch(struct req_batch *rb)
2096 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2097 struct req_batch *rb)
2100 io_put_task(rb->task, rb->task_refs);
2102 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2105 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2106 struct io_submit_state *state)
2109 io_dismantle_req(req);
2111 if (req->task != rb->task) {
2113 io_put_task(rb->task, rb->task_refs);
2114 rb->task = req->task;
2120 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2121 state->reqs[state->free_reqs++] = req;
2123 list_add(&req->compl.list, &state->comp.free_list);
2126 static void io_submit_flush_completions(struct io_comp_state *cs,
2127 struct io_ring_ctx *ctx)
2130 struct io_kiocb *req;
2131 struct req_batch rb;
2133 io_init_req_batch(&rb);
2134 spin_lock_irq(&ctx->completion_lock);
2135 for (i = 0; i < nr; i++) {
2137 __io_cqring_fill_event(ctx, req->user_data, req->result,
2140 io_commit_cqring(ctx);
2141 spin_unlock_irq(&ctx->completion_lock);
2143 io_cqring_ev_posted(ctx);
2144 for (i = 0; i < nr; i++) {
2147 /* submission and completion refs */
2148 if (req_ref_sub_and_test(req, 2))
2149 io_req_free_batch(&rb, req, &ctx->submit_state);
2152 io_req_free_batch_finish(ctx, &rb);
2157 * Drop reference to request, return next in chain (if there is one) if this
2158 * was the last reference to this request.
2160 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2162 struct io_kiocb *nxt = NULL;
2164 if (req_ref_put_and_test(req)) {
2165 nxt = io_req_find_next(req);
2171 static inline void io_put_req(struct io_kiocb *req)
2173 if (req_ref_put_and_test(req))
2177 static void io_put_req_deferred_cb(struct callback_head *cb)
2179 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2184 static void io_free_req_deferred(struct io_kiocb *req)
2186 req->task_work.func = io_put_req_deferred_cb;
2187 if (unlikely(io_req_task_work_add(req)))
2188 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2191 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2193 if (req_ref_sub_and_test(req, refs))
2194 io_free_req_deferred(req);
2197 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2199 /* See comment at the top of this file */
2201 return __io_cqring_events(ctx);
2204 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2206 struct io_rings *rings = ctx->rings;
2208 /* make sure SQ entry isn't read before tail */
2209 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2212 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2214 unsigned int cflags;
2216 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2217 cflags |= IORING_CQE_F_BUFFER;
2218 req->flags &= ~REQ_F_BUFFER_SELECTED;
2223 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2225 struct io_buffer *kbuf;
2227 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2228 return io_put_kbuf(req, kbuf);
2231 static inline bool io_run_task_work(void)
2234 * Not safe to run on exiting task, and the task_work handling will
2235 * not add work to such a task.
2237 if (unlikely(current->flags & PF_EXITING))
2239 if (current->task_works) {
2240 __set_current_state(TASK_RUNNING);
2249 * Find and free completed poll iocbs
2251 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2252 struct list_head *done)
2254 struct req_batch rb;
2255 struct io_kiocb *req;
2257 /* order with ->result store in io_complete_rw_iopoll() */
2260 io_init_req_batch(&rb);
2261 while (!list_empty(done)) {
2264 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2265 list_del(&req->inflight_entry);
2267 if (READ_ONCE(req->result) == -EAGAIN &&
2268 !(req->flags & REQ_F_DONT_REISSUE)) {
2269 req->iopoll_completed = 0;
2271 io_queue_async_work(req);
2275 if (req->flags & REQ_F_BUFFER_SELECTED)
2276 cflags = io_put_rw_kbuf(req);
2278 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2281 if (req_ref_put_and_test(req))
2282 io_req_free_batch(&rb, req, &ctx->submit_state);
2285 io_commit_cqring(ctx);
2286 io_cqring_ev_posted_iopoll(ctx);
2287 io_req_free_batch_finish(ctx, &rb);
2290 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2293 struct io_kiocb *req, *tmp;
2299 * Only spin for completions if we don't have multiple devices hanging
2300 * off our complete list, and we're under the requested amount.
2302 spin = !ctx->poll_multi_file && *nr_events < min;
2305 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2306 struct kiocb *kiocb = &req->rw.kiocb;
2309 * Move completed and retryable entries to our local lists.
2310 * If we find a request that requires polling, break out
2311 * and complete those lists first, if we have entries there.
2313 if (READ_ONCE(req->iopoll_completed)) {
2314 list_move_tail(&req->inflight_entry, &done);
2317 if (!list_empty(&done))
2320 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2324 /* iopoll may have completed current req */
2325 if (READ_ONCE(req->iopoll_completed))
2326 list_move_tail(&req->inflight_entry, &done);
2333 if (!list_empty(&done))
2334 io_iopoll_complete(ctx, nr_events, &done);
2340 * We can't just wait for polled events to come to us, we have to actively
2341 * find and complete them.
2343 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2345 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2348 mutex_lock(&ctx->uring_lock);
2349 while (!list_empty(&ctx->iopoll_list)) {
2350 unsigned int nr_events = 0;
2352 io_do_iopoll(ctx, &nr_events, 0);
2354 /* let it sleep and repeat later if can't complete a request */
2358 * Ensure we allow local-to-the-cpu processing to take place,
2359 * in this case we need to ensure that we reap all events.
2360 * Also let task_work, etc. to progress by releasing the mutex
2362 if (need_resched()) {
2363 mutex_unlock(&ctx->uring_lock);
2365 mutex_lock(&ctx->uring_lock);
2368 mutex_unlock(&ctx->uring_lock);
2371 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2373 unsigned int nr_events = 0;
2377 * We disallow the app entering submit/complete with polling, but we
2378 * still need to lock the ring to prevent racing with polled issue
2379 * that got punted to a workqueue.
2381 mutex_lock(&ctx->uring_lock);
2383 * Don't enter poll loop if we already have events pending.
2384 * If we do, we can potentially be spinning for commands that
2385 * already triggered a CQE (eg in error).
2387 if (test_bit(0, &ctx->cq_check_overflow))
2388 __io_cqring_overflow_flush(ctx, false);
2389 if (io_cqring_events(ctx))
2393 * If a submit got punted to a workqueue, we can have the
2394 * application entering polling for a command before it gets
2395 * issued. That app will hold the uring_lock for the duration
2396 * of the poll right here, so we need to take a breather every
2397 * now and then to ensure that the issue has a chance to add
2398 * the poll to the issued list. Otherwise we can spin here
2399 * forever, while the workqueue is stuck trying to acquire the
2402 if (list_empty(&ctx->iopoll_list)) {
2403 mutex_unlock(&ctx->uring_lock);
2405 mutex_lock(&ctx->uring_lock);
2407 if (list_empty(&ctx->iopoll_list))
2410 ret = io_do_iopoll(ctx, &nr_events, min);
2411 } while (!ret && nr_events < min && !need_resched());
2413 mutex_unlock(&ctx->uring_lock);
2417 static void kiocb_end_write(struct io_kiocb *req)
2420 * Tell lockdep we inherited freeze protection from submission
2423 if (req->flags & REQ_F_ISREG) {
2424 struct super_block *sb = file_inode(req->file)->i_sb;
2426 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2432 static bool io_resubmit_prep(struct io_kiocb *req)
2434 struct io_async_rw *rw = req->async_data;
2437 return !io_req_prep_async(req);
2438 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2439 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2443 static bool io_rw_should_reissue(struct io_kiocb *req)
2445 umode_t mode = file_inode(req->file)->i_mode;
2446 struct io_ring_ctx *ctx = req->ctx;
2448 if (!S_ISBLK(mode) && !S_ISREG(mode))
2450 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2451 !(ctx->flags & IORING_SETUP_IOPOLL)))
2454 * If ref is dying, we might be running poll reap from the exit work.
2455 * Don't attempt to reissue from that path, just let it fail with
2458 if (percpu_ref_is_dying(&ctx->refs))
2463 static bool io_resubmit_prep(struct io_kiocb *req)
2467 static bool io_rw_should_reissue(struct io_kiocb *req)
2473 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2474 unsigned int issue_flags)
2478 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2479 kiocb_end_write(req);
2480 if (res != req->result) {
2481 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2482 io_rw_should_reissue(req)) {
2483 req->flags |= REQ_F_REISSUE;
2486 req_set_fail_links(req);
2488 if (req->flags & REQ_F_BUFFER_SELECTED)
2489 cflags = io_put_rw_kbuf(req);
2490 __io_req_complete(req, issue_flags, res, cflags);
2493 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2495 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2497 __io_complete_rw(req, res, res2, 0);
2500 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2502 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2504 if (kiocb->ki_flags & IOCB_WRITE)
2505 kiocb_end_write(req);
2506 if (unlikely(res != req->result)) {
2507 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2508 io_resubmit_prep(req))) {
2509 req_set_fail_links(req);
2510 req->flags |= REQ_F_DONT_REISSUE;
2514 WRITE_ONCE(req->result, res);
2515 /* order with io_iopoll_complete() checking ->result */
2517 WRITE_ONCE(req->iopoll_completed, 1);
2521 * After the iocb has been issued, it's safe to be found on the poll list.
2522 * Adding the kiocb to the list AFTER submission ensures that we don't
2523 * find it from a io_do_iopoll() thread before the issuer is done
2524 * accessing the kiocb cookie.
2526 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2528 struct io_ring_ctx *ctx = req->ctx;
2531 * Track whether we have multiple files in our lists. This will impact
2532 * how we do polling eventually, not spinning if we're on potentially
2533 * different devices.
2535 if (list_empty(&ctx->iopoll_list)) {
2536 ctx->poll_multi_file = false;
2537 } else if (!ctx->poll_multi_file) {
2538 struct io_kiocb *list_req;
2540 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2542 if (list_req->file != req->file)
2543 ctx->poll_multi_file = true;
2547 * For fast devices, IO may have already completed. If it has, add
2548 * it to the front so we find it first.
2550 if (READ_ONCE(req->iopoll_completed))
2551 list_add(&req->inflight_entry, &ctx->iopoll_list);
2553 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2556 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2557 * task context or in io worker task context. If current task context is
2558 * sq thread, we don't need to check whether should wake up sq thread.
2560 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2561 wq_has_sleeper(&ctx->sq_data->wait))
2562 wake_up(&ctx->sq_data->wait);
2565 static inline void io_state_file_put(struct io_submit_state *state)
2567 if (state->file_refs) {
2568 fput_many(state->file, state->file_refs);
2569 state->file_refs = 0;
2574 * Get as many references to a file as we have IOs left in this submission,
2575 * assuming most submissions are for one file, or at least that each file
2576 * has more than one submission.
2578 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2583 if (state->file_refs) {
2584 if (state->fd == fd) {
2588 io_state_file_put(state);
2590 state->file = fget_many(fd, state->ios_left);
2591 if (unlikely(!state->file))
2595 state->file_refs = state->ios_left - 1;
2599 static bool io_bdev_nowait(struct block_device *bdev)
2601 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2605 * If we tracked the file through the SCM inflight mechanism, we could support
2606 * any file. For now, just ensure that anything potentially problematic is done
2609 static bool __io_file_supports_async(struct file *file, int rw)
2611 umode_t mode = file_inode(file)->i_mode;
2613 if (S_ISBLK(mode)) {
2614 if (IS_ENABLED(CONFIG_BLOCK) &&
2615 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2619 if (S_ISCHR(mode) || S_ISSOCK(mode))
2621 if (S_ISREG(mode)) {
2622 if (IS_ENABLED(CONFIG_BLOCK) &&
2623 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2624 file->f_op != &io_uring_fops)
2629 /* any ->read/write should understand O_NONBLOCK */
2630 if (file->f_flags & O_NONBLOCK)
2633 if (!(file->f_mode & FMODE_NOWAIT))
2637 return file->f_op->read_iter != NULL;
2639 return file->f_op->write_iter != NULL;
2642 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2644 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2646 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2649 return __io_file_supports_async(req->file, rw);
2652 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2654 struct io_ring_ctx *ctx = req->ctx;
2655 struct kiocb *kiocb = &req->rw.kiocb;
2656 struct file *file = req->file;
2660 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2661 req->flags |= REQ_F_ISREG;
2663 kiocb->ki_pos = READ_ONCE(sqe->off);
2664 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2665 req->flags |= REQ_F_CUR_POS;
2666 kiocb->ki_pos = file->f_pos;
2668 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2669 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2670 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2674 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2675 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2676 req->flags |= REQ_F_NOWAIT;
2678 ioprio = READ_ONCE(sqe->ioprio);
2680 ret = ioprio_check_cap(ioprio);
2684 kiocb->ki_ioprio = ioprio;
2686 kiocb->ki_ioprio = get_current_ioprio();
2688 if (ctx->flags & IORING_SETUP_IOPOLL) {
2689 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2690 !kiocb->ki_filp->f_op->iopoll)
2693 kiocb->ki_flags |= IOCB_HIPRI;
2694 kiocb->ki_complete = io_complete_rw_iopoll;
2695 req->iopoll_completed = 0;
2697 if (kiocb->ki_flags & IOCB_HIPRI)
2699 kiocb->ki_complete = io_complete_rw;
2702 if (req->opcode == IORING_OP_READ_FIXED ||
2703 req->opcode == IORING_OP_WRITE_FIXED) {
2705 io_req_set_rsrc_node(req);
2708 req->rw.addr = READ_ONCE(sqe->addr);
2709 req->rw.len = READ_ONCE(sqe->len);
2710 req->buf_index = READ_ONCE(sqe->buf_index);
2714 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2720 case -ERESTARTNOINTR:
2721 case -ERESTARTNOHAND:
2722 case -ERESTART_RESTARTBLOCK:
2724 * We can't just restart the syscall, since previously
2725 * submitted sqes may already be in progress. Just fail this
2731 kiocb->ki_complete(kiocb, ret, 0);
2735 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2736 unsigned int issue_flags)
2738 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2739 struct io_async_rw *io = req->async_data;
2740 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2742 /* add previously done IO, if any */
2743 if (io && io->bytes_done > 0) {
2745 ret = io->bytes_done;
2747 ret += io->bytes_done;
2750 if (req->flags & REQ_F_CUR_POS)
2751 req->file->f_pos = kiocb->ki_pos;
2752 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2753 __io_complete_rw(req, ret, 0, issue_flags);
2755 io_rw_done(kiocb, ret);
2757 if (check_reissue && req->flags & REQ_F_REISSUE) {
2758 req->flags &= ~REQ_F_REISSUE;
2759 if (io_resubmit_prep(req)) {
2761 io_queue_async_work(req);
2765 req_set_fail_links(req);
2766 if (req->flags & REQ_F_BUFFER_SELECTED)
2767 cflags = io_put_rw_kbuf(req);
2768 __io_req_complete(req, issue_flags, ret, cflags);
2773 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2774 struct io_mapped_ubuf *imu)
2776 size_t len = req->rw.len;
2777 u64 buf_end, buf_addr = req->rw.addr;
2780 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2782 /* not inside the mapped region */
2783 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2787 * May not be a start of buffer, set size appropriately
2788 * and advance us to the beginning.
2790 offset = buf_addr - imu->ubuf;
2791 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2795 * Don't use iov_iter_advance() here, as it's really slow for
2796 * using the latter parts of a big fixed buffer - it iterates
2797 * over each segment manually. We can cheat a bit here, because
2800 * 1) it's a BVEC iter, we set it up
2801 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2802 * first and last bvec
2804 * So just find our index, and adjust the iterator afterwards.
2805 * If the offset is within the first bvec (or the whole first
2806 * bvec, just use iov_iter_advance(). This makes it easier
2807 * since we can just skip the first segment, which may not
2808 * be PAGE_SIZE aligned.
2810 const struct bio_vec *bvec = imu->bvec;
2812 if (offset <= bvec->bv_len) {
2813 iov_iter_advance(iter, offset);
2815 unsigned long seg_skip;
2817 /* skip first vec */
2818 offset -= bvec->bv_len;
2819 seg_skip = 1 + (offset >> PAGE_SHIFT);
2821 iter->bvec = bvec + seg_skip;
2822 iter->nr_segs -= seg_skip;
2823 iter->count -= bvec->bv_len + offset;
2824 iter->iov_offset = offset & ~PAGE_MASK;
2831 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2833 struct io_ring_ctx *ctx = req->ctx;
2834 struct io_mapped_ubuf *imu = req->imu;
2835 u16 index, buf_index = req->buf_index;
2838 if (unlikely(buf_index >= ctx->nr_user_bufs))
2840 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2841 imu = READ_ONCE(ctx->user_bufs[index]);
2844 return __io_import_fixed(req, rw, iter, imu);
2847 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2850 mutex_unlock(&ctx->uring_lock);
2853 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2856 * "Normal" inline submissions always hold the uring_lock, since we
2857 * grab it from the system call. Same is true for the SQPOLL offload.
2858 * The only exception is when we've detached the request and issue it
2859 * from an async worker thread, grab the lock for that case.
2862 mutex_lock(&ctx->uring_lock);
2865 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2866 int bgid, struct io_buffer *kbuf,
2869 struct io_buffer *head;
2871 if (req->flags & REQ_F_BUFFER_SELECTED)
2874 io_ring_submit_lock(req->ctx, needs_lock);
2876 lockdep_assert_held(&req->ctx->uring_lock);
2878 head = xa_load(&req->ctx->io_buffers, bgid);
2880 if (!list_empty(&head->list)) {
2881 kbuf = list_last_entry(&head->list, struct io_buffer,
2883 list_del(&kbuf->list);
2886 xa_erase(&req->ctx->io_buffers, bgid);
2888 if (*len > kbuf->len)
2891 kbuf = ERR_PTR(-ENOBUFS);
2894 io_ring_submit_unlock(req->ctx, needs_lock);
2899 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2902 struct io_buffer *kbuf;
2905 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2906 bgid = req->buf_index;
2907 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2910 req->rw.addr = (u64) (unsigned long) kbuf;
2911 req->flags |= REQ_F_BUFFER_SELECTED;
2912 return u64_to_user_ptr(kbuf->addr);
2915 #ifdef CONFIG_COMPAT
2916 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2919 struct compat_iovec __user *uiov;
2920 compat_ssize_t clen;
2924 uiov = u64_to_user_ptr(req->rw.addr);
2925 if (!access_ok(uiov, sizeof(*uiov)))
2927 if (__get_user(clen, &uiov->iov_len))
2933 buf = io_rw_buffer_select(req, &len, needs_lock);
2935 return PTR_ERR(buf);
2936 iov[0].iov_base = buf;
2937 iov[0].iov_len = (compat_size_t) len;
2942 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2945 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2949 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2952 len = iov[0].iov_len;
2955 buf = io_rw_buffer_select(req, &len, needs_lock);
2957 return PTR_ERR(buf);
2958 iov[0].iov_base = buf;
2959 iov[0].iov_len = len;
2963 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2966 if (req->flags & REQ_F_BUFFER_SELECTED) {
2967 struct io_buffer *kbuf;
2969 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2970 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2971 iov[0].iov_len = kbuf->len;
2974 if (req->rw.len != 1)
2977 #ifdef CONFIG_COMPAT
2978 if (req->ctx->compat)
2979 return io_compat_import(req, iov, needs_lock);
2982 return __io_iov_buffer_select(req, iov, needs_lock);
2985 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2986 struct iov_iter *iter, bool needs_lock)
2988 void __user *buf = u64_to_user_ptr(req->rw.addr);
2989 size_t sqe_len = req->rw.len;
2990 u8 opcode = req->opcode;
2993 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2995 return io_import_fixed(req, rw, iter);
2998 /* buffer index only valid with fixed read/write, or buffer select */
2999 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3002 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3003 if (req->flags & REQ_F_BUFFER_SELECT) {
3004 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3006 return PTR_ERR(buf);
3007 req->rw.len = sqe_len;
3010 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3015 if (req->flags & REQ_F_BUFFER_SELECT) {
3016 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3018 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3023 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3027 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3029 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3033 * For files that don't have ->read_iter() and ->write_iter(), handle them
3034 * by looping over ->read() or ->write() manually.
3036 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3038 struct kiocb *kiocb = &req->rw.kiocb;
3039 struct file *file = req->file;
3043 * Don't support polled IO through this interface, and we can't
3044 * support non-blocking either. For the latter, this just causes
3045 * the kiocb to be handled from an async context.
3047 if (kiocb->ki_flags & IOCB_HIPRI)
3049 if (kiocb->ki_flags & IOCB_NOWAIT)
3052 while (iov_iter_count(iter)) {
3056 if (!iov_iter_is_bvec(iter)) {
3057 iovec = iov_iter_iovec(iter);
3059 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3060 iovec.iov_len = req->rw.len;
3064 nr = file->f_op->read(file, iovec.iov_base,
3065 iovec.iov_len, io_kiocb_ppos(kiocb));
3067 nr = file->f_op->write(file, iovec.iov_base,
3068 iovec.iov_len, io_kiocb_ppos(kiocb));
3077 if (nr != iovec.iov_len)
3081 iov_iter_advance(iter, nr);
3087 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3088 const struct iovec *fast_iov, struct iov_iter *iter)
3090 struct io_async_rw *rw = req->async_data;
3092 memcpy(&rw->iter, iter, sizeof(*iter));
3093 rw->free_iovec = iovec;
3095 /* can only be fixed buffers, no need to do anything */
3096 if (iov_iter_is_bvec(iter))
3099 unsigned iov_off = 0;
3101 rw->iter.iov = rw->fast_iov;
3102 if (iter->iov != fast_iov) {
3103 iov_off = iter->iov - fast_iov;
3104 rw->iter.iov += iov_off;
3106 if (rw->fast_iov != fast_iov)
3107 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3108 sizeof(struct iovec) * iter->nr_segs);
3110 req->flags |= REQ_F_NEED_CLEANUP;
3114 static inline int io_alloc_async_data(struct io_kiocb *req)
3116 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3117 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3118 return req->async_data == NULL;
3121 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3122 const struct iovec *fast_iov,
3123 struct iov_iter *iter, bool force)
3125 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3127 if (!req->async_data) {
3128 if (io_alloc_async_data(req)) {
3133 io_req_map_rw(req, iovec, fast_iov, iter);
3138 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3140 struct io_async_rw *iorw = req->async_data;
3141 struct iovec *iov = iorw->fast_iov;
3144 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3145 if (unlikely(ret < 0))
3148 iorw->bytes_done = 0;
3149 iorw->free_iovec = iov;
3151 req->flags |= REQ_F_NEED_CLEANUP;
3155 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3157 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3159 return io_prep_rw(req, sqe);
3163 * This is our waitqueue callback handler, registered through lock_page_async()
3164 * when we initially tried to do the IO with the iocb armed our waitqueue.
3165 * This gets called when the page is unlocked, and we generally expect that to
3166 * happen when the page IO is completed and the page is now uptodate. This will
3167 * queue a task_work based retry of the operation, attempting to copy the data
3168 * again. If the latter fails because the page was NOT uptodate, then we will
3169 * do a thread based blocking retry of the operation. That's the unexpected
3172 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3173 int sync, void *arg)
3175 struct wait_page_queue *wpq;
3176 struct io_kiocb *req = wait->private;
3177 struct wait_page_key *key = arg;
3179 wpq = container_of(wait, struct wait_page_queue, wait);
3181 if (!wake_page_match(wpq, key))
3184 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3185 list_del_init(&wait->entry);
3187 /* submit ref gets dropped, acquire a new one */
3189 io_req_task_queue(req);
3194 * This controls whether a given IO request should be armed for async page
3195 * based retry. If we return false here, the request is handed to the async
3196 * worker threads for retry. If we're doing buffered reads on a regular file,
3197 * we prepare a private wait_page_queue entry and retry the operation. This
3198 * will either succeed because the page is now uptodate and unlocked, or it
3199 * will register a callback when the page is unlocked at IO completion. Through
3200 * that callback, io_uring uses task_work to setup a retry of the operation.
3201 * That retry will attempt the buffered read again. The retry will generally
3202 * succeed, or in rare cases where it fails, we then fall back to using the
3203 * async worker threads for a blocking retry.
3205 static bool io_rw_should_retry(struct io_kiocb *req)
3207 struct io_async_rw *rw = req->async_data;
3208 struct wait_page_queue *wait = &rw->wpq;
3209 struct kiocb *kiocb = &req->rw.kiocb;
3211 /* never retry for NOWAIT, we just complete with -EAGAIN */
3212 if (req->flags & REQ_F_NOWAIT)
3215 /* Only for buffered IO */
3216 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3220 * just use poll if we can, and don't attempt if the fs doesn't
3221 * support callback based unlocks
3223 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3226 wait->wait.func = io_async_buf_func;
3227 wait->wait.private = req;
3228 wait->wait.flags = 0;
3229 INIT_LIST_HEAD(&wait->wait.entry);
3230 kiocb->ki_flags |= IOCB_WAITQ;
3231 kiocb->ki_flags &= ~IOCB_NOWAIT;
3232 kiocb->ki_waitq = wait;
3236 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3238 if (req->file->f_op->read_iter)
3239 return call_read_iter(req->file, &req->rw.kiocb, iter);
3240 else if (req->file->f_op->read)
3241 return loop_rw_iter(READ, req, iter);
3246 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3248 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3249 struct kiocb *kiocb = &req->rw.kiocb;
3250 struct iov_iter __iter, *iter = &__iter;
3251 struct io_async_rw *rw = req->async_data;
3252 ssize_t io_size, ret, ret2;
3253 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3259 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3263 io_size = iov_iter_count(iter);
3264 req->result = io_size;
3266 /* Ensure we clear previously set non-block flag */
3267 if (!force_nonblock)
3268 kiocb->ki_flags &= ~IOCB_NOWAIT;
3270 kiocb->ki_flags |= IOCB_NOWAIT;
3272 /* If the file doesn't support async, just async punt */
3273 if (force_nonblock && !io_file_supports_async(req, READ)) {
3274 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3275 return ret ?: -EAGAIN;
3278 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3279 if (unlikely(ret)) {
3284 ret = io_iter_do_read(req, iter);
3286 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3287 req->flags &= ~REQ_F_REISSUE;
3288 /* IOPOLL retry should happen for io-wq threads */
3289 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3291 /* no retry on NONBLOCK nor RWF_NOWAIT */
3292 if (req->flags & REQ_F_NOWAIT)
3294 /* some cases will consume bytes even on error returns */
3295 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3297 } else if (ret == -EIOCBQUEUED) {
3299 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3300 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3301 /* read all, failed, already did sync or don't want to retry */
3305 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3310 rw = req->async_data;
3311 /* now use our persistent iterator, if we aren't already */
3316 rw->bytes_done += ret;
3317 /* if we can retry, do so with the callbacks armed */
3318 if (!io_rw_should_retry(req)) {
3319 kiocb->ki_flags &= ~IOCB_WAITQ;
3324 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3325 * we get -EIOCBQUEUED, then we'll get a notification when the
3326 * desired page gets unlocked. We can also get a partial read
3327 * here, and if we do, then just retry at the new offset.
3329 ret = io_iter_do_read(req, iter);
3330 if (ret == -EIOCBQUEUED)
3332 /* we got some bytes, but not all. retry. */
3333 kiocb->ki_flags &= ~IOCB_WAITQ;
3334 } while (ret > 0 && ret < io_size);
3336 kiocb_done(kiocb, ret, issue_flags);
3338 /* it's faster to check here then delegate to kfree */
3344 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3346 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3348 return io_prep_rw(req, sqe);
3351 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3353 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3354 struct kiocb *kiocb = &req->rw.kiocb;
3355 struct iov_iter __iter, *iter = &__iter;
3356 struct io_async_rw *rw = req->async_data;
3357 ssize_t ret, ret2, io_size;
3358 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3364 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3368 io_size = iov_iter_count(iter);
3369 req->result = io_size;
3371 /* Ensure we clear previously set non-block flag */
3372 if (!force_nonblock)
3373 kiocb->ki_flags &= ~IOCB_NOWAIT;
3375 kiocb->ki_flags |= IOCB_NOWAIT;
3377 /* If the file doesn't support async, just async punt */
3378 if (force_nonblock && !io_file_supports_async(req, WRITE))
3381 /* file path doesn't support NOWAIT for non-direct_IO */
3382 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3383 (req->flags & REQ_F_ISREG))
3386 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3391 * Open-code file_start_write here to grab freeze protection,
3392 * which will be released by another thread in
3393 * io_complete_rw(). Fool lockdep by telling it the lock got
3394 * released so that it doesn't complain about the held lock when
3395 * we return to userspace.
3397 if (req->flags & REQ_F_ISREG) {
3398 sb_start_write(file_inode(req->file)->i_sb);
3399 __sb_writers_release(file_inode(req->file)->i_sb,
3402 kiocb->ki_flags |= IOCB_WRITE;
3404 if (req->file->f_op->write_iter)
3405 ret2 = call_write_iter(req->file, kiocb, iter);
3406 else if (req->file->f_op->write)
3407 ret2 = loop_rw_iter(WRITE, req, iter);
3411 if (req->flags & REQ_F_REISSUE) {
3412 req->flags &= ~REQ_F_REISSUE;
3417 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3418 * retry them without IOCB_NOWAIT.
3420 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3422 /* no retry on NONBLOCK nor RWF_NOWAIT */
3423 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3425 if (!force_nonblock || ret2 != -EAGAIN) {
3426 /* IOPOLL retry should happen for io-wq threads */
3427 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3430 kiocb_done(kiocb, ret2, issue_flags);
3433 /* some cases will consume bytes even on error returns */
3434 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3435 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3436 return ret ?: -EAGAIN;
3439 /* it's reportedly faster than delegating the null check to kfree() */
3445 static int io_renameat_prep(struct io_kiocb *req,
3446 const struct io_uring_sqe *sqe)
3448 struct io_rename *ren = &req->rename;
3449 const char __user *oldf, *newf;
3451 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3454 ren->old_dfd = READ_ONCE(sqe->fd);
3455 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3456 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3457 ren->new_dfd = READ_ONCE(sqe->len);
3458 ren->flags = READ_ONCE(sqe->rename_flags);
3460 ren->oldpath = getname(oldf);
3461 if (IS_ERR(ren->oldpath))
3462 return PTR_ERR(ren->oldpath);
3464 ren->newpath = getname(newf);
3465 if (IS_ERR(ren->newpath)) {
3466 putname(ren->oldpath);
3467 return PTR_ERR(ren->newpath);
3470 req->flags |= REQ_F_NEED_CLEANUP;
3474 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3476 struct io_rename *ren = &req->rename;
3479 if (issue_flags & IO_URING_F_NONBLOCK)
3482 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3483 ren->newpath, ren->flags);
3485 req->flags &= ~REQ_F_NEED_CLEANUP;
3487 req_set_fail_links(req);
3488 io_req_complete(req, ret);
3492 static int io_unlinkat_prep(struct io_kiocb *req,
3493 const struct io_uring_sqe *sqe)
3495 struct io_unlink *un = &req->unlink;
3496 const char __user *fname;
3498 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3501 un->dfd = READ_ONCE(sqe->fd);
3503 un->flags = READ_ONCE(sqe->unlink_flags);
3504 if (un->flags & ~AT_REMOVEDIR)
3507 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3508 un->filename = getname(fname);
3509 if (IS_ERR(un->filename))
3510 return PTR_ERR(un->filename);
3512 req->flags |= REQ_F_NEED_CLEANUP;
3516 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3518 struct io_unlink *un = &req->unlink;
3521 if (issue_flags & IO_URING_F_NONBLOCK)
3524 if (un->flags & AT_REMOVEDIR)
3525 ret = do_rmdir(un->dfd, un->filename);
3527 ret = do_unlinkat(un->dfd, un->filename);
3529 req->flags &= ~REQ_F_NEED_CLEANUP;
3531 req_set_fail_links(req);
3532 io_req_complete(req, ret);
3536 static int io_shutdown_prep(struct io_kiocb *req,
3537 const struct io_uring_sqe *sqe)
3539 #if defined(CONFIG_NET)
3540 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3542 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3546 req->shutdown.how = READ_ONCE(sqe->len);
3553 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3555 #if defined(CONFIG_NET)
3556 struct socket *sock;
3559 if (issue_flags & IO_URING_F_NONBLOCK)
3562 sock = sock_from_file(req->file);
3563 if (unlikely(!sock))
3566 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3568 req_set_fail_links(req);
3569 io_req_complete(req, ret);
3576 static int __io_splice_prep(struct io_kiocb *req,
3577 const struct io_uring_sqe *sqe)
3579 struct io_splice* sp = &req->splice;
3580 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3582 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3586 sp->len = READ_ONCE(sqe->len);
3587 sp->flags = READ_ONCE(sqe->splice_flags);
3589 if (unlikely(sp->flags & ~valid_flags))
3592 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3593 (sp->flags & SPLICE_F_FD_IN_FIXED));
3596 req->flags |= REQ_F_NEED_CLEANUP;
3600 static int io_tee_prep(struct io_kiocb *req,
3601 const struct io_uring_sqe *sqe)
3603 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3605 return __io_splice_prep(req, sqe);
3608 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3610 struct io_splice *sp = &req->splice;
3611 struct file *in = sp->file_in;
3612 struct file *out = sp->file_out;
3613 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3616 if (issue_flags & IO_URING_F_NONBLOCK)
3619 ret = do_tee(in, out, sp->len, flags);
3621 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3623 req->flags &= ~REQ_F_NEED_CLEANUP;
3626 req_set_fail_links(req);
3627 io_req_complete(req, ret);
3631 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3633 struct io_splice* sp = &req->splice;
3635 sp->off_in = READ_ONCE(sqe->splice_off_in);
3636 sp->off_out = READ_ONCE(sqe->off);
3637 return __io_splice_prep(req, sqe);
3640 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3642 struct io_splice *sp = &req->splice;
3643 struct file *in = sp->file_in;
3644 struct file *out = sp->file_out;
3645 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3646 loff_t *poff_in, *poff_out;
3649 if (issue_flags & IO_URING_F_NONBLOCK)
3652 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3653 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3656 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3658 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3660 req->flags &= ~REQ_F_NEED_CLEANUP;
3663 req_set_fail_links(req);
3664 io_req_complete(req, ret);
3669 * IORING_OP_NOP just posts a completion event, nothing else.
3671 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3673 struct io_ring_ctx *ctx = req->ctx;
3675 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3678 __io_req_complete(req, issue_flags, 0, 0);
3682 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3684 struct io_ring_ctx *ctx = req->ctx;
3689 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3691 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3694 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3695 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3698 req->sync.off = READ_ONCE(sqe->off);
3699 req->sync.len = READ_ONCE(sqe->len);
3703 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3705 loff_t end = req->sync.off + req->sync.len;
3708 /* fsync always requires a blocking context */
3709 if (issue_flags & IO_URING_F_NONBLOCK)
3712 ret = vfs_fsync_range(req->file, req->sync.off,
3713 end > 0 ? end : LLONG_MAX,
3714 req->sync.flags & IORING_FSYNC_DATASYNC);
3716 req_set_fail_links(req);
3717 io_req_complete(req, ret);
3721 static int io_fallocate_prep(struct io_kiocb *req,
3722 const struct io_uring_sqe *sqe)
3724 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3726 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3729 req->sync.off = READ_ONCE(sqe->off);
3730 req->sync.len = READ_ONCE(sqe->addr);
3731 req->sync.mode = READ_ONCE(sqe->len);
3735 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3739 /* fallocate always requiring blocking context */
3740 if (issue_flags & IO_URING_F_NONBLOCK)
3742 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3745 req_set_fail_links(req);
3746 io_req_complete(req, ret);
3750 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3752 const char __user *fname;
3755 if (unlikely(sqe->ioprio || sqe->buf_index))
3757 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3760 /* open.how should be already initialised */
3761 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3762 req->open.how.flags |= O_LARGEFILE;
3764 req->open.dfd = READ_ONCE(sqe->fd);
3765 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3766 req->open.filename = getname(fname);
3767 if (IS_ERR(req->open.filename)) {
3768 ret = PTR_ERR(req->open.filename);
3769 req->open.filename = NULL;
3772 req->open.nofile = rlimit(RLIMIT_NOFILE);
3773 req->flags |= REQ_F_NEED_CLEANUP;
3777 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3781 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3783 mode = READ_ONCE(sqe->len);
3784 flags = READ_ONCE(sqe->open_flags);
3785 req->open.how = build_open_how(flags, mode);
3786 return __io_openat_prep(req, sqe);
3789 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3791 struct open_how __user *how;
3795 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3797 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3798 len = READ_ONCE(sqe->len);
3799 if (len < OPEN_HOW_SIZE_VER0)
3802 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3807 return __io_openat_prep(req, sqe);
3810 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3812 struct open_flags op;
3815 bool resolve_nonblock;
3818 ret = build_open_flags(&req->open.how, &op);
3821 nonblock_set = op.open_flag & O_NONBLOCK;
3822 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3823 if (issue_flags & IO_URING_F_NONBLOCK) {
3825 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3826 * it'll always -EAGAIN
3828 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3830 op.lookup_flags |= LOOKUP_CACHED;
3831 op.open_flag |= O_NONBLOCK;
3834 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3838 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3839 /* only retry if RESOLVE_CACHED wasn't already set by application */
3840 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3841 file == ERR_PTR(-EAGAIN)) {
3843 * We could hang on to this 'fd', but seems like marginal
3844 * gain for something that is now known to be a slower path.
3845 * So just put it, and we'll get a new one when we retry.
3853 ret = PTR_ERR(file);
3855 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3856 file->f_flags &= ~O_NONBLOCK;
3857 fsnotify_open(file);
3858 fd_install(ret, file);
3861 putname(req->open.filename);
3862 req->flags &= ~REQ_F_NEED_CLEANUP;
3864 req_set_fail_links(req);
3865 __io_req_complete(req, issue_flags, ret, 0);
3869 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3871 return io_openat2(req, issue_flags);
3874 static int io_remove_buffers_prep(struct io_kiocb *req,
3875 const struct io_uring_sqe *sqe)
3877 struct io_provide_buf *p = &req->pbuf;
3880 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3883 tmp = READ_ONCE(sqe->fd);
3884 if (!tmp || tmp > USHRT_MAX)
3887 memset(p, 0, sizeof(*p));
3889 p->bgid = READ_ONCE(sqe->buf_group);
3893 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3894 int bgid, unsigned nbufs)
3898 /* shouldn't happen */
3902 /* the head kbuf is the list itself */
3903 while (!list_empty(&buf->list)) {
3904 struct io_buffer *nxt;
3906 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3907 list_del(&nxt->list);
3914 xa_erase(&ctx->io_buffers, bgid);
3919 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3921 struct io_provide_buf *p = &req->pbuf;
3922 struct io_ring_ctx *ctx = req->ctx;
3923 struct io_buffer *head;
3925 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3927 io_ring_submit_lock(ctx, !force_nonblock);
3929 lockdep_assert_held(&ctx->uring_lock);
3932 head = xa_load(&ctx->io_buffers, p->bgid);
3934 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3936 req_set_fail_links(req);
3938 /* complete before unlock, IOPOLL may need the lock */
3939 __io_req_complete(req, issue_flags, ret, 0);
3940 io_ring_submit_unlock(ctx, !force_nonblock);
3944 static int io_provide_buffers_prep(struct io_kiocb *req,
3945 const struct io_uring_sqe *sqe)
3947 unsigned long size, tmp_check;
3948 struct io_provide_buf *p = &req->pbuf;
3951 if (sqe->ioprio || sqe->rw_flags)
3954 tmp = READ_ONCE(sqe->fd);
3955 if (!tmp || tmp > USHRT_MAX)
3958 p->addr = READ_ONCE(sqe->addr);
3959 p->len = READ_ONCE(sqe->len);
3961 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3964 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3967 size = (unsigned long)p->len * p->nbufs;
3968 if (!access_ok(u64_to_user_ptr(p->addr), size))
3971 p->bgid = READ_ONCE(sqe->buf_group);
3972 tmp = READ_ONCE(sqe->off);
3973 if (tmp > USHRT_MAX)
3979 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3981 struct io_buffer *buf;
3982 u64 addr = pbuf->addr;
3983 int i, bid = pbuf->bid;
3985 for (i = 0; i < pbuf->nbufs; i++) {
3986 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3991 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3996 INIT_LIST_HEAD(&buf->list);
3999 list_add_tail(&buf->list, &(*head)->list);
4003 return i ? i : -ENOMEM;
4006 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4008 struct io_provide_buf *p = &req->pbuf;
4009 struct io_ring_ctx *ctx = req->ctx;
4010 struct io_buffer *head, *list;
4012 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4014 io_ring_submit_lock(ctx, !force_nonblock);
4016 lockdep_assert_held(&ctx->uring_lock);
4018 list = head = xa_load(&ctx->io_buffers, p->bgid);
4020 ret = io_add_buffers(p, &head);
4021 if (ret >= 0 && !list) {
4022 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4024 __io_remove_buffers(ctx, head, p->bgid, -1U);
4027 req_set_fail_links(req);
4028 /* complete before unlock, IOPOLL may need the lock */
4029 __io_req_complete(req, issue_flags, ret, 0);
4030 io_ring_submit_unlock(ctx, !force_nonblock);
4034 static int io_epoll_ctl_prep(struct io_kiocb *req,
4035 const struct io_uring_sqe *sqe)
4037 #if defined(CONFIG_EPOLL)
4038 if (sqe->ioprio || sqe->buf_index)
4040 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4043 req->epoll.epfd = READ_ONCE(sqe->fd);
4044 req->epoll.op = READ_ONCE(sqe->len);
4045 req->epoll.fd = READ_ONCE(sqe->off);
4047 if (ep_op_has_event(req->epoll.op)) {
4048 struct epoll_event __user *ev;
4050 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4051 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4061 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4063 #if defined(CONFIG_EPOLL)
4064 struct io_epoll *ie = &req->epoll;
4066 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4068 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4069 if (force_nonblock && ret == -EAGAIN)
4073 req_set_fail_links(req);
4074 __io_req_complete(req, issue_flags, ret, 0);
4081 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4083 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4084 if (sqe->ioprio || sqe->buf_index || sqe->off)
4086 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4089 req->madvise.addr = READ_ONCE(sqe->addr);
4090 req->madvise.len = READ_ONCE(sqe->len);
4091 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4098 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4100 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4101 struct io_madvise *ma = &req->madvise;
4104 if (issue_flags & IO_URING_F_NONBLOCK)
4107 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4109 req_set_fail_links(req);
4110 io_req_complete(req, ret);
4117 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4119 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4121 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4124 req->fadvise.offset = READ_ONCE(sqe->off);
4125 req->fadvise.len = READ_ONCE(sqe->len);
4126 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4130 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4132 struct io_fadvise *fa = &req->fadvise;
4135 if (issue_flags & IO_URING_F_NONBLOCK) {
4136 switch (fa->advice) {
4137 case POSIX_FADV_NORMAL:
4138 case POSIX_FADV_RANDOM:
4139 case POSIX_FADV_SEQUENTIAL:
4146 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4148 req_set_fail_links(req);
4149 __io_req_complete(req, issue_flags, ret, 0);
4153 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4155 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4157 if (sqe->ioprio || sqe->buf_index)
4159 if (req->flags & REQ_F_FIXED_FILE)
4162 req->statx.dfd = READ_ONCE(sqe->fd);
4163 req->statx.mask = READ_ONCE(sqe->len);
4164 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4165 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4166 req->statx.flags = READ_ONCE(sqe->statx_flags);
4171 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4173 struct io_statx *ctx = &req->statx;
4176 if (issue_flags & IO_URING_F_NONBLOCK)
4179 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4183 req_set_fail_links(req);
4184 io_req_complete(req, ret);
4188 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4190 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4192 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4193 sqe->rw_flags || sqe->buf_index)
4195 if (req->flags & REQ_F_FIXED_FILE)
4198 req->close.fd = READ_ONCE(sqe->fd);
4202 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4204 struct files_struct *files = current->files;
4205 struct io_close *close = &req->close;
4206 struct fdtable *fdt;
4207 struct file *file = NULL;
4210 spin_lock(&files->file_lock);
4211 fdt = files_fdtable(files);
4212 if (close->fd >= fdt->max_fds) {
4213 spin_unlock(&files->file_lock);
4216 file = fdt->fd[close->fd];
4217 if (!file || file->f_op == &io_uring_fops) {
4218 spin_unlock(&files->file_lock);
4223 /* if the file has a flush method, be safe and punt to async */
4224 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4225 spin_unlock(&files->file_lock);
4229 ret = __close_fd_get_file(close->fd, &file);
4230 spin_unlock(&files->file_lock);
4237 /* No ->flush() or already async, safely close from here */
4238 ret = filp_close(file, current->files);
4241 req_set_fail_links(req);
4244 __io_req_complete(req, issue_flags, ret, 0);
4248 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4250 struct io_ring_ctx *ctx = req->ctx;
4252 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4254 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4257 req->sync.off = READ_ONCE(sqe->off);
4258 req->sync.len = READ_ONCE(sqe->len);
4259 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4263 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4267 /* sync_file_range always requires a blocking context */
4268 if (issue_flags & IO_URING_F_NONBLOCK)
4271 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4274 req_set_fail_links(req);
4275 io_req_complete(req, ret);
4279 #if defined(CONFIG_NET)
4280 static int io_setup_async_msg(struct io_kiocb *req,
4281 struct io_async_msghdr *kmsg)
4283 struct io_async_msghdr *async_msg = req->async_data;
4287 if (io_alloc_async_data(req)) {
4288 kfree(kmsg->free_iov);
4291 async_msg = req->async_data;
4292 req->flags |= REQ_F_NEED_CLEANUP;
4293 memcpy(async_msg, kmsg, sizeof(*kmsg));
4294 async_msg->msg.msg_name = &async_msg->addr;
4295 /* if were using fast_iov, set it to the new one */
4296 if (!async_msg->free_iov)
4297 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4302 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4303 struct io_async_msghdr *iomsg)
4305 iomsg->msg.msg_name = &iomsg->addr;
4306 iomsg->free_iov = iomsg->fast_iov;
4307 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4308 req->sr_msg.msg_flags, &iomsg->free_iov);
4311 static int io_sendmsg_prep_async(struct io_kiocb *req)
4315 ret = io_sendmsg_copy_hdr(req, req->async_data);
4317 req->flags |= REQ_F_NEED_CLEANUP;
4321 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4323 struct io_sr_msg *sr = &req->sr_msg;
4325 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4328 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4329 sr->len = READ_ONCE(sqe->len);
4330 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4331 if (sr->msg_flags & MSG_DONTWAIT)
4332 req->flags |= REQ_F_NOWAIT;
4334 #ifdef CONFIG_COMPAT
4335 if (req->ctx->compat)
4336 sr->msg_flags |= MSG_CMSG_COMPAT;
4341 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4343 struct io_async_msghdr iomsg, *kmsg;
4344 struct socket *sock;
4349 sock = sock_from_file(req->file);
4350 if (unlikely(!sock))
4353 kmsg = req->async_data;
4355 ret = io_sendmsg_copy_hdr(req, &iomsg);
4361 flags = req->sr_msg.msg_flags;
4362 if (issue_flags & IO_URING_F_NONBLOCK)
4363 flags |= MSG_DONTWAIT;
4364 if (flags & MSG_WAITALL)
4365 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4367 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4368 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4369 return io_setup_async_msg(req, kmsg);
4370 if (ret == -ERESTARTSYS)
4373 /* fast path, check for non-NULL to avoid function call */
4375 kfree(kmsg->free_iov);
4376 req->flags &= ~REQ_F_NEED_CLEANUP;
4378 req_set_fail_links(req);
4379 __io_req_complete(req, issue_flags, ret, 0);
4383 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4385 struct io_sr_msg *sr = &req->sr_msg;
4388 struct socket *sock;
4393 sock = sock_from_file(req->file);
4394 if (unlikely(!sock))
4397 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4401 msg.msg_name = NULL;
4402 msg.msg_control = NULL;
4403 msg.msg_controllen = 0;
4404 msg.msg_namelen = 0;
4406 flags = req->sr_msg.msg_flags;
4407 if (issue_flags & IO_URING_F_NONBLOCK)
4408 flags |= MSG_DONTWAIT;
4409 if (flags & MSG_WAITALL)
4410 min_ret = iov_iter_count(&msg.msg_iter);
4412 msg.msg_flags = flags;
4413 ret = sock_sendmsg(sock, &msg);
4414 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4416 if (ret == -ERESTARTSYS)
4420 req_set_fail_links(req);
4421 __io_req_complete(req, issue_flags, ret, 0);
4425 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4426 struct io_async_msghdr *iomsg)
4428 struct io_sr_msg *sr = &req->sr_msg;
4429 struct iovec __user *uiov;
4433 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4434 &iomsg->uaddr, &uiov, &iov_len);
4438 if (req->flags & REQ_F_BUFFER_SELECT) {
4441 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4443 sr->len = iomsg->fast_iov[0].iov_len;
4444 iomsg->free_iov = NULL;
4446 iomsg->free_iov = iomsg->fast_iov;
4447 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4448 &iomsg->free_iov, &iomsg->msg.msg_iter,
4457 #ifdef CONFIG_COMPAT
4458 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4459 struct io_async_msghdr *iomsg)
4461 struct io_sr_msg *sr = &req->sr_msg;
4462 struct compat_iovec __user *uiov;
4467 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4472 uiov = compat_ptr(ptr);
4473 if (req->flags & REQ_F_BUFFER_SELECT) {
4474 compat_ssize_t clen;
4478 if (!access_ok(uiov, sizeof(*uiov)))
4480 if (__get_user(clen, &uiov->iov_len))
4485 iomsg->free_iov = NULL;
4487 iomsg->free_iov = iomsg->fast_iov;
4488 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4489 UIO_FASTIOV, &iomsg->free_iov,
4490 &iomsg->msg.msg_iter, true);
4499 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4500 struct io_async_msghdr *iomsg)
4502 iomsg->msg.msg_name = &iomsg->addr;
4504 #ifdef CONFIG_COMPAT
4505 if (req->ctx->compat)
4506 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4509 return __io_recvmsg_copy_hdr(req, iomsg);
4512 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4515 struct io_sr_msg *sr = &req->sr_msg;
4516 struct io_buffer *kbuf;
4518 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4523 req->flags |= REQ_F_BUFFER_SELECTED;
4527 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4529 return io_put_kbuf(req, req->sr_msg.kbuf);
4532 static int io_recvmsg_prep_async(struct io_kiocb *req)
4536 ret = io_recvmsg_copy_hdr(req, req->async_data);
4538 req->flags |= REQ_F_NEED_CLEANUP;
4542 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4544 struct io_sr_msg *sr = &req->sr_msg;
4546 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4549 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4550 sr->len = READ_ONCE(sqe->len);
4551 sr->bgid = READ_ONCE(sqe->buf_group);
4552 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4553 if (sr->msg_flags & MSG_DONTWAIT)
4554 req->flags |= REQ_F_NOWAIT;
4556 #ifdef CONFIG_COMPAT
4557 if (req->ctx->compat)
4558 sr->msg_flags |= MSG_CMSG_COMPAT;
4563 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4565 struct io_async_msghdr iomsg, *kmsg;
4566 struct socket *sock;
4567 struct io_buffer *kbuf;
4570 int ret, cflags = 0;
4571 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4573 sock = sock_from_file(req->file);
4574 if (unlikely(!sock))
4577 kmsg = req->async_data;
4579 ret = io_recvmsg_copy_hdr(req, &iomsg);
4585 if (req->flags & REQ_F_BUFFER_SELECT) {
4586 kbuf = io_recv_buffer_select(req, !force_nonblock);
4588 return PTR_ERR(kbuf);
4589 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4590 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4591 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4592 1, req->sr_msg.len);
4595 flags = req->sr_msg.msg_flags;
4597 flags |= MSG_DONTWAIT;
4598 if (flags & MSG_WAITALL)
4599 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4601 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4602 kmsg->uaddr, flags);
4603 if (force_nonblock && ret == -EAGAIN)
4604 return io_setup_async_msg(req, kmsg);
4605 if (ret == -ERESTARTSYS)
4608 if (req->flags & REQ_F_BUFFER_SELECTED)
4609 cflags = io_put_recv_kbuf(req);
4610 /* fast path, check for non-NULL to avoid function call */
4612 kfree(kmsg->free_iov);
4613 req->flags &= ~REQ_F_NEED_CLEANUP;
4614 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4615 req_set_fail_links(req);
4616 __io_req_complete(req, issue_flags, ret, cflags);
4620 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4622 struct io_buffer *kbuf;
4623 struct io_sr_msg *sr = &req->sr_msg;
4625 void __user *buf = sr->buf;
4626 struct socket *sock;
4630 int ret, cflags = 0;
4631 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4633 sock = sock_from_file(req->file);
4634 if (unlikely(!sock))
4637 if (req->flags & REQ_F_BUFFER_SELECT) {
4638 kbuf = io_recv_buffer_select(req, !force_nonblock);
4640 return PTR_ERR(kbuf);
4641 buf = u64_to_user_ptr(kbuf->addr);
4644 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4648 msg.msg_name = NULL;
4649 msg.msg_control = NULL;
4650 msg.msg_controllen = 0;
4651 msg.msg_namelen = 0;
4652 msg.msg_iocb = NULL;
4655 flags = req->sr_msg.msg_flags;
4657 flags |= MSG_DONTWAIT;
4658 if (flags & MSG_WAITALL)
4659 min_ret = iov_iter_count(&msg.msg_iter);
4661 ret = sock_recvmsg(sock, &msg, flags);
4662 if (force_nonblock && ret == -EAGAIN)
4664 if (ret == -ERESTARTSYS)
4667 if (req->flags & REQ_F_BUFFER_SELECTED)
4668 cflags = io_put_recv_kbuf(req);
4669 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4670 req_set_fail_links(req);
4671 __io_req_complete(req, issue_flags, ret, cflags);
4675 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4677 struct io_accept *accept = &req->accept;
4679 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4681 if (sqe->ioprio || sqe->len || sqe->buf_index)
4684 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4685 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4686 accept->flags = READ_ONCE(sqe->accept_flags);
4687 accept->nofile = rlimit(RLIMIT_NOFILE);
4691 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4693 struct io_accept *accept = &req->accept;
4694 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4695 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4698 if (req->file->f_flags & O_NONBLOCK)
4699 req->flags |= REQ_F_NOWAIT;
4701 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4702 accept->addr_len, accept->flags,
4704 if (ret == -EAGAIN && force_nonblock)
4707 if (ret == -ERESTARTSYS)
4709 req_set_fail_links(req);
4711 __io_req_complete(req, issue_flags, ret, 0);
4715 static int io_connect_prep_async(struct io_kiocb *req)
4717 struct io_async_connect *io = req->async_data;
4718 struct io_connect *conn = &req->connect;
4720 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4723 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4725 struct io_connect *conn = &req->connect;
4727 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4729 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4732 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4733 conn->addr_len = READ_ONCE(sqe->addr2);
4737 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4739 struct io_async_connect __io, *io;
4740 unsigned file_flags;
4742 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4744 if (req->async_data) {
4745 io = req->async_data;
4747 ret = move_addr_to_kernel(req->connect.addr,
4748 req->connect.addr_len,
4755 file_flags = force_nonblock ? O_NONBLOCK : 0;
4757 ret = __sys_connect_file(req->file, &io->address,
4758 req->connect.addr_len, file_flags);
4759 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4760 if (req->async_data)
4762 if (io_alloc_async_data(req)) {
4766 memcpy(req->async_data, &__io, sizeof(__io));
4769 if (ret == -ERESTARTSYS)
4773 req_set_fail_links(req);
4774 __io_req_complete(req, issue_flags, ret, 0);
4777 #else /* !CONFIG_NET */
4778 #define IO_NETOP_FN(op) \
4779 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4781 return -EOPNOTSUPP; \
4784 #define IO_NETOP_PREP(op) \
4786 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4788 return -EOPNOTSUPP; \
4791 #define IO_NETOP_PREP_ASYNC(op) \
4793 static int io_##op##_prep_async(struct io_kiocb *req) \
4795 return -EOPNOTSUPP; \
4798 IO_NETOP_PREP_ASYNC(sendmsg);
4799 IO_NETOP_PREP_ASYNC(recvmsg);
4800 IO_NETOP_PREP_ASYNC(connect);
4801 IO_NETOP_PREP(accept);
4804 #endif /* CONFIG_NET */
4806 struct io_poll_table {
4807 struct poll_table_struct pt;
4808 struct io_kiocb *req;
4812 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4813 __poll_t mask, task_work_func_t func)
4817 /* for instances that support it check for an event match first: */
4818 if (mask && !(mask & poll->events))
4821 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4823 list_del_init(&poll->wait.entry);
4826 req->task_work.func = func;
4829 * If this fails, then the task is exiting. When a task exits, the
4830 * work gets canceled, so just cancel this request as well instead
4831 * of executing it. We can't safely execute it anyway, as we may not
4832 * have the needed state needed for it anyway.
4834 ret = io_req_task_work_add(req);
4835 if (unlikely(ret)) {
4836 WRITE_ONCE(poll->canceled, true);
4837 io_req_task_work_add_fallback(req, func);
4842 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4843 __acquires(&req->ctx->completion_lock)
4845 struct io_ring_ctx *ctx = req->ctx;
4847 if (!req->result && !READ_ONCE(poll->canceled)) {
4848 struct poll_table_struct pt = { ._key = poll->events };
4850 req->result = vfs_poll(req->file, &pt) & poll->events;
4853 spin_lock_irq(&ctx->completion_lock);
4854 if (!req->result && !READ_ONCE(poll->canceled)) {
4855 add_wait_queue(poll->head, &poll->wait);
4862 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4864 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4865 if (req->opcode == IORING_OP_POLL_ADD)
4866 return req->async_data;
4867 return req->apoll->double_poll;
4870 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4872 if (req->opcode == IORING_OP_POLL_ADD)
4874 return &req->apoll->poll;
4877 static void io_poll_remove_double(struct io_kiocb *req)
4878 __must_hold(&req->ctx->completion_lock)
4880 struct io_poll_iocb *poll = io_poll_get_double(req);
4882 lockdep_assert_held(&req->ctx->completion_lock);
4884 if (poll && poll->head) {
4885 struct wait_queue_head *head = poll->head;
4887 spin_lock(&head->lock);
4888 list_del_init(&poll->wait.entry);
4889 if (poll->wait.private)
4892 spin_unlock(&head->lock);
4896 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4897 __must_hold(&req->ctx->completion_lock)
4899 struct io_ring_ctx *ctx = req->ctx;
4900 unsigned flags = IORING_CQE_F_MORE;
4903 if (READ_ONCE(req->poll.canceled)) {
4905 req->poll.events |= EPOLLONESHOT;
4907 error = mangle_poll(mask);
4909 if (req->poll.events & EPOLLONESHOT)
4911 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4912 io_poll_remove_waitqs(req);
4913 req->poll.done = true;
4916 if (flags & IORING_CQE_F_MORE)
4919 io_commit_cqring(ctx);
4920 return !(flags & IORING_CQE_F_MORE);
4923 static void io_poll_task_func(struct callback_head *cb)
4925 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4926 struct io_ring_ctx *ctx = req->ctx;
4927 struct io_kiocb *nxt;
4929 if (io_poll_rewait(req, &req->poll)) {
4930 spin_unlock_irq(&ctx->completion_lock);
4934 done = io_poll_complete(req, req->result);
4936 hash_del(&req->hash_node);
4939 add_wait_queue(req->poll.head, &req->poll.wait);
4941 spin_unlock_irq(&ctx->completion_lock);
4942 io_cqring_ev_posted(ctx);
4945 nxt = io_put_req_find_next(req);
4947 __io_req_task_submit(nxt);
4952 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4953 int sync, void *key)
4955 struct io_kiocb *req = wait->private;
4956 struct io_poll_iocb *poll = io_poll_get_single(req);
4957 __poll_t mask = key_to_poll(key);
4959 /* for instances that support it check for an event match first: */
4960 if (mask && !(mask & poll->events))
4962 if (!(poll->events & EPOLLONESHOT))
4963 return poll->wait.func(&poll->wait, mode, sync, key);
4965 list_del_init(&wait->entry);
4967 if (poll && poll->head) {
4970 spin_lock(&poll->head->lock);
4971 done = list_empty(&poll->wait.entry);
4973 list_del_init(&poll->wait.entry);
4974 /* make sure double remove sees this as being gone */
4975 wait->private = NULL;
4976 spin_unlock(&poll->head->lock);
4978 /* use wait func handler, so it matches the rq type */
4979 poll->wait.func(&poll->wait, mode, sync, key);
4986 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4987 wait_queue_func_t wake_func)
4991 poll->canceled = false;
4992 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4993 /* mask in events that we always want/need */
4994 poll->events = events | IO_POLL_UNMASK;
4995 INIT_LIST_HEAD(&poll->wait.entry);
4996 init_waitqueue_func_entry(&poll->wait, wake_func);
4999 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5000 struct wait_queue_head *head,
5001 struct io_poll_iocb **poll_ptr)
5003 struct io_kiocb *req = pt->req;
5006 * If poll->head is already set, it's because the file being polled
5007 * uses multiple waitqueues for poll handling (eg one for read, one
5008 * for write). Setup a separate io_poll_iocb if this happens.
5010 if (unlikely(poll->head)) {
5011 struct io_poll_iocb *poll_one = poll;
5013 /* already have a 2nd entry, fail a third attempt */
5015 pt->error = -EINVAL;
5019 * Can't handle multishot for double wait for now, turn it
5020 * into one-shot mode.
5022 if (!(req->poll.events & EPOLLONESHOT))
5023 req->poll.events |= EPOLLONESHOT;
5024 /* double add on the same waitqueue head, ignore */
5025 if (poll->head == head)
5027 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5029 pt->error = -ENOMEM;
5032 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5034 poll->wait.private = req;
5041 if (poll->events & EPOLLEXCLUSIVE)
5042 add_wait_queue_exclusive(head, &poll->wait);
5044 add_wait_queue(head, &poll->wait);
5047 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5048 struct poll_table_struct *p)
5050 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5051 struct async_poll *apoll = pt->req->apoll;
5053 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5056 static void io_async_task_func(struct callback_head *cb)
5058 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5059 struct async_poll *apoll = req->apoll;
5060 struct io_ring_ctx *ctx = req->ctx;
5062 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5064 if (io_poll_rewait(req, &apoll->poll)) {
5065 spin_unlock_irq(&ctx->completion_lock);
5069 hash_del(&req->hash_node);
5070 io_poll_remove_double(req);
5071 spin_unlock_irq(&ctx->completion_lock);
5073 if (!READ_ONCE(apoll->poll.canceled))
5074 __io_req_task_submit(req);
5076 io_req_complete_failed(req, -ECANCELED);
5079 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5082 struct io_kiocb *req = wait->private;
5083 struct io_poll_iocb *poll = &req->apoll->poll;
5085 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5088 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5091 static void io_poll_req_insert(struct io_kiocb *req)
5093 struct io_ring_ctx *ctx = req->ctx;
5094 struct hlist_head *list;
5096 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5097 hlist_add_head(&req->hash_node, list);
5100 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5101 struct io_poll_iocb *poll,
5102 struct io_poll_table *ipt, __poll_t mask,
5103 wait_queue_func_t wake_func)
5104 __acquires(&ctx->completion_lock)
5106 struct io_ring_ctx *ctx = req->ctx;
5107 bool cancel = false;
5109 INIT_HLIST_NODE(&req->hash_node);
5110 io_init_poll_iocb(poll, mask, wake_func);
5111 poll->file = req->file;
5112 poll->wait.private = req;
5114 ipt->pt._key = mask;
5116 ipt->error = -EINVAL;
5118 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5120 spin_lock_irq(&ctx->completion_lock);
5121 if (likely(poll->head)) {
5122 spin_lock(&poll->head->lock);
5123 if (unlikely(list_empty(&poll->wait.entry))) {
5129 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5130 list_del_init(&poll->wait.entry);
5132 WRITE_ONCE(poll->canceled, true);
5133 else if (!poll->done) /* actually waiting for an event */
5134 io_poll_req_insert(req);
5135 spin_unlock(&poll->head->lock);
5141 static bool io_arm_poll_handler(struct io_kiocb *req)
5143 const struct io_op_def *def = &io_op_defs[req->opcode];
5144 struct io_ring_ctx *ctx = req->ctx;
5145 struct async_poll *apoll;
5146 struct io_poll_table ipt;
5150 if (!req->file || !file_can_poll(req->file))
5152 if (req->flags & REQ_F_POLLED)
5156 else if (def->pollout)
5160 /* if we can't nonblock try, then no point in arming a poll handler */
5161 if (!io_file_supports_async(req, rw))
5164 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5165 if (unlikely(!apoll))
5167 apoll->double_poll = NULL;
5169 req->flags |= REQ_F_POLLED;
5172 mask = EPOLLONESHOT;
5174 mask |= POLLIN | POLLRDNORM;
5176 mask |= POLLOUT | POLLWRNORM;
5178 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5179 if ((req->opcode == IORING_OP_RECVMSG) &&
5180 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5183 mask |= POLLERR | POLLPRI;
5185 ipt.pt._qproc = io_async_queue_proc;
5187 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5189 if (ret || ipt.error) {
5190 io_poll_remove_double(req);
5191 spin_unlock_irq(&ctx->completion_lock);
5194 spin_unlock_irq(&ctx->completion_lock);
5195 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5196 apoll->poll.events);
5200 static bool __io_poll_remove_one(struct io_kiocb *req,
5201 struct io_poll_iocb *poll, bool do_cancel)
5202 __must_hold(&req->ctx->completion_lock)
5204 bool do_complete = false;
5208 spin_lock(&poll->head->lock);
5210 WRITE_ONCE(poll->canceled, true);
5211 if (!list_empty(&poll->wait.entry)) {
5212 list_del_init(&poll->wait.entry);
5215 spin_unlock(&poll->head->lock);
5216 hash_del(&req->hash_node);
5220 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5221 __must_hold(&req->ctx->completion_lock)
5225 io_poll_remove_double(req);
5226 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5228 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5229 /* non-poll requests have submit ref still */
5235 static bool io_poll_remove_one(struct io_kiocb *req)
5236 __must_hold(&req->ctx->completion_lock)
5240 do_complete = io_poll_remove_waitqs(req);
5242 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5243 io_commit_cqring(req->ctx);
5244 req_set_fail_links(req);
5245 io_put_req_deferred(req, 1);
5252 * Returns true if we found and killed one or more poll requests
5254 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5255 struct files_struct *files)
5257 struct hlist_node *tmp;
5258 struct io_kiocb *req;
5261 spin_lock_irq(&ctx->completion_lock);
5262 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5263 struct hlist_head *list;
5265 list = &ctx->cancel_hash[i];
5266 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5267 if (io_match_task(req, tsk, files))
5268 posted += io_poll_remove_one(req);
5271 spin_unlock_irq(&ctx->completion_lock);
5274 io_cqring_ev_posted(ctx);
5279 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5281 __must_hold(&ctx->completion_lock)
5283 struct hlist_head *list;
5284 struct io_kiocb *req;
5286 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5287 hlist_for_each_entry(req, list, hash_node) {
5288 if (sqe_addr != req->user_data)
5290 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5297 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5299 __must_hold(&ctx->completion_lock)
5301 struct io_kiocb *req;
5303 req = io_poll_find(ctx, sqe_addr, poll_only);
5306 if (io_poll_remove_one(req))
5312 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5317 events = READ_ONCE(sqe->poll32_events);
5319 events = swahw32(events);
5321 if (!(flags & IORING_POLL_ADD_MULTI))
5322 events |= EPOLLONESHOT;
5323 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5326 static int io_poll_update_prep(struct io_kiocb *req,
5327 const struct io_uring_sqe *sqe)
5329 struct io_poll_update *upd = &req->poll_update;
5332 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5334 if (sqe->ioprio || sqe->buf_index)
5336 flags = READ_ONCE(sqe->len);
5337 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5338 IORING_POLL_ADD_MULTI))
5340 /* meaningless without update */
5341 if (flags == IORING_POLL_ADD_MULTI)
5344 upd->old_user_data = READ_ONCE(sqe->addr);
5345 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5346 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5348 upd->new_user_data = READ_ONCE(sqe->off);
5349 if (!upd->update_user_data && upd->new_user_data)
5351 if (upd->update_events)
5352 upd->events = io_poll_parse_events(sqe, flags);
5353 else if (sqe->poll32_events)
5359 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5362 struct io_kiocb *req = wait->private;
5363 struct io_poll_iocb *poll = &req->poll;
5365 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5368 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5369 struct poll_table_struct *p)
5371 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5373 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5376 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5378 struct io_poll_iocb *poll = &req->poll;
5381 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5383 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5385 flags = READ_ONCE(sqe->len);
5386 if (flags & ~IORING_POLL_ADD_MULTI)
5389 poll->events = io_poll_parse_events(sqe, flags);
5393 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5395 struct io_poll_iocb *poll = &req->poll;
5396 struct io_ring_ctx *ctx = req->ctx;
5397 struct io_poll_table ipt;
5400 ipt.pt._qproc = io_poll_queue_proc;
5402 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5405 if (mask) { /* no async, we'd stolen it */
5407 io_poll_complete(req, mask);
5409 spin_unlock_irq(&ctx->completion_lock);
5412 io_cqring_ev_posted(ctx);
5413 if (poll->events & EPOLLONESHOT)
5419 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5421 struct io_ring_ctx *ctx = req->ctx;
5422 struct io_kiocb *preq;
5426 spin_lock_irq(&ctx->completion_lock);
5427 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5433 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5435 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5440 * Don't allow racy completion with singleshot, as we cannot safely
5441 * update those. For multishot, if we're racing with completion, just
5442 * let completion re-add it.
5444 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5445 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5449 /* we now have a detached poll request. reissue. */
5453 spin_unlock_irq(&ctx->completion_lock);
5454 req_set_fail_links(req);
5455 io_req_complete(req, ret);
5458 /* only mask one event flags, keep behavior flags */
5459 if (req->poll_update.update_events) {
5460 preq->poll.events &= ~0xffff;
5461 preq->poll.events |= req->poll_update.events & 0xffff;
5462 preq->poll.events |= IO_POLL_UNMASK;
5464 if (req->poll_update.update_user_data)
5465 preq->user_data = req->poll_update.new_user_data;
5466 spin_unlock_irq(&ctx->completion_lock);
5468 /* complete update request, we're done with it */
5469 io_req_complete(req, ret);
5472 ret = io_poll_add(preq, issue_flags);
5474 req_set_fail_links(preq);
5475 io_req_complete(preq, ret);
5481 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5483 struct io_timeout_data *data = container_of(timer,
5484 struct io_timeout_data, timer);
5485 struct io_kiocb *req = data->req;
5486 struct io_ring_ctx *ctx = req->ctx;
5487 unsigned long flags;
5489 spin_lock_irqsave(&ctx->completion_lock, flags);
5490 list_del_init(&req->timeout.list);
5491 atomic_set(&req->ctx->cq_timeouts,
5492 atomic_read(&req->ctx->cq_timeouts) + 1);
5494 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5495 io_commit_cqring(ctx);
5496 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5498 io_cqring_ev_posted(ctx);
5499 req_set_fail_links(req);
5501 return HRTIMER_NORESTART;
5504 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5506 __must_hold(&ctx->completion_lock)
5508 struct io_timeout_data *io;
5509 struct io_kiocb *req;
5512 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5513 found = user_data == req->user_data;
5518 return ERR_PTR(-ENOENT);
5520 io = req->async_data;
5521 if (hrtimer_try_to_cancel(&io->timer) == -1)
5522 return ERR_PTR(-EALREADY);
5523 list_del_init(&req->timeout.list);
5527 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5528 __must_hold(&ctx->completion_lock)
5530 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5533 return PTR_ERR(req);
5535 req_set_fail_links(req);
5536 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5537 io_put_req_deferred(req, 1);
5541 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5542 struct timespec64 *ts, enum hrtimer_mode mode)
5543 __must_hold(&ctx->completion_lock)
5545 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5546 struct io_timeout_data *data;
5549 return PTR_ERR(req);
5551 req->timeout.off = 0; /* noseq */
5552 data = req->async_data;
5553 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5554 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5555 data->timer.function = io_timeout_fn;
5556 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5560 static int io_timeout_remove_prep(struct io_kiocb *req,
5561 const struct io_uring_sqe *sqe)
5563 struct io_timeout_rem *tr = &req->timeout_rem;
5565 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5567 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5569 if (sqe->ioprio || sqe->buf_index || sqe->len)
5572 tr->addr = READ_ONCE(sqe->addr);
5573 tr->flags = READ_ONCE(sqe->timeout_flags);
5574 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5575 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5577 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5579 } else if (tr->flags) {
5580 /* timeout removal doesn't support flags */
5587 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5589 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5594 * Remove or update an existing timeout command
5596 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5598 struct io_timeout_rem *tr = &req->timeout_rem;
5599 struct io_ring_ctx *ctx = req->ctx;
5602 spin_lock_irq(&ctx->completion_lock);
5603 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5604 ret = io_timeout_cancel(ctx, tr->addr);
5606 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5607 io_translate_timeout_mode(tr->flags));
5609 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5610 io_commit_cqring(ctx);
5611 spin_unlock_irq(&ctx->completion_lock);
5612 io_cqring_ev_posted(ctx);
5614 req_set_fail_links(req);
5619 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5620 bool is_timeout_link)
5622 struct io_timeout_data *data;
5624 u32 off = READ_ONCE(sqe->off);
5626 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5628 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5630 if (off && is_timeout_link)
5632 flags = READ_ONCE(sqe->timeout_flags);
5633 if (flags & ~IORING_TIMEOUT_ABS)
5636 req->timeout.off = off;
5638 if (!req->async_data && io_alloc_async_data(req))
5641 data = req->async_data;
5644 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5647 data->mode = io_translate_timeout_mode(flags);
5648 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5649 if (is_timeout_link)
5650 io_req_track_inflight(req);
5654 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5656 struct io_ring_ctx *ctx = req->ctx;
5657 struct io_timeout_data *data = req->async_data;
5658 struct list_head *entry;
5659 u32 tail, off = req->timeout.off;
5661 spin_lock_irq(&ctx->completion_lock);
5664 * sqe->off holds how many events that need to occur for this
5665 * timeout event to be satisfied. If it isn't set, then this is
5666 * a pure timeout request, sequence isn't used.
5668 if (io_is_timeout_noseq(req)) {
5669 entry = ctx->timeout_list.prev;
5673 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5674 req->timeout.target_seq = tail + off;
5676 /* Update the last seq here in case io_flush_timeouts() hasn't.
5677 * This is safe because ->completion_lock is held, and submissions
5678 * and completions are never mixed in the same ->completion_lock section.
5680 ctx->cq_last_tm_flush = tail;
5683 * Insertion sort, ensuring the first entry in the list is always
5684 * the one we need first.
5686 list_for_each_prev(entry, &ctx->timeout_list) {
5687 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5690 if (io_is_timeout_noseq(nxt))
5692 /* nxt.seq is behind @tail, otherwise would've been completed */
5693 if (off >= nxt->timeout.target_seq - tail)
5697 list_add(&req->timeout.list, entry);
5698 data->timer.function = io_timeout_fn;
5699 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5700 spin_unlock_irq(&ctx->completion_lock);
5704 struct io_cancel_data {
5705 struct io_ring_ctx *ctx;
5709 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5711 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5712 struct io_cancel_data *cd = data;
5714 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5717 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5718 struct io_ring_ctx *ctx)
5720 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5721 enum io_wq_cancel cancel_ret;
5724 if (!tctx || !tctx->io_wq)
5727 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5728 switch (cancel_ret) {
5729 case IO_WQ_CANCEL_OK:
5732 case IO_WQ_CANCEL_RUNNING:
5735 case IO_WQ_CANCEL_NOTFOUND:
5743 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5744 struct io_kiocb *req, __u64 sqe_addr,
5747 unsigned long flags;
5750 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5751 spin_lock_irqsave(&ctx->completion_lock, flags);
5754 ret = io_timeout_cancel(ctx, sqe_addr);
5757 ret = io_poll_cancel(ctx, sqe_addr, false);
5761 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5762 io_commit_cqring(ctx);
5763 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5764 io_cqring_ev_posted(ctx);
5767 req_set_fail_links(req);
5770 static int io_async_cancel_prep(struct io_kiocb *req,
5771 const struct io_uring_sqe *sqe)
5773 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5775 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5777 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5780 req->cancel.addr = READ_ONCE(sqe->addr);
5784 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5786 struct io_ring_ctx *ctx = req->ctx;
5787 u64 sqe_addr = req->cancel.addr;
5788 struct io_tctx_node *node;
5791 /* tasks should wait for their io-wq threads, so safe w/o sync */
5792 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5793 spin_lock_irq(&ctx->completion_lock);
5796 ret = io_timeout_cancel(ctx, sqe_addr);
5799 ret = io_poll_cancel(ctx, sqe_addr, false);
5802 spin_unlock_irq(&ctx->completion_lock);
5804 /* slow path, try all io-wq's */
5805 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5807 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5808 struct io_uring_task *tctx = node->task->io_uring;
5810 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5814 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5816 spin_lock_irq(&ctx->completion_lock);
5818 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5819 io_commit_cqring(ctx);
5820 spin_unlock_irq(&ctx->completion_lock);
5821 io_cqring_ev_posted(ctx);
5824 req_set_fail_links(req);
5829 static int io_rsrc_update_prep(struct io_kiocb *req,
5830 const struct io_uring_sqe *sqe)
5832 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5834 if (sqe->ioprio || sqe->rw_flags)
5837 req->rsrc_update.offset = READ_ONCE(sqe->off);
5838 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5839 if (!req->rsrc_update.nr_args)
5841 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5845 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5847 struct io_ring_ctx *ctx = req->ctx;
5848 struct io_uring_rsrc_update2 up;
5851 if (issue_flags & IO_URING_F_NONBLOCK)
5854 up.offset = req->rsrc_update.offset;
5855 up.data = req->rsrc_update.arg;
5860 mutex_lock(&ctx->uring_lock);
5861 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5862 &up, req->rsrc_update.nr_args);
5863 mutex_unlock(&ctx->uring_lock);
5866 req_set_fail_links(req);
5867 __io_req_complete(req, issue_flags, ret, 0);
5871 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5873 switch (req->opcode) {
5876 case IORING_OP_READV:
5877 case IORING_OP_READ_FIXED:
5878 case IORING_OP_READ:
5879 return io_read_prep(req, sqe);
5880 case IORING_OP_WRITEV:
5881 case IORING_OP_WRITE_FIXED:
5882 case IORING_OP_WRITE:
5883 return io_write_prep(req, sqe);
5884 case IORING_OP_POLL_ADD:
5885 return io_poll_add_prep(req, sqe);
5886 case IORING_OP_POLL_REMOVE:
5887 return io_poll_update_prep(req, sqe);
5888 case IORING_OP_FSYNC:
5889 return io_fsync_prep(req, sqe);
5890 case IORING_OP_SYNC_FILE_RANGE:
5891 return io_sfr_prep(req, sqe);
5892 case IORING_OP_SENDMSG:
5893 case IORING_OP_SEND:
5894 return io_sendmsg_prep(req, sqe);
5895 case IORING_OP_RECVMSG:
5896 case IORING_OP_RECV:
5897 return io_recvmsg_prep(req, sqe);
5898 case IORING_OP_CONNECT:
5899 return io_connect_prep(req, sqe);
5900 case IORING_OP_TIMEOUT:
5901 return io_timeout_prep(req, sqe, false);
5902 case IORING_OP_TIMEOUT_REMOVE:
5903 return io_timeout_remove_prep(req, sqe);
5904 case IORING_OP_ASYNC_CANCEL:
5905 return io_async_cancel_prep(req, sqe);
5906 case IORING_OP_LINK_TIMEOUT:
5907 return io_timeout_prep(req, sqe, true);
5908 case IORING_OP_ACCEPT:
5909 return io_accept_prep(req, sqe);
5910 case IORING_OP_FALLOCATE:
5911 return io_fallocate_prep(req, sqe);
5912 case IORING_OP_OPENAT:
5913 return io_openat_prep(req, sqe);
5914 case IORING_OP_CLOSE:
5915 return io_close_prep(req, sqe);
5916 case IORING_OP_FILES_UPDATE:
5917 return io_rsrc_update_prep(req, sqe);
5918 case IORING_OP_STATX:
5919 return io_statx_prep(req, sqe);
5920 case IORING_OP_FADVISE:
5921 return io_fadvise_prep(req, sqe);
5922 case IORING_OP_MADVISE:
5923 return io_madvise_prep(req, sqe);
5924 case IORING_OP_OPENAT2:
5925 return io_openat2_prep(req, sqe);
5926 case IORING_OP_EPOLL_CTL:
5927 return io_epoll_ctl_prep(req, sqe);
5928 case IORING_OP_SPLICE:
5929 return io_splice_prep(req, sqe);
5930 case IORING_OP_PROVIDE_BUFFERS:
5931 return io_provide_buffers_prep(req, sqe);
5932 case IORING_OP_REMOVE_BUFFERS:
5933 return io_remove_buffers_prep(req, sqe);
5935 return io_tee_prep(req, sqe);
5936 case IORING_OP_SHUTDOWN:
5937 return io_shutdown_prep(req, sqe);
5938 case IORING_OP_RENAMEAT:
5939 return io_renameat_prep(req, sqe);
5940 case IORING_OP_UNLINKAT:
5941 return io_unlinkat_prep(req, sqe);
5944 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5949 static int io_req_prep_async(struct io_kiocb *req)
5951 if (!io_op_defs[req->opcode].needs_async_setup)
5953 if (WARN_ON_ONCE(req->async_data))
5955 if (io_alloc_async_data(req))
5958 switch (req->opcode) {
5959 case IORING_OP_READV:
5960 return io_rw_prep_async(req, READ);
5961 case IORING_OP_WRITEV:
5962 return io_rw_prep_async(req, WRITE);
5963 case IORING_OP_SENDMSG:
5964 return io_sendmsg_prep_async(req);
5965 case IORING_OP_RECVMSG:
5966 return io_recvmsg_prep_async(req);
5967 case IORING_OP_CONNECT:
5968 return io_connect_prep_async(req);
5970 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5975 static u32 io_get_sequence(struct io_kiocb *req)
5977 struct io_kiocb *pos;
5978 struct io_ring_ctx *ctx = req->ctx;
5979 u32 total_submitted, nr_reqs = 0;
5981 io_for_each_link(pos, req)
5984 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5985 return total_submitted - nr_reqs;
5988 static int io_req_defer(struct io_kiocb *req)
5990 struct io_ring_ctx *ctx = req->ctx;
5991 struct io_defer_entry *de;
5995 /* Still need defer if there is pending req in defer list. */
5996 if (likely(list_empty_careful(&ctx->defer_list) &&
5997 !(req->flags & REQ_F_IO_DRAIN)))
6000 seq = io_get_sequence(req);
6001 /* Still a chance to pass the sequence check */
6002 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6005 ret = io_req_prep_async(req);
6008 io_prep_async_link(req);
6009 de = kmalloc(sizeof(*de), GFP_KERNEL);
6013 spin_lock_irq(&ctx->completion_lock);
6014 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6015 spin_unlock_irq(&ctx->completion_lock);
6017 io_queue_async_work(req);
6018 return -EIOCBQUEUED;
6021 trace_io_uring_defer(ctx, req, req->user_data);
6024 list_add_tail(&de->list, &ctx->defer_list);
6025 spin_unlock_irq(&ctx->completion_lock);
6026 return -EIOCBQUEUED;
6029 static void io_clean_op(struct io_kiocb *req)
6031 if (req->flags & REQ_F_BUFFER_SELECTED) {
6032 switch (req->opcode) {
6033 case IORING_OP_READV:
6034 case IORING_OP_READ_FIXED:
6035 case IORING_OP_READ:
6036 kfree((void *)(unsigned long)req->rw.addr);
6038 case IORING_OP_RECVMSG:
6039 case IORING_OP_RECV:
6040 kfree(req->sr_msg.kbuf);
6043 req->flags &= ~REQ_F_BUFFER_SELECTED;
6046 if (req->flags & REQ_F_NEED_CLEANUP) {
6047 switch (req->opcode) {
6048 case IORING_OP_READV:
6049 case IORING_OP_READ_FIXED:
6050 case IORING_OP_READ:
6051 case IORING_OP_WRITEV:
6052 case IORING_OP_WRITE_FIXED:
6053 case IORING_OP_WRITE: {
6054 struct io_async_rw *io = req->async_data;
6056 kfree(io->free_iovec);
6059 case IORING_OP_RECVMSG:
6060 case IORING_OP_SENDMSG: {
6061 struct io_async_msghdr *io = req->async_data;
6063 kfree(io->free_iov);
6066 case IORING_OP_SPLICE:
6068 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6069 io_put_file(req->splice.file_in);
6071 case IORING_OP_OPENAT:
6072 case IORING_OP_OPENAT2:
6073 if (req->open.filename)
6074 putname(req->open.filename);
6076 case IORING_OP_RENAMEAT:
6077 putname(req->rename.oldpath);
6078 putname(req->rename.newpath);
6080 case IORING_OP_UNLINKAT:
6081 putname(req->unlink.filename);
6084 req->flags &= ~REQ_F_NEED_CLEANUP;
6086 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6087 kfree(req->apoll->double_poll);
6091 if (req->flags & REQ_F_INFLIGHT) {
6092 struct io_uring_task *tctx = req->task->io_uring;
6094 atomic_dec(&tctx->inflight_tracked);
6095 req->flags &= ~REQ_F_INFLIGHT;
6099 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6101 struct io_ring_ctx *ctx = req->ctx;
6102 const struct cred *creds = NULL;
6105 if (req->work.creds && req->work.creds != current_cred())
6106 creds = override_creds(req->work.creds);
6108 switch (req->opcode) {
6110 ret = io_nop(req, issue_flags);
6112 case IORING_OP_READV:
6113 case IORING_OP_READ_FIXED:
6114 case IORING_OP_READ:
6115 ret = io_read(req, issue_flags);
6117 case IORING_OP_WRITEV:
6118 case IORING_OP_WRITE_FIXED:
6119 case IORING_OP_WRITE:
6120 ret = io_write(req, issue_flags);
6122 case IORING_OP_FSYNC:
6123 ret = io_fsync(req, issue_flags);
6125 case IORING_OP_POLL_ADD:
6126 ret = io_poll_add(req, issue_flags);
6128 case IORING_OP_POLL_REMOVE:
6129 ret = io_poll_update(req, issue_flags);
6131 case IORING_OP_SYNC_FILE_RANGE:
6132 ret = io_sync_file_range(req, issue_flags);
6134 case IORING_OP_SENDMSG:
6135 ret = io_sendmsg(req, issue_flags);
6137 case IORING_OP_SEND:
6138 ret = io_send(req, issue_flags);
6140 case IORING_OP_RECVMSG:
6141 ret = io_recvmsg(req, issue_flags);
6143 case IORING_OP_RECV:
6144 ret = io_recv(req, issue_flags);
6146 case IORING_OP_TIMEOUT:
6147 ret = io_timeout(req, issue_flags);
6149 case IORING_OP_TIMEOUT_REMOVE:
6150 ret = io_timeout_remove(req, issue_flags);
6152 case IORING_OP_ACCEPT:
6153 ret = io_accept(req, issue_flags);
6155 case IORING_OP_CONNECT:
6156 ret = io_connect(req, issue_flags);
6158 case IORING_OP_ASYNC_CANCEL:
6159 ret = io_async_cancel(req, issue_flags);
6161 case IORING_OP_FALLOCATE:
6162 ret = io_fallocate(req, issue_flags);
6164 case IORING_OP_OPENAT:
6165 ret = io_openat(req, issue_flags);
6167 case IORING_OP_CLOSE:
6168 ret = io_close(req, issue_flags);
6170 case IORING_OP_FILES_UPDATE:
6171 ret = io_files_update(req, issue_flags);
6173 case IORING_OP_STATX:
6174 ret = io_statx(req, issue_flags);
6176 case IORING_OP_FADVISE:
6177 ret = io_fadvise(req, issue_flags);
6179 case IORING_OP_MADVISE:
6180 ret = io_madvise(req, issue_flags);
6182 case IORING_OP_OPENAT2:
6183 ret = io_openat2(req, issue_flags);
6185 case IORING_OP_EPOLL_CTL:
6186 ret = io_epoll_ctl(req, issue_flags);
6188 case IORING_OP_SPLICE:
6189 ret = io_splice(req, issue_flags);
6191 case IORING_OP_PROVIDE_BUFFERS:
6192 ret = io_provide_buffers(req, issue_flags);
6194 case IORING_OP_REMOVE_BUFFERS:
6195 ret = io_remove_buffers(req, issue_flags);
6198 ret = io_tee(req, issue_flags);
6200 case IORING_OP_SHUTDOWN:
6201 ret = io_shutdown(req, issue_flags);
6203 case IORING_OP_RENAMEAT:
6204 ret = io_renameat(req, issue_flags);
6206 case IORING_OP_UNLINKAT:
6207 ret = io_unlinkat(req, issue_flags);
6215 revert_creds(creds);
6220 /* If the op doesn't have a file, we're not polling for it */
6221 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6222 const bool in_async = io_wq_current_is_worker();
6224 /* workqueue context doesn't hold uring_lock, grab it now */
6226 mutex_lock(&ctx->uring_lock);
6228 io_iopoll_req_issued(req, in_async);
6231 mutex_unlock(&ctx->uring_lock);
6237 static void io_wq_submit_work(struct io_wq_work *work)
6239 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6240 struct io_kiocb *timeout;
6243 timeout = io_prep_linked_timeout(req);
6245 io_queue_linked_timeout(timeout);
6247 if (work->flags & IO_WQ_WORK_CANCEL)
6252 ret = io_issue_sqe(req, 0);
6254 * We can get EAGAIN for polled IO even though we're
6255 * forcing a sync submission from here, since we can't
6256 * wait for request slots on the block side.
6264 /* avoid locking problems by failing it from a clean context */
6266 /* io-wq is going to take one down */
6268 io_req_task_queue_fail(req, ret);
6272 #define FFS_ASYNC_READ 0x1UL
6273 #define FFS_ASYNC_WRITE 0x2UL
6275 #define FFS_ISREG 0x4UL
6277 #define FFS_ISREG 0x0UL
6279 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6281 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6284 struct io_fixed_file *table_l2;
6286 table_l2 = table->files[i >> IORING_FILE_TABLE_SHIFT];
6287 return &table_l2[i & IORING_FILE_TABLE_MASK];
6290 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6293 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6295 return (struct file *) (slot->file_ptr & FFS_MASK);
6298 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6300 unsigned long file_ptr = (unsigned long) file;
6302 if (__io_file_supports_async(file, READ))
6303 file_ptr |= FFS_ASYNC_READ;
6304 if (__io_file_supports_async(file, WRITE))
6305 file_ptr |= FFS_ASYNC_WRITE;
6306 if (S_ISREG(file_inode(file)->i_mode))
6307 file_ptr |= FFS_ISREG;
6308 file_slot->file_ptr = file_ptr;
6311 static struct file *io_file_get(struct io_submit_state *state,
6312 struct io_kiocb *req, int fd, bool fixed)
6314 struct io_ring_ctx *ctx = req->ctx;
6318 unsigned long file_ptr;
6320 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6322 fd = array_index_nospec(fd, ctx->nr_user_files);
6323 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6324 file = (struct file *) (file_ptr & FFS_MASK);
6325 file_ptr &= ~FFS_MASK;
6326 /* mask in overlapping REQ_F and FFS bits */
6327 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6328 io_req_set_rsrc_node(req);
6330 trace_io_uring_file_get(ctx, fd);
6331 file = __io_file_get(state, fd);
6333 /* we don't allow fixed io_uring files */
6334 if (file && unlikely(file->f_op == &io_uring_fops))
6335 io_req_track_inflight(req);
6341 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6343 struct io_timeout_data *data = container_of(timer,
6344 struct io_timeout_data, timer);
6345 struct io_kiocb *prev, *req = data->req;
6346 struct io_ring_ctx *ctx = req->ctx;
6347 unsigned long flags;
6349 spin_lock_irqsave(&ctx->completion_lock, flags);
6350 prev = req->timeout.head;
6351 req->timeout.head = NULL;
6354 * We don't expect the list to be empty, that will only happen if we
6355 * race with the completion of the linked work.
6358 io_remove_next_linked(prev);
6359 if (!req_ref_inc_not_zero(prev))
6362 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6365 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6366 io_put_req_deferred(prev, 1);
6367 io_put_req_deferred(req, 1);
6369 io_req_complete_post(req, -ETIME, 0);
6371 return HRTIMER_NORESTART;
6374 static void io_queue_linked_timeout(struct io_kiocb *req)
6376 struct io_ring_ctx *ctx = req->ctx;
6378 spin_lock_irq(&ctx->completion_lock);
6380 * If the back reference is NULL, then our linked request finished
6381 * before we got a chance to setup the timer
6383 if (req->timeout.head) {
6384 struct io_timeout_data *data = req->async_data;
6386 data->timer.function = io_link_timeout_fn;
6387 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6390 spin_unlock_irq(&ctx->completion_lock);
6391 /* drop submission reference */
6395 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6397 struct io_kiocb *nxt = req->link;
6399 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6400 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6403 nxt->timeout.head = req;
6404 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6405 req->flags |= REQ_F_LINK_TIMEOUT;
6409 static void __io_queue_sqe(struct io_kiocb *req)
6411 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6414 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6417 * We async punt it if the file wasn't marked NOWAIT, or if the file
6418 * doesn't support non-blocking read/write attempts
6421 /* drop submission reference */
6422 if (req->flags & REQ_F_COMPLETE_INLINE) {
6423 struct io_ring_ctx *ctx = req->ctx;
6424 struct io_comp_state *cs = &ctx->submit_state.comp;
6426 cs->reqs[cs->nr++] = req;
6427 if (cs->nr == ARRAY_SIZE(cs->reqs))
6428 io_submit_flush_completions(cs, ctx);
6432 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6433 if (!io_arm_poll_handler(req)) {
6435 * Queued up for async execution, worker will release
6436 * submit reference when the iocb is actually submitted.
6438 io_queue_async_work(req);
6441 io_req_complete_failed(req, ret);
6444 io_queue_linked_timeout(linked_timeout);
6447 static void io_queue_sqe(struct io_kiocb *req)
6451 ret = io_req_defer(req);
6453 if (ret != -EIOCBQUEUED) {
6455 io_req_complete_failed(req, ret);
6457 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6458 ret = io_req_prep_async(req);
6461 io_queue_async_work(req);
6463 __io_queue_sqe(req);
6468 * Check SQE restrictions (opcode and flags).
6470 * Returns 'true' if SQE is allowed, 'false' otherwise.
6472 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6473 struct io_kiocb *req,
6474 unsigned int sqe_flags)
6476 if (!ctx->restricted)
6479 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6482 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6483 ctx->restrictions.sqe_flags_required)
6486 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6487 ctx->restrictions.sqe_flags_required))
6493 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6494 const struct io_uring_sqe *sqe)
6496 struct io_submit_state *state;
6497 unsigned int sqe_flags;
6498 int personality, ret = 0;
6500 req->opcode = READ_ONCE(sqe->opcode);
6501 /* same numerical values with corresponding REQ_F_*, safe to copy */
6502 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6503 req->user_data = READ_ONCE(sqe->user_data);
6504 req->async_data = NULL;
6508 req->fixed_rsrc_refs = NULL;
6509 /* one is dropped after submission, the other at completion */
6510 atomic_set(&req->refs, 2);
6511 req->task = current;
6513 req->work.creds = NULL;
6515 /* enforce forwards compatibility on users */
6516 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6518 if (unlikely(req->opcode >= IORING_OP_LAST))
6520 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6523 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6524 !io_op_defs[req->opcode].buffer_select)
6527 personality = READ_ONCE(sqe->personality);
6529 req->work.creds = xa_load(&ctx->personalities, personality);
6530 if (!req->work.creds)
6532 get_cred(req->work.creds);
6534 state = &ctx->submit_state;
6537 * Plug now if we have more than 1 IO left after this, and the target
6538 * is potentially a read/write to block based storage.
6540 if (!state->plug_started && state->ios_left > 1 &&
6541 io_op_defs[req->opcode].plug) {
6542 blk_start_plug(&state->plug);
6543 state->plug_started = true;
6546 if (io_op_defs[req->opcode].needs_file) {
6547 bool fixed = req->flags & REQ_F_FIXED_FILE;
6549 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6550 if (unlikely(!req->file))
6558 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6559 const struct io_uring_sqe *sqe)
6561 struct io_submit_link *link = &ctx->submit_state.link;
6564 ret = io_init_req(ctx, req, sqe);
6565 if (unlikely(ret)) {
6568 /* fail even hard links since we don't submit */
6569 link->head->flags |= REQ_F_FAIL_LINK;
6570 io_req_complete_failed(link->head, -ECANCELED);
6573 io_req_complete_failed(req, ret);
6576 ret = io_req_prep(req, sqe);
6580 /* don't need @sqe from now on */
6581 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6582 true, ctx->flags & IORING_SETUP_SQPOLL);
6585 * If we already have a head request, queue this one for async
6586 * submittal once the head completes. If we don't have a head but
6587 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6588 * submitted sync once the chain is complete. If none of those
6589 * conditions are true (normal request), then just queue it.
6592 struct io_kiocb *head = link->head;
6595 * Taking sequential execution of a link, draining both sides
6596 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6597 * requests in the link. So, it drains the head and the
6598 * next after the link request. The last one is done via
6599 * drain_next flag to persist the effect across calls.
6601 if (req->flags & REQ_F_IO_DRAIN) {
6602 head->flags |= REQ_F_IO_DRAIN;
6603 ctx->drain_next = 1;
6605 ret = io_req_prep_async(req);
6608 trace_io_uring_link(ctx, req, head);
6609 link->last->link = req;
6612 /* last request of a link, enqueue the link */
6613 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6618 if (unlikely(ctx->drain_next)) {
6619 req->flags |= REQ_F_IO_DRAIN;
6620 ctx->drain_next = 0;
6622 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6634 * Batched submission is done, ensure local IO is flushed out.
6636 static void io_submit_state_end(struct io_submit_state *state,
6637 struct io_ring_ctx *ctx)
6639 if (state->link.head)
6640 io_queue_sqe(state->link.head);
6642 io_submit_flush_completions(&state->comp, ctx);
6643 if (state->plug_started)
6644 blk_finish_plug(&state->plug);
6645 io_state_file_put(state);
6649 * Start submission side cache.
6651 static void io_submit_state_start(struct io_submit_state *state,
6652 unsigned int max_ios)
6654 state->plug_started = false;
6655 state->ios_left = max_ios;
6656 /* set only head, no need to init link_last in advance */
6657 state->link.head = NULL;
6660 static void io_commit_sqring(struct io_ring_ctx *ctx)
6662 struct io_rings *rings = ctx->rings;
6665 * Ensure any loads from the SQEs are done at this point,
6666 * since once we write the new head, the application could
6667 * write new data to them.
6669 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6673 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6674 * that is mapped by userspace. This means that care needs to be taken to
6675 * ensure that reads are stable, as we cannot rely on userspace always
6676 * being a good citizen. If members of the sqe are validated and then later
6677 * used, it's important that those reads are done through READ_ONCE() to
6678 * prevent a re-load down the line.
6680 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6682 u32 *sq_array = ctx->sq_array;
6686 * The cached sq head (or cq tail) serves two purposes:
6688 * 1) allows us to batch the cost of updating the user visible
6690 * 2) allows the kernel side to track the head on its own, even
6691 * though the application is the one updating it.
6693 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6694 if (likely(head < ctx->sq_entries))
6695 return &ctx->sq_sqes[head];
6697 /* drop invalid entries */
6698 ctx->cached_sq_dropped++;
6699 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6703 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6707 /* make sure SQ entry isn't read before tail */
6708 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6710 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6713 percpu_counter_add(¤t->io_uring->inflight, nr);
6714 refcount_add(nr, ¤t->usage);
6715 io_submit_state_start(&ctx->submit_state, nr);
6717 while (submitted < nr) {
6718 const struct io_uring_sqe *sqe;
6719 struct io_kiocb *req;
6721 req = io_alloc_req(ctx);
6722 if (unlikely(!req)) {
6724 submitted = -EAGAIN;
6727 sqe = io_get_sqe(ctx);
6728 if (unlikely(!sqe)) {
6729 kmem_cache_free(req_cachep, req);
6732 /* will complete beyond this point, count as submitted */
6734 if (io_submit_sqe(ctx, req, sqe))
6738 if (unlikely(submitted != nr)) {
6739 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6740 struct io_uring_task *tctx = current->io_uring;
6741 int unused = nr - ref_used;
6743 percpu_ref_put_many(&ctx->refs, unused);
6744 percpu_counter_sub(&tctx->inflight, unused);
6745 put_task_struct_many(current, unused);
6748 io_submit_state_end(&ctx->submit_state, ctx);
6749 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6750 io_commit_sqring(ctx);
6755 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6757 /* Tell userspace we may need a wakeup call */
6758 spin_lock_irq(&ctx->completion_lock);
6759 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6760 spin_unlock_irq(&ctx->completion_lock);
6763 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6765 spin_lock_irq(&ctx->completion_lock);
6766 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6767 spin_unlock_irq(&ctx->completion_lock);
6770 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6772 unsigned int to_submit;
6775 to_submit = io_sqring_entries(ctx);
6776 /* if we're handling multiple rings, cap submit size for fairness */
6777 if (cap_entries && to_submit > 8)
6780 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6781 unsigned nr_events = 0;
6783 mutex_lock(&ctx->uring_lock);
6784 if (!list_empty(&ctx->iopoll_list))
6785 io_do_iopoll(ctx, &nr_events, 0);
6788 * Don't submit if refs are dying, good for io_uring_register(),
6789 * but also it is relied upon by io_ring_exit_work()
6791 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6792 !(ctx->flags & IORING_SETUP_R_DISABLED))
6793 ret = io_submit_sqes(ctx, to_submit);
6794 mutex_unlock(&ctx->uring_lock);
6797 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6798 wake_up(&ctx->sqo_sq_wait);
6803 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6805 struct io_ring_ctx *ctx;
6806 unsigned sq_thread_idle = 0;
6808 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6809 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6810 sqd->sq_thread_idle = sq_thread_idle;
6813 static int io_sq_thread(void *data)
6815 struct io_sq_data *sqd = data;
6816 struct io_ring_ctx *ctx;
6817 unsigned long timeout = 0;
6818 char buf[TASK_COMM_LEN];
6821 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6822 set_task_comm(current, buf);
6824 if (sqd->sq_cpu != -1)
6825 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6827 set_cpus_allowed_ptr(current, cpu_online_mask);
6828 current->flags |= PF_NO_SETAFFINITY;
6830 mutex_lock(&sqd->lock);
6831 /* a user may had exited before the thread started */
6832 io_run_task_work_head(&sqd->park_task_work);
6834 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6836 bool cap_entries, sqt_spin, needs_sched;
6838 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6839 signal_pending(current)) {
6840 bool did_sig = false;
6842 mutex_unlock(&sqd->lock);
6843 if (signal_pending(current)) {
6844 struct ksignal ksig;
6846 did_sig = get_signal(&ksig);
6849 mutex_lock(&sqd->lock);
6851 io_run_task_work_head(&sqd->park_task_work);
6854 timeout = jiffies + sqd->sq_thread_idle;
6858 cap_entries = !list_is_singular(&sqd->ctx_list);
6859 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6860 const struct cred *creds = NULL;
6862 if (ctx->sq_creds != current_cred())
6863 creds = override_creds(ctx->sq_creds);
6864 ret = __io_sq_thread(ctx, cap_entries);
6866 revert_creds(creds);
6867 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6871 if (sqt_spin || !time_after(jiffies, timeout)) {
6875 timeout = jiffies + sqd->sq_thread_idle;
6879 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6880 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6881 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6882 io_ring_set_wakeup_flag(ctx);
6885 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6886 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6887 !list_empty_careful(&ctx->iopoll_list)) {
6888 needs_sched = false;
6891 if (io_sqring_entries(ctx)) {
6892 needs_sched = false;
6898 mutex_unlock(&sqd->lock);
6900 mutex_lock(&sqd->lock);
6902 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6903 io_ring_clear_wakeup_flag(ctx);
6906 finish_wait(&sqd->wait, &wait);
6907 io_run_task_work_head(&sqd->park_task_work);
6908 timeout = jiffies + sqd->sq_thread_idle;
6911 io_uring_cancel_sqpoll(sqd);
6913 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6914 io_ring_set_wakeup_flag(ctx);
6916 io_run_task_work_head(&sqd->park_task_work);
6917 mutex_unlock(&sqd->lock);
6919 complete(&sqd->exited);
6923 struct io_wait_queue {
6924 struct wait_queue_entry wq;
6925 struct io_ring_ctx *ctx;
6927 unsigned nr_timeouts;
6930 static inline bool io_should_wake(struct io_wait_queue *iowq)
6932 struct io_ring_ctx *ctx = iowq->ctx;
6935 * Wake up if we have enough events, or if a timeout occurred since we
6936 * started waiting. For timeouts, we always want to return to userspace,
6937 * regardless of event count.
6939 return io_cqring_events(ctx) >= iowq->to_wait ||
6940 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6943 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6944 int wake_flags, void *key)
6946 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6950 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6951 * the task, and the next invocation will do it.
6953 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6954 return autoremove_wake_function(curr, mode, wake_flags, key);
6958 static int io_run_task_work_sig(void)
6960 if (io_run_task_work())
6962 if (!signal_pending(current))
6964 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6965 return -ERESTARTSYS;
6969 /* when returns >0, the caller should retry */
6970 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6971 struct io_wait_queue *iowq,
6972 signed long *timeout)
6976 /* make sure we run task_work before checking for signals */
6977 ret = io_run_task_work_sig();
6978 if (ret || io_should_wake(iowq))
6980 /* let the caller flush overflows, retry */
6981 if (test_bit(0, &ctx->cq_check_overflow))
6984 *timeout = schedule_timeout(*timeout);
6985 return !*timeout ? -ETIME : 1;
6989 * Wait until events become available, if we don't already have some. The
6990 * application must reap them itself, as they reside on the shared cq ring.
6992 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6993 const sigset_t __user *sig, size_t sigsz,
6994 struct __kernel_timespec __user *uts)
6996 struct io_wait_queue iowq = {
6999 .func = io_wake_function,
7000 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7003 .to_wait = min_events,
7005 struct io_rings *rings = ctx->rings;
7006 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7010 io_cqring_overflow_flush(ctx, false);
7011 if (io_cqring_events(ctx) >= min_events)
7013 if (!io_run_task_work())
7018 #ifdef CONFIG_COMPAT
7019 if (in_compat_syscall())
7020 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7024 ret = set_user_sigmask(sig, sigsz);
7031 struct timespec64 ts;
7033 if (get_timespec64(&ts, uts))
7035 timeout = timespec64_to_jiffies(&ts);
7038 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7039 trace_io_uring_cqring_wait(ctx, min_events);
7041 /* if we can't even flush overflow, don't wait for more */
7042 if (!io_cqring_overflow_flush(ctx, false)) {
7046 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7047 TASK_INTERRUPTIBLE);
7048 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7049 finish_wait(&ctx->wait, &iowq.wq);
7053 restore_saved_sigmask_unless(ret == -EINTR);
7055 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7058 static void io_free_file_tables(struct io_file_table *table, unsigned nr_files)
7060 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7062 for (i = 0; i < nr_tables; i++)
7063 kfree(table->files[i]);
7064 kfree(table->files);
7065 table->files = NULL;
7068 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7070 spin_lock_bh(&ctx->rsrc_ref_lock);
7073 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7075 spin_unlock_bh(&ctx->rsrc_ref_lock);
7078 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7080 percpu_ref_exit(&ref_node->refs);
7084 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7085 struct io_rsrc_data *data_to_kill)
7087 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7088 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7091 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7093 rsrc_node->rsrc_data = data_to_kill;
7094 io_rsrc_ref_lock(ctx);
7095 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7096 io_rsrc_ref_unlock(ctx);
7098 atomic_inc(&data_to_kill->refs);
7099 percpu_ref_kill(&rsrc_node->refs);
7100 ctx->rsrc_node = NULL;
7103 if (!ctx->rsrc_node) {
7104 ctx->rsrc_node = ctx->rsrc_backup_node;
7105 ctx->rsrc_backup_node = NULL;
7109 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7111 if (ctx->rsrc_backup_node)
7113 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7114 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7117 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7121 /* As we may drop ->uring_lock, other task may have started quiesce */
7125 data->quiesce = true;
7127 ret = io_rsrc_node_switch_start(ctx);
7130 io_rsrc_node_switch(ctx, data);
7132 /* kill initial ref, already quiesced if zero */
7133 if (atomic_dec_and_test(&data->refs))
7135 flush_delayed_work(&ctx->rsrc_put_work);
7136 ret = wait_for_completion_interruptible(&data->done);
7140 atomic_inc(&data->refs);
7141 /* wait for all works potentially completing data->done */
7142 flush_delayed_work(&ctx->rsrc_put_work);
7143 reinit_completion(&data->done);
7145 mutex_unlock(&ctx->uring_lock);
7146 ret = io_run_task_work_sig();
7147 mutex_lock(&ctx->uring_lock);
7149 data->quiesce = false;
7154 static void io_rsrc_data_free(struct io_rsrc_data *data)
7160 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7161 rsrc_put_fn *do_put,
7164 struct io_rsrc_data *data;
7166 data = kzalloc(sizeof(*data), GFP_KERNEL);
7170 data->tags = kvcalloc(nr, sizeof(*data->tags), GFP_KERNEL);
7176 atomic_set(&data->refs, 1);
7178 data->do_put = do_put;
7179 init_completion(&data->done);
7183 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7185 #if defined(CONFIG_UNIX)
7186 if (ctx->ring_sock) {
7187 struct sock *sock = ctx->ring_sock->sk;
7188 struct sk_buff *skb;
7190 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7196 for (i = 0; i < ctx->nr_user_files; i++) {
7199 file = io_file_from_index(ctx, i);
7204 io_free_file_tables(&ctx->file_table, ctx->nr_user_files);
7205 io_rsrc_data_free(ctx->file_data);
7206 ctx->file_data = NULL;
7207 ctx->nr_user_files = 0;
7210 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7214 if (!ctx->file_data)
7216 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7218 __io_sqe_files_unregister(ctx);
7222 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7223 __releases(&sqd->lock)
7225 WARN_ON_ONCE(sqd->thread == current);
7228 * Do the dance but not conditional clear_bit() because it'd race with
7229 * other threads incrementing park_pending and setting the bit.
7231 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7232 if (atomic_dec_return(&sqd->park_pending))
7233 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7234 mutex_unlock(&sqd->lock);
7237 static void io_sq_thread_park(struct io_sq_data *sqd)
7238 __acquires(&sqd->lock)
7240 WARN_ON_ONCE(sqd->thread == current);
7242 atomic_inc(&sqd->park_pending);
7243 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7244 mutex_lock(&sqd->lock);
7246 wake_up_process(sqd->thread);
7249 static void io_sq_thread_stop(struct io_sq_data *sqd)
7251 WARN_ON_ONCE(sqd->thread == current);
7252 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7254 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7255 mutex_lock(&sqd->lock);
7257 wake_up_process(sqd->thread);
7258 mutex_unlock(&sqd->lock);
7259 wait_for_completion(&sqd->exited);
7262 static void io_put_sq_data(struct io_sq_data *sqd)
7264 if (refcount_dec_and_test(&sqd->refs)) {
7265 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7267 io_sq_thread_stop(sqd);
7272 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7274 struct io_sq_data *sqd = ctx->sq_data;
7277 io_sq_thread_park(sqd);
7278 list_del_init(&ctx->sqd_list);
7279 io_sqd_update_thread_idle(sqd);
7280 io_sq_thread_unpark(sqd);
7282 io_put_sq_data(sqd);
7283 ctx->sq_data = NULL;
7287 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7289 struct io_ring_ctx *ctx_attach;
7290 struct io_sq_data *sqd;
7293 f = fdget(p->wq_fd);
7295 return ERR_PTR(-ENXIO);
7296 if (f.file->f_op != &io_uring_fops) {
7298 return ERR_PTR(-EINVAL);
7301 ctx_attach = f.file->private_data;
7302 sqd = ctx_attach->sq_data;
7305 return ERR_PTR(-EINVAL);
7307 if (sqd->task_tgid != current->tgid) {
7309 return ERR_PTR(-EPERM);
7312 refcount_inc(&sqd->refs);
7317 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7320 struct io_sq_data *sqd;
7323 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7324 sqd = io_attach_sq_data(p);
7329 /* fall through for EPERM case, setup new sqd/task */
7330 if (PTR_ERR(sqd) != -EPERM)
7334 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7336 return ERR_PTR(-ENOMEM);
7338 atomic_set(&sqd->park_pending, 0);
7339 refcount_set(&sqd->refs, 1);
7340 INIT_LIST_HEAD(&sqd->ctx_list);
7341 mutex_init(&sqd->lock);
7342 init_waitqueue_head(&sqd->wait);
7343 init_completion(&sqd->exited);
7347 #if defined(CONFIG_UNIX)
7349 * Ensure the UNIX gc is aware of our file set, so we are certain that
7350 * the io_uring can be safely unregistered on process exit, even if we have
7351 * loops in the file referencing.
7353 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7355 struct sock *sk = ctx->ring_sock->sk;
7356 struct scm_fp_list *fpl;
7357 struct sk_buff *skb;
7360 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7364 skb = alloc_skb(0, GFP_KERNEL);
7373 fpl->user = get_uid(current_user());
7374 for (i = 0; i < nr; i++) {
7375 struct file *file = io_file_from_index(ctx, i + offset);
7379 fpl->fp[nr_files] = get_file(file);
7380 unix_inflight(fpl->user, fpl->fp[nr_files]);
7385 fpl->max = SCM_MAX_FD;
7386 fpl->count = nr_files;
7387 UNIXCB(skb).fp = fpl;
7388 skb->destructor = unix_destruct_scm;
7389 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7390 skb_queue_head(&sk->sk_receive_queue, skb);
7392 for (i = 0; i < nr_files; i++)
7403 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7404 * causes regular reference counting to break down. We rely on the UNIX
7405 * garbage collection to take care of this problem for us.
7407 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7409 unsigned left, total;
7413 left = ctx->nr_user_files;
7415 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7417 ret = __io_sqe_files_scm(ctx, this_files, total);
7421 total += this_files;
7427 while (total < ctx->nr_user_files) {
7428 struct file *file = io_file_from_index(ctx, total);
7438 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7444 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7446 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7448 table->files = kcalloc(nr_tables, sizeof(*table->files), GFP_KERNEL);
7452 for (i = 0; i < nr_tables; i++) {
7453 unsigned int this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7455 table->files[i] = kcalloc(this_files, sizeof(*table->files[i]),
7457 if (!table->files[i])
7459 nr_files -= this_files;
7465 io_free_file_tables(table, nr_tables * IORING_MAX_FILES_TABLE);
7469 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7471 struct file *file = prsrc->file;
7472 #if defined(CONFIG_UNIX)
7473 struct sock *sock = ctx->ring_sock->sk;
7474 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7475 struct sk_buff *skb;
7478 __skb_queue_head_init(&list);
7481 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7482 * remove this entry and rearrange the file array.
7484 skb = skb_dequeue(head);
7486 struct scm_fp_list *fp;
7488 fp = UNIXCB(skb).fp;
7489 for (i = 0; i < fp->count; i++) {
7492 if (fp->fp[i] != file)
7495 unix_notinflight(fp->user, fp->fp[i]);
7496 left = fp->count - 1 - i;
7498 memmove(&fp->fp[i], &fp->fp[i + 1],
7499 left * sizeof(struct file *));
7506 __skb_queue_tail(&list, skb);
7516 __skb_queue_tail(&list, skb);
7518 skb = skb_dequeue(head);
7521 if (skb_peek(&list)) {
7522 spin_lock_irq(&head->lock);
7523 while ((skb = __skb_dequeue(&list)) != NULL)
7524 __skb_queue_tail(head, skb);
7525 spin_unlock_irq(&head->lock);
7532 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7534 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7535 struct io_ring_ctx *ctx = rsrc_data->ctx;
7536 struct io_rsrc_put *prsrc, *tmp;
7538 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7539 list_del(&prsrc->list);
7542 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7543 unsigned long flags;
7545 io_ring_submit_lock(ctx, lock_ring);
7546 spin_lock_irqsave(&ctx->completion_lock, flags);
7547 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7549 io_commit_cqring(ctx);
7550 spin_unlock_irqrestore(&ctx->completion_lock, flags);
7551 io_cqring_ev_posted(ctx);
7552 io_ring_submit_unlock(ctx, lock_ring);
7555 rsrc_data->do_put(ctx, prsrc);
7559 io_rsrc_node_destroy(ref_node);
7560 if (atomic_dec_and_test(&rsrc_data->refs))
7561 complete(&rsrc_data->done);
7564 static void io_rsrc_put_work(struct work_struct *work)
7566 struct io_ring_ctx *ctx;
7567 struct llist_node *node;
7569 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7570 node = llist_del_all(&ctx->rsrc_put_llist);
7573 struct io_rsrc_node *ref_node;
7574 struct llist_node *next = node->next;
7576 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7577 __io_rsrc_put_work(ref_node);
7582 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7584 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7585 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7586 bool first_add = false;
7588 io_rsrc_ref_lock(ctx);
7591 while (!list_empty(&ctx->rsrc_ref_list)) {
7592 node = list_first_entry(&ctx->rsrc_ref_list,
7593 struct io_rsrc_node, node);
7594 /* recycle ref nodes in order */
7597 list_del(&node->node);
7598 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7600 io_rsrc_ref_unlock(ctx);
7603 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7606 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7608 struct io_rsrc_node *ref_node;
7610 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7614 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7619 INIT_LIST_HEAD(&ref_node->node);
7620 INIT_LIST_HEAD(&ref_node->rsrc_list);
7621 ref_node->done = false;
7625 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7626 unsigned nr_args, u64 __user *tags)
7628 __s32 __user *fds = (__s32 __user *) arg;
7632 struct io_rsrc_data *file_data;
7638 if (nr_args > IORING_MAX_FIXED_FILES)
7640 ret = io_rsrc_node_switch_start(ctx);
7644 file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put, nr_args);
7647 ctx->file_data = file_data;
7649 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7652 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7655 if ((tags && copy_from_user(&tag, &tags[i], sizeof(tag))) ||
7656 copy_from_user(&fd, &fds[i], sizeof(fd))) {
7660 /* allow sparse sets */
7670 if (unlikely(!file))
7674 * Don't allow io_uring instances to be registered. If UNIX
7675 * isn't enabled, then this causes a reference cycle and this
7676 * instance can never get freed. If UNIX is enabled we'll
7677 * handle it just fine, but there's still no point in allowing
7678 * a ring fd as it doesn't support regular read/write anyway.
7680 if (file->f_op == &io_uring_fops) {
7684 ctx->file_data->tags[i] = tag;
7685 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7688 ret = io_sqe_files_scm(ctx);
7690 __io_sqe_files_unregister(ctx);
7694 io_rsrc_node_switch(ctx, NULL);
7697 for (i = 0; i < ctx->nr_user_files; i++) {
7698 file = io_file_from_index(ctx, i);
7702 io_free_file_tables(&ctx->file_table, nr_args);
7703 ctx->nr_user_files = 0;
7705 io_rsrc_data_free(ctx->file_data);
7706 ctx->file_data = NULL;
7710 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7713 #if defined(CONFIG_UNIX)
7714 struct sock *sock = ctx->ring_sock->sk;
7715 struct sk_buff_head *head = &sock->sk_receive_queue;
7716 struct sk_buff *skb;
7719 * See if we can merge this file into an existing skb SCM_RIGHTS
7720 * file set. If there's no room, fall back to allocating a new skb
7721 * and filling it in.
7723 spin_lock_irq(&head->lock);
7724 skb = skb_peek(head);
7726 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7728 if (fpl->count < SCM_MAX_FD) {
7729 __skb_unlink(skb, head);
7730 spin_unlock_irq(&head->lock);
7731 fpl->fp[fpl->count] = get_file(file);
7732 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7734 spin_lock_irq(&head->lock);
7735 __skb_queue_head(head, skb);
7740 spin_unlock_irq(&head->lock);
7747 return __io_sqe_files_scm(ctx, 1, index);
7753 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7754 struct io_rsrc_node *node, void *rsrc)
7756 struct io_rsrc_put *prsrc;
7758 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7762 prsrc->tag = data->tags[idx];
7764 list_add(&prsrc->list, &node->rsrc_list);
7768 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7769 struct io_uring_rsrc_update2 *up,
7772 u64 __user *tags = u64_to_user_ptr(up->tags);
7773 __s32 __user *fds = u64_to_user_ptr(up->data);
7774 struct io_rsrc_data *data = ctx->file_data;
7775 struct io_fixed_file *file_slot;
7779 bool needs_switch = false;
7781 if (!ctx->file_data)
7783 if (up->offset + nr_args > ctx->nr_user_files)
7786 for (done = 0; done < nr_args; done++) {
7789 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7790 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7794 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7798 if (fd == IORING_REGISTER_FILES_SKIP)
7801 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7802 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7804 if (file_slot->file_ptr) {
7805 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7806 err = io_queue_rsrc_removal(data, up->offset + done,
7807 ctx->rsrc_node, file);
7810 file_slot->file_ptr = 0;
7811 needs_switch = true;
7820 * Don't allow io_uring instances to be registered. If
7821 * UNIX isn't enabled, then this causes a reference
7822 * cycle and this instance can never get freed. If UNIX
7823 * is enabled we'll handle it just fine, but there's
7824 * still no point in allowing a ring fd as it doesn't
7825 * support regular read/write anyway.
7827 if (file->f_op == &io_uring_fops) {
7832 data->tags[up->offset + done] = tag;
7833 io_fixed_file_set(file_slot, file);
7834 err = io_sqe_file_register(ctx, file, i);
7836 file_slot->file_ptr = 0;
7844 io_rsrc_node_switch(ctx, data);
7845 return done ? done : err;
7848 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7850 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7852 req = io_put_req_find_next(req);
7853 return req ? &req->work : NULL;
7856 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7857 struct task_struct *task)
7859 struct io_wq_hash *hash;
7860 struct io_wq_data data;
7861 unsigned int concurrency;
7863 hash = ctx->hash_map;
7865 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7867 return ERR_PTR(-ENOMEM);
7868 refcount_set(&hash->refs, 1);
7869 init_waitqueue_head(&hash->wait);
7870 ctx->hash_map = hash;
7875 data.free_work = io_free_work;
7876 data.do_work = io_wq_submit_work;
7878 /* Do QD, or 4 * CPUS, whatever is smallest */
7879 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7881 return io_wq_create(concurrency, &data);
7884 static int io_uring_alloc_task_context(struct task_struct *task,
7885 struct io_ring_ctx *ctx)
7887 struct io_uring_task *tctx;
7890 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7891 if (unlikely(!tctx))
7894 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7895 if (unlikely(ret)) {
7900 tctx->io_wq = io_init_wq_offload(ctx, task);
7901 if (IS_ERR(tctx->io_wq)) {
7902 ret = PTR_ERR(tctx->io_wq);
7903 percpu_counter_destroy(&tctx->inflight);
7909 init_waitqueue_head(&tctx->wait);
7911 atomic_set(&tctx->in_idle, 0);
7912 atomic_set(&tctx->inflight_tracked, 0);
7913 task->io_uring = tctx;
7914 spin_lock_init(&tctx->task_lock);
7915 INIT_WQ_LIST(&tctx->task_list);
7916 tctx->task_state = 0;
7917 init_task_work(&tctx->task_work, tctx_task_work);
7921 void __io_uring_free(struct task_struct *tsk)
7923 struct io_uring_task *tctx = tsk->io_uring;
7925 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7926 WARN_ON_ONCE(tctx->io_wq);
7928 percpu_counter_destroy(&tctx->inflight);
7930 tsk->io_uring = NULL;
7933 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7934 struct io_uring_params *p)
7938 /* Retain compatibility with failing for an invalid attach attempt */
7939 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7940 IORING_SETUP_ATTACH_WQ) {
7943 f = fdget(p->wq_fd);
7947 if (f.file->f_op != &io_uring_fops)
7950 if (ctx->flags & IORING_SETUP_SQPOLL) {
7951 struct task_struct *tsk;
7952 struct io_sq_data *sqd;
7955 sqd = io_get_sq_data(p, &attached);
7961 ctx->sq_creds = get_current_cred();
7963 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7964 if (!ctx->sq_thread_idle)
7965 ctx->sq_thread_idle = HZ;
7967 io_sq_thread_park(sqd);
7968 list_add(&ctx->sqd_list, &sqd->ctx_list);
7969 io_sqd_update_thread_idle(sqd);
7970 /* don't attach to a dying SQPOLL thread, would be racy */
7971 ret = (attached && !sqd->thread) ? -ENXIO : 0;
7972 io_sq_thread_unpark(sqd);
7979 if (p->flags & IORING_SETUP_SQ_AFF) {
7980 int cpu = p->sq_thread_cpu;
7983 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
7990 sqd->task_pid = current->pid;
7991 sqd->task_tgid = current->tgid;
7992 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7999 ret = io_uring_alloc_task_context(tsk, ctx);
8000 wake_up_new_task(tsk);
8003 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8004 /* Can't have SQ_AFF without SQPOLL */
8011 complete(&ctx->sq_data->exited);
8013 io_sq_thread_finish(ctx);
8017 static inline void __io_unaccount_mem(struct user_struct *user,
8018 unsigned long nr_pages)
8020 atomic_long_sub(nr_pages, &user->locked_vm);
8023 static inline int __io_account_mem(struct user_struct *user,
8024 unsigned long nr_pages)
8026 unsigned long page_limit, cur_pages, new_pages;
8028 /* Don't allow more pages than we can safely lock */
8029 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8032 cur_pages = atomic_long_read(&user->locked_vm);
8033 new_pages = cur_pages + nr_pages;
8034 if (new_pages > page_limit)
8036 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8037 new_pages) != cur_pages);
8042 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8045 __io_unaccount_mem(ctx->user, nr_pages);
8047 if (ctx->mm_account)
8048 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8051 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8056 ret = __io_account_mem(ctx->user, nr_pages);
8061 if (ctx->mm_account)
8062 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8067 static void io_mem_free(void *ptr)
8074 page = virt_to_head_page(ptr);
8075 if (put_page_testzero(page))
8076 free_compound_page(page);
8079 static void *io_mem_alloc(size_t size)
8081 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8082 __GFP_NORETRY | __GFP_ACCOUNT;
8084 return (void *) __get_free_pages(gfp_flags, get_order(size));
8087 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8090 struct io_rings *rings;
8091 size_t off, sq_array_size;
8093 off = struct_size(rings, cqes, cq_entries);
8094 if (off == SIZE_MAX)
8098 off = ALIGN(off, SMP_CACHE_BYTES);
8106 sq_array_size = array_size(sizeof(u32), sq_entries);
8107 if (sq_array_size == SIZE_MAX)
8110 if (check_add_overflow(off, sq_array_size, &off))
8116 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8118 struct io_mapped_ubuf *imu = *slot;
8121 if (imu != ctx->dummy_ubuf) {
8122 for (i = 0; i < imu->nr_bvecs; i++)
8123 unpin_user_page(imu->bvec[i].bv_page);
8124 if (imu->acct_pages)
8125 io_unaccount_mem(ctx, imu->acct_pages);
8131 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8133 io_buffer_unmap(ctx, &prsrc->buf);
8137 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8141 for (i = 0; i < ctx->nr_user_bufs; i++)
8142 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8143 kfree(ctx->user_bufs);
8144 io_rsrc_data_free(ctx->buf_data);
8145 ctx->user_bufs = NULL;
8146 ctx->buf_data = NULL;
8147 ctx->nr_user_bufs = 0;
8150 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8157 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8159 __io_sqe_buffers_unregister(ctx);
8163 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8164 void __user *arg, unsigned index)
8166 struct iovec __user *src;
8168 #ifdef CONFIG_COMPAT
8170 struct compat_iovec __user *ciovs;
8171 struct compat_iovec ciov;
8173 ciovs = (struct compat_iovec __user *) arg;
8174 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8177 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8178 dst->iov_len = ciov.iov_len;
8182 src = (struct iovec __user *) arg;
8183 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8189 * Not super efficient, but this is just a registration time. And we do cache
8190 * the last compound head, so generally we'll only do a full search if we don't
8193 * We check if the given compound head page has already been accounted, to
8194 * avoid double accounting it. This allows us to account the full size of the
8195 * page, not just the constituent pages of a huge page.
8197 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8198 int nr_pages, struct page *hpage)
8202 /* check current page array */
8203 for (i = 0; i < nr_pages; i++) {
8204 if (!PageCompound(pages[i]))
8206 if (compound_head(pages[i]) == hpage)
8210 /* check previously registered pages */
8211 for (i = 0; i < ctx->nr_user_bufs; i++) {
8212 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8214 for (j = 0; j < imu->nr_bvecs; j++) {
8215 if (!PageCompound(imu->bvec[j].bv_page))
8217 if (compound_head(imu->bvec[j].bv_page) == hpage)
8225 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8226 int nr_pages, struct io_mapped_ubuf *imu,
8227 struct page **last_hpage)
8231 for (i = 0; i < nr_pages; i++) {
8232 if (!PageCompound(pages[i])) {
8237 hpage = compound_head(pages[i]);
8238 if (hpage == *last_hpage)
8240 *last_hpage = hpage;
8241 if (headpage_already_acct(ctx, pages, i, hpage))
8243 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8247 if (!imu->acct_pages)
8250 ret = io_account_mem(ctx, imu->acct_pages);
8252 imu->acct_pages = 0;
8256 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8257 struct io_mapped_ubuf **pimu,
8258 struct page **last_hpage)
8260 struct io_mapped_ubuf *imu = NULL;
8261 struct vm_area_struct **vmas = NULL;
8262 struct page **pages = NULL;
8263 unsigned long off, start, end, ubuf;
8265 int ret, pret, nr_pages, i;
8267 if (!iov->iov_base) {
8268 *pimu = ctx->dummy_ubuf;
8272 ubuf = (unsigned long) iov->iov_base;
8273 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8274 start = ubuf >> PAGE_SHIFT;
8275 nr_pages = end - start;
8280 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8284 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8289 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8294 mmap_read_lock(current->mm);
8295 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8297 if (pret == nr_pages) {
8298 /* don't support file backed memory */
8299 for (i = 0; i < nr_pages; i++) {
8300 struct vm_area_struct *vma = vmas[i];
8303 !is_file_hugepages(vma->vm_file)) {
8309 ret = pret < 0 ? pret : -EFAULT;
8311 mmap_read_unlock(current->mm);
8314 * if we did partial map, or found file backed vmas,
8315 * release any pages we did get
8318 unpin_user_pages(pages, pret);
8322 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8324 unpin_user_pages(pages, pret);
8328 off = ubuf & ~PAGE_MASK;
8329 size = iov->iov_len;
8330 for (i = 0; i < nr_pages; i++) {
8333 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8334 imu->bvec[i].bv_page = pages[i];
8335 imu->bvec[i].bv_len = vec_len;
8336 imu->bvec[i].bv_offset = off;
8340 /* store original address for later verification */
8342 imu->ubuf_end = ubuf + iov->iov_len;
8343 imu->nr_bvecs = nr_pages;
8354 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8356 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8357 return ctx->user_bufs ? 0 : -ENOMEM;
8360 static int io_buffer_validate(struct iovec *iov)
8362 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8365 * Don't impose further limits on the size and buffer
8366 * constraints here, we'll -EINVAL later when IO is
8367 * submitted if they are wrong.
8370 return iov->iov_len ? -EFAULT : 0;
8374 /* arbitrary limit, but we need something */
8375 if (iov->iov_len > SZ_1G)
8378 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8384 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8385 unsigned int nr_args, u64 __user *tags)
8387 struct page *last_hpage = NULL;
8388 struct io_rsrc_data *data;
8394 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8396 ret = io_rsrc_node_switch_start(ctx);
8399 data = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, nr_args);
8402 ret = io_buffers_map_alloc(ctx, nr_args);
8404 io_rsrc_data_free(data);
8408 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8411 if (tags && copy_from_user(&tag, &tags[i], sizeof(tag))) {
8415 ret = io_copy_iov(ctx, &iov, arg, i);
8418 ret = io_buffer_validate(&iov);
8421 if (!iov.iov_base && tag) {
8426 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8430 data->tags[i] = tag;
8433 WARN_ON_ONCE(ctx->buf_data);
8435 ctx->buf_data = data;
8437 __io_sqe_buffers_unregister(ctx);
8439 io_rsrc_node_switch(ctx, NULL);
8443 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8444 struct io_uring_rsrc_update2 *up,
8445 unsigned int nr_args)
8447 u64 __user *tags = u64_to_user_ptr(up->tags);
8448 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8449 struct page *last_hpage = NULL;
8450 bool needs_switch = false;
8456 if (up->offset + nr_args > ctx->nr_user_bufs)
8459 for (done = 0; done < nr_args; done++) {
8460 struct io_mapped_ubuf *imu;
8461 int offset = up->offset + done;
8464 err = io_copy_iov(ctx, &iov, iovs, done);
8467 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8471 err = io_buffer_validate(&iov);
8474 if (!iov.iov_base && tag) {
8478 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8482 i = array_index_nospec(offset, ctx->nr_user_bufs);
8483 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8484 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8485 ctx->rsrc_node, ctx->user_bufs[i]);
8486 if (unlikely(err)) {
8487 io_buffer_unmap(ctx, &imu);
8490 ctx->user_bufs[i] = NULL;
8491 needs_switch = true;
8494 ctx->user_bufs[i] = imu;
8495 ctx->buf_data->tags[offset] = tag;
8499 io_rsrc_node_switch(ctx, ctx->buf_data);
8500 return done ? done : err;
8503 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8505 __s32 __user *fds = arg;
8511 if (copy_from_user(&fd, fds, sizeof(*fds)))
8514 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8515 if (IS_ERR(ctx->cq_ev_fd)) {
8516 int ret = PTR_ERR(ctx->cq_ev_fd);
8517 ctx->cq_ev_fd = NULL;
8524 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8526 if (ctx->cq_ev_fd) {
8527 eventfd_ctx_put(ctx->cq_ev_fd);
8528 ctx->cq_ev_fd = NULL;
8535 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8537 struct io_buffer *buf;
8538 unsigned long index;
8540 xa_for_each(&ctx->io_buffers, index, buf)
8541 __io_remove_buffers(ctx, buf, index, -1U);
8544 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8546 struct io_kiocb *req, *nxt;
8548 list_for_each_entry_safe(req, nxt, list, compl.list) {
8549 if (tsk && req->task != tsk)
8551 list_del(&req->compl.list);
8552 kmem_cache_free(req_cachep, req);
8556 static void io_req_caches_free(struct io_ring_ctx *ctx)
8558 struct io_submit_state *submit_state = &ctx->submit_state;
8559 struct io_comp_state *cs = &ctx->submit_state.comp;
8561 mutex_lock(&ctx->uring_lock);
8563 if (submit_state->free_reqs) {
8564 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8565 submit_state->reqs);
8566 submit_state->free_reqs = 0;
8569 io_flush_cached_locked_reqs(ctx, cs);
8570 io_req_cache_free(&cs->free_list, NULL);
8571 mutex_unlock(&ctx->uring_lock);
8574 static bool io_wait_rsrc_data(struct io_rsrc_data *data)
8578 if (!atomic_dec_and_test(&data->refs))
8579 wait_for_completion(&data->done);
8583 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8585 io_sq_thread_finish(ctx);
8587 if (ctx->mm_account) {
8588 mmdrop(ctx->mm_account);
8589 ctx->mm_account = NULL;
8592 mutex_lock(&ctx->uring_lock);
8593 if (io_wait_rsrc_data(ctx->buf_data))
8594 __io_sqe_buffers_unregister(ctx);
8595 if (io_wait_rsrc_data(ctx->file_data))
8596 __io_sqe_files_unregister(ctx);
8598 __io_cqring_overflow_flush(ctx, true);
8599 mutex_unlock(&ctx->uring_lock);
8600 io_eventfd_unregister(ctx);
8601 io_destroy_buffers(ctx);
8603 put_cred(ctx->sq_creds);
8605 /* there are no registered resources left, nobody uses it */
8607 io_rsrc_node_destroy(ctx->rsrc_node);
8608 if (ctx->rsrc_backup_node)
8609 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8610 flush_delayed_work(&ctx->rsrc_put_work);
8612 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8613 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8615 #if defined(CONFIG_UNIX)
8616 if (ctx->ring_sock) {
8617 ctx->ring_sock->file = NULL; /* so that iput() is called */
8618 sock_release(ctx->ring_sock);
8622 io_mem_free(ctx->rings);
8623 io_mem_free(ctx->sq_sqes);
8625 percpu_ref_exit(&ctx->refs);
8626 free_uid(ctx->user);
8627 io_req_caches_free(ctx);
8629 io_wq_put_hash(ctx->hash_map);
8630 kfree(ctx->cancel_hash);
8631 kfree(ctx->dummy_ubuf);
8635 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8637 struct io_ring_ctx *ctx = file->private_data;
8640 poll_wait(file, &ctx->cq_wait, wait);
8642 * synchronizes with barrier from wq_has_sleeper call in
8646 if (!io_sqring_full(ctx))
8647 mask |= EPOLLOUT | EPOLLWRNORM;
8650 * Don't flush cqring overflow list here, just do a simple check.
8651 * Otherwise there could possible be ABBA deadlock:
8654 * lock(&ctx->uring_lock);
8656 * lock(&ctx->uring_lock);
8659 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8660 * pushs them to do the flush.
8662 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8663 mask |= EPOLLIN | EPOLLRDNORM;
8668 static int io_uring_fasync(int fd, struct file *file, int on)
8670 struct io_ring_ctx *ctx = file->private_data;
8672 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8675 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8677 const struct cred *creds;
8679 creds = xa_erase(&ctx->personalities, id);
8688 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8690 return io_run_task_work_head(&ctx->exit_task_work);
8693 struct io_tctx_exit {
8694 struct callback_head task_work;
8695 struct completion completion;
8696 struct io_ring_ctx *ctx;
8699 static void io_tctx_exit_cb(struct callback_head *cb)
8701 struct io_uring_task *tctx = current->io_uring;
8702 struct io_tctx_exit *work;
8704 work = container_of(cb, struct io_tctx_exit, task_work);
8706 * When @in_idle, we're in cancellation and it's racy to remove the
8707 * node. It'll be removed by the end of cancellation, just ignore it.
8709 if (!atomic_read(&tctx->in_idle))
8710 io_uring_del_task_file((unsigned long)work->ctx);
8711 complete(&work->completion);
8714 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8716 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8718 return req->ctx == data;
8721 static void io_ring_exit_work(struct work_struct *work)
8723 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8724 unsigned long timeout = jiffies + HZ * 60 * 5;
8725 struct io_tctx_exit exit;
8726 struct io_tctx_node *node;
8730 * If we're doing polled IO and end up having requests being
8731 * submitted async (out-of-line), then completions can come in while
8732 * we're waiting for refs to drop. We need to reap these manually,
8733 * as nobody else will be looking for them.
8736 io_uring_try_cancel_requests(ctx, NULL, NULL);
8738 struct io_sq_data *sqd = ctx->sq_data;
8739 struct task_struct *tsk;
8741 io_sq_thread_park(sqd);
8743 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8744 io_wq_cancel_cb(tsk->io_uring->io_wq,
8745 io_cancel_ctx_cb, ctx, true);
8746 io_sq_thread_unpark(sqd);
8749 WARN_ON_ONCE(time_after(jiffies, timeout));
8750 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8752 init_completion(&exit.completion);
8753 init_task_work(&exit.task_work, io_tctx_exit_cb);
8756 * Some may use context even when all refs and requests have been put,
8757 * and they are free to do so while still holding uring_lock or
8758 * completion_lock, see __io_req_task_submit(). Apart from other work,
8759 * this lock/unlock section also waits them to finish.
8761 mutex_lock(&ctx->uring_lock);
8762 while (!list_empty(&ctx->tctx_list)) {
8763 WARN_ON_ONCE(time_after(jiffies, timeout));
8765 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8767 /* don't spin on a single task if cancellation failed */
8768 list_rotate_left(&ctx->tctx_list);
8769 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8770 if (WARN_ON_ONCE(ret))
8772 wake_up_process(node->task);
8774 mutex_unlock(&ctx->uring_lock);
8775 wait_for_completion(&exit.completion);
8776 mutex_lock(&ctx->uring_lock);
8778 mutex_unlock(&ctx->uring_lock);
8779 spin_lock_irq(&ctx->completion_lock);
8780 spin_unlock_irq(&ctx->completion_lock);
8782 io_ring_ctx_free(ctx);
8785 /* Returns true if we found and killed one or more timeouts */
8786 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8787 struct files_struct *files)
8789 struct io_kiocb *req, *tmp;
8792 spin_lock_irq(&ctx->completion_lock);
8793 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8794 if (io_match_task(req, tsk, files)) {
8795 io_kill_timeout(req, -ECANCELED);
8800 io_commit_cqring(ctx);
8801 spin_unlock_irq(&ctx->completion_lock);
8803 io_cqring_ev_posted(ctx);
8804 return canceled != 0;
8807 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8809 unsigned long index;
8810 struct creds *creds;
8812 mutex_lock(&ctx->uring_lock);
8813 percpu_ref_kill(&ctx->refs);
8815 __io_cqring_overflow_flush(ctx, true);
8816 xa_for_each(&ctx->personalities, index, creds)
8817 io_unregister_personality(ctx, index);
8818 mutex_unlock(&ctx->uring_lock);
8820 io_kill_timeouts(ctx, NULL, NULL);
8821 io_poll_remove_all(ctx, NULL, NULL);
8823 /* if we failed setting up the ctx, we might not have any rings */
8824 io_iopoll_try_reap_events(ctx);
8826 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8828 * Use system_unbound_wq to avoid spawning tons of event kworkers
8829 * if we're exiting a ton of rings at the same time. It just adds
8830 * noise and overhead, there's no discernable change in runtime
8831 * over using system_wq.
8833 queue_work(system_unbound_wq, &ctx->exit_work);
8836 static int io_uring_release(struct inode *inode, struct file *file)
8838 struct io_ring_ctx *ctx = file->private_data;
8840 file->private_data = NULL;
8841 io_ring_ctx_wait_and_kill(ctx);
8845 struct io_task_cancel {
8846 struct task_struct *task;
8847 struct files_struct *files;
8850 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8852 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8853 struct io_task_cancel *cancel = data;
8856 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8857 unsigned long flags;
8858 struct io_ring_ctx *ctx = req->ctx;
8860 /* protect against races with linked timeouts */
8861 spin_lock_irqsave(&ctx->completion_lock, flags);
8862 ret = io_match_task(req, cancel->task, cancel->files);
8863 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8865 ret = io_match_task(req, cancel->task, cancel->files);
8870 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8871 struct task_struct *task,
8872 struct files_struct *files)
8874 struct io_defer_entry *de;
8877 spin_lock_irq(&ctx->completion_lock);
8878 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8879 if (io_match_task(de->req, task, files)) {
8880 list_cut_position(&list, &ctx->defer_list, &de->list);
8884 spin_unlock_irq(&ctx->completion_lock);
8885 if (list_empty(&list))
8888 while (!list_empty(&list)) {
8889 de = list_first_entry(&list, struct io_defer_entry, list);
8890 list_del_init(&de->list);
8891 io_req_complete_failed(de->req, -ECANCELED);
8897 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8899 struct io_tctx_node *node;
8900 enum io_wq_cancel cret;
8903 mutex_lock(&ctx->uring_lock);
8904 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8905 struct io_uring_task *tctx = node->task->io_uring;
8908 * io_wq will stay alive while we hold uring_lock, because it's
8909 * killed after ctx nodes, which requires to take the lock.
8911 if (!tctx || !tctx->io_wq)
8913 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8914 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8916 mutex_unlock(&ctx->uring_lock);
8921 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8922 struct task_struct *task,
8923 struct files_struct *files)
8925 struct io_task_cancel cancel = { .task = task, .files = files, };
8926 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8929 enum io_wq_cancel cret;
8933 ret |= io_uring_try_cancel_iowq(ctx);
8934 } else if (tctx && tctx->io_wq) {
8936 * Cancels requests of all rings, not only @ctx, but
8937 * it's fine as the task is in exit/exec.
8939 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8941 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8944 /* SQPOLL thread does its own polling */
8945 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8946 (ctx->sq_data && ctx->sq_data->thread == current)) {
8947 while (!list_empty_careful(&ctx->iopoll_list)) {
8948 io_iopoll_try_reap_events(ctx);
8953 ret |= io_cancel_defer_files(ctx, task, files);
8954 ret |= io_poll_remove_all(ctx, task, files);
8955 ret |= io_kill_timeouts(ctx, task, files);
8956 ret |= io_run_task_work();
8957 ret |= io_run_ctx_fallback(ctx);
8964 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8966 struct io_uring_task *tctx = current->io_uring;
8967 struct io_tctx_node *node;
8970 if (unlikely(!tctx)) {
8971 ret = io_uring_alloc_task_context(current, ctx);
8974 tctx = current->io_uring;
8976 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8977 node = kmalloc(sizeof(*node), GFP_KERNEL);
8981 node->task = current;
8983 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8990 mutex_lock(&ctx->uring_lock);
8991 list_add(&node->ctx_node, &ctx->tctx_list);
8992 mutex_unlock(&ctx->uring_lock);
8999 * Note that this task has used io_uring. We use it for cancelation purposes.
9001 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
9003 struct io_uring_task *tctx = current->io_uring;
9005 if (likely(tctx && tctx->last == ctx))
9007 return __io_uring_add_task_file(ctx);
9011 * Remove this io_uring_file -> task mapping.
9013 static void io_uring_del_task_file(unsigned long index)
9015 struct io_uring_task *tctx = current->io_uring;
9016 struct io_tctx_node *node;
9020 node = xa_erase(&tctx->xa, index);
9024 WARN_ON_ONCE(current != node->task);
9025 WARN_ON_ONCE(list_empty(&node->ctx_node));
9027 mutex_lock(&node->ctx->uring_lock);
9028 list_del(&node->ctx_node);
9029 mutex_unlock(&node->ctx->uring_lock);
9031 if (tctx->last == node->ctx)
9036 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9038 struct io_tctx_node *node;
9039 unsigned long index;
9041 xa_for_each(&tctx->xa, index, node)
9042 io_uring_del_task_file(index);
9044 io_wq_put_and_exit(tctx->io_wq);
9049 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9052 return atomic_read(&tctx->inflight_tracked);
9053 return percpu_counter_sum(&tctx->inflight);
9056 static void io_uring_try_cancel(struct files_struct *files)
9058 struct io_uring_task *tctx = current->io_uring;
9059 struct io_tctx_node *node;
9060 unsigned long index;
9062 xa_for_each(&tctx->xa, index, node) {
9063 struct io_ring_ctx *ctx = node->ctx;
9065 /* sqpoll task will cancel all its requests */
9067 io_uring_try_cancel_requests(ctx, current, files);
9071 /* should only be called by SQPOLL task */
9072 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd)
9074 struct io_uring_task *tctx = current->io_uring;
9075 struct io_ring_ctx *ctx;
9079 if (!current->io_uring)
9081 WARN_ON_ONCE(!sqd || sqd->thread != current);
9083 atomic_inc(&tctx->in_idle);
9085 /* read completions before cancelations */
9086 inflight = tctx_inflight(tctx, false);
9089 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9090 io_uring_try_cancel_requests(ctx, current, NULL);
9092 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9094 * If we've seen completions, retry without waiting. This
9095 * avoids a race where a completion comes in before we did
9096 * prepare_to_wait().
9098 if (inflight == tctx_inflight(tctx, false))
9100 finish_wait(&tctx->wait, &wait);
9102 atomic_dec(&tctx->in_idle);
9106 * Find any io_uring fd that this task has registered or done IO on, and cancel
9109 void __io_uring_cancel(struct files_struct *files)
9111 struct io_uring_task *tctx = current->io_uring;
9115 /* make sure overflow events are dropped */
9116 atomic_inc(&tctx->in_idle);
9118 /* read completions before cancelations */
9119 inflight = tctx_inflight(tctx, !!files);
9122 io_uring_try_cancel(files);
9123 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9126 * If we've seen completions, retry without waiting. This
9127 * avoids a race where a completion comes in before we did
9128 * prepare_to_wait().
9130 if (inflight == tctx_inflight(tctx, !!files))
9132 finish_wait(&tctx->wait, &wait);
9134 atomic_dec(&tctx->in_idle);
9136 io_uring_clean_tctx(tctx);
9138 /* for exec all current's requests should be gone, kill tctx */
9139 __io_uring_free(current);
9143 static void *io_uring_validate_mmap_request(struct file *file,
9144 loff_t pgoff, size_t sz)
9146 struct io_ring_ctx *ctx = file->private_data;
9147 loff_t offset = pgoff << PAGE_SHIFT;
9152 case IORING_OFF_SQ_RING:
9153 case IORING_OFF_CQ_RING:
9156 case IORING_OFF_SQES:
9160 return ERR_PTR(-EINVAL);
9163 page = virt_to_head_page(ptr);
9164 if (sz > page_size(page))
9165 return ERR_PTR(-EINVAL);
9172 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9174 size_t sz = vma->vm_end - vma->vm_start;
9178 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9180 return PTR_ERR(ptr);
9182 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9183 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9186 #else /* !CONFIG_MMU */
9188 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9190 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9193 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9195 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9198 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9199 unsigned long addr, unsigned long len,
9200 unsigned long pgoff, unsigned long flags)
9204 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9206 return PTR_ERR(ptr);
9208 return (unsigned long) ptr;
9211 #endif /* !CONFIG_MMU */
9213 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9218 if (!io_sqring_full(ctx))
9220 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9222 if (!io_sqring_full(ctx))
9225 } while (!signal_pending(current));
9227 finish_wait(&ctx->sqo_sq_wait, &wait);
9231 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9232 struct __kernel_timespec __user **ts,
9233 const sigset_t __user **sig)
9235 struct io_uring_getevents_arg arg;
9238 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9239 * is just a pointer to the sigset_t.
9241 if (!(flags & IORING_ENTER_EXT_ARG)) {
9242 *sig = (const sigset_t __user *) argp;
9248 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9249 * timespec and sigset_t pointers if good.
9251 if (*argsz != sizeof(arg))
9253 if (copy_from_user(&arg, argp, sizeof(arg)))
9255 *sig = u64_to_user_ptr(arg.sigmask);
9256 *argsz = arg.sigmask_sz;
9257 *ts = u64_to_user_ptr(arg.ts);
9261 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9262 u32, min_complete, u32, flags, const void __user *, argp,
9265 struct io_ring_ctx *ctx;
9272 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9273 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9277 if (unlikely(!f.file))
9281 if (unlikely(f.file->f_op != &io_uring_fops))
9285 ctx = f.file->private_data;
9286 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9290 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9294 * For SQ polling, the thread will do all submissions and completions.
9295 * Just return the requested submit count, and wake the thread if
9299 if (ctx->flags & IORING_SETUP_SQPOLL) {
9300 io_cqring_overflow_flush(ctx, false);
9303 if (unlikely(ctx->sq_data->thread == NULL)) {
9306 if (flags & IORING_ENTER_SQ_WAKEUP)
9307 wake_up(&ctx->sq_data->wait);
9308 if (flags & IORING_ENTER_SQ_WAIT) {
9309 ret = io_sqpoll_wait_sq(ctx);
9313 submitted = to_submit;
9314 } else if (to_submit) {
9315 ret = io_uring_add_task_file(ctx);
9318 mutex_lock(&ctx->uring_lock);
9319 submitted = io_submit_sqes(ctx, to_submit);
9320 mutex_unlock(&ctx->uring_lock);
9322 if (submitted != to_submit)
9325 if (flags & IORING_ENTER_GETEVENTS) {
9326 const sigset_t __user *sig;
9327 struct __kernel_timespec __user *ts;
9329 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9333 min_complete = min(min_complete, ctx->cq_entries);
9336 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9337 * space applications don't need to do io completion events
9338 * polling again, they can rely on io_sq_thread to do polling
9339 * work, which can reduce cpu usage and uring_lock contention.
9341 if (ctx->flags & IORING_SETUP_IOPOLL &&
9342 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9343 ret = io_iopoll_check(ctx, min_complete);
9345 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9350 percpu_ref_put(&ctx->refs);
9353 return submitted ? submitted : ret;
9356 #ifdef CONFIG_PROC_FS
9357 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9358 const struct cred *cred)
9360 struct user_namespace *uns = seq_user_ns(m);
9361 struct group_info *gi;
9366 seq_printf(m, "%5d\n", id);
9367 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9368 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9369 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9370 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9371 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9372 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9373 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9374 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9375 seq_puts(m, "\n\tGroups:\t");
9376 gi = cred->group_info;
9377 for (g = 0; g < gi->ngroups; g++) {
9378 seq_put_decimal_ull(m, g ? " " : "",
9379 from_kgid_munged(uns, gi->gid[g]));
9381 seq_puts(m, "\n\tCapEff:\t");
9382 cap = cred->cap_effective;
9383 CAP_FOR_EACH_U32(__capi)
9384 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9389 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9391 struct io_sq_data *sq = NULL;
9396 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9397 * since fdinfo case grabs it in the opposite direction of normal use
9398 * cases. If we fail to get the lock, we just don't iterate any
9399 * structures that could be going away outside the io_uring mutex.
9401 has_lock = mutex_trylock(&ctx->uring_lock);
9403 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9409 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9410 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9411 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9412 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9413 struct file *f = io_file_from_index(ctx, i);
9416 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9418 seq_printf(m, "%5u: <none>\n", i);
9420 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9421 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9422 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9423 unsigned int len = buf->ubuf_end - buf->ubuf;
9425 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9427 if (has_lock && !xa_empty(&ctx->personalities)) {
9428 unsigned long index;
9429 const struct cred *cred;
9431 seq_printf(m, "Personalities:\n");
9432 xa_for_each(&ctx->personalities, index, cred)
9433 io_uring_show_cred(m, index, cred);
9435 seq_printf(m, "PollList:\n");
9436 spin_lock_irq(&ctx->completion_lock);
9437 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9438 struct hlist_head *list = &ctx->cancel_hash[i];
9439 struct io_kiocb *req;
9441 hlist_for_each_entry(req, list, hash_node)
9442 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9443 req->task->task_works != NULL);
9445 spin_unlock_irq(&ctx->completion_lock);
9447 mutex_unlock(&ctx->uring_lock);
9450 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9452 struct io_ring_ctx *ctx = f->private_data;
9454 if (percpu_ref_tryget(&ctx->refs)) {
9455 __io_uring_show_fdinfo(ctx, m);
9456 percpu_ref_put(&ctx->refs);
9461 static const struct file_operations io_uring_fops = {
9462 .release = io_uring_release,
9463 .mmap = io_uring_mmap,
9465 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9466 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9468 .poll = io_uring_poll,
9469 .fasync = io_uring_fasync,
9470 #ifdef CONFIG_PROC_FS
9471 .show_fdinfo = io_uring_show_fdinfo,
9475 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9476 struct io_uring_params *p)
9478 struct io_rings *rings;
9479 size_t size, sq_array_offset;
9481 /* make sure these are sane, as we already accounted them */
9482 ctx->sq_entries = p->sq_entries;
9483 ctx->cq_entries = p->cq_entries;
9485 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9486 if (size == SIZE_MAX)
9489 rings = io_mem_alloc(size);
9494 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9495 rings->sq_ring_mask = p->sq_entries - 1;
9496 rings->cq_ring_mask = p->cq_entries - 1;
9497 rings->sq_ring_entries = p->sq_entries;
9498 rings->cq_ring_entries = p->cq_entries;
9499 ctx->sq_mask = rings->sq_ring_mask;
9500 ctx->cq_mask = rings->cq_ring_mask;
9502 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9503 if (size == SIZE_MAX) {
9504 io_mem_free(ctx->rings);
9509 ctx->sq_sqes = io_mem_alloc(size);
9510 if (!ctx->sq_sqes) {
9511 io_mem_free(ctx->rings);
9519 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9523 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9527 ret = io_uring_add_task_file(ctx);
9532 fd_install(fd, file);
9537 * Allocate an anonymous fd, this is what constitutes the application
9538 * visible backing of an io_uring instance. The application mmaps this
9539 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9540 * we have to tie this fd to a socket for file garbage collection purposes.
9542 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9545 #if defined(CONFIG_UNIX)
9548 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9551 return ERR_PTR(ret);
9554 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9555 O_RDWR | O_CLOEXEC);
9556 #if defined(CONFIG_UNIX)
9558 sock_release(ctx->ring_sock);
9559 ctx->ring_sock = NULL;
9561 ctx->ring_sock->file = file;
9567 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9568 struct io_uring_params __user *params)
9570 struct io_ring_ctx *ctx;
9576 if (entries > IORING_MAX_ENTRIES) {
9577 if (!(p->flags & IORING_SETUP_CLAMP))
9579 entries = IORING_MAX_ENTRIES;
9583 * Use twice as many entries for the CQ ring. It's possible for the
9584 * application to drive a higher depth than the size of the SQ ring,
9585 * since the sqes are only used at submission time. This allows for
9586 * some flexibility in overcommitting a bit. If the application has
9587 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9588 * of CQ ring entries manually.
9590 p->sq_entries = roundup_pow_of_two(entries);
9591 if (p->flags & IORING_SETUP_CQSIZE) {
9593 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9594 * to a power-of-two, if it isn't already. We do NOT impose
9595 * any cq vs sq ring sizing.
9599 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9600 if (!(p->flags & IORING_SETUP_CLAMP))
9602 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9604 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9605 if (p->cq_entries < p->sq_entries)
9608 p->cq_entries = 2 * p->sq_entries;
9611 ctx = io_ring_ctx_alloc(p);
9614 ctx->compat = in_compat_syscall();
9615 if (!capable(CAP_IPC_LOCK))
9616 ctx->user = get_uid(current_user());
9619 * This is just grabbed for accounting purposes. When a process exits,
9620 * the mm is exited and dropped before the files, hence we need to hang
9621 * on to this mm purely for the purposes of being able to unaccount
9622 * memory (locked/pinned vm). It's not used for anything else.
9624 mmgrab(current->mm);
9625 ctx->mm_account = current->mm;
9627 ret = io_allocate_scq_urings(ctx, p);
9631 ret = io_sq_offload_create(ctx, p);
9634 /* always set a rsrc node */
9635 ret = io_rsrc_node_switch_start(ctx);
9638 io_rsrc_node_switch(ctx, NULL);
9640 memset(&p->sq_off, 0, sizeof(p->sq_off));
9641 p->sq_off.head = offsetof(struct io_rings, sq.head);
9642 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9643 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9644 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9645 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9646 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9647 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9649 memset(&p->cq_off, 0, sizeof(p->cq_off));
9650 p->cq_off.head = offsetof(struct io_rings, cq.head);
9651 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9652 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9653 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9654 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9655 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9656 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9658 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9659 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9660 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9661 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9662 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9664 if (copy_to_user(params, p, sizeof(*p))) {
9669 file = io_uring_get_file(ctx);
9671 ret = PTR_ERR(file);
9676 * Install ring fd as the very last thing, so we don't risk someone
9677 * having closed it before we finish setup
9679 ret = io_uring_install_fd(ctx, file);
9681 /* fput will clean it up */
9686 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9689 io_ring_ctx_wait_and_kill(ctx);
9694 * Sets up an aio uring context, and returns the fd. Applications asks for a
9695 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9696 * params structure passed in.
9698 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9700 struct io_uring_params p;
9703 if (copy_from_user(&p, params, sizeof(p)))
9705 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9710 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9711 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9712 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9713 IORING_SETUP_R_DISABLED))
9716 return io_uring_create(entries, &p, params);
9719 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9720 struct io_uring_params __user *, params)
9722 return io_uring_setup(entries, params);
9725 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9727 struct io_uring_probe *p;
9731 size = struct_size(p, ops, nr_args);
9732 if (size == SIZE_MAX)
9734 p = kzalloc(size, GFP_KERNEL);
9739 if (copy_from_user(p, arg, size))
9742 if (memchr_inv(p, 0, size))
9745 p->last_op = IORING_OP_LAST - 1;
9746 if (nr_args > IORING_OP_LAST)
9747 nr_args = IORING_OP_LAST;
9749 for (i = 0; i < nr_args; i++) {
9751 if (!io_op_defs[i].not_supported)
9752 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9757 if (copy_to_user(arg, p, size))
9764 static int io_register_personality(struct io_ring_ctx *ctx)
9766 const struct cred *creds;
9770 creds = get_current_cred();
9772 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9773 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9780 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9781 unsigned int nr_args)
9783 struct io_uring_restriction *res;
9787 /* Restrictions allowed only if rings started disabled */
9788 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9791 /* We allow only a single restrictions registration */
9792 if (ctx->restrictions.registered)
9795 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9798 size = array_size(nr_args, sizeof(*res));
9799 if (size == SIZE_MAX)
9802 res = memdup_user(arg, size);
9804 return PTR_ERR(res);
9808 for (i = 0; i < nr_args; i++) {
9809 switch (res[i].opcode) {
9810 case IORING_RESTRICTION_REGISTER_OP:
9811 if (res[i].register_op >= IORING_REGISTER_LAST) {
9816 __set_bit(res[i].register_op,
9817 ctx->restrictions.register_op);
9819 case IORING_RESTRICTION_SQE_OP:
9820 if (res[i].sqe_op >= IORING_OP_LAST) {
9825 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9827 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9828 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9830 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9831 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9840 /* Reset all restrictions if an error happened */
9842 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9844 ctx->restrictions.registered = true;
9850 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9852 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9855 if (ctx->restrictions.registered)
9856 ctx->restricted = 1;
9858 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9859 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9860 wake_up(&ctx->sq_data->wait);
9864 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9865 struct io_uring_rsrc_update2 *up,
9873 if (check_add_overflow(up->offset, nr_args, &tmp))
9875 err = io_rsrc_node_switch_start(ctx);
9880 case IORING_RSRC_FILE:
9881 return __io_sqe_files_update(ctx, up, nr_args);
9882 case IORING_RSRC_BUFFER:
9883 return __io_sqe_buffers_update(ctx, up, nr_args);
9888 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9891 struct io_uring_rsrc_update2 up;
9895 memset(&up, 0, sizeof(up));
9896 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9898 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9901 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9904 struct io_uring_rsrc_update2 up;
9906 if (size != sizeof(up))
9908 if (copy_from_user(&up, arg, sizeof(up)))
9912 return __io_register_rsrc_update(ctx, up.type, &up, up.nr);
9915 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9918 struct io_uring_rsrc_register rr;
9920 /* keep it extendible */
9921 if (size != sizeof(rr))
9924 memset(&rr, 0, sizeof(rr));
9925 if (copy_from_user(&rr, arg, size))
9931 case IORING_RSRC_FILE:
9932 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
9933 rr.nr, u64_to_user_ptr(rr.tags));
9934 case IORING_RSRC_BUFFER:
9935 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
9936 rr.nr, u64_to_user_ptr(rr.tags));
9941 static bool io_register_op_must_quiesce(int op)
9944 case IORING_REGISTER_BUFFERS:
9945 case IORING_UNREGISTER_BUFFERS:
9946 case IORING_REGISTER_FILES:
9947 case IORING_UNREGISTER_FILES:
9948 case IORING_REGISTER_FILES_UPDATE:
9949 case IORING_REGISTER_PROBE:
9950 case IORING_REGISTER_PERSONALITY:
9951 case IORING_UNREGISTER_PERSONALITY:
9952 case IORING_REGISTER_RSRC:
9953 case IORING_REGISTER_RSRC_UPDATE:
9960 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9961 void __user *arg, unsigned nr_args)
9962 __releases(ctx->uring_lock)
9963 __acquires(ctx->uring_lock)
9968 * We're inside the ring mutex, if the ref is already dying, then
9969 * someone else killed the ctx or is already going through
9970 * io_uring_register().
9972 if (percpu_ref_is_dying(&ctx->refs))
9975 if (ctx->restricted) {
9976 if (opcode >= IORING_REGISTER_LAST)
9978 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
9979 if (!test_bit(opcode, ctx->restrictions.register_op))
9983 if (io_register_op_must_quiesce(opcode)) {
9984 percpu_ref_kill(&ctx->refs);
9987 * Drop uring mutex before waiting for references to exit. If
9988 * another thread is currently inside io_uring_enter() it might
9989 * need to grab the uring_lock to make progress. If we hold it
9990 * here across the drain wait, then we can deadlock. It's safe
9991 * to drop the mutex here, since no new references will come in
9992 * after we've killed the percpu ref.
9994 mutex_unlock(&ctx->uring_lock);
9996 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9999 ret = io_run_task_work_sig();
10003 mutex_lock(&ctx->uring_lock);
10006 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10012 case IORING_REGISTER_BUFFERS:
10013 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10015 case IORING_UNREGISTER_BUFFERS:
10017 if (arg || nr_args)
10019 ret = io_sqe_buffers_unregister(ctx);
10021 case IORING_REGISTER_FILES:
10022 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10024 case IORING_UNREGISTER_FILES:
10026 if (arg || nr_args)
10028 ret = io_sqe_files_unregister(ctx);
10030 case IORING_REGISTER_FILES_UPDATE:
10031 ret = io_register_files_update(ctx, arg, nr_args);
10033 case IORING_REGISTER_EVENTFD:
10034 case IORING_REGISTER_EVENTFD_ASYNC:
10038 ret = io_eventfd_register(ctx, arg);
10041 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10042 ctx->eventfd_async = 1;
10044 ctx->eventfd_async = 0;
10046 case IORING_UNREGISTER_EVENTFD:
10048 if (arg || nr_args)
10050 ret = io_eventfd_unregister(ctx);
10052 case IORING_REGISTER_PROBE:
10054 if (!arg || nr_args > 256)
10056 ret = io_probe(ctx, arg, nr_args);
10058 case IORING_REGISTER_PERSONALITY:
10060 if (arg || nr_args)
10062 ret = io_register_personality(ctx);
10064 case IORING_UNREGISTER_PERSONALITY:
10068 ret = io_unregister_personality(ctx, nr_args);
10070 case IORING_REGISTER_ENABLE_RINGS:
10072 if (arg || nr_args)
10074 ret = io_register_enable_rings(ctx);
10076 case IORING_REGISTER_RESTRICTIONS:
10077 ret = io_register_restrictions(ctx, arg, nr_args);
10079 case IORING_REGISTER_RSRC:
10080 ret = io_register_rsrc(ctx, arg, nr_args);
10082 case IORING_REGISTER_RSRC_UPDATE:
10083 ret = io_register_rsrc_update(ctx, arg, nr_args);
10090 if (io_register_op_must_quiesce(opcode)) {
10091 /* bring the ctx back to life */
10092 percpu_ref_reinit(&ctx->refs);
10093 reinit_completion(&ctx->ref_comp);
10098 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10099 void __user *, arg, unsigned int, nr_args)
10101 struct io_ring_ctx *ctx;
10110 if (f.file->f_op != &io_uring_fops)
10113 ctx = f.file->private_data;
10115 io_run_task_work();
10117 mutex_lock(&ctx->uring_lock);
10118 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10119 mutex_unlock(&ctx->uring_lock);
10120 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10121 ctx->cq_ev_fd != NULL, ret);
10127 static int __init io_uring_init(void)
10129 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10130 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10131 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10134 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10135 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10136 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10137 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10138 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10139 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10140 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10141 BUILD_BUG_SQE_ELEM(8, __u64, off);
10142 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10143 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10144 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10145 BUILD_BUG_SQE_ELEM(24, __u32, len);
10146 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10147 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10148 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10149 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10150 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10151 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10152 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10153 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10154 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10155 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10156 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10157 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10158 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10159 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10160 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10161 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10162 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10163 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10164 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10166 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10167 sizeof(struct io_uring_rsrc_update));
10168 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10169 sizeof(struct io_uring_rsrc_update2));
10170 /* should fit into one byte */
10171 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10173 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10174 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10175 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10179 __initcall(io_uring_init);