1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/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>
81 #include <linux/tracehook.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
93 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96 #define IORING_MAX_FIXED_FILES (1U << 15)
97 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
98 IORING_REGISTER_LAST + IORING_OP_LAST)
100 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
101 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
102 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
104 #define IORING_MAX_REG_BUFFERS (1U << 14)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
109 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
110 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
112 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
115 u32 head ____cacheline_aligned_in_smp;
116 u32 tail ____cacheline_aligned_in_smp;
120 * This data is shared with the application through the mmap at offsets
121 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
123 * The offsets to the member fields are published through struct
124 * io_sqring_offsets when calling io_uring_setup.
128 * Head and tail offsets into the ring; the offsets need to be
129 * masked to get valid indices.
131 * The kernel controls head of the sq ring and the tail of the cq ring,
132 * and the application controls tail of the sq ring and the head of the
135 struct io_uring sq, cq;
137 * Bitmasks to apply to head and tail offsets (constant, equals
140 u32 sq_ring_mask, cq_ring_mask;
141 /* Ring sizes (constant, power of 2) */
142 u32 sq_ring_entries, cq_ring_entries;
144 * Number of invalid entries dropped by the kernel due to
145 * invalid index stored in array
147 * Written by the kernel, shouldn't be modified by the
148 * application (i.e. get number of "new events" by comparing to
151 * After a new SQ head value was read by the application this
152 * counter includes all submissions that were dropped reaching
153 * the new SQ head (and possibly more).
159 * Written by the kernel, shouldn't be modified by the
162 * The application needs a full memory barrier before checking
163 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
169 * Written by the application, shouldn't be modified by the
174 * Number of completion events lost because the queue was full;
175 * this should be avoided by the application by making sure
176 * there are not more requests pending than there is space in
177 * the completion queue.
179 * Written by the kernel, shouldn't be modified by the
180 * application (i.e. get number of "new events" by comparing to
183 * As completion events come in out of order this counter is not
184 * ordered with any other data.
188 * Ring buffer of completion events.
190 * The kernel writes completion events fresh every time they are
191 * produced, so the application is allowed to modify pending
194 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
197 enum io_uring_cmd_flags {
198 IO_URING_F_NONBLOCK = 1,
199 IO_URING_F_COMPLETE_DEFER = 2,
202 struct io_mapped_ubuf {
205 unsigned int nr_bvecs;
206 unsigned long acct_pages;
207 struct bio_vec bvec[];
212 struct io_overflow_cqe {
213 struct io_uring_cqe cqe;
214 struct list_head list;
217 struct io_fixed_file {
218 /* file * with additional FFS_* flags */
219 unsigned long file_ptr;
223 struct list_head list;
228 struct io_mapped_ubuf *buf;
232 struct io_file_table {
233 struct io_fixed_file *files;
236 struct io_rsrc_node {
237 struct percpu_ref refs;
238 struct list_head node;
239 struct list_head rsrc_list;
240 struct io_rsrc_data *rsrc_data;
241 struct llist_node llist;
245 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
247 struct io_rsrc_data {
248 struct io_ring_ctx *ctx;
254 struct completion done;
259 struct list_head list;
265 struct io_restriction {
266 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
267 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
268 u8 sqe_flags_allowed;
269 u8 sqe_flags_required;
274 IO_SQ_THREAD_SHOULD_STOP = 0,
275 IO_SQ_THREAD_SHOULD_PARK,
280 atomic_t park_pending;
283 /* ctx's that are using this sqd */
284 struct list_head ctx_list;
286 struct task_struct *thread;
287 struct wait_queue_head wait;
289 unsigned sq_thread_idle;
295 struct completion exited;
298 #define IO_COMPL_BATCH 32
299 #define IO_REQ_CACHE_SIZE 32
300 #define IO_REQ_ALLOC_BATCH 8
302 struct io_submit_link {
303 struct io_kiocb *head;
304 struct io_kiocb *last;
307 struct io_submit_state {
308 struct blk_plug plug;
309 struct io_submit_link link;
312 * io_kiocb alloc cache
314 void *reqs[IO_REQ_CACHE_SIZE];
315 unsigned int free_reqs;
320 * Batch completion logic
322 struct io_kiocb *compl_reqs[IO_COMPL_BATCH];
323 unsigned int compl_nr;
324 /* inline/task_work completion list, under ->uring_lock */
325 struct list_head free_list;
327 unsigned int ios_left;
331 /* const or read-mostly hot data */
333 struct percpu_ref refs;
335 struct io_rings *rings;
337 unsigned int compat: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int off_timeout_used: 1;
342 unsigned int drain_active: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 struct io_file_table file_table;
372 unsigned nr_user_files;
373 unsigned nr_user_bufs;
374 struct io_mapped_ubuf **user_bufs;
376 struct io_submit_state submit_state;
377 struct list_head timeout_list;
378 struct list_head ltimeout_list;
379 struct list_head cq_overflow_list;
380 struct xarray io_buffers;
381 struct xarray personalities;
383 unsigned sq_thread_idle;
384 } ____cacheline_aligned_in_smp;
386 /* IRQ completion list, under ->completion_lock */
387 struct list_head locked_free_list;
388 unsigned int locked_free_nr;
390 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
391 struct io_sq_data *sq_data; /* if using sq thread polling */
393 struct wait_queue_head sqo_sq_wait;
394 struct list_head sqd_list;
396 unsigned long check_cq_overflow;
399 unsigned cached_cq_tail;
401 struct eventfd_ctx *cq_ev_fd;
402 struct wait_queue_head poll_wait;
403 struct wait_queue_head cq_wait;
405 atomic_t cq_timeouts;
406 struct fasync_struct *cq_fasync;
407 unsigned cq_last_tm_flush;
408 } ____cacheline_aligned_in_smp;
411 spinlock_t completion_lock;
413 spinlock_t timeout_lock;
416 * ->iopoll_list is protected by the ctx->uring_lock for
417 * io_uring instances that don't use IORING_SETUP_SQPOLL.
418 * For SQPOLL, only the single threaded io_sq_thread() will
419 * manipulate the list, hence no extra locking is needed there.
421 struct list_head iopoll_list;
422 struct hlist_head *cancel_hash;
423 unsigned cancel_hash_bits;
424 bool poll_multi_queue;
425 } ____cacheline_aligned_in_smp;
427 struct io_restriction restrictions;
429 /* slow path rsrc auxilary data, used by update/register */
431 struct io_rsrc_node *rsrc_backup_node;
432 struct io_mapped_ubuf *dummy_ubuf;
433 struct io_rsrc_data *file_data;
434 struct io_rsrc_data *buf_data;
436 struct delayed_work rsrc_put_work;
437 struct llist_head rsrc_put_llist;
438 struct list_head rsrc_ref_list;
439 spinlock_t rsrc_ref_lock;
442 /* Keep this last, we don't need it for the fast path */
444 #if defined(CONFIG_UNIX)
445 struct socket *ring_sock;
447 /* hashed buffered write serialization */
448 struct io_wq_hash *hash_map;
450 /* Only used for accounting purposes */
451 struct user_struct *user;
452 struct mm_struct *mm_account;
454 /* ctx exit and cancelation */
455 struct llist_head fallback_llist;
456 struct delayed_work fallback_work;
457 struct work_struct exit_work;
458 struct list_head tctx_list;
459 struct completion ref_comp;
463 struct io_uring_task {
464 /* submission side */
467 struct wait_queue_head wait;
468 const struct io_ring_ctx *last;
470 struct percpu_counter inflight;
471 atomic_t inflight_tracked;
474 spinlock_t task_lock;
475 struct io_wq_work_list task_list;
476 struct callback_head task_work;
481 * First field must be the file pointer in all the
482 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
484 struct io_poll_iocb {
486 struct wait_queue_head *head;
490 struct wait_queue_entry wait;
493 struct io_poll_update {
499 bool update_user_data;
507 struct io_timeout_data {
508 struct io_kiocb *req;
509 struct hrtimer timer;
510 struct timespec64 ts;
511 enum hrtimer_mode mode;
517 struct sockaddr __user *addr;
518 int __user *addr_len;
521 unsigned long nofile;
541 struct list_head list;
542 /* head of the link, used by linked timeouts only */
543 struct io_kiocb *head;
544 /* for linked completions */
545 struct io_kiocb *prev;
548 struct io_timeout_rem {
553 struct timespec64 ts;
559 /* NOTE: kiocb has the file as the first member, so don't do it here */
567 struct sockaddr __user *addr;
574 struct compat_msghdr __user *umsg_compat;
575 struct user_msghdr __user *umsg;
581 struct io_buffer *kbuf;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
624 struct file *file_in;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
670 struct io_completion {
675 struct io_async_connect {
676 struct sockaddr_storage address;
679 struct io_async_msghdr {
680 struct iovec fast_iov[UIO_FASTIOV];
681 /* points to an allocated iov, if NULL we use fast_iov instead */
682 struct iovec *free_iov;
683 struct sockaddr __user *uaddr;
685 struct sockaddr_storage addr;
689 struct iovec fast_iov[UIO_FASTIOV];
690 const struct iovec *free_iovec;
691 struct iov_iter iter;
693 struct wait_page_queue wpq;
697 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
698 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
699 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
700 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
701 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
702 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
704 /* first byte is taken by user flags, shift it to not overlap */
709 REQ_F_LINK_TIMEOUT_BIT,
710 REQ_F_NEED_CLEANUP_BIT,
712 REQ_F_BUFFER_SELECTED_BIT,
713 REQ_F_COMPLETE_INLINE_BIT,
715 REQ_F_DONT_REISSUE_BIT,
718 REQ_F_ARM_LTIMEOUT_BIT,
719 /* keep async read/write and isreg together and in order */
720 REQ_F_NOWAIT_READ_BIT,
721 REQ_F_NOWAIT_WRITE_BIT,
724 /* not a real bit, just to check we're not overflowing the space */
730 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
731 /* drain existing IO first */
732 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
734 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
735 /* doesn't sever on completion < 0 */
736 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
738 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
739 /* IOSQE_BUFFER_SELECT */
740 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
742 /* fail rest of links */
743 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
744 /* on inflight list, should be cancelled and waited on exit reliably */
745 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
746 /* read/write uses file position */
747 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
748 /* must not punt to workers */
749 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
750 /* has or had linked timeout */
751 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
753 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
754 /* already went through poll handler */
755 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
756 /* buffer already selected */
757 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
758 /* completion is deferred through io_comp_state */
759 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
760 /* caller should reissue async */
761 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
762 /* don't attempt request reissue, see io_rw_reissue() */
763 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
764 /* supports async reads */
765 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
766 /* supports async writes */
767 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
769 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
770 /* has creds assigned */
771 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
772 /* skip refcounting if not set */
773 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
774 /* there is a linked timeout that has to be armed */
775 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
779 struct io_poll_iocb poll;
780 struct io_poll_iocb *double_poll;
783 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
785 struct io_task_work {
787 struct io_wq_work_node node;
788 struct llist_node fallback_node;
790 io_req_tw_func_t func;
794 IORING_RSRC_FILE = 0,
795 IORING_RSRC_BUFFER = 1,
799 * NOTE! Each of the iocb union members has the file pointer
800 * as the first entry in their struct definition. So you can
801 * access the file pointer through any of the sub-structs,
802 * or directly as just 'ki_filp' in this struct.
808 struct io_poll_iocb poll;
809 struct io_poll_update poll_update;
810 struct io_accept accept;
812 struct io_cancel cancel;
813 struct io_timeout timeout;
814 struct io_timeout_rem timeout_rem;
815 struct io_connect connect;
816 struct io_sr_msg sr_msg;
818 struct io_close close;
819 struct io_rsrc_update rsrc_update;
820 struct io_fadvise fadvise;
821 struct io_madvise madvise;
822 struct io_epoll epoll;
823 struct io_splice splice;
824 struct io_provide_buf pbuf;
825 struct io_statx statx;
826 struct io_shutdown shutdown;
827 struct io_rename rename;
828 struct io_unlink unlink;
829 /* use only after cleaning per-op data, see io_clean_op() */
830 struct io_completion compl;
833 /* opcode allocated if it needs to store data for async defer */
836 /* polled IO has completed */
842 struct io_ring_ctx *ctx;
845 struct task_struct *task;
848 struct io_kiocb *link;
849 struct percpu_ref *fixed_rsrc_refs;
851 /* used with ctx->iopoll_list with reads/writes */
852 struct list_head inflight_entry;
853 struct io_task_work io_task_work;
854 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
855 struct hlist_node hash_node;
856 struct async_poll *apoll;
857 struct io_wq_work work;
858 const struct cred *creds;
860 /* store used ubuf, so we can prevent reloading */
861 struct io_mapped_ubuf *imu;
864 struct io_tctx_node {
865 struct list_head ctx_node;
866 struct task_struct *task;
867 struct io_ring_ctx *ctx;
870 struct io_defer_entry {
871 struct list_head list;
872 struct io_kiocb *req;
877 /* needs req->file assigned */
878 unsigned needs_file : 1;
879 /* hash wq insertion if file is a regular file */
880 unsigned hash_reg_file : 1;
881 /* unbound wq insertion if file is a non-regular file */
882 unsigned unbound_nonreg_file : 1;
883 /* opcode is not supported by this kernel */
884 unsigned not_supported : 1;
885 /* set if opcode supports polled "wait" */
887 unsigned pollout : 1;
888 /* op supports buffer selection */
889 unsigned buffer_select : 1;
890 /* do prep async if is going to be punted */
891 unsigned needs_async_setup : 1;
892 /* should block plug */
894 /* size of async data needed, if any */
895 unsigned short async_size;
898 static const struct io_op_def io_op_defs[] = {
899 [IORING_OP_NOP] = {},
900 [IORING_OP_READV] = {
902 .unbound_nonreg_file = 1,
905 .needs_async_setup = 1,
907 .async_size = sizeof(struct io_async_rw),
909 [IORING_OP_WRITEV] = {
912 .unbound_nonreg_file = 1,
914 .needs_async_setup = 1,
916 .async_size = sizeof(struct io_async_rw),
918 [IORING_OP_FSYNC] = {
921 [IORING_OP_READ_FIXED] = {
923 .unbound_nonreg_file = 1,
926 .async_size = sizeof(struct io_async_rw),
928 [IORING_OP_WRITE_FIXED] = {
931 .unbound_nonreg_file = 1,
934 .async_size = sizeof(struct io_async_rw),
936 [IORING_OP_POLL_ADD] = {
938 .unbound_nonreg_file = 1,
940 [IORING_OP_POLL_REMOVE] = {},
941 [IORING_OP_SYNC_FILE_RANGE] = {
944 [IORING_OP_SENDMSG] = {
946 .unbound_nonreg_file = 1,
948 .needs_async_setup = 1,
949 .async_size = sizeof(struct io_async_msghdr),
951 [IORING_OP_RECVMSG] = {
953 .unbound_nonreg_file = 1,
956 .needs_async_setup = 1,
957 .async_size = sizeof(struct io_async_msghdr),
959 [IORING_OP_TIMEOUT] = {
960 .async_size = sizeof(struct io_timeout_data),
962 [IORING_OP_TIMEOUT_REMOVE] = {
963 /* used by timeout updates' prep() */
965 [IORING_OP_ACCEPT] = {
967 .unbound_nonreg_file = 1,
970 [IORING_OP_ASYNC_CANCEL] = {},
971 [IORING_OP_LINK_TIMEOUT] = {
972 .async_size = sizeof(struct io_timeout_data),
974 [IORING_OP_CONNECT] = {
976 .unbound_nonreg_file = 1,
978 .needs_async_setup = 1,
979 .async_size = sizeof(struct io_async_connect),
981 [IORING_OP_FALLOCATE] = {
984 [IORING_OP_OPENAT] = {},
985 [IORING_OP_CLOSE] = {},
986 [IORING_OP_FILES_UPDATE] = {},
987 [IORING_OP_STATX] = {},
990 .unbound_nonreg_file = 1,
994 .async_size = sizeof(struct io_async_rw),
996 [IORING_OP_WRITE] = {
999 .unbound_nonreg_file = 1,
1002 .async_size = sizeof(struct io_async_rw),
1004 [IORING_OP_FADVISE] = {
1007 [IORING_OP_MADVISE] = {},
1008 [IORING_OP_SEND] = {
1010 .unbound_nonreg_file = 1,
1013 [IORING_OP_RECV] = {
1015 .unbound_nonreg_file = 1,
1019 [IORING_OP_OPENAT2] = {
1021 [IORING_OP_EPOLL_CTL] = {
1022 .unbound_nonreg_file = 1,
1024 [IORING_OP_SPLICE] = {
1027 .unbound_nonreg_file = 1,
1029 [IORING_OP_PROVIDE_BUFFERS] = {},
1030 [IORING_OP_REMOVE_BUFFERS] = {},
1034 .unbound_nonreg_file = 1,
1036 [IORING_OP_SHUTDOWN] = {
1039 [IORING_OP_RENAMEAT] = {},
1040 [IORING_OP_UNLINKAT] = {},
1043 /* requests with any of those set should undergo io_disarm_next() */
1044 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1046 static bool io_disarm_next(struct io_kiocb *req);
1047 static void io_uring_del_tctx_node(unsigned long index);
1048 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1049 struct task_struct *task,
1051 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1053 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1054 long res, unsigned int cflags);
1055 static void io_put_req(struct io_kiocb *req);
1056 static void io_put_req_deferred(struct io_kiocb *req);
1057 static void io_dismantle_req(struct io_kiocb *req);
1058 static void io_queue_linked_timeout(struct io_kiocb *req);
1059 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1060 struct io_uring_rsrc_update2 *up,
1062 static void io_clean_op(struct io_kiocb *req);
1063 static struct file *io_file_get(struct io_ring_ctx *ctx,
1064 struct io_kiocb *req, int fd, bool fixed);
1065 static void __io_queue_sqe(struct io_kiocb *req);
1066 static void io_rsrc_put_work(struct work_struct *work);
1068 static void io_req_task_queue(struct io_kiocb *req);
1069 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1070 static int io_req_prep_async(struct io_kiocb *req);
1072 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1073 unsigned int issue_flags, u32 slot_index);
1074 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1076 static struct kmem_cache *req_cachep;
1078 static const struct file_operations io_uring_fops;
1080 struct sock *io_uring_get_socket(struct file *file)
1082 #if defined(CONFIG_UNIX)
1083 if (file->f_op == &io_uring_fops) {
1084 struct io_ring_ctx *ctx = file->private_data;
1086 return ctx->ring_sock->sk;
1091 EXPORT_SYMBOL(io_uring_get_socket);
1093 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1096 mutex_lock(&ctx->uring_lock);
1101 #define io_for_each_link(pos, head) \
1102 for (pos = (head); pos; pos = pos->link)
1105 * Shamelessly stolen from the mm implementation of page reference checking,
1106 * see commit f958d7b528b1 for details.
1108 #define req_ref_zero_or_close_to_overflow(req) \
1109 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1111 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1113 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1114 return atomic_inc_not_zero(&req->refs);
1117 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1119 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1122 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1123 return atomic_dec_and_test(&req->refs);
1126 static inline void req_ref_put(struct io_kiocb *req)
1128 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1129 WARN_ON_ONCE(req_ref_put_and_test(req));
1132 static inline void req_ref_get(struct io_kiocb *req)
1134 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1135 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1136 atomic_inc(&req->refs);
1139 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1141 if (!(req->flags & REQ_F_REFCOUNT)) {
1142 req->flags |= REQ_F_REFCOUNT;
1143 atomic_set(&req->refs, nr);
1147 static inline void io_req_set_refcount(struct io_kiocb *req)
1149 __io_req_set_refcount(req, 1);
1152 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1154 struct io_ring_ctx *ctx = req->ctx;
1156 if (!req->fixed_rsrc_refs) {
1157 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1158 percpu_ref_get(req->fixed_rsrc_refs);
1162 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1164 bool got = percpu_ref_tryget(ref);
1166 /* already at zero, wait for ->release() */
1168 wait_for_completion(compl);
1169 percpu_ref_resurrect(ref);
1171 percpu_ref_put(ref);
1174 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1177 struct io_kiocb *req;
1179 if (task && head->task != task)
1184 io_for_each_link(req, head) {
1185 if (req->flags & REQ_F_INFLIGHT)
1191 static inline void req_set_fail(struct io_kiocb *req)
1193 req->flags |= REQ_F_FAIL;
1196 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1202 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1204 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1206 complete(&ctx->ref_comp);
1209 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1211 return !req->timeout.off;
1214 static void io_fallback_req_func(struct work_struct *work)
1216 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1217 fallback_work.work);
1218 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1219 struct io_kiocb *req, *tmp;
1220 bool locked = false;
1222 percpu_ref_get(&ctx->refs);
1223 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1224 req->io_task_work.func(req, &locked);
1227 if (ctx->submit_state.compl_nr)
1228 io_submit_flush_completions(ctx);
1229 mutex_unlock(&ctx->uring_lock);
1231 percpu_ref_put(&ctx->refs);
1235 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1237 struct io_ring_ctx *ctx;
1240 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1245 * Use 5 bits less than the max cq entries, that should give us around
1246 * 32 entries per hash list if totally full and uniformly spread.
1248 hash_bits = ilog2(p->cq_entries);
1252 ctx->cancel_hash_bits = hash_bits;
1253 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1255 if (!ctx->cancel_hash)
1257 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1259 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1260 if (!ctx->dummy_ubuf)
1262 /* set invalid range, so io_import_fixed() fails meeting it */
1263 ctx->dummy_ubuf->ubuf = -1UL;
1265 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1266 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1269 ctx->flags = p->flags;
1270 init_waitqueue_head(&ctx->sqo_sq_wait);
1271 INIT_LIST_HEAD(&ctx->sqd_list);
1272 init_waitqueue_head(&ctx->poll_wait);
1273 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1274 init_completion(&ctx->ref_comp);
1275 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1276 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1277 mutex_init(&ctx->uring_lock);
1278 init_waitqueue_head(&ctx->cq_wait);
1279 spin_lock_init(&ctx->completion_lock);
1280 spin_lock_init(&ctx->timeout_lock);
1281 INIT_LIST_HEAD(&ctx->iopoll_list);
1282 INIT_LIST_HEAD(&ctx->defer_list);
1283 INIT_LIST_HEAD(&ctx->timeout_list);
1284 INIT_LIST_HEAD(&ctx->ltimeout_list);
1285 spin_lock_init(&ctx->rsrc_ref_lock);
1286 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1287 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1288 init_llist_head(&ctx->rsrc_put_llist);
1289 INIT_LIST_HEAD(&ctx->tctx_list);
1290 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1291 INIT_LIST_HEAD(&ctx->locked_free_list);
1292 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1295 kfree(ctx->dummy_ubuf);
1296 kfree(ctx->cancel_hash);
1301 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1303 struct io_rings *r = ctx->rings;
1305 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1309 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1311 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1312 struct io_ring_ctx *ctx = req->ctx;
1314 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1320 #define FFS_ASYNC_READ 0x1UL
1321 #define FFS_ASYNC_WRITE 0x2UL
1323 #define FFS_ISREG 0x4UL
1325 #define FFS_ISREG 0x0UL
1327 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1329 static inline bool io_req_ffs_set(struct io_kiocb *req)
1331 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1334 static void io_req_track_inflight(struct io_kiocb *req)
1336 if (!(req->flags & REQ_F_INFLIGHT)) {
1337 req->flags |= REQ_F_INFLIGHT;
1338 atomic_inc(¤t->io_uring->inflight_tracked);
1342 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1344 req->flags &= ~REQ_F_LINK_TIMEOUT;
1347 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1349 if (WARN_ON_ONCE(!req->link))
1352 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1353 req->flags |= REQ_F_LINK_TIMEOUT;
1355 /* linked timeouts should have two refs once prep'ed */
1356 io_req_set_refcount(req);
1357 __io_req_set_refcount(req->link, 2);
1361 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1363 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1365 return __io_prep_linked_timeout(req);
1368 static void io_prep_async_work(struct io_kiocb *req)
1370 const struct io_op_def *def = &io_op_defs[req->opcode];
1371 struct io_ring_ctx *ctx = req->ctx;
1373 if (!(req->flags & REQ_F_CREDS)) {
1374 req->flags |= REQ_F_CREDS;
1375 req->creds = get_current_cred();
1378 req->work.list.next = NULL;
1379 req->work.flags = 0;
1380 if (req->flags & REQ_F_FORCE_ASYNC)
1381 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1383 if (req->flags & REQ_F_ISREG) {
1384 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1385 io_wq_hash_work(&req->work, file_inode(req->file));
1386 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1387 if (def->unbound_nonreg_file)
1388 req->work.flags |= IO_WQ_WORK_UNBOUND;
1391 switch (req->opcode) {
1392 case IORING_OP_SPLICE:
1394 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1395 req->work.flags |= IO_WQ_WORK_UNBOUND;
1400 static void io_prep_async_link(struct io_kiocb *req)
1402 struct io_kiocb *cur;
1404 if (req->flags & REQ_F_LINK_TIMEOUT) {
1405 struct io_ring_ctx *ctx = req->ctx;
1407 spin_lock(&ctx->completion_lock);
1408 io_for_each_link(cur, req)
1409 io_prep_async_work(cur);
1410 spin_unlock(&ctx->completion_lock);
1412 io_for_each_link(cur, req)
1413 io_prep_async_work(cur);
1417 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1419 struct io_ring_ctx *ctx = req->ctx;
1420 struct io_kiocb *link = io_prep_linked_timeout(req);
1421 struct io_uring_task *tctx = req->task->io_uring;
1423 /* must not take the lock, NULL it as a precaution */
1427 BUG_ON(!tctx->io_wq);
1429 /* init ->work of the whole link before punting */
1430 io_prep_async_link(req);
1433 * Not expected to happen, but if we do have a bug where this _can_
1434 * happen, catch it here and ensure the request is marked as
1435 * canceled. That will make io-wq go through the usual work cancel
1436 * procedure rather than attempt to run this request (or create a new
1439 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1440 req->work.flags |= IO_WQ_WORK_CANCEL;
1442 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1443 &req->work, req->flags);
1444 io_wq_enqueue(tctx->io_wq, &req->work);
1446 io_queue_linked_timeout(link);
1449 static void io_kill_timeout(struct io_kiocb *req, int status)
1450 __must_hold(&req->ctx->completion_lock)
1451 __must_hold(&req->ctx->timeout_lock)
1453 struct io_timeout_data *io = req->async_data;
1455 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1456 atomic_set(&req->ctx->cq_timeouts,
1457 atomic_read(&req->ctx->cq_timeouts) + 1);
1458 list_del_init(&req->timeout.list);
1459 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1460 io_put_req_deferred(req);
1464 static void io_queue_deferred(struct io_ring_ctx *ctx)
1466 while (!list_empty(&ctx->defer_list)) {
1467 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1468 struct io_defer_entry, list);
1470 if (req_need_defer(de->req, de->seq))
1472 list_del_init(&de->list);
1473 io_req_task_queue(de->req);
1478 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1479 __must_hold(&ctx->completion_lock)
1481 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1483 spin_lock_irq(&ctx->timeout_lock);
1484 while (!list_empty(&ctx->timeout_list)) {
1485 u32 events_needed, events_got;
1486 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1487 struct io_kiocb, timeout.list);
1489 if (io_is_timeout_noseq(req))
1493 * Since seq can easily wrap around over time, subtract
1494 * the last seq at which timeouts were flushed before comparing.
1495 * Assuming not more than 2^31-1 events have happened since,
1496 * these subtractions won't have wrapped, so we can check if
1497 * target is in [last_seq, current_seq] by comparing the two.
1499 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1500 events_got = seq - ctx->cq_last_tm_flush;
1501 if (events_got < events_needed)
1504 list_del_init(&req->timeout.list);
1505 io_kill_timeout(req, 0);
1507 ctx->cq_last_tm_flush = seq;
1508 spin_unlock_irq(&ctx->timeout_lock);
1511 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1513 if (ctx->off_timeout_used)
1514 io_flush_timeouts(ctx);
1515 if (ctx->drain_active)
1516 io_queue_deferred(ctx);
1519 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1521 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1522 __io_commit_cqring_flush(ctx);
1523 /* order cqe stores with ring update */
1524 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1527 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1529 struct io_rings *r = ctx->rings;
1531 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1534 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1536 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1539 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1541 struct io_rings *rings = ctx->rings;
1542 unsigned tail, mask = ctx->cq_entries - 1;
1545 * writes to the cq entry need to come after reading head; the
1546 * control dependency is enough as we're using WRITE_ONCE to
1549 if (__io_cqring_events(ctx) == ctx->cq_entries)
1552 tail = ctx->cached_cq_tail++;
1553 return &rings->cqes[tail & mask];
1556 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1558 if (likely(!ctx->cq_ev_fd))
1560 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1562 return !ctx->eventfd_async || io_wq_current_is_worker();
1566 * This should only get called when at least one event has been posted.
1567 * Some applications rely on the eventfd notification count only changing
1568 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1569 * 1:1 relationship between how many times this function is called (and
1570 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1572 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1575 * wake_up_all() may seem excessive, but io_wake_function() and
1576 * io_should_wake() handle the termination of the loop and only
1577 * wake as many waiters as we need to.
1579 if (wq_has_sleeper(&ctx->cq_wait))
1580 wake_up_all(&ctx->cq_wait);
1581 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1582 wake_up(&ctx->sq_data->wait);
1583 if (io_should_trigger_evfd(ctx))
1584 eventfd_signal(ctx->cq_ev_fd, 1);
1585 if (waitqueue_active(&ctx->poll_wait)) {
1586 wake_up_interruptible(&ctx->poll_wait);
1587 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1591 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1593 if (ctx->flags & IORING_SETUP_SQPOLL) {
1594 if (wq_has_sleeper(&ctx->cq_wait))
1595 wake_up_all(&ctx->cq_wait);
1597 if (io_should_trigger_evfd(ctx))
1598 eventfd_signal(ctx->cq_ev_fd, 1);
1599 if (waitqueue_active(&ctx->poll_wait)) {
1600 wake_up_interruptible(&ctx->poll_wait);
1601 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1605 /* Returns true if there are no backlogged entries after the flush */
1606 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1608 bool all_flushed, posted;
1610 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1614 spin_lock(&ctx->completion_lock);
1615 while (!list_empty(&ctx->cq_overflow_list)) {
1616 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1617 struct io_overflow_cqe *ocqe;
1621 ocqe = list_first_entry(&ctx->cq_overflow_list,
1622 struct io_overflow_cqe, list);
1624 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1626 io_account_cq_overflow(ctx);
1629 list_del(&ocqe->list);
1633 all_flushed = list_empty(&ctx->cq_overflow_list);
1635 clear_bit(0, &ctx->check_cq_overflow);
1636 WRITE_ONCE(ctx->rings->sq_flags,
1637 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1641 io_commit_cqring(ctx);
1642 spin_unlock(&ctx->completion_lock);
1644 io_cqring_ev_posted(ctx);
1648 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1652 if (test_bit(0, &ctx->check_cq_overflow)) {
1653 /* iopoll syncs against uring_lock, not completion_lock */
1654 if (ctx->flags & IORING_SETUP_IOPOLL)
1655 mutex_lock(&ctx->uring_lock);
1656 ret = __io_cqring_overflow_flush(ctx, false);
1657 if (ctx->flags & IORING_SETUP_IOPOLL)
1658 mutex_unlock(&ctx->uring_lock);
1664 /* must to be called somewhat shortly after putting a request */
1665 static inline void io_put_task(struct task_struct *task, int nr)
1667 struct io_uring_task *tctx = task->io_uring;
1669 if (likely(task == current)) {
1670 tctx->cached_refs += nr;
1672 percpu_counter_sub(&tctx->inflight, nr);
1673 if (unlikely(atomic_read(&tctx->in_idle)))
1674 wake_up(&tctx->wait);
1675 put_task_struct_many(task, nr);
1679 static void io_task_refs_refill(struct io_uring_task *tctx)
1681 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1683 percpu_counter_add(&tctx->inflight, refill);
1684 refcount_add(refill, ¤t->usage);
1685 tctx->cached_refs += refill;
1688 static inline void io_get_task_refs(int nr)
1690 struct io_uring_task *tctx = current->io_uring;
1692 tctx->cached_refs -= nr;
1693 if (unlikely(tctx->cached_refs < 0))
1694 io_task_refs_refill(tctx);
1697 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1698 long res, unsigned int cflags)
1700 struct io_overflow_cqe *ocqe;
1702 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1705 * If we're in ring overflow flush mode, or in task cancel mode,
1706 * or cannot allocate an overflow entry, then we need to drop it
1709 io_account_cq_overflow(ctx);
1712 if (list_empty(&ctx->cq_overflow_list)) {
1713 set_bit(0, &ctx->check_cq_overflow);
1714 WRITE_ONCE(ctx->rings->sq_flags,
1715 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1718 ocqe->cqe.user_data = user_data;
1719 ocqe->cqe.res = res;
1720 ocqe->cqe.flags = cflags;
1721 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1725 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1726 long res, unsigned int cflags)
1728 struct io_uring_cqe *cqe;
1730 trace_io_uring_complete(ctx, user_data, res, cflags);
1733 * If we can't get a cq entry, userspace overflowed the
1734 * submission (by quite a lot). Increment the overflow count in
1737 cqe = io_get_cqe(ctx);
1739 WRITE_ONCE(cqe->user_data, user_data);
1740 WRITE_ONCE(cqe->res, res);
1741 WRITE_ONCE(cqe->flags, cflags);
1744 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1747 /* not as hot to bloat with inlining */
1748 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1749 long res, unsigned int cflags)
1751 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1754 static void io_req_complete_post(struct io_kiocb *req, long res,
1755 unsigned int cflags)
1757 struct io_ring_ctx *ctx = req->ctx;
1759 spin_lock(&ctx->completion_lock);
1760 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1762 * If we're the last reference to this request, add to our locked
1765 if (req_ref_put_and_test(req)) {
1766 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1767 if (req->flags & IO_DISARM_MASK)
1768 io_disarm_next(req);
1770 io_req_task_queue(req->link);
1774 io_dismantle_req(req);
1775 io_put_task(req->task, 1);
1776 list_add(&req->inflight_entry, &ctx->locked_free_list);
1777 ctx->locked_free_nr++;
1779 if (!percpu_ref_tryget(&ctx->refs))
1782 io_commit_cqring(ctx);
1783 spin_unlock(&ctx->completion_lock);
1786 io_cqring_ev_posted(ctx);
1787 percpu_ref_put(&ctx->refs);
1791 static inline bool io_req_needs_clean(struct io_kiocb *req)
1793 return req->flags & IO_REQ_CLEAN_FLAGS;
1796 static void io_req_complete_state(struct io_kiocb *req, long res,
1797 unsigned int cflags)
1799 if (io_req_needs_clean(req))
1802 req->compl.cflags = cflags;
1803 req->flags |= REQ_F_COMPLETE_INLINE;
1806 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1807 long res, unsigned cflags)
1809 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1810 io_req_complete_state(req, res, cflags);
1812 io_req_complete_post(req, res, cflags);
1815 static inline void io_req_complete(struct io_kiocb *req, long res)
1817 __io_req_complete(req, 0, res, 0);
1820 static void io_req_complete_failed(struct io_kiocb *req, long res)
1823 io_req_complete_post(req, res, 0);
1826 static void io_req_complete_fail_submit(struct io_kiocb *req)
1829 * We don't submit, fail them all, for that replace hardlinks with
1830 * normal links. Extra REQ_F_LINK is tolerated.
1832 req->flags &= ~REQ_F_HARDLINK;
1833 req->flags |= REQ_F_LINK;
1834 io_req_complete_failed(req, req->result);
1838 * Don't initialise the fields below on every allocation, but do that in
1839 * advance and keep them valid across allocations.
1841 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1845 req->async_data = NULL;
1846 /* not necessary, but safer to zero */
1850 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1851 struct io_submit_state *state)
1853 spin_lock(&ctx->completion_lock);
1854 list_splice_init(&ctx->locked_free_list, &state->free_list);
1855 ctx->locked_free_nr = 0;
1856 spin_unlock(&ctx->completion_lock);
1859 /* Returns true IFF there are requests in the cache */
1860 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1862 struct io_submit_state *state = &ctx->submit_state;
1866 * If we have more than a batch's worth of requests in our IRQ side
1867 * locked cache, grab the lock and move them over to our submission
1870 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1871 io_flush_cached_locked_reqs(ctx, state);
1873 nr = state->free_reqs;
1874 while (!list_empty(&state->free_list)) {
1875 struct io_kiocb *req = list_first_entry(&state->free_list,
1876 struct io_kiocb, inflight_entry);
1878 list_del(&req->inflight_entry);
1879 state->reqs[nr++] = req;
1880 if (nr == ARRAY_SIZE(state->reqs))
1884 state->free_reqs = nr;
1889 * A request might get retired back into the request caches even before opcode
1890 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1891 * Because of that, io_alloc_req() should be called only under ->uring_lock
1892 * and with extra caution to not get a request that is still worked on.
1894 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1895 __must_hold(&ctx->uring_lock)
1897 struct io_submit_state *state = &ctx->submit_state;
1898 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1901 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1903 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1906 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1910 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1911 * retry single alloc to be on the safe side.
1913 if (unlikely(ret <= 0)) {
1914 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1915 if (!state->reqs[0])
1920 for (i = 0; i < ret; i++)
1921 io_preinit_req(state->reqs[i], ctx);
1922 state->free_reqs = ret;
1925 return state->reqs[state->free_reqs];
1928 static inline void io_put_file(struct file *file)
1934 static void io_dismantle_req(struct io_kiocb *req)
1936 unsigned int flags = req->flags;
1938 if (io_req_needs_clean(req))
1940 if (!(flags & REQ_F_FIXED_FILE))
1941 io_put_file(req->file);
1942 if (req->fixed_rsrc_refs)
1943 percpu_ref_put(req->fixed_rsrc_refs);
1944 if (req->async_data) {
1945 kfree(req->async_data);
1946 req->async_data = NULL;
1950 static void __io_free_req(struct io_kiocb *req)
1952 struct io_ring_ctx *ctx = req->ctx;
1954 io_dismantle_req(req);
1955 io_put_task(req->task, 1);
1957 spin_lock(&ctx->completion_lock);
1958 list_add(&req->inflight_entry, &ctx->locked_free_list);
1959 ctx->locked_free_nr++;
1960 spin_unlock(&ctx->completion_lock);
1962 percpu_ref_put(&ctx->refs);
1965 static inline void io_remove_next_linked(struct io_kiocb *req)
1967 struct io_kiocb *nxt = req->link;
1969 req->link = nxt->link;
1973 static bool io_kill_linked_timeout(struct io_kiocb *req)
1974 __must_hold(&req->ctx->completion_lock)
1975 __must_hold(&req->ctx->timeout_lock)
1977 struct io_kiocb *link = req->link;
1979 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1980 struct io_timeout_data *io = link->async_data;
1982 io_remove_next_linked(req);
1983 link->timeout.head = NULL;
1984 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1985 list_del(&link->timeout.list);
1986 io_cqring_fill_event(link->ctx, link->user_data,
1988 io_put_req_deferred(link);
1995 static void io_fail_links(struct io_kiocb *req)
1996 __must_hold(&req->ctx->completion_lock)
1998 struct io_kiocb *nxt, *link = req->link;
2002 long res = -ECANCELED;
2004 if (link->flags & REQ_F_FAIL)
2010 trace_io_uring_fail_link(req, link);
2011 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2012 io_put_req_deferred(link);
2017 static bool io_disarm_next(struct io_kiocb *req)
2018 __must_hold(&req->ctx->completion_lock)
2020 bool posted = false;
2022 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2023 struct io_kiocb *link = req->link;
2025 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2026 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2027 io_remove_next_linked(req);
2028 io_cqring_fill_event(link->ctx, link->user_data,
2030 io_put_req_deferred(link);
2033 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2034 struct io_ring_ctx *ctx = req->ctx;
2036 spin_lock_irq(&ctx->timeout_lock);
2037 posted = io_kill_linked_timeout(req);
2038 spin_unlock_irq(&ctx->timeout_lock);
2040 if (unlikely((req->flags & REQ_F_FAIL) &&
2041 !(req->flags & REQ_F_HARDLINK))) {
2042 posted |= (req->link != NULL);
2048 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2050 struct io_kiocb *nxt;
2053 * If LINK is set, we have dependent requests in this chain. If we
2054 * didn't fail this request, queue the first one up, moving any other
2055 * dependencies to the next request. In case of failure, fail the rest
2058 if (req->flags & IO_DISARM_MASK) {
2059 struct io_ring_ctx *ctx = req->ctx;
2062 spin_lock(&ctx->completion_lock);
2063 posted = io_disarm_next(req);
2065 io_commit_cqring(req->ctx);
2066 spin_unlock(&ctx->completion_lock);
2068 io_cqring_ev_posted(ctx);
2075 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2077 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2079 return __io_req_find_next(req);
2082 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2087 if (ctx->submit_state.compl_nr)
2088 io_submit_flush_completions(ctx);
2089 mutex_unlock(&ctx->uring_lock);
2092 percpu_ref_put(&ctx->refs);
2095 static void tctx_task_work(struct callback_head *cb)
2097 bool locked = false;
2098 struct io_ring_ctx *ctx = NULL;
2099 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2103 struct io_wq_work_node *node;
2105 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2106 io_submit_flush_completions(ctx);
2108 spin_lock_irq(&tctx->task_lock);
2109 node = tctx->task_list.first;
2110 INIT_WQ_LIST(&tctx->task_list);
2112 tctx->task_running = false;
2113 spin_unlock_irq(&tctx->task_lock);
2118 struct io_wq_work_node *next = node->next;
2119 struct io_kiocb *req = container_of(node, struct io_kiocb,
2122 if (req->ctx != ctx) {
2123 ctx_flush_and_put(ctx, &locked);
2125 /* if not contended, grab and improve batching */
2126 locked = mutex_trylock(&ctx->uring_lock);
2127 percpu_ref_get(&ctx->refs);
2129 req->io_task_work.func(req, &locked);
2136 ctx_flush_and_put(ctx, &locked);
2139 static void io_req_task_work_add(struct io_kiocb *req)
2141 struct task_struct *tsk = req->task;
2142 struct io_uring_task *tctx = tsk->io_uring;
2143 enum task_work_notify_mode notify;
2144 struct io_wq_work_node *node;
2145 unsigned long flags;
2148 WARN_ON_ONCE(!tctx);
2150 spin_lock_irqsave(&tctx->task_lock, flags);
2151 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2152 running = tctx->task_running;
2154 tctx->task_running = true;
2155 spin_unlock_irqrestore(&tctx->task_lock, flags);
2157 /* task_work already pending, we're done */
2162 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2163 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2164 * processing task_work. There's no reliable way to tell if TWA_RESUME
2167 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2168 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2169 wake_up_process(tsk);
2173 spin_lock_irqsave(&tctx->task_lock, flags);
2174 tctx->task_running = false;
2175 node = tctx->task_list.first;
2176 INIT_WQ_LIST(&tctx->task_list);
2177 spin_unlock_irqrestore(&tctx->task_lock, flags);
2180 req = container_of(node, struct io_kiocb, io_task_work.node);
2182 if (llist_add(&req->io_task_work.fallback_node,
2183 &req->ctx->fallback_llist))
2184 schedule_delayed_work(&req->ctx->fallback_work, 1);
2188 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2190 struct io_ring_ctx *ctx = req->ctx;
2192 /* not needed for normal modes, but SQPOLL depends on it */
2193 io_tw_lock(ctx, locked);
2194 io_req_complete_failed(req, req->result);
2197 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2199 struct io_ring_ctx *ctx = req->ctx;
2201 io_tw_lock(ctx, locked);
2202 /* req->task == current here, checking PF_EXITING is safe */
2203 if (likely(!(req->task->flags & PF_EXITING)))
2204 __io_queue_sqe(req);
2206 io_req_complete_failed(req, -EFAULT);
2209 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2212 req->io_task_work.func = io_req_task_cancel;
2213 io_req_task_work_add(req);
2216 static void io_req_task_queue(struct io_kiocb *req)
2218 req->io_task_work.func = io_req_task_submit;
2219 io_req_task_work_add(req);
2222 static void io_req_task_queue_reissue(struct io_kiocb *req)
2224 req->io_task_work.func = io_queue_async_work;
2225 io_req_task_work_add(req);
2228 static inline void io_queue_next(struct io_kiocb *req)
2230 struct io_kiocb *nxt = io_req_find_next(req);
2233 io_req_task_queue(nxt);
2236 static void io_free_req(struct io_kiocb *req)
2242 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2248 struct task_struct *task;
2253 static inline void io_init_req_batch(struct req_batch *rb)
2260 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2261 struct req_batch *rb)
2264 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2266 io_put_task(rb->task, rb->task_refs);
2269 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2270 struct io_submit_state *state)
2273 io_dismantle_req(req);
2275 if (req->task != rb->task) {
2277 io_put_task(rb->task, rb->task_refs);
2278 rb->task = req->task;
2284 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2285 state->reqs[state->free_reqs++] = req;
2287 list_add(&req->inflight_entry, &state->free_list);
2290 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2291 __must_hold(&ctx->uring_lock)
2293 struct io_submit_state *state = &ctx->submit_state;
2294 int i, nr = state->compl_nr;
2295 struct req_batch rb;
2297 spin_lock(&ctx->completion_lock);
2298 for (i = 0; i < nr; i++) {
2299 struct io_kiocb *req = state->compl_reqs[i];
2301 __io_cqring_fill_event(ctx, req->user_data, req->result,
2304 io_commit_cqring(ctx);
2305 spin_unlock(&ctx->completion_lock);
2306 io_cqring_ev_posted(ctx);
2308 io_init_req_batch(&rb);
2309 for (i = 0; i < nr; i++) {
2310 struct io_kiocb *req = state->compl_reqs[i];
2312 if (req_ref_put_and_test(req))
2313 io_req_free_batch(&rb, req, &ctx->submit_state);
2316 io_req_free_batch_finish(ctx, &rb);
2317 state->compl_nr = 0;
2321 * Drop reference to request, return next in chain (if there is one) if this
2322 * was the last reference to this request.
2324 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2326 struct io_kiocb *nxt = NULL;
2328 if (req_ref_put_and_test(req)) {
2329 nxt = io_req_find_next(req);
2335 static inline void io_put_req(struct io_kiocb *req)
2337 if (req_ref_put_and_test(req))
2341 static inline void io_put_req_deferred(struct io_kiocb *req)
2343 if (req_ref_put_and_test(req)) {
2344 req->io_task_work.func = io_free_req_work;
2345 io_req_task_work_add(req);
2349 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2351 /* See comment at the top of this file */
2353 return __io_cqring_events(ctx);
2356 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2358 struct io_rings *rings = ctx->rings;
2360 /* make sure SQ entry isn't read before tail */
2361 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2364 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2366 unsigned int cflags;
2368 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2369 cflags |= IORING_CQE_F_BUFFER;
2370 req->flags &= ~REQ_F_BUFFER_SELECTED;
2375 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2377 struct io_buffer *kbuf;
2379 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2381 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2382 return io_put_kbuf(req, kbuf);
2385 static inline bool io_run_task_work(void)
2387 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2388 __set_current_state(TASK_RUNNING);
2389 tracehook_notify_signal();
2397 * Find and free completed poll iocbs
2399 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2400 struct list_head *done)
2402 struct req_batch rb;
2403 struct io_kiocb *req;
2405 /* order with ->result store in io_complete_rw_iopoll() */
2408 io_init_req_batch(&rb);
2409 while (!list_empty(done)) {
2410 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2411 list_del(&req->inflight_entry);
2413 if (READ_ONCE(req->result) == -EAGAIN &&
2414 !(req->flags & REQ_F_DONT_REISSUE)) {
2415 req->iopoll_completed = 0;
2416 io_req_task_queue_reissue(req);
2420 __io_cqring_fill_event(ctx, req->user_data, req->result,
2421 io_put_rw_kbuf(req));
2424 if (req_ref_put_and_test(req))
2425 io_req_free_batch(&rb, req, &ctx->submit_state);
2428 io_commit_cqring(ctx);
2429 io_cqring_ev_posted_iopoll(ctx);
2430 io_req_free_batch_finish(ctx, &rb);
2433 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2436 struct io_kiocb *req, *tmp;
2441 * Only spin for completions if we don't have multiple devices hanging
2442 * off our complete list, and we're under the requested amount.
2444 spin = !ctx->poll_multi_queue && *nr_events < min;
2446 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2447 struct kiocb *kiocb = &req->rw.kiocb;
2451 * Move completed and retryable entries to our local lists.
2452 * If we find a request that requires polling, break out
2453 * and complete those lists first, if we have entries there.
2455 if (READ_ONCE(req->iopoll_completed)) {
2456 list_move_tail(&req->inflight_entry, &done);
2459 if (!list_empty(&done))
2462 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2463 if (unlikely(ret < 0))
2468 /* iopoll may have completed current req */
2469 if (READ_ONCE(req->iopoll_completed))
2470 list_move_tail(&req->inflight_entry, &done);
2473 if (!list_empty(&done))
2474 io_iopoll_complete(ctx, nr_events, &done);
2480 * We can't just wait for polled events to come to us, we have to actively
2481 * find and complete them.
2483 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2485 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2488 mutex_lock(&ctx->uring_lock);
2489 while (!list_empty(&ctx->iopoll_list)) {
2490 unsigned int nr_events = 0;
2492 io_do_iopoll(ctx, &nr_events, 0);
2494 /* let it sleep and repeat later if can't complete a request */
2498 * Ensure we allow local-to-the-cpu processing to take place,
2499 * in this case we need to ensure that we reap all events.
2500 * Also let task_work, etc. to progress by releasing the mutex
2502 if (need_resched()) {
2503 mutex_unlock(&ctx->uring_lock);
2505 mutex_lock(&ctx->uring_lock);
2508 mutex_unlock(&ctx->uring_lock);
2511 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2513 unsigned int nr_events = 0;
2517 * We disallow the app entering submit/complete with polling, but we
2518 * still need to lock the ring to prevent racing with polled issue
2519 * that got punted to a workqueue.
2521 mutex_lock(&ctx->uring_lock);
2523 * Don't enter poll loop if we already have events pending.
2524 * If we do, we can potentially be spinning for commands that
2525 * already triggered a CQE (eg in error).
2527 if (test_bit(0, &ctx->check_cq_overflow))
2528 __io_cqring_overflow_flush(ctx, false);
2529 if (io_cqring_events(ctx))
2533 * If a submit got punted to a workqueue, we can have the
2534 * application entering polling for a command before it gets
2535 * issued. That app will hold the uring_lock for the duration
2536 * of the poll right here, so we need to take a breather every
2537 * now and then to ensure that the issue has a chance to add
2538 * the poll to the issued list. Otherwise we can spin here
2539 * forever, while the workqueue is stuck trying to acquire the
2542 if (list_empty(&ctx->iopoll_list)) {
2543 u32 tail = ctx->cached_cq_tail;
2545 mutex_unlock(&ctx->uring_lock);
2547 mutex_lock(&ctx->uring_lock);
2549 /* some requests don't go through iopoll_list */
2550 if (tail != ctx->cached_cq_tail ||
2551 list_empty(&ctx->iopoll_list))
2554 ret = io_do_iopoll(ctx, &nr_events, min);
2555 } while (!ret && nr_events < min && !need_resched());
2557 mutex_unlock(&ctx->uring_lock);
2561 static void kiocb_end_write(struct io_kiocb *req)
2564 * Tell lockdep we inherited freeze protection from submission
2567 if (req->flags & REQ_F_ISREG) {
2568 struct super_block *sb = file_inode(req->file)->i_sb;
2570 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2576 static bool io_resubmit_prep(struct io_kiocb *req)
2578 struct io_async_rw *rw = req->async_data;
2581 return !io_req_prep_async(req);
2582 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2583 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2587 static bool io_rw_should_reissue(struct io_kiocb *req)
2589 umode_t mode = file_inode(req->file)->i_mode;
2590 struct io_ring_ctx *ctx = req->ctx;
2592 if (!S_ISBLK(mode) && !S_ISREG(mode))
2594 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2595 !(ctx->flags & IORING_SETUP_IOPOLL)))
2598 * If ref is dying, we might be running poll reap from the exit work.
2599 * Don't attempt to reissue from that path, just let it fail with
2602 if (percpu_ref_is_dying(&ctx->refs))
2605 * Play it safe and assume not safe to re-import and reissue if we're
2606 * not in the original thread group (or in task context).
2608 if (!same_thread_group(req->task, current) || !in_task())
2613 static bool io_resubmit_prep(struct io_kiocb *req)
2617 static bool io_rw_should_reissue(struct io_kiocb *req)
2623 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2625 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2626 kiocb_end_write(req);
2627 if (res != req->result) {
2628 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2629 io_rw_should_reissue(req)) {
2630 req->flags |= REQ_F_REISSUE;
2639 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2641 unsigned int cflags = io_put_rw_kbuf(req);
2642 long res = req->result;
2645 struct io_ring_ctx *ctx = req->ctx;
2646 struct io_submit_state *state = &ctx->submit_state;
2648 io_req_complete_state(req, res, cflags);
2649 state->compl_reqs[state->compl_nr++] = req;
2650 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2651 io_submit_flush_completions(ctx);
2653 io_req_complete_post(req, res, cflags);
2657 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2658 unsigned int issue_flags)
2660 if (__io_complete_rw_common(req, res))
2662 __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2665 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2667 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2669 if (__io_complete_rw_common(req, res))
2672 req->io_task_work.func = io_req_task_complete;
2673 io_req_task_work_add(req);
2676 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2678 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2680 if (kiocb->ki_flags & IOCB_WRITE)
2681 kiocb_end_write(req);
2682 if (unlikely(res != req->result)) {
2683 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2684 io_resubmit_prep(req))) {
2686 req->flags |= REQ_F_DONT_REISSUE;
2690 WRITE_ONCE(req->result, res);
2691 /* order with io_iopoll_complete() checking ->result */
2693 WRITE_ONCE(req->iopoll_completed, 1);
2697 * After the iocb has been issued, it's safe to be found on the poll list.
2698 * Adding the kiocb to the list AFTER submission ensures that we don't
2699 * find it from a io_do_iopoll() thread before the issuer is done
2700 * accessing the kiocb cookie.
2702 static void io_iopoll_req_issued(struct io_kiocb *req)
2704 struct io_ring_ctx *ctx = req->ctx;
2705 const bool in_async = io_wq_current_is_worker();
2707 /* workqueue context doesn't hold uring_lock, grab it now */
2708 if (unlikely(in_async))
2709 mutex_lock(&ctx->uring_lock);
2712 * Track whether we have multiple files in our lists. This will impact
2713 * how we do polling eventually, not spinning if we're on potentially
2714 * different devices.
2716 if (list_empty(&ctx->iopoll_list)) {
2717 ctx->poll_multi_queue = false;
2718 } else if (!ctx->poll_multi_queue) {
2719 struct io_kiocb *list_req;
2720 unsigned int queue_num0, queue_num1;
2722 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2725 if (list_req->file != req->file) {
2726 ctx->poll_multi_queue = true;
2728 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2729 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2730 if (queue_num0 != queue_num1)
2731 ctx->poll_multi_queue = true;
2736 * For fast devices, IO may have already completed. If it has, add
2737 * it to the front so we find it first.
2739 if (READ_ONCE(req->iopoll_completed))
2740 list_add(&req->inflight_entry, &ctx->iopoll_list);
2742 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2744 if (unlikely(in_async)) {
2746 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2747 * in sq thread task context or in io worker task context. If
2748 * current task context is sq thread, we don't need to check
2749 * whether should wake up sq thread.
2751 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2752 wq_has_sleeper(&ctx->sq_data->wait))
2753 wake_up(&ctx->sq_data->wait);
2755 mutex_unlock(&ctx->uring_lock);
2759 static bool io_bdev_nowait(struct block_device *bdev)
2761 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2765 * If we tracked the file through the SCM inflight mechanism, we could support
2766 * any file. For now, just ensure that anything potentially problematic is done
2769 static bool __io_file_supports_nowait(struct file *file, int rw)
2771 umode_t mode = file_inode(file)->i_mode;
2773 if (S_ISBLK(mode)) {
2774 if (IS_ENABLED(CONFIG_BLOCK) &&
2775 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2781 if (S_ISREG(mode)) {
2782 if (IS_ENABLED(CONFIG_BLOCK) &&
2783 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2784 file->f_op != &io_uring_fops)
2789 /* any ->read/write should understand O_NONBLOCK */
2790 if (file->f_flags & O_NONBLOCK)
2793 if (!(file->f_mode & FMODE_NOWAIT))
2797 return file->f_op->read_iter != NULL;
2799 return file->f_op->write_iter != NULL;
2802 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2804 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2806 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2809 return __io_file_supports_nowait(req->file, rw);
2812 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2814 struct io_ring_ctx *ctx = req->ctx;
2815 struct kiocb *kiocb = &req->rw.kiocb;
2816 struct file *file = req->file;
2820 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2821 req->flags |= REQ_F_ISREG;
2823 kiocb->ki_pos = READ_ONCE(sqe->off);
2824 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2825 req->flags |= REQ_F_CUR_POS;
2826 kiocb->ki_pos = file->f_pos;
2828 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2829 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2830 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2834 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2835 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2836 req->flags |= REQ_F_NOWAIT;
2838 ioprio = READ_ONCE(sqe->ioprio);
2840 ret = ioprio_check_cap(ioprio);
2844 kiocb->ki_ioprio = ioprio;
2846 kiocb->ki_ioprio = get_current_ioprio();
2848 if (ctx->flags & IORING_SETUP_IOPOLL) {
2849 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2850 !kiocb->ki_filp->f_op->iopoll)
2853 kiocb->ki_flags |= IOCB_HIPRI;
2854 kiocb->ki_complete = io_complete_rw_iopoll;
2855 req->iopoll_completed = 0;
2857 if (kiocb->ki_flags & IOCB_HIPRI)
2859 kiocb->ki_complete = io_complete_rw;
2862 if (req->opcode == IORING_OP_READ_FIXED ||
2863 req->opcode == IORING_OP_WRITE_FIXED) {
2865 io_req_set_rsrc_node(req);
2868 req->rw.addr = READ_ONCE(sqe->addr);
2869 req->rw.len = READ_ONCE(sqe->len);
2870 req->buf_index = READ_ONCE(sqe->buf_index);
2874 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2880 case -ERESTARTNOINTR:
2881 case -ERESTARTNOHAND:
2882 case -ERESTART_RESTARTBLOCK:
2884 * We can't just restart the syscall, since previously
2885 * submitted sqes may already be in progress. Just fail this
2891 kiocb->ki_complete(kiocb, ret, 0);
2895 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2896 unsigned int issue_flags)
2898 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2899 struct io_async_rw *io = req->async_data;
2900 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2902 /* add previously done IO, if any */
2903 if (io && io->bytes_done > 0) {
2905 ret = io->bytes_done;
2907 ret += io->bytes_done;
2910 if (req->flags & REQ_F_CUR_POS)
2911 req->file->f_pos = kiocb->ki_pos;
2912 if (ret >= 0 && check_reissue)
2913 __io_complete_rw(req, ret, 0, issue_flags);
2915 io_rw_done(kiocb, ret);
2917 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2918 req->flags &= ~REQ_F_REISSUE;
2919 if (io_resubmit_prep(req)) {
2920 io_req_task_queue_reissue(req);
2923 __io_req_complete(req, issue_flags, ret,
2924 io_put_rw_kbuf(req));
2929 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2930 struct io_mapped_ubuf *imu)
2932 size_t len = req->rw.len;
2933 u64 buf_end, buf_addr = req->rw.addr;
2936 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2938 /* not inside the mapped region */
2939 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2943 * May not be a start of buffer, set size appropriately
2944 * and advance us to the beginning.
2946 offset = buf_addr - imu->ubuf;
2947 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2951 * Don't use iov_iter_advance() here, as it's really slow for
2952 * using the latter parts of a big fixed buffer - it iterates
2953 * over each segment manually. We can cheat a bit here, because
2956 * 1) it's a BVEC iter, we set it up
2957 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2958 * first and last bvec
2960 * So just find our index, and adjust the iterator afterwards.
2961 * If the offset is within the first bvec (or the whole first
2962 * bvec, just use iov_iter_advance(). This makes it easier
2963 * since we can just skip the first segment, which may not
2964 * be PAGE_SIZE aligned.
2966 const struct bio_vec *bvec = imu->bvec;
2968 if (offset <= bvec->bv_len) {
2969 iov_iter_advance(iter, offset);
2971 unsigned long seg_skip;
2973 /* skip first vec */
2974 offset -= bvec->bv_len;
2975 seg_skip = 1 + (offset >> PAGE_SHIFT);
2977 iter->bvec = bvec + seg_skip;
2978 iter->nr_segs -= seg_skip;
2979 iter->count -= bvec->bv_len + offset;
2980 iter->iov_offset = offset & ~PAGE_MASK;
2987 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2989 struct io_ring_ctx *ctx = req->ctx;
2990 struct io_mapped_ubuf *imu = req->imu;
2991 u16 index, buf_index = req->buf_index;
2994 if (unlikely(buf_index >= ctx->nr_user_bufs))
2996 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2997 imu = READ_ONCE(ctx->user_bufs[index]);
3000 return __io_import_fixed(req, rw, iter, imu);
3003 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3006 mutex_unlock(&ctx->uring_lock);
3009 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3012 * "Normal" inline submissions always hold the uring_lock, since we
3013 * grab it from the system call. Same is true for the SQPOLL offload.
3014 * The only exception is when we've detached the request and issue it
3015 * from an async worker thread, grab the lock for that case.
3018 mutex_lock(&ctx->uring_lock);
3021 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3022 int bgid, struct io_buffer *kbuf,
3025 struct io_buffer *head;
3027 if (req->flags & REQ_F_BUFFER_SELECTED)
3030 io_ring_submit_lock(req->ctx, needs_lock);
3032 lockdep_assert_held(&req->ctx->uring_lock);
3034 head = xa_load(&req->ctx->io_buffers, bgid);
3036 if (!list_empty(&head->list)) {
3037 kbuf = list_last_entry(&head->list, struct io_buffer,
3039 list_del(&kbuf->list);
3042 xa_erase(&req->ctx->io_buffers, bgid);
3044 if (*len > kbuf->len)
3047 kbuf = ERR_PTR(-ENOBUFS);
3050 io_ring_submit_unlock(req->ctx, needs_lock);
3055 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3058 struct io_buffer *kbuf;
3061 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3062 bgid = req->buf_index;
3063 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3066 req->rw.addr = (u64) (unsigned long) kbuf;
3067 req->flags |= REQ_F_BUFFER_SELECTED;
3068 return u64_to_user_ptr(kbuf->addr);
3071 #ifdef CONFIG_COMPAT
3072 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3075 struct compat_iovec __user *uiov;
3076 compat_ssize_t clen;
3080 uiov = u64_to_user_ptr(req->rw.addr);
3081 if (!access_ok(uiov, sizeof(*uiov)))
3083 if (__get_user(clen, &uiov->iov_len))
3089 buf = io_rw_buffer_select(req, &len, needs_lock);
3091 return PTR_ERR(buf);
3092 iov[0].iov_base = buf;
3093 iov[0].iov_len = (compat_size_t) len;
3098 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3101 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3105 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3108 len = iov[0].iov_len;
3111 buf = io_rw_buffer_select(req, &len, needs_lock);
3113 return PTR_ERR(buf);
3114 iov[0].iov_base = buf;
3115 iov[0].iov_len = len;
3119 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3122 if (req->flags & REQ_F_BUFFER_SELECTED) {
3123 struct io_buffer *kbuf;
3125 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3126 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3127 iov[0].iov_len = kbuf->len;
3130 if (req->rw.len != 1)
3133 #ifdef CONFIG_COMPAT
3134 if (req->ctx->compat)
3135 return io_compat_import(req, iov, needs_lock);
3138 return __io_iov_buffer_select(req, iov, needs_lock);
3141 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3142 struct iov_iter *iter, bool needs_lock)
3144 void __user *buf = u64_to_user_ptr(req->rw.addr);
3145 size_t sqe_len = req->rw.len;
3146 u8 opcode = req->opcode;
3149 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3151 return io_import_fixed(req, rw, iter);
3154 /* buffer index only valid with fixed read/write, or buffer select */
3155 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3158 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3159 if (req->flags & REQ_F_BUFFER_SELECT) {
3160 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3162 return PTR_ERR(buf);
3163 req->rw.len = sqe_len;
3166 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3171 if (req->flags & REQ_F_BUFFER_SELECT) {
3172 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3174 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3179 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3183 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3185 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3189 * For files that don't have ->read_iter() and ->write_iter(), handle them
3190 * by looping over ->read() or ->write() manually.
3192 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3194 struct kiocb *kiocb = &req->rw.kiocb;
3195 struct file *file = req->file;
3199 * Don't support polled IO through this interface, and we can't
3200 * support non-blocking either. For the latter, this just causes
3201 * the kiocb to be handled from an async context.
3203 if (kiocb->ki_flags & IOCB_HIPRI)
3205 if (kiocb->ki_flags & IOCB_NOWAIT)
3208 while (iov_iter_count(iter)) {
3212 if (!iov_iter_is_bvec(iter)) {
3213 iovec = iov_iter_iovec(iter);
3215 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3216 iovec.iov_len = req->rw.len;
3220 nr = file->f_op->read(file, iovec.iov_base,
3221 iovec.iov_len, io_kiocb_ppos(kiocb));
3223 nr = file->f_op->write(file, iovec.iov_base,
3224 iovec.iov_len, io_kiocb_ppos(kiocb));
3233 if (nr != iovec.iov_len)
3237 iov_iter_advance(iter, nr);
3243 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3244 const struct iovec *fast_iov, struct iov_iter *iter)
3246 struct io_async_rw *rw = req->async_data;
3248 memcpy(&rw->iter, iter, sizeof(*iter));
3249 rw->free_iovec = iovec;
3251 /* can only be fixed buffers, no need to do anything */
3252 if (iov_iter_is_bvec(iter))
3255 unsigned iov_off = 0;
3257 rw->iter.iov = rw->fast_iov;
3258 if (iter->iov != fast_iov) {
3259 iov_off = iter->iov - fast_iov;
3260 rw->iter.iov += iov_off;
3262 if (rw->fast_iov != fast_iov)
3263 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3264 sizeof(struct iovec) * iter->nr_segs);
3266 req->flags |= REQ_F_NEED_CLEANUP;
3270 static inline int io_alloc_async_data(struct io_kiocb *req)
3272 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3273 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3274 return req->async_data == NULL;
3277 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3278 const struct iovec *fast_iov,
3279 struct iov_iter *iter, bool force)
3281 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3283 if (!req->async_data) {
3284 if (io_alloc_async_data(req)) {
3289 io_req_map_rw(req, iovec, fast_iov, iter);
3294 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3296 struct io_async_rw *iorw = req->async_data;
3297 struct iovec *iov = iorw->fast_iov;
3300 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3301 if (unlikely(ret < 0))
3304 iorw->bytes_done = 0;
3305 iorw->free_iovec = iov;
3307 req->flags |= REQ_F_NEED_CLEANUP;
3311 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3313 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3315 return io_prep_rw(req, sqe);
3319 * This is our waitqueue callback handler, registered through lock_page_async()
3320 * when we initially tried to do the IO with the iocb armed our waitqueue.
3321 * This gets called when the page is unlocked, and we generally expect that to
3322 * happen when the page IO is completed and the page is now uptodate. This will
3323 * queue a task_work based retry of the operation, attempting to copy the data
3324 * again. If the latter fails because the page was NOT uptodate, then we will
3325 * do a thread based blocking retry of the operation. That's the unexpected
3328 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3329 int sync, void *arg)
3331 struct wait_page_queue *wpq;
3332 struct io_kiocb *req = wait->private;
3333 struct wait_page_key *key = arg;
3335 wpq = container_of(wait, struct wait_page_queue, wait);
3337 if (!wake_page_match(wpq, key))
3340 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3341 list_del_init(&wait->entry);
3342 io_req_task_queue(req);
3347 * This controls whether a given IO request should be armed for async page
3348 * based retry. If we return false here, the request is handed to the async
3349 * worker threads for retry. If we're doing buffered reads on a regular file,
3350 * we prepare a private wait_page_queue entry and retry the operation. This
3351 * will either succeed because the page is now uptodate and unlocked, or it
3352 * will register a callback when the page is unlocked at IO completion. Through
3353 * that callback, io_uring uses task_work to setup a retry of the operation.
3354 * That retry will attempt the buffered read again. The retry will generally
3355 * succeed, or in rare cases where it fails, we then fall back to using the
3356 * async worker threads for a blocking retry.
3358 static bool io_rw_should_retry(struct io_kiocb *req)
3360 struct io_async_rw *rw = req->async_data;
3361 struct wait_page_queue *wait = &rw->wpq;
3362 struct kiocb *kiocb = &req->rw.kiocb;
3364 /* never retry for NOWAIT, we just complete with -EAGAIN */
3365 if (req->flags & REQ_F_NOWAIT)
3368 /* Only for buffered IO */
3369 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3373 * just use poll if we can, and don't attempt if the fs doesn't
3374 * support callback based unlocks
3376 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3379 wait->wait.func = io_async_buf_func;
3380 wait->wait.private = req;
3381 wait->wait.flags = 0;
3382 INIT_LIST_HEAD(&wait->wait.entry);
3383 kiocb->ki_flags |= IOCB_WAITQ;
3384 kiocb->ki_flags &= ~IOCB_NOWAIT;
3385 kiocb->ki_waitq = wait;
3389 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3391 if (req->file->f_op->read_iter)
3392 return call_read_iter(req->file, &req->rw.kiocb, iter);
3393 else if (req->file->f_op->read)
3394 return loop_rw_iter(READ, req, iter);
3399 static bool need_read_all(struct io_kiocb *req)
3401 return req->flags & REQ_F_ISREG ||
3402 S_ISBLK(file_inode(req->file)->i_mode);
3405 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3407 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3408 struct kiocb *kiocb = &req->rw.kiocb;
3409 struct iov_iter __iter, *iter = &__iter;
3410 struct io_async_rw *rw = req->async_data;
3411 ssize_t io_size, ret, ret2;
3412 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3418 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3422 io_size = iov_iter_count(iter);
3423 req->result = io_size;
3425 /* Ensure we clear previously set non-block flag */
3426 if (!force_nonblock)
3427 kiocb->ki_flags &= ~IOCB_NOWAIT;
3429 kiocb->ki_flags |= IOCB_NOWAIT;
3431 /* If the file doesn't support async, just async punt */
3432 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3433 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3434 return ret ?: -EAGAIN;
3437 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3438 if (unlikely(ret)) {
3443 ret = io_iter_do_read(req, iter);
3445 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3446 req->flags &= ~REQ_F_REISSUE;
3447 /* IOPOLL retry should happen for io-wq threads */
3448 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3450 /* no retry on NONBLOCK nor RWF_NOWAIT */
3451 if (req->flags & REQ_F_NOWAIT)
3453 /* some cases will consume bytes even on error returns */
3454 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3456 } else if (ret == -EIOCBQUEUED) {
3458 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3459 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3460 /* read all, failed, already did sync or don't want to retry */
3464 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3469 rw = req->async_data;
3470 /* now use our persistent iterator, if we aren't already */
3475 rw->bytes_done += ret;
3476 /* if we can retry, do so with the callbacks armed */
3477 if (!io_rw_should_retry(req)) {
3478 kiocb->ki_flags &= ~IOCB_WAITQ;
3483 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3484 * we get -EIOCBQUEUED, then we'll get a notification when the
3485 * desired page gets unlocked. We can also get a partial read
3486 * here, and if we do, then just retry at the new offset.
3488 ret = io_iter_do_read(req, iter);
3489 if (ret == -EIOCBQUEUED)
3491 /* we got some bytes, but not all. retry. */
3492 kiocb->ki_flags &= ~IOCB_WAITQ;
3493 } while (ret > 0 && ret < io_size);
3495 kiocb_done(kiocb, ret, issue_flags);
3497 /* it's faster to check here then delegate to kfree */
3503 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3505 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3507 return io_prep_rw(req, sqe);
3510 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3512 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3513 struct kiocb *kiocb = &req->rw.kiocb;
3514 struct iov_iter __iter, *iter = &__iter;
3515 struct io_async_rw *rw = req->async_data;
3516 ssize_t ret, ret2, io_size;
3517 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3523 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3527 io_size = iov_iter_count(iter);
3528 req->result = io_size;
3530 /* Ensure we clear previously set non-block flag */
3531 if (!force_nonblock)
3532 kiocb->ki_flags &= ~IOCB_NOWAIT;
3534 kiocb->ki_flags |= IOCB_NOWAIT;
3536 /* If the file doesn't support async, just async punt */
3537 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3540 /* file path doesn't support NOWAIT for non-direct_IO */
3541 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3542 (req->flags & REQ_F_ISREG))
3545 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3550 * Open-code file_start_write here to grab freeze protection,
3551 * which will be released by another thread in
3552 * io_complete_rw(). Fool lockdep by telling it the lock got
3553 * released so that it doesn't complain about the held lock when
3554 * we return to userspace.
3556 if (req->flags & REQ_F_ISREG) {
3557 sb_start_write(file_inode(req->file)->i_sb);
3558 __sb_writers_release(file_inode(req->file)->i_sb,
3561 kiocb->ki_flags |= IOCB_WRITE;
3563 if (req->file->f_op->write_iter)
3564 ret2 = call_write_iter(req->file, kiocb, iter);
3565 else if (req->file->f_op->write)
3566 ret2 = loop_rw_iter(WRITE, req, iter);
3570 if (req->flags & REQ_F_REISSUE) {
3571 req->flags &= ~REQ_F_REISSUE;
3576 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3577 * retry them without IOCB_NOWAIT.
3579 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3581 /* no retry on NONBLOCK nor RWF_NOWAIT */
3582 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3584 if (!force_nonblock || ret2 != -EAGAIN) {
3585 /* IOPOLL retry should happen for io-wq threads */
3586 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3589 kiocb_done(kiocb, ret2, issue_flags);
3592 /* some cases will consume bytes even on error returns */
3593 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3594 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3595 return ret ?: -EAGAIN;
3598 /* it's reportedly faster than delegating the null check to kfree() */
3604 static int io_renameat_prep(struct io_kiocb *req,
3605 const struct io_uring_sqe *sqe)
3607 struct io_rename *ren = &req->rename;
3608 const char __user *oldf, *newf;
3610 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3612 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3614 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3617 ren->old_dfd = READ_ONCE(sqe->fd);
3618 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3619 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3620 ren->new_dfd = READ_ONCE(sqe->len);
3621 ren->flags = READ_ONCE(sqe->rename_flags);
3623 ren->oldpath = getname(oldf);
3624 if (IS_ERR(ren->oldpath))
3625 return PTR_ERR(ren->oldpath);
3627 ren->newpath = getname(newf);
3628 if (IS_ERR(ren->newpath)) {
3629 putname(ren->oldpath);
3630 return PTR_ERR(ren->newpath);
3633 req->flags |= REQ_F_NEED_CLEANUP;
3637 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3639 struct io_rename *ren = &req->rename;
3642 if (issue_flags & IO_URING_F_NONBLOCK)
3645 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3646 ren->newpath, ren->flags);
3648 req->flags &= ~REQ_F_NEED_CLEANUP;
3651 io_req_complete(req, ret);
3655 static int io_unlinkat_prep(struct io_kiocb *req,
3656 const struct io_uring_sqe *sqe)
3658 struct io_unlink *un = &req->unlink;
3659 const char __user *fname;
3661 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3663 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3666 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3669 un->dfd = READ_ONCE(sqe->fd);
3671 un->flags = READ_ONCE(sqe->unlink_flags);
3672 if (un->flags & ~AT_REMOVEDIR)
3675 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3676 un->filename = getname(fname);
3677 if (IS_ERR(un->filename))
3678 return PTR_ERR(un->filename);
3680 req->flags |= REQ_F_NEED_CLEANUP;
3684 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3686 struct io_unlink *un = &req->unlink;
3689 if (issue_flags & IO_URING_F_NONBLOCK)
3692 if (un->flags & AT_REMOVEDIR)
3693 ret = do_rmdir(un->dfd, un->filename);
3695 ret = do_unlinkat(un->dfd, un->filename);
3697 req->flags &= ~REQ_F_NEED_CLEANUP;
3700 io_req_complete(req, ret);
3704 static int io_shutdown_prep(struct io_kiocb *req,
3705 const struct io_uring_sqe *sqe)
3707 #if defined(CONFIG_NET)
3708 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3710 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3711 sqe->buf_index || sqe->splice_fd_in))
3714 req->shutdown.how = READ_ONCE(sqe->len);
3721 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3723 #if defined(CONFIG_NET)
3724 struct socket *sock;
3727 if (issue_flags & IO_URING_F_NONBLOCK)
3730 sock = sock_from_file(req->file);
3731 if (unlikely(!sock))
3734 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3737 io_req_complete(req, ret);
3744 static int __io_splice_prep(struct io_kiocb *req,
3745 const struct io_uring_sqe *sqe)
3747 struct io_splice *sp = &req->splice;
3748 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3750 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3754 sp->len = READ_ONCE(sqe->len);
3755 sp->flags = READ_ONCE(sqe->splice_flags);
3757 if (unlikely(sp->flags & ~valid_flags))
3760 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3761 (sp->flags & SPLICE_F_FD_IN_FIXED));
3764 req->flags |= REQ_F_NEED_CLEANUP;
3768 static int io_tee_prep(struct io_kiocb *req,
3769 const struct io_uring_sqe *sqe)
3771 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3773 return __io_splice_prep(req, sqe);
3776 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3778 struct io_splice *sp = &req->splice;
3779 struct file *in = sp->file_in;
3780 struct file *out = sp->file_out;
3781 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3784 if (issue_flags & IO_URING_F_NONBLOCK)
3787 ret = do_tee(in, out, sp->len, flags);
3789 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3791 req->flags &= ~REQ_F_NEED_CLEANUP;
3795 io_req_complete(req, ret);
3799 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3801 struct io_splice *sp = &req->splice;
3803 sp->off_in = READ_ONCE(sqe->splice_off_in);
3804 sp->off_out = READ_ONCE(sqe->off);
3805 return __io_splice_prep(req, sqe);
3808 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3810 struct io_splice *sp = &req->splice;
3811 struct file *in = sp->file_in;
3812 struct file *out = sp->file_out;
3813 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3814 loff_t *poff_in, *poff_out;
3817 if (issue_flags & IO_URING_F_NONBLOCK)
3820 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3821 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3824 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3826 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3828 req->flags &= ~REQ_F_NEED_CLEANUP;
3832 io_req_complete(req, ret);
3837 * IORING_OP_NOP just posts a completion event, nothing else.
3839 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3841 struct io_ring_ctx *ctx = req->ctx;
3843 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3846 __io_req_complete(req, issue_flags, 0, 0);
3850 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3852 struct io_ring_ctx *ctx = req->ctx;
3857 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3859 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
3863 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3864 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3867 req->sync.off = READ_ONCE(sqe->off);
3868 req->sync.len = READ_ONCE(sqe->len);
3872 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3874 loff_t end = req->sync.off + req->sync.len;
3877 /* fsync always requires a blocking context */
3878 if (issue_flags & IO_URING_F_NONBLOCK)
3881 ret = vfs_fsync_range(req->file, req->sync.off,
3882 end > 0 ? end : LLONG_MAX,
3883 req->sync.flags & IORING_FSYNC_DATASYNC);
3886 io_req_complete(req, ret);
3890 static int io_fallocate_prep(struct io_kiocb *req,
3891 const struct io_uring_sqe *sqe)
3893 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
3896 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3899 req->sync.off = READ_ONCE(sqe->off);
3900 req->sync.len = READ_ONCE(sqe->addr);
3901 req->sync.mode = READ_ONCE(sqe->len);
3905 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3909 /* fallocate always requiring blocking context */
3910 if (issue_flags & IO_URING_F_NONBLOCK)
3912 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3916 io_req_complete(req, ret);
3920 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3922 const char __user *fname;
3925 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3927 if (unlikely(sqe->ioprio || sqe->buf_index))
3929 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3932 /* open.how should be already initialised */
3933 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3934 req->open.how.flags |= O_LARGEFILE;
3936 req->open.dfd = READ_ONCE(sqe->fd);
3937 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3938 req->open.filename = getname(fname);
3939 if (IS_ERR(req->open.filename)) {
3940 ret = PTR_ERR(req->open.filename);
3941 req->open.filename = NULL;
3945 req->open.file_slot = READ_ONCE(sqe->file_index);
3946 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
3949 req->open.nofile = rlimit(RLIMIT_NOFILE);
3950 req->flags |= REQ_F_NEED_CLEANUP;
3954 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3956 u64 mode = READ_ONCE(sqe->len);
3957 u64 flags = READ_ONCE(sqe->open_flags);
3959 req->open.how = build_open_how(flags, mode);
3960 return __io_openat_prep(req, sqe);
3963 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3965 struct open_how __user *how;
3969 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3970 len = READ_ONCE(sqe->len);
3971 if (len < OPEN_HOW_SIZE_VER0)
3974 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3979 return __io_openat_prep(req, sqe);
3982 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3984 struct open_flags op;
3986 bool resolve_nonblock, nonblock_set;
3987 bool fixed = !!req->open.file_slot;
3990 ret = build_open_flags(&req->open.how, &op);
3993 nonblock_set = op.open_flag & O_NONBLOCK;
3994 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3995 if (issue_flags & IO_URING_F_NONBLOCK) {
3997 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3998 * it'll always -EAGAIN
4000 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4002 op.lookup_flags |= LOOKUP_CACHED;
4003 op.open_flag |= O_NONBLOCK;
4007 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4012 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4015 * We could hang on to this 'fd' on retrying, but seems like
4016 * marginal gain for something that is now known to be a slower
4017 * path. So just put it, and we'll get a new one when we retry.
4022 ret = PTR_ERR(file);
4023 /* only retry if RESOLVE_CACHED wasn't already set by application */
4024 if (ret == -EAGAIN &&
4025 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4030 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4031 file->f_flags &= ~O_NONBLOCK;
4032 fsnotify_open(file);
4035 fd_install(ret, file);
4037 ret = io_install_fixed_file(req, file, issue_flags,
4038 req->open.file_slot - 1);
4040 putname(req->open.filename);
4041 req->flags &= ~REQ_F_NEED_CLEANUP;
4044 __io_req_complete(req, issue_flags, ret, 0);
4048 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4050 return io_openat2(req, issue_flags);
4053 static int io_remove_buffers_prep(struct io_kiocb *req,
4054 const struct io_uring_sqe *sqe)
4056 struct io_provide_buf *p = &req->pbuf;
4059 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4063 tmp = READ_ONCE(sqe->fd);
4064 if (!tmp || tmp > USHRT_MAX)
4067 memset(p, 0, sizeof(*p));
4069 p->bgid = READ_ONCE(sqe->buf_group);
4073 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4074 int bgid, unsigned nbufs)
4078 /* shouldn't happen */
4082 /* the head kbuf is the list itself */
4083 while (!list_empty(&buf->list)) {
4084 struct io_buffer *nxt;
4086 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4087 list_del(&nxt->list);
4094 xa_erase(&ctx->io_buffers, bgid);
4099 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4101 struct io_provide_buf *p = &req->pbuf;
4102 struct io_ring_ctx *ctx = req->ctx;
4103 struct io_buffer *head;
4105 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4107 io_ring_submit_lock(ctx, !force_nonblock);
4109 lockdep_assert_held(&ctx->uring_lock);
4112 head = xa_load(&ctx->io_buffers, p->bgid);
4114 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4118 /* complete before unlock, IOPOLL may need the lock */
4119 __io_req_complete(req, issue_flags, ret, 0);
4120 io_ring_submit_unlock(ctx, !force_nonblock);
4124 static int io_provide_buffers_prep(struct io_kiocb *req,
4125 const struct io_uring_sqe *sqe)
4127 unsigned long size, tmp_check;
4128 struct io_provide_buf *p = &req->pbuf;
4131 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4134 tmp = READ_ONCE(sqe->fd);
4135 if (!tmp || tmp > USHRT_MAX)
4138 p->addr = READ_ONCE(sqe->addr);
4139 p->len = READ_ONCE(sqe->len);
4141 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4144 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4147 size = (unsigned long)p->len * p->nbufs;
4148 if (!access_ok(u64_to_user_ptr(p->addr), size))
4151 p->bgid = READ_ONCE(sqe->buf_group);
4152 tmp = READ_ONCE(sqe->off);
4153 if (tmp > USHRT_MAX)
4159 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4161 struct io_buffer *buf;
4162 u64 addr = pbuf->addr;
4163 int i, bid = pbuf->bid;
4165 for (i = 0; i < pbuf->nbufs; i++) {
4166 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4171 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4176 INIT_LIST_HEAD(&buf->list);
4179 list_add_tail(&buf->list, &(*head)->list);
4183 return i ? i : -ENOMEM;
4186 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4188 struct io_provide_buf *p = &req->pbuf;
4189 struct io_ring_ctx *ctx = req->ctx;
4190 struct io_buffer *head, *list;
4192 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4194 io_ring_submit_lock(ctx, !force_nonblock);
4196 lockdep_assert_held(&ctx->uring_lock);
4198 list = head = xa_load(&ctx->io_buffers, p->bgid);
4200 ret = io_add_buffers(p, &head);
4201 if (ret >= 0 && !list) {
4202 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4204 __io_remove_buffers(ctx, head, p->bgid, -1U);
4208 /* complete before unlock, IOPOLL may need the lock */
4209 __io_req_complete(req, issue_flags, ret, 0);
4210 io_ring_submit_unlock(ctx, !force_nonblock);
4214 static int io_epoll_ctl_prep(struct io_kiocb *req,
4215 const struct io_uring_sqe *sqe)
4217 #if defined(CONFIG_EPOLL)
4218 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4220 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4223 req->epoll.epfd = READ_ONCE(sqe->fd);
4224 req->epoll.op = READ_ONCE(sqe->len);
4225 req->epoll.fd = READ_ONCE(sqe->off);
4227 if (ep_op_has_event(req->epoll.op)) {
4228 struct epoll_event __user *ev;
4230 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4231 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4241 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4243 #if defined(CONFIG_EPOLL)
4244 struct io_epoll *ie = &req->epoll;
4246 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4248 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4249 if (force_nonblock && ret == -EAGAIN)
4254 __io_req_complete(req, issue_flags, ret, 0);
4261 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4263 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4264 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4266 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4269 req->madvise.addr = READ_ONCE(sqe->addr);
4270 req->madvise.len = READ_ONCE(sqe->len);
4271 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4278 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4280 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4281 struct io_madvise *ma = &req->madvise;
4284 if (issue_flags & IO_URING_F_NONBLOCK)
4287 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4290 io_req_complete(req, ret);
4297 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4299 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4301 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4304 req->fadvise.offset = READ_ONCE(sqe->off);
4305 req->fadvise.len = READ_ONCE(sqe->len);
4306 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4310 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4312 struct io_fadvise *fa = &req->fadvise;
4315 if (issue_flags & IO_URING_F_NONBLOCK) {
4316 switch (fa->advice) {
4317 case POSIX_FADV_NORMAL:
4318 case POSIX_FADV_RANDOM:
4319 case POSIX_FADV_SEQUENTIAL:
4326 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4329 __io_req_complete(req, issue_flags, ret, 0);
4333 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4335 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4337 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4339 if (req->flags & REQ_F_FIXED_FILE)
4342 req->statx.dfd = READ_ONCE(sqe->fd);
4343 req->statx.mask = READ_ONCE(sqe->len);
4344 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4345 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4346 req->statx.flags = READ_ONCE(sqe->statx_flags);
4351 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4353 struct io_statx *ctx = &req->statx;
4356 if (issue_flags & IO_URING_F_NONBLOCK)
4359 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4364 io_req_complete(req, ret);
4368 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4370 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4372 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4373 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4375 if (req->flags & REQ_F_FIXED_FILE)
4378 req->close.fd = READ_ONCE(sqe->fd);
4382 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4384 struct files_struct *files = current->files;
4385 struct io_close *close = &req->close;
4386 struct fdtable *fdt;
4387 struct file *file = NULL;
4390 spin_lock(&files->file_lock);
4391 fdt = files_fdtable(files);
4392 if (close->fd >= fdt->max_fds) {
4393 spin_unlock(&files->file_lock);
4396 file = fdt->fd[close->fd];
4397 if (!file || file->f_op == &io_uring_fops) {
4398 spin_unlock(&files->file_lock);
4403 /* if the file has a flush method, be safe and punt to async */
4404 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4405 spin_unlock(&files->file_lock);
4409 ret = __close_fd_get_file(close->fd, &file);
4410 spin_unlock(&files->file_lock);
4417 /* No ->flush() or already async, safely close from here */
4418 ret = filp_close(file, current->files);
4424 __io_req_complete(req, issue_flags, ret, 0);
4428 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4430 struct io_ring_ctx *ctx = req->ctx;
4432 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4434 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4438 req->sync.off = READ_ONCE(sqe->off);
4439 req->sync.len = READ_ONCE(sqe->len);
4440 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4444 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4448 /* sync_file_range always requires a blocking context */
4449 if (issue_flags & IO_URING_F_NONBLOCK)
4452 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4456 io_req_complete(req, ret);
4460 #if defined(CONFIG_NET)
4461 static int io_setup_async_msg(struct io_kiocb *req,
4462 struct io_async_msghdr *kmsg)
4464 struct io_async_msghdr *async_msg = req->async_data;
4468 if (io_alloc_async_data(req)) {
4469 kfree(kmsg->free_iov);
4472 async_msg = req->async_data;
4473 req->flags |= REQ_F_NEED_CLEANUP;
4474 memcpy(async_msg, kmsg, sizeof(*kmsg));
4475 async_msg->msg.msg_name = &async_msg->addr;
4476 /* if were using fast_iov, set it to the new one */
4477 if (!async_msg->free_iov)
4478 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4483 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4484 struct io_async_msghdr *iomsg)
4486 iomsg->msg.msg_name = &iomsg->addr;
4487 iomsg->free_iov = iomsg->fast_iov;
4488 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4489 req->sr_msg.msg_flags, &iomsg->free_iov);
4492 static int io_sendmsg_prep_async(struct io_kiocb *req)
4496 ret = io_sendmsg_copy_hdr(req, req->async_data);
4498 req->flags |= REQ_F_NEED_CLEANUP;
4502 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4504 struct io_sr_msg *sr = &req->sr_msg;
4506 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4509 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4510 sr->len = READ_ONCE(sqe->len);
4511 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4512 if (sr->msg_flags & MSG_DONTWAIT)
4513 req->flags |= REQ_F_NOWAIT;
4515 #ifdef CONFIG_COMPAT
4516 if (req->ctx->compat)
4517 sr->msg_flags |= MSG_CMSG_COMPAT;
4522 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4524 struct io_async_msghdr iomsg, *kmsg;
4525 struct socket *sock;
4530 sock = sock_from_file(req->file);
4531 if (unlikely(!sock))
4534 kmsg = req->async_data;
4536 ret = io_sendmsg_copy_hdr(req, &iomsg);
4542 flags = req->sr_msg.msg_flags;
4543 if (issue_flags & IO_URING_F_NONBLOCK)
4544 flags |= MSG_DONTWAIT;
4545 if (flags & MSG_WAITALL)
4546 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4548 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4549 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4550 return io_setup_async_msg(req, kmsg);
4551 if (ret == -ERESTARTSYS)
4554 /* fast path, check for non-NULL to avoid function call */
4556 kfree(kmsg->free_iov);
4557 req->flags &= ~REQ_F_NEED_CLEANUP;
4560 __io_req_complete(req, issue_flags, ret, 0);
4564 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4566 struct io_sr_msg *sr = &req->sr_msg;
4569 struct socket *sock;
4574 sock = sock_from_file(req->file);
4575 if (unlikely(!sock))
4578 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4582 msg.msg_name = NULL;
4583 msg.msg_control = NULL;
4584 msg.msg_controllen = 0;
4585 msg.msg_namelen = 0;
4587 flags = req->sr_msg.msg_flags;
4588 if (issue_flags & IO_URING_F_NONBLOCK)
4589 flags |= MSG_DONTWAIT;
4590 if (flags & MSG_WAITALL)
4591 min_ret = iov_iter_count(&msg.msg_iter);
4593 msg.msg_flags = flags;
4594 ret = sock_sendmsg(sock, &msg);
4595 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4597 if (ret == -ERESTARTSYS)
4602 __io_req_complete(req, issue_flags, ret, 0);
4606 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4607 struct io_async_msghdr *iomsg)
4609 struct io_sr_msg *sr = &req->sr_msg;
4610 struct iovec __user *uiov;
4614 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4615 &iomsg->uaddr, &uiov, &iov_len);
4619 if (req->flags & REQ_F_BUFFER_SELECT) {
4622 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4624 sr->len = iomsg->fast_iov[0].iov_len;
4625 iomsg->free_iov = NULL;
4627 iomsg->free_iov = iomsg->fast_iov;
4628 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4629 &iomsg->free_iov, &iomsg->msg.msg_iter,
4638 #ifdef CONFIG_COMPAT
4639 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4640 struct io_async_msghdr *iomsg)
4642 struct io_sr_msg *sr = &req->sr_msg;
4643 struct compat_iovec __user *uiov;
4648 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4653 uiov = compat_ptr(ptr);
4654 if (req->flags & REQ_F_BUFFER_SELECT) {
4655 compat_ssize_t clen;
4659 if (!access_ok(uiov, sizeof(*uiov)))
4661 if (__get_user(clen, &uiov->iov_len))
4666 iomsg->free_iov = NULL;
4668 iomsg->free_iov = iomsg->fast_iov;
4669 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4670 UIO_FASTIOV, &iomsg->free_iov,
4671 &iomsg->msg.msg_iter, true);
4680 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4681 struct io_async_msghdr *iomsg)
4683 iomsg->msg.msg_name = &iomsg->addr;
4685 #ifdef CONFIG_COMPAT
4686 if (req->ctx->compat)
4687 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4690 return __io_recvmsg_copy_hdr(req, iomsg);
4693 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4696 struct io_sr_msg *sr = &req->sr_msg;
4697 struct io_buffer *kbuf;
4699 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4704 req->flags |= REQ_F_BUFFER_SELECTED;
4708 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4710 return io_put_kbuf(req, req->sr_msg.kbuf);
4713 static int io_recvmsg_prep_async(struct io_kiocb *req)
4717 ret = io_recvmsg_copy_hdr(req, req->async_data);
4719 req->flags |= REQ_F_NEED_CLEANUP;
4723 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4725 struct io_sr_msg *sr = &req->sr_msg;
4727 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4730 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4731 sr->len = READ_ONCE(sqe->len);
4732 sr->bgid = READ_ONCE(sqe->buf_group);
4733 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4734 if (sr->msg_flags & MSG_DONTWAIT)
4735 req->flags |= REQ_F_NOWAIT;
4737 #ifdef CONFIG_COMPAT
4738 if (req->ctx->compat)
4739 sr->msg_flags |= MSG_CMSG_COMPAT;
4744 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4746 struct io_async_msghdr iomsg, *kmsg;
4747 struct socket *sock;
4748 struct io_buffer *kbuf;
4751 int ret, cflags = 0;
4752 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4754 sock = sock_from_file(req->file);
4755 if (unlikely(!sock))
4758 kmsg = req->async_data;
4760 ret = io_recvmsg_copy_hdr(req, &iomsg);
4766 if (req->flags & REQ_F_BUFFER_SELECT) {
4767 kbuf = io_recv_buffer_select(req, !force_nonblock);
4769 return PTR_ERR(kbuf);
4770 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4771 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4772 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4773 1, req->sr_msg.len);
4776 flags = req->sr_msg.msg_flags;
4778 flags |= MSG_DONTWAIT;
4779 if (flags & MSG_WAITALL)
4780 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4782 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4783 kmsg->uaddr, flags);
4784 if (force_nonblock && ret == -EAGAIN)
4785 return io_setup_async_msg(req, kmsg);
4786 if (ret == -ERESTARTSYS)
4789 if (req->flags & REQ_F_BUFFER_SELECTED)
4790 cflags = io_put_recv_kbuf(req);
4791 /* fast path, check for non-NULL to avoid function call */
4793 kfree(kmsg->free_iov);
4794 req->flags &= ~REQ_F_NEED_CLEANUP;
4795 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4797 __io_req_complete(req, issue_flags, ret, cflags);
4801 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4803 struct io_buffer *kbuf;
4804 struct io_sr_msg *sr = &req->sr_msg;
4806 void __user *buf = sr->buf;
4807 struct socket *sock;
4811 int ret, cflags = 0;
4812 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4814 sock = sock_from_file(req->file);
4815 if (unlikely(!sock))
4818 if (req->flags & REQ_F_BUFFER_SELECT) {
4819 kbuf = io_recv_buffer_select(req, !force_nonblock);
4821 return PTR_ERR(kbuf);
4822 buf = u64_to_user_ptr(kbuf->addr);
4825 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4829 msg.msg_name = NULL;
4830 msg.msg_control = NULL;
4831 msg.msg_controllen = 0;
4832 msg.msg_namelen = 0;
4833 msg.msg_iocb = NULL;
4836 flags = req->sr_msg.msg_flags;
4838 flags |= MSG_DONTWAIT;
4839 if (flags & MSG_WAITALL)
4840 min_ret = iov_iter_count(&msg.msg_iter);
4842 ret = sock_recvmsg(sock, &msg, flags);
4843 if (force_nonblock && ret == -EAGAIN)
4845 if (ret == -ERESTARTSYS)
4848 if (req->flags & REQ_F_BUFFER_SELECTED)
4849 cflags = io_put_recv_kbuf(req);
4850 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4852 __io_req_complete(req, issue_flags, ret, cflags);
4856 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4858 struct io_accept *accept = &req->accept;
4860 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4862 if (sqe->ioprio || sqe->len || sqe->buf_index)
4865 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4866 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4867 accept->flags = READ_ONCE(sqe->accept_flags);
4868 accept->nofile = rlimit(RLIMIT_NOFILE);
4870 accept->file_slot = READ_ONCE(sqe->file_index);
4871 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
4872 (accept->flags & SOCK_CLOEXEC)))
4874 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
4876 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
4877 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
4881 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4883 struct io_accept *accept = &req->accept;
4884 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4885 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4886 bool fixed = !!accept->file_slot;
4890 if (req->file->f_flags & O_NONBLOCK)
4891 req->flags |= REQ_F_NOWAIT;
4894 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
4895 if (unlikely(fd < 0))
4898 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
4903 ret = PTR_ERR(file);
4904 if (ret == -EAGAIN && force_nonblock)
4906 if (ret == -ERESTARTSYS)
4909 } else if (!fixed) {
4910 fd_install(fd, file);
4913 ret = io_install_fixed_file(req, file, issue_flags,
4914 accept->file_slot - 1);
4916 __io_req_complete(req, issue_flags, ret, 0);
4920 static int io_connect_prep_async(struct io_kiocb *req)
4922 struct io_async_connect *io = req->async_data;
4923 struct io_connect *conn = &req->connect;
4925 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4928 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4930 struct io_connect *conn = &req->connect;
4932 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4934 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
4938 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4939 conn->addr_len = READ_ONCE(sqe->addr2);
4943 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4945 struct io_async_connect __io, *io;
4946 unsigned file_flags;
4948 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4950 if (req->async_data) {
4951 io = req->async_data;
4953 ret = move_addr_to_kernel(req->connect.addr,
4954 req->connect.addr_len,
4961 file_flags = force_nonblock ? O_NONBLOCK : 0;
4963 ret = __sys_connect_file(req->file, &io->address,
4964 req->connect.addr_len, file_flags);
4965 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4966 if (req->async_data)
4968 if (io_alloc_async_data(req)) {
4972 memcpy(req->async_data, &__io, sizeof(__io));
4975 if (ret == -ERESTARTSYS)
4980 __io_req_complete(req, issue_flags, ret, 0);
4983 #else /* !CONFIG_NET */
4984 #define IO_NETOP_FN(op) \
4985 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4987 return -EOPNOTSUPP; \
4990 #define IO_NETOP_PREP(op) \
4992 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4994 return -EOPNOTSUPP; \
4997 #define IO_NETOP_PREP_ASYNC(op) \
4999 static int io_##op##_prep_async(struct io_kiocb *req) \
5001 return -EOPNOTSUPP; \
5004 IO_NETOP_PREP_ASYNC(sendmsg);
5005 IO_NETOP_PREP_ASYNC(recvmsg);
5006 IO_NETOP_PREP_ASYNC(connect);
5007 IO_NETOP_PREP(accept);
5010 #endif /* CONFIG_NET */
5012 struct io_poll_table {
5013 struct poll_table_struct pt;
5014 struct io_kiocb *req;
5019 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5020 __poll_t mask, io_req_tw_func_t func)
5022 /* for instances that support it check for an event match first: */
5023 if (mask && !(mask & poll->events))
5026 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5028 list_del_init(&poll->wait.entry);
5031 req->io_task_work.func = func;
5034 * If this fails, then the task is exiting. When a task exits, the
5035 * work gets canceled, so just cancel this request as well instead
5036 * of executing it. We can't safely execute it anyway, as we may not
5037 * have the needed state needed for it anyway.
5039 io_req_task_work_add(req);
5043 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5044 __acquires(&req->ctx->completion_lock)
5046 struct io_ring_ctx *ctx = req->ctx;
5048 /* req->task == current here, checking PF_EXITING is safe */
5049 if (unlikely(req->task->flags & PF_EXITING))
5050 WRITE_ONCE(poll->canceled, true);
5052 if (!req->result && !READ_ONCE(poll->canceled)) {
5053 struct poll_table_struct pt = { ._key = poll->events };
5055 req->result = vfs_poll(req->file, &pt) & poll->events;
5058 spin_lock(&ctx->completion_lock);
5059 if (!req->result && !READ_ONCE(poll->canceled)) {
5060 add_wait_queue(poll->head, &poll->wait);
5067 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5069 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5070 if (req->opcode == IORING_OP_POLL_ADD)
5071 return req->async_data;
5072 return req->apoll->double_poll;
5075 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5077 if (req->opcode == IORING_OP_POLL_ADD)
5079 return &req->apoll->poll;
5082 static void io_poll_remove_double(struct io_kiocb *req)
5083 __must_hold(&req->ctx->completion_lock)
5085 struct io_poll_iocb *poll = io_poll_get_double(req);
5087 lockdep_assert_held(&req->ctx->completion_lock);
5089 if (poll && poll->head) {
5090 struct wait_queue_head *head = poll->head;
5092 spin_lock_irq(&head->lock);
5093 list_del_init(&poll->wait.entry);
5094 if (poll->wait.private)
5097 spin_unlock_irq(&head->lock);
5101 static bool __io_poll_complete(struct io_kiocb *req, __poll_t mask)
5102 __must_hold(&req->ctx->completion_lock)
5104 struct io_ring_ctx *ctx = req->ctx;
5105 unsigned flags = IORING_CQE_F_MORE;
5108 if (READ_ONCE(req->poll.canceled)) {
5110 req->poll.events |= EPOLLONESHOT;
5112 error = mangle_poll(mask);
5114 if (req->poll.events & EPOLLONESHOT)
5116 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5117 req->poll.done = true;
5120 if (flags & IORING_CQE_F_MORE)
5123 return !(flags & IORING_CQE_F_MORE);
5126 static inline bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5127 __must_hold(&req->ctx->completion_lock)
5131 done = __io_poll_complete(req, mask);
5132 io_commit_cqring(req->ctx);
5136 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5138 struct io_ring_ctx *ctx = req->ctx;
5139 struct io_kiocb *nxt;
5141 if (io_poll_rewait(req, &req->poll)) {
5142 spin_unlock(&ctx->completion_lock);
5146 done = __io_poll_complete(req, req->result);
5148 io_poll_remove_double(req);
5149 hash_del(&req->hash_node);
5152 add_wait_queue(req->poll.head, &req->poll.wait);
5154 io_commit_cqring(ctx);
5155 spin_unlock(&ctx->completion_lock);
5156 io_cqring_ev_posted(ctx);
5159 nxt = io_put_req_find_next(req);
5161 io_req_task_submit(nxt, locked);
5166 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5167 int sync, void *key)
5169 struct io_kiocb *req = wait->private;
5170 struct io_poll_iocb *poll = io_poll_get_single(req);
5171 __poll_t mask = key_to_poll(key);
5172 unsigned long flags;
5174 /* for instances that support it check for an event match first: */
5175 if (mask && !(mask & poll->events))
5177 if (!(poll->events & EPOLLONESHOT))
5178 return poll->wait.func(&poll->wait, mode, sync, key);
5180 list_del_init(&wait->entry);
5185 spin_lock_irqsave(&poll->head->lock, flags);
5186 done = list_empty(&poll->wait.entry);
5188 list_del_init(&poll->wait.entry);
5189 /* make sure double remove sees this as being gone */
5190 wait->private = NULL;
5191 spin_unlock_irqrestore(&poll->head->lock, flags);
5193 /* use wait func handler, so it matches the rq type */
5194 poll->wait.func(&poll->wait, mode, sync, key);
5201 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5202 wait_queue_func_t wake_func)
5206 poll->canceled = false;
5207 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5208 /* mask in events that we always want/need */
5209 poll->events = events | IO_POLL_UNMASK;
5210 INIT_LIST_HEAD(&poll->wait.entry);
5211 init_waitqueue_func_entry(&poll->wait, wake_func);
5214 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5215 struct wait_queue_head *head,
5216 struct io_poll_iocb **poll_ptr)
5218 struct io_kiocb *req = pt->req;
5221 * The file being polled uses multiple waitqueues for poll handling
5222 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5225 if (unlikely(pt->nr_entries)) {
5226 struct io_poll_iocb *poll_one = poll;
5228 /* double add on the same waitqueue head, ignore */
5229 if (poll_one->head == head)
5231 /* already have a 2nd entry, fail a third attempt */
5233 if ((*poll_ptr)->head == head)
5235 pt->error = -EINVAL;
5239 * Can't handle multishot for double wait for now, turn it
5240 * into one-shot mode.
5242 if (!(poll_one->events & EPOLLONESHOT))
5243 poll_one->events |= EPOLLONESHOT;
5244 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5246 pt->error = -ENOMEM;
5249 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5251 poll->wait.private = req;
5258 if (poll->events & EPOLLEXCLUSIVE)
5259 add_wait_queue_exclusive(head, &poll->wait);
5261 add_wait_queue(head, &poll->wait);
5264 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5265 struct poll_table_struct *p)
5267 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5268 struct async_poll *apoll = pt->req->apoll;
5270 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5273 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5275 struct async_poll *apoll = req->apoll;
5276 struct io_ring_ctx *ctx = req->ctx;
5278 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5280 if (io_poll_rewait(req, &apoll->poll)) {
5281 spin_unlock(&ctx->completion_lock);
5285 hash_del(&req->hash_node);
5286 io_poll_remove_double(req);
5287 spin_unlock(&ctx->completion_lock);
5289 if (!READ_ONCE(apoll->poll.canceled))
5290 io_req_task_submit(req, locked);
5292 io_req_complete_failed(req, -ECANCELED);
5295 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5298 struct io_kiocb *req = wait->private;
5299 struct io_poll_iocb *poll = &req->apoll->poll;
5301 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5304 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5307 static void io_poll_req_insert(struct io_kiocb *req)
5309 struct io_ring_ctx *ctx = req->ctx;
5310 struct hlist_head *list;
5312 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5313 hlist_add_head(&req->hash_node, list);
5316 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5317 struct io_poll_iocb *poll,
5318 struct io_poll_table *ipt, __poll_t mask,
5319 wait_queue_func_t wake_func)
5320 __acquires(&ctx->completion_lock)
5322 struct io_ring_ctx *ctx = req->ctx;
5323 bool cancel = false;
5325 INIT_HLIST_NODE(&req->hash_node);
5326 io_init_poll_iocb(poll, mask, wake_func);
5327 poll->file = req->file;
5328 poll->wait.private = req;
5330 ipt->pt._key = mask;
5333 ipt->nr_entries = 0;
5335 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5336 if (unlikely(!ipt->nr_entries) && !ipt->error)
5337 ipt->error = -EINVAL;
5339 spin_lock(&ctx->completion_lock);
5340 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5341 io_poll_remove_double(req);
5342 if (likely(poll->head)) {
5343 spin_lock_irq(&poll->head->lock);
5344 if (unlikely(list_empty(&poll->wait.entry))) {
5350 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5351 list_del_init(&poll->wait.entry);
5353 WRITE_ONCE(poll->canceled, true);
5354 else if (!poll->done) /* actually waiting for an event */
5355 io_poll_req_insert(req);
5356 spin_unlock_irq(&poll->head->lock);
5368 static int io_arm_poll_handler(struct io_kiocb *req)
5370 const struct io_op_def *def = &io_op_defs[req->opcode];
5371 struct io_ring_ctx *ctx = req->ctx;
5372 struct async_poll *apoll;
5373 struct io_poll_table ipt;
5374 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5377 if (!req->file || !file_can_poll(req->file))
5378 return IO_APOLL_ABORTED;
5379 if (req->flags & REQ_F_POLLED)
5380 return IO_APOLL_ABORTED;
5381 if (!def->pollin && !def->pollout)
5382 return IO_APOLL_ABORTED;
5386 mask |= POLLIN | POLLRDNORM;
5388 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5389 if ((req->opcode == IORING_OP_RECVMSG) &&
5390 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5394 mask |= POLLOUT | POLLWRNORM;
5397 /* if we can't nonblock try, then no point in arming a poll handler */
5398 if (!io_file_supports_nowait(req, rw))
5399 return IO_APOLL_ABORTED;
5401 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5402 if (unlikely(!apoll))
5403 return IO_APOLL_ABORTED;
5404 apoll->double_poll = NULL;
5406 req->flags |= REQ_F_POLLED;
5407 ipt.pt._qproc = io_async_queue_proc;
5408 io_req_set_refcount(req);
5410 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5412 spin_unlock(&ctx->completion_lock);
5413 if (ret || ipt.error)
5414 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5416 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5417 mask, apoll->poll.events);
5421 static bool __io_poll_remove_one(struct io_kiocb *req,
5422 struct io_poll_iocb *poll, bool do_cancel)
5423 __must_hold(&req->ctx->completion_lock)
5425 bool do_complete = false;
5429 spin_lock_irq(&poll->head->lock);
5431 WRITE_ONCE(poll->canceled, true);
5432 if (!list_empty(&poll->wait.entry)) {
5433 list_del_init(&poll->wait.entry);
5436 spin_unlock_irq(&poll->head->lock);
5437 hash_del(&req->hash_node);
5441 static bool io_poll_remove_one(struct io_kiocb *req)
5442 __must_hold(&req->ctx->completion_lock)
5446 io_poll_remove_double(req);
5447 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5450 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5451 io_commit_cqring(req->ctx);
5453 io_put_req_deferred(req);
5459 * Returns true if we found and killed one or more poll requests
5461 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5464 struct hlist_node *tmp;
5465 struct io_kiocb *req;
5468 spin_lock(&ctx->completion_lock);
5469 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5470 struct hlist_head *list;
5472 list = &ctx->cancel_hash[i];
5473 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5474 if (io_match_task(req, tsk, cancel_all))
5475 posted += io_poll_remove_one(req);
5478 spin_unlock(&ctx->completion_lock);
5481 io_cqring_ev_posted(ctx);
5486 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5488 __must_hold(&ctx->completion_lock)
5490 struct hlist_head *list;
5491 struct io_kiocb *req;
5493 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5494 hlist_for_each_entry(req, list, hash_node) {
5495 if (sqe_addr != req->user_data)
5497 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5504 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5506 __must_hold(&ctx->completion_lock)
5508 struct io_kiocb *req;
5510 req = io_poll_find(ctx, sqe_addr, poll_only);
5513 if (io_poll_remove_one(req))
5519 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5524 events = READ_ONCE(sqe->poll32_events);
5526 events = swahw32(events);
5528 if (!(flags & IORING_POLL_ADD_MULTI))
5529 events |= EPOLLONESHOT;
5530 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5533 static int io_poll_update_prep(struct io_kiocb *req,
5534 const struct io_uring_sqe *sqe)
5536 struct io_poll_update *upd = &req->poll_update;
5539 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5541 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5543 flags = READ_ONCE(sqe->len);
5544 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5545 IORING_POLL_ADD_MULTI))
5547 /* meaningless without update */
5548 if (flags == IORING_POLL_ADD_MULTI)
5551 upd->old_user_data = READ_ONCE(sqe->addr);
5552 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5553 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5555 upd->new_user_data = READ_ONCE(sqe->off);
5556 if (!upd->update_user_data && upd->new_user_data)
5558 if (upd->update_events)
5559 upd->events = io_poll_parse_events(sqe, flags);
5560 else if (sqe->poll32_events)
5566 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5569 struct io_kiocb *req = wait->private;
5570 struct io_poll_iocb *poll = &req->poll;
5572 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5575 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5576 struct poll_table_struct *p)
5578 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5580 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5583 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5585 struct io_poll_iocb *poll = &req->poll;
5588 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5590 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5592 flags = READ_ONCE(sqe->len);
5593 if (flags & ~IORING_POLL_ADD_MULTI)
5596 io_req_set_refcount(req);
5597 poll->events = io_poll_parse_events(sqe, flags);
5601 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5603 struct io_poll_iocb *poll = &req->poll;
5604 struct io_ring_ctx *ctx = req->ctx;
5605 struct io_poll_table ipt;
5608 ipt.pt._qproc = io_poll_queue_proc;
5610 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5613 if (mask) { /* no async, we'd stolen it */
5615 io_poll_complete(req, mask);
5617 spin_unlock(&ctx->completion_lock);
5620 io_cqring_ev_posted(ctx);
5621 if (poll->events & EPOLLONESHOT)
5627 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5629 struct io_ring_ctx *ctx = req->ctx;
5630 struct io_kiocb *preq;
5634 spin_lock(&ctx->completion_lock);
5635 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5641 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5643 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5648 * Don't allow racy completion with singleshot, as we cannot safely
5649 * update those. For multishot, if we're racing with completion, just
5650 * let completion re-add it.
5652 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5653 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5657 /* we now have a detached poll request. reissue. */
5661 spin_unlock(&ctx->completion_lock);
5663 io_req_complete(req, ret);
5666 /* only mask one event flags, keep behavior flags */
5667 if (req->poll_update.update_events) {
5668 preq->poll.events &= ~0xffff;
5669 preq->poll.events |= req->poll_update.events & 0xffff;
5670 preq->poll.events |= IO_POLL_UNMASK;
5672 if (req->poll_update.update_user_data)
5673 preq->user_data = req->poll_update.new_user_data;
5674 spin_unlock(&ctx->completion_lock);
5676 /* complete update request, we're done with it */
5677 io_req_complete(req, ret);
5680 ret = io_poll_add(preq, issue_flags);
5683 io_req_complete(preq, ret);
5689 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5692 io_req_complete_post(req, -ETIME, 0);
5695 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5697 struct io_timeout_data *data = container_of(timer,
5698 struct io_timeout_data, timer);
5699 struct io_kiocb *req = data->req;
5700 struct io_ring_ctx *ctx = req->ctx;
5701 unsigned long flags;
5703 spin_lock_irqsave(&ctx->timeout_lock, flags);
5704 list_del_init(&req->timeout.list);
5705 atomic_set(&req->ctx->cq_timeouts,
5706 atomic_read(&req->ctx->cq_timeouts) + 1);
5707 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5709 req->io_task_work.func = io_req_task_timeout;
5710 io_req_task_work_add(req);
5711 return HRTIMER_NORESTART;
5714 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5716 __must_hold(&ctx->timeout_lock)
5718 struct io_timeout_data *io;
5719 struct io_kiocb *req;
5722 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5723 found = user_data == req->user_data;
5728 return ERR_PTR(-ENOENT);
5730 io = req->async_data;
5731 if (hrtimer_try_to_cancel(&io->timer) == -1)
5732 return ERR_PTR(-EALREADY);
5733 list_del_init(&req->timeout.list);
5737 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5738 __must_hold(&ctx->completion_lock)
5739 __must_hold(&ctx->timeout_lock)
5741 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5744 return PTR_ERR(req);
5747 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5748 io_put_req_deferred(req);
5752 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5754 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5755 case IORING_TIMEOUT_BOOTTIME:
5756 return CLOCK_BOOTTIME;
5757 case IORING_TIMEOUT_REALTIME:
5758 return CLOCK_REALTIME;
5760 /* can't happen, vetted at prep time */
5764 return CLOCK_MONOTONIC;
5768 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5769 struct timespec64 *ts, enum hrtimer_mode mode)
5770 __must_hold(&ctx->timeout_lock)
5772 struct io_timeout_data *io;
5773 struct io_kiocb *req;
5776 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5777 found = user_data == req->user_data;
5784 io = req->async_data;
5785 if (hrtimer_try_to_cancel(&io->timer) == -1)
5787 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5788 io->timer.function = io_link_timeout_fn;
5789 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5793 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5794 struct timespec64 *ts, enum hrtimer_mode mode)
5795 __must_hold(&ctx->timeout_lock)
5797 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5798 struct io_timeout_data *data;
5801 return PTR_ERR(req);
5803 req->timeout.off = 0; /* noseq */
5804 data = req->async_data;
5805 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5806 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5807 data->timer.function = io_timeout_fn;
5808 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5812 static int io_timeout_remove_prep(struct io_kiocb *req,
5813 const struct io_uring_sqe *sqe)
5815 struct io_timeout_rem *tr = &req->timeout_rem;
5817 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5819 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5821 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5824 tr->ltimeout = false;
5825 tr->addr = READ_ONCE(sqe->addr);
5826 tr->flags = READ_ONCE(sqe->timeout_flags);
5827 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5828 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5830 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5831 tr->ltimeout = true;
5832 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5834 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5836 } else if (tr->flags) {
5837 /* timeout removal doesn't support flags */
5844 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5846 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5851 * Remove or update an existing timeout command
5853 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5855 struct io_timeout_rem *tr = &req->timeout_rem;
5856 struct io_ring_ctx *ctx = req->ctx;
5859 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5860 spin_lock(&ctx->completion_lock);
5861 spin_lock_irq(&ctx->timeout_lock);
5862 ret = io_timeout_cancel(ctx, tr->addr);
5863 spin_unlock_irq(&ctx->timeout_lock);
5864 spin_unlock(&ctx->completion_lock);
5866 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
5868 spin_lock_irq(&ctx->timeout_lock);
5870 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
5872 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
5873 spin_unlock_irq(&ctx->timeout_lock);
5878 io_req_complete_post(req, ret, 0);
5882 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5883 bool is_timeout_link)
5885 struct io_timeout_data *data;
5887 u32 off = READ_ONCE(sqe->off);
5889 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5891 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5894 if (off && is_timeout_link)
5896 flags = READ_ONCE(sqe->timeout_flags);
5897 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
5899 /* more than one clock specified is invalid, obviously */
5900 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5903 INIT_LIST_HEAD(&req->timeout.list);
5904 req->timeout.off = off;
5905 if (unlikely(off && !req->ctx->off_timeout_used))
5906 req->ctx->off_timeout_used = true;
5908 if (!req->async_data && io_alloc_async_data(req))
5911 data = req->async_data;
5913 data->flags = flags;
5915 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5918 data->mode = io_translate_timeout_mode(flags);
5919 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
5921 if (is_timeout_link) {
5922 struct io_submit_link *link = &req->ctx->submit_state.link;
5926 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5928 req->timeout.head = link->last;
5929 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5934 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5936 struct io_ring_ctx *ctx = req->ctx;
5937 struct io_timeout_data *data = req->async_data;
5938 struct list_head *entry;
5939 u32 tail, off = req->timeout.off;
5941 spin_lock_irq(&ctx->timeout_lock);
5944 * sqe->off holds how many events that need to occur for this
5945 * timeout event to be satisfied. If it isn't set, then this is
5946 * a pure timeout request, sequence isn't used.
5948 if (io_is_timeout_noseq(req)) {
5949 entry = ctx->timeout_list.prev;
5953 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5954 req->timeout.target_seq = tail + off;
5956 /* Update the last seq here in case io_flush_timeouts() hasn't.
5957 * This is safe because ->completion_lock is held, and submissions
5958 * and completions are never mixed in the same ->completion_lock section.
5960 ctx->cq_last_tm_flush = tail;
5963 * Insertion sort, ensuring the first entry in the list is always
5964 * the one we need first.
5966 list_for_each_prev(entry, &ctx->timeout_list) {
5967 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5970 if (io_is_timeout_noseq(nxt))
5972 /* nxt.seq is behind @tail, otherwise would've been completed */
5973 if (off >= nxt->timeout.target_seq - tail)
5977 list_add(&req->timeout.list, entry);
5978 data->timer.function = io_timeout_fn;
5979 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5980 spin_unlock_irq(&ctx->timeout_lock);
5984 struct io_cancel_data {
5985 struct io_ring_ctx *ctx;
5989 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5991 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5992 struct io_cancel_data *cd = data;
5994 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5997 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5998 struct io_ring_ctx *ctx)
6000 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6001 enum io_wq_cancel cancel_ret;
6004 if (!tctx || !tctx->io_wq)
6007 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6008 switch (cancel_ret) {
6009 case IO_WQ_CANCEL_OK:
6012 case IO_WQ_CANCEL_RUNNING:
6015 case IO_WQ_CANCEL_NOTFOUND:
6023 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6025 struct io_ring_ctx *ctx = req->ctx;
6028 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6030 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6034 spin_lock(&ctx->completion_lock);
6035 spin_lock_irq(&ctx->timeout_lock);
6036 ret = io_timeout_cancel(ctx, sqe_addr);
6037 spin_unlock_irq(&ctx->timeout_lock);
6040 ret = io_poll_cancel(ctx, sqe_addr, false);
6042 spin_unlock(&ctx->completion_lock);
6046 static int io_async_cancel_prep(struct io_kiocb *req,
6047 const struct io_uring_sqe *sqe)
6049 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6051 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6053 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6057 req->cancel.addr = READ_ONCE(sqe->addr);
6061 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6063 struct io_ring_ctx *ctx = req->ctx;
6064 u64 sqe_addr = req->cancel.addr;
6065 struct io_tctx_node *node;
6068 ret = io_try_cancel_userdata(req, sqe_addr);
6072 /* slow path, try all io-wq's */
6073 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6075 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6076 struct io_uring_task *tctx = node->task->io_uring;
6078 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6082 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6086 io_req_complete_post(req, ret, 0);
6090 static int io_rsrc_update_prep(struct io_kiocb *req,
6091 const struct io_uring_sqe *sqe)
6093 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6095 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6098 req->rsrc_update.offset = READ_ONCE(sqe->off);
6099 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6100 if (!req->rsrc_update.nr_args)
6102 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6106 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6108 struct io_ring_ctx *ctx = req->ctx;
6109 struct io_uring_rsrc_update2 up;
6112 if (issue_flags & IO_URING_F_NONBLOCK)
6115 up.offset = req->rsrc_update.offset;
6116 up.data = req->rsrc_update.arg;
6121 mutex_lock(&ctx->uring_lock);
6122 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6123 &up, req->rsrc_update.nr_args);
6124 mutex_unlock(&ctx->uring_lock);
6128 __io_req_complete(req, issue_flags, ret, 0);
6132 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6134 switch (req->opcode) {
6137 case IORING_OP_READV:
6138 case IORING_OP_READ_FIXED:
6139 case IORING_OP_READ:
6140 return io_read_prep(req, sqe);
6141 case IORING_OP_WRITEV:
6142 case IORING_OP_WRITE_FIXED:
6143 case IORING_OP_WRITE:
6144 return io_write_prep(req, sqe);
6145 case IORING_OP_POLL_ADD:
6146 return io_poll_add_prep(req, sqe);
6147 case IORING_OP_POLL_REMOVE:
6148 return io_poll_update_prep(req, sqe);
6149 case IORING_OP_FSYNC:
6150 return io_fsync_prep(req, sqe);
6151 case IORING_OP_SYNC_FILE_RANGE:
6152 return io_sfr_prep(req, sqe);
6153 case IORING_OP_SENDMSG:
6154 case IORING_OP_SEND:
6155 return io_sendmsg_prep(req, sqe);
6156 case IORING_OP_RECVMSG:
6157 case IORING_OP_RECV:
6158 return io_recvmsg_prep(req, sqe);
6159 case IORING_OP_CONNECT:
6160 return io_connect_prep(req, sqe);
6161 case IORING_OP_TIMEOUT:
6162 return io_timeout_prep(req, sqe, false);
6163 case IORING_OP_TIMEOUT_REMOVE:
6164 return io_timeout_remove_prep(req, sqe);
6165 case IORING_OP_ASYNC_CANCEL:
6166 return io_async_cancel_prep(req, sqe);
6167 case IORING_OP_LINK_TIMEOUT:
6168 return io_timeout_prep(req, sqe, true);
6169 case IORING_OP_ACCEPT:
6170 return io_accept_prep(req, sqe);
6171 case IORING_OP_FALLOCATE:
6172 return io_fallocate_prep(req, sqe);
6173 case IORING_OP_OPENAT:
6174 return io_openat_prep(req, sqe);
6175 case IORING_OP_CLOSE:
6176 return io_close_prep(req, sqe);
6177 case IORING_OP_FILES_UPDATE:
6178 return io_rsrc_update_prep(req, sqe);
6179 case IORING_OP_STATX:
6180 return io_statx_prep(req, sqe);
6181 case IORING_OP_FADVISE:
6182 return io_fadvise_prep(req, sqe);
6183 case IORING_OP_MADVISE:
6184 return io_madvise_prep(req, sqe);
6185 case IORING_OP_OPENAT2:
6186 return io_openat2_prep(req, sqe);
6187 case IORING_OP_EPOLL_CTL:
6188 return io_epoll_ctl_prep(req, sqe);
6189 case IORING_OP_SPLICE:
6190 return io_splice_prep(req, sqe);
6191 case IORING_OP_PROVIDE_BUFFERS:
6192 return io_provide_buffers_prep(req, sqe);
6193 case IORING_OP_REMOVE_BUFFERS:
6194 return io_remove_buffers_prep(req, sqe);
6196 return io_tee_prep(req, sqe);
6197 case IORING_OP_SHUTDOWN:
6198 return io_shutdown_prep(req, sqe);
6199 case IORING_OP_RENAMEAT:
6200 return io_renameat_prep(req, sqe);
6201 case IORING_OP_UNLINKAT:
6202 return io_unlinkat_prep(req, sqe);
6205 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6210 static int io_req_prep_async(struct io_kiocb *req)
6212 if (!io_op_defs[req->opcode].needs_async_setup)
6214 if (WARN_ON_ONCE(req->async_data))
6216 if (io_alloc_async_data(req))
6219 switch (req->opcode) {
6220 case IORING_OP_READV:
6221 return io_rw_prep_async(req, READ);
6222 case IORING_OP_WRITEV:
6223 return io_rw_prep_async(req, WRITE);
6224 case IORING_OP_SENDMSG:
6225 return io_sendmsg_prep_async(req);
6226 case IORING_OP_RECVMSG:
6227 return io_recvmsg_prep_async(req);
6228 case IORING_OP_CONNECT:
6229 return io_connect_prep_async(req);
6231 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6236 static u32 io_get_sequence(struct io_kiocb *req)
6238 u32 seq = req->ctx->cached_sq_head;
6240 /* need original cached_sq_head, but it was increased for each req */
6241 io_for_each_link(req, req)
6246 static bool io_drain_req(struct io_kiocb *req)
6248 struct io_kiocb *pos;
6249 struct io_ring_ctx *ctx = req->ctx;
6250 struct io_defer_entry *de;
6254 if (req->flags & REQ_F_FAIL) {
6255 io_req_complete_fail_submit(req);
6260 * If we need to drain a request in the middle of a link, drain the
6261 * head request and the next request/link after the current link.
6262 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6263 * maintained for every request of our link.
6265 if (ctx->drain_next) {
6266 req->flags |= REQ_F_IO_DRAIN;
6267 ctx->drain_next = false;
6269 /* not interested in head, start from the first linked */
6270 io_for_each_link(pos, req->link) {
6271 if (pos->flags & REQ_F_IO_DRAIN) {
6272 ctx->drain_next = true;
6273 req->flags |= REQ_F_IO_DRAIN;
6278 /* Still need defer if there is pending req in defer list. */
6279 if (likely(list_empty_careful(&ctx->defer_list) &&
6280 !(req->flags & REQ_F_IO_DRAIN))) {
6281 ctx->drain_active = false;
6285 seq = io_get_sequence(req);
6286 /* Still a chance to pass the sequence check */
6287 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6290 ret = io_req_prep_async(req);
6293 io_prep_async_link(req);
6294 de = kmalloc(sizeof(*de), GFP_KERNEL);
6298 io_req_complete_failed(req, ret);
6302 spin_lock(&ctx->completion_lock);
6303 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6304 spin_unlock(&ctx->completion_lock);
6306 io_queue_async_work(req, NULL);
6310 trace_io_uring_defer(ctx, req, req->user_data);
6313 list_add_tail(&de->list, &ctx->defer_list);
6314 spin_unlock(&ctx->completion_lock);
6318 static void io_clean_op(struct io_kiocb *req)
6320 if (req->flags & REQ_F_BUFFER_SELECTED) {
6321 switch (req->opcode) {
6322 case IORING_OP_READV:
6323 case IORING_OP_READ_FIXED:
6324 case IORING_OP_READ:
6325 kfree((void *)(unsigned long)req->rw.addr);
6327 case IORING_OP_RECVMSG:
6328 case IORING_OP_RECV:
6329 kfree(req->sr_msg.kbuf);
6334 if (req->flags & REQ_F_NEED_CLEANUP) {
6335 switch (req->opcode) {
6336 case IORING_OP_READV:
6337 case IORING_OP_READ_FIXED:
6338 case IORING_OP_READ:
6339 case IORING_OP_WRITEV:
6340 case IORING_OP_WRITE_FIXED:
6341 case IORING_OP_WRITE: {
6342 struct io_async_rw *io = req->async_data;
6344 kfree(io->free_iovec);
6347 case IORING_OP_RECVMSG:
6348 case IORING_OP_SENDMSG: {
6349 struct io_async_msghdr *io = req->async_data;
6351 kfree(io->free_iov);
6354 case IORING_OP_SPLICE:
6356 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6357 io_put_file(req->splice.file_in);
6359 case IORING_OP_OPENAT:
6360 case IORING_OP_OPENAT2:
6361 if (req->open.filename)
6362 putname(req->open.filename);
6364 case IORING_OP_RENAMEAT:
6365 putname(req->rename.oldpath);
6366 putname(req->rename.newpath);
6368 case IORING_OP_UNLINKAT:
6369 putname(req->unlink.filename);
6373 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6374 kfree(req->apoll->double_poll);
6378 if (req->flags & REQ_F_INFLIGHT) {
6379 struct io_uring_task *tctx = req->task->io_uring;
6381 atomic_dec(&tctx->inflight_tracked);
6383 if (req->flags & REQ_F_CREDS)
6384 put_cred(req->creds);
6386 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6389 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6391 struct io_ring_ctx *ctx = req->ctx;
6392 const struct cred *creds = NULL;
6395 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6396 creds = override_creds(req->creds);
6398 switch (req->opcode) {
6400 ret = io_nop(req, issue_flags);
6402 case IORING_OP_READV:
6403 case IORING_OP_READ_FIXED:
6404 case IORING_OP_READ:
6405 ret = io_read(req, issue_flags);
6407 case IORING_OP_WRITEV:
6408 case IORING_OP_WRITE_FIXED:
6409 case IORING_OP_WRITE:
6410 ret = io_write(req, issue_flags);
6412 case IORING_OP_FSYNC:
6413 ret = io_fsync(req, issue_flags);
6415 case IORING_OP_POLL_ADD:
6416 ret = io_poll_add(req, issue_flags);
6418 case IORING_OP_POLL_REMOVE:
6419 ret = io_poll_update(req, issue_flags);
6421 case IORING_OP_SYNC_FILE_RANGE:
6422 ret = io_sync_file_range(req, issue_flags);
6424 case IORING_OP_SENDMSG:
6425 ret = io_sendmsg(req, issue_flags);
6427 case IORING_OP_SEND:
6428 ret = io_send(req, issue_flags);
6430 case IORING_OP_RECVMSG:
6431 ret = io_recvmsg(req, issue_flags);
6433 case IORING_OP_RECV:
6434 ret = io_recv(req, issue_flags);
6436 case IORING_OP_TIMEOUT:
6437 ret = io_timeout(req, issue_flags);
6439 case IORING_OP_TIMEOUT_REMOVE:
6440 ret = io_timeout_remove(req, issue_flags);
6442 case IORING_OP_ACCEPT:
6443 ret = io_accept(req, issue_flags);
6445 case IORING_OP_CONNECT:
6446 ret = io_connect(req, issue_flags);
6448 case IORING_OP_ASYNC_CANCEL:
6449 ret = io_async_cancel(req, issue_flags);
6451 case IORING_OP_FALLOCATE:
6452 ret = io_fallocate(req, issue_flags);
6454 case IORING_OP_OPENAT:
6455 ret = io_openat(req, issue_flags);
6457 case IORING_OP_CLOSE:
6458 ret = io_close(req, issue_flags);
6460 case IORING_OP_FILES_UPDATE:
6461 ret = io_files_update(req, issue_flags);
6463 case IORING_OP_STATX:
6464 ret = io_statx(req, issue_flags);
6466 case IORING_OP_FADVISE:
6467 ret = io_fadvise(req, issue_flags);
6469 case IORING_OP_MADVISE:
6470 ret = io_madvise(req, issue_flags);
6472 case IORING_OP_OPENAT2:
6473 ret = io_openat2(req, issue_flags);
6475 case IORING_OP_EPOLL_CTL:
6476 ret = io_epoll_ctl(req, issue_flags);
6478 case IORING_OP_SPLICE:
6479 ret = io_splice(req, issue_flags);
6481 case IORING_OP_PROVIDE_BUFFERS:
6482 ret = io_provide_buffers(req, issue_flags);
6484 case IORING_OP_REMOVE_BUFFERS:
6485 ret = io_remove_buffers(req, issue_flags);
6488 ret = io_tee(req, issue_flags);
6490 case IORING_OP_SHUTDOWN:
6491 ret = io_shutdown(req, issue_flags);
6493 case IORING_OP_RENAMEAT:
6494 ret = io_renameat(req, issue_flags);
6496 case IORING_OP_UNLINKAT:
6497 ret = io_unlinkat(req, issue_flags);
6505 revert_creds(creds);
6508 /* If the op doesn't have a file, we're not polling for it */
6509 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6510 io_iopoll_req_issued(req);
6515 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6517 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6519 req = io_put_req_find_next(req);
6520 return req ? &req->work : NULL;
6523 static void io_wq_submit_work(struct io_wq_work *work)
6525 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6526 struct io_kiocb *timeout;
6529 /* one will be dropped by ->io_free_work() after returning to io-wq */
6530 if (!(req->flags & REQ_F_REFCOUNT))
6531 __io_req_set_refcount(req, 2);
6535 timeout = io_prep_linked_timeout(req);
6537 io_queue_linked_timeout(timeout);
6539 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6540 if (work->flags & IO_WQ_WORK_CANCEL)
6545 ret = io_issue_sqe(req, 0);
6547 * We can get EAGAIN for polled IO even though we're
6548 * forcing a sync submission from here, since we can't
6549 * wait for request slots on the block side.
6557 /* avoid locking problems by failing it from a clean context */
6559 io_req_task_queue_fail(req, ret);
6562 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6565 return &table->files[i];
6568 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6571 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6573 return (struct file *) (slot->file_ptr & FFS_MASK);
6576 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6578 unsigned long file_ptr = (unsigned long) file;
6580 if (__io_file_supports_nowait(file, READ))
6581 file_ptr |= FFS_ASYNC_READ;
6582 if (__io_file_supports_nowait(file, WRITE))
6583 file_ptr |= FFS_ASYNC_WRITE;
6584 if (S_ISREG(file_inode(file)->i_mode))
6585 file_ptr |= FFS_ISREG;
6586 file_slot->file_ptr = file_ptr;
6589 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6590 struct io_kiocb *req, int fd)
6593 unsigned long file_ptr;
6595 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6597 fd = array_index_nospec(fd, ctx->nr_user_files);
6598 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6599 file = (struct file *) (file_ptr & FFS_MASK);
6600 file_ptr &= ~FFS_MASK;
6601 /* mask in overlapping REQ_F and FFS bits */
6602 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6603 io_req_set_rsrc_node(req);
6607 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6608 struct io_kiocb *req, int fd)
6610 struct file *file = fget(fd);
6612 trace_io_uring_file_get(ctx, fd);
6614 /* we don't allow fixed io_uring files */
6615 if (file && unlikely(file->f_op == &io_uring_fops))
6616 io_req_track_inflight(req);
6620 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6621 struct io_kiocb *req, int fd, bool fixed)
6624 return io_file_get_fixed(ctx, req, fd);
6626 return io_file_get_normal(ctx, req, fd);
6629 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6631 struct io_kiocb *prev = req->timeout.prev;
6635 ret = io_try_cancel_userdata(req, prev->user_data);
6636 io_req_complete_post(req, ret ?: -ETIME, 0);
6639 io_req_complete_post(req, -ETIME, 0);
6643 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6645 struct io_timeout_data *data = container_of(timer,
6646 struct io_timeout_data, timer);
6647 struct io_kiocb *prev, *req = data->req;
6648 struct io_ring_ctx *ctx = req->ctx;
6649 unsigned long flags;
6651 spin_lock_irqsave(&ctx->timeout_lock, flags);
6652 prev = req->timeout.head;
6653 req->timeout.head = NULL;
6656 * We don't expect the list to be empty, that will only happen if we
6657 * race with the completion of the linked work.
6660 io_remove_next_linked(prev);
6661 if (!req_ref_inc_not_zero(prev))
6664 list_del(&req->timeout.list);
6665 req->timeout.prev = prev;
6666 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6668 req->io_task_work.func = io_req_task_link_timeout;
6669 io_req_task_work_add(req);
6670 return HRTIMER_NORESTART;
6673 static void io_queue_linked_timeout(struct io_kiocb *req)
6675 struct io_ring_ctx *ctx = req->ctx;
6677 spin_lock_irq(&ctx->timeout_lock);
6679 * If the back reference is NULL, then our linked request finished
6680 * before we got a chance to setup the timer
6682 if (req->timeout.head) {
6683 struct io_timeout_data *data = req->async_data;
6685 data->timer.function = io_link_timeout_fn;
6686 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6688 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6690 spin_unlock_irq(&ctx->timeout_lock);
6691 /* drop submission reference */
6695 static void __io_queue_sqe(struct io_kiocb *req)
6696 __must_hold(&req->ctx->uring_lock)
6698 struct io_kiocb *linked_timeout;
6702 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6705 * We async punt it if the file wasn't marked NOWAIT, or if the file
6706 * doesn't support non-blocking read/write attempts
6709 if (req->flags & REQ_F_COMPLETE_INLINE) {
6710 struct io_ring_ctx *ctx = req->ctx;
6711 struct io_submit_state *state = &ctx->submit_state;
6713 state->compl_reqs[state->compl_nr++] = req;
6714 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6715 io_submit_flush_completions(ctx);
6719 linked_timeout = io_prep_linked_timeout(req);
6721 io_queue_linked_timeout(linked_timeout);
6722 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6723 linked_timeout = io_prep_linked_timeout(req);
6725 switch (io_arm_poll_handler(req)) {
6726 case IO_APOLL_READY:
6728 io_unprep_linked_timeout(req);
6730 case IO_APOLL_ABORTED:
6732 * Queued up for async execution, worker will release
6733 * submit reference when the iocb is actually submitted.
6735 io_queue_async_work(req, NULL);
6740 io_queue_linked_timeout(linked_timeout);
6742 io_req_complete_failed(req, ret);
6746 static inline void io_queue_sqe(struct io_kiocb *req)
6747 __must_hold(&req->ctx->uring_lock)
6749 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6752 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6753 __io_queue_sqe(req);
6754 } else if (req->flags & REQ_F_FAIL) {
6755 io_req_complete_fail_submit(req);
6757 int ret = io_req_prep_async(req);
6760 io_req_complete_failed(req, ret);
6762 io_queue_async_work(req, NULL);
6767 * Check SQE restrictions (opcode and flags).
6769 * Returns 'true' if SQE is allowed, 'false' otherwise.
6771 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6772 struct io_kiocb *req,
6773 unsigned int sqe_flags)
6775 if (likely(!ctx->restricted))
6778 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6781 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6782 ctx->restrictions.sqe_flags_required)
6785 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6786 ctx->restrictions.sqe_flags_required))
6792 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6793 const struct io_uring_sqe *sqe)
6794 __must_hold(&ctx->uring_lock)
6796 struct io_submit_state *state;
6797 unsigned int sqe_flags;
6798 int personality, ret = 0;
6800 /* req is partially pre-initialised, see io_preinit_req() */
6801 req->opcode = READ_ONCE(sqe->opcode);
6802 /* same numerical values with corresponding REQ_F_*, safe to copy */
6803 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6804 req->user_data = READ_ONCE(sqe->user_data);
6806 req->fixed_rsrc_refs = NULL;
6807 req->task = current;
6809 /* enforce forwards compatibility on users */
6810 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6812 if (unlikely(req->opcode >= IORING_OP_LAST))
6814 if (!io_check_restriction(ctx, req, sqe_flags))
6817 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6818 !io_op_defs[req->opcode].buffer_select)
6820 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6821 ctx->drain_active = true;
6823 personality = READ_ONCE(sqe->personality);
6825 req->creds = xa_load(&ctx->personalities, personality);
6828 get_cred(req->creds);
6829 req->flags |= REQ_F_CREDS;
6831 state = &ctx->submit_state;
6834 * Plug now if we have more than 1 IO left after this, and the target
6835 * is potentially a read/write to block based storage.
6837 if (!state->plug_started && state->ios_left > 1 &&
6838 io_op_defs[req->opcode].plug) {
6839 blk_start_plug(&state->plug);
6840 state->plug_started = true;
6843 if (io_op_defs[req->opcode].needs_file) {
6844 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6845 (sqe_flags & IOSQE_FIXED_FILE));
6846 if (unlikely(!req->file))
6854 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6855 const struct io_uring_sqe *sqe)
6856 __must_hold(&ctx->uring_lock)
6858 struct io_submit_link *link = &ctx->submit_state.link;
6861 ret = io_init_req(ctx, req, sqe);
6862 if (unlikely(ret)) {
6864 /* fail even hard links since we don't submit */
6867 * we can judge a link req is failed or cancelled by if
6868 * REQ_F_FAIL is set, but the head is an exception since
6869 * it may be set REQ_F_FAIL because of other req's failure
6870 * so let's leverage req->result to distinguish if a head
6871 * is set REQ_F_FAIL because of its failure or other req's
6872 * failure so that we can set the correct ret code for it.
6873 * init result here to avoid affecting the normal path.
6875 if (!(link->head->flags & REQ_F_FAIL))
6876 req_fail_link_node(link->head, -ECANCELED);
6877 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6879 * the current req is a normal req, we should return
6880 * error and thus break the submittion loop.
6882 io_req_complete_failed(req, ret);
6885 req_fail_link_node(req, ret);
6887 ret = io_req_prep(req, sqe);
6892 /* don't need @sqe from now on */
6893 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6895 ctx->flags & IORING_SETUP_SQPOLL);
6898 * If we already have a head request, queue this one for async
6899 * submittal once the head completes. If we don't have a head but
6900 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6901 * submitted sync once the chain is complete. If none of those
6902 * conditions are true (normal request), then just queue it.
6905 struct io_kiocb *head = link->head;
6907 if (!(req->flags & REQ_F_FAIL)) {
6908 ret = io_req_prep_async(req);
6909 if (unlikely(ret)) {
6910 req_fail_link_node(req, ret);
6911 if (!(head->flags & REQ_F_FAIL))
6912 req_fail_link_node(head, -ECANCELED);
6915 trace_io_uring_link(ctx, req, head);
6916 link->last->link = req;
6919 /* last request of a link, enqueue the link */
6920 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6925 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6937 * Batched submission is done, ensure local IO is flushed out.
6939 static void io_submit_state_end(struct io_submit_state *state,
6940 struct io_ring_ctx *ctx)
6942 if (state->link.head)
6943 io_queue_sqe(state->link.head);
6944 if (state->compl_nr)
6945 io_submit_flush_completions(ctx);
6946 if (state->plug_started)
6947 blk_finish_plug(&state->plug);
6951 * Start submission side cache.
6953 static void io_submit_state_start(struct io_submit_state *state,
6954 unsigned int max_ios)
6956 state->plug_started = false;
6957 state->ios_left = max_ios;
6958 /* set only head, no need to init link_last in advance */
6959 state->link.head = NULL;
6962 static void io_commit_sqring(struct io_ring_ctx *ctx)
6964 struct io_rings *rings = ctx->rings;
6967 * Ensure any loads from the SQEs are done at this point,
6968 * since once we write the new head, the application could
6969 * write new data to them.
6971 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6975 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6976 * that is mapped by userspace. This means that care needs to be taken to
6977 * ensure that reads are stable, as we cannot rely on userspace always
6978 * being a good citizen. If members of the sqe are validated and then later
6979 * used, it's important that those reads are done through READ_ONCE() to
6980 * prevent a re-load down the line.
6982 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6984 unsigned head, mask = ctx->sq_entries - 1;
6985 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6988 * The cached sq head (or cq tail) serves two purposes:
6990 * 1) allows us to batch the cost of updating the user visible
6992 * 2) allows the kernel side to track the head on its own, even
6993 * though the application is the one updating it.
6995 head = READ_ONCE(ctx->sq_array[sq_idx]);
6996 if (likely(head < ctx->sq_entries))
6997 return &ctx->sq_sqes[head];
6999 /* drop invalid entries */
7001 WRITE_ONCE(ctx->rings->sq_dropped,
7002 READ_ONCE(ctx->rings->sq_dropped) + 1);
7006 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7007 __must_hold(&ctx->uring_lock)
7011 /* make sure SQ entry isn't read before tail */
7012 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7013 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7015 io_get_task_refs(nr);
7017 io_submit_state_start(&ctx->submit_state, nr);
7018 while (submitted < nr) {
7019 const struct io_uring_sqe *sqe;
7020 struct io_kiocb *req;
7022 req = io_alloc_req(ctx);
7023 if (unlikely(!req)) {
7025 submitted = -EAGAIN;
7028 sqe = io_get_sqe(ctx);
7029 if (unlikely(!sqe)) {
7030 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7033 /* will complete beyond this point, count as submitted */
7035 if (io_submit_sqe(ctx, req, sqe))
7039 if (unlikely(submitted != nr)) {
7040 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7041 int unused = nr - ref_used;
7043 current->io_uring->cached_refs += unused;
7044 percpu_ref_put_many(&ctx->refs, unused);
7047 io_submit_state_end(&ctx->submit_state, ctx);
7048 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7049 io_commit_sqring(ctx);
7054 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7056 return READ_ONCE(sqd->state);
7059 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7061 /* Tell userspace we may need a wakeup call */
7062 spin_lock(&ctx->completion_lock);
7063 WRITE_ONCE(ctx->rings->sq_flags,
7064 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7065 spin_unlock(&ctx->completion_lock);
7068 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7070 spin_lock(&ctx->completion_lock);
7071 WRITE_ONCE(ctx->rings->sq_flags,
7072 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7073 spin_unlock(&ctx->completion_lock);
7076 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7078 unsigned int to_submit;
7081 to_submit = io_sqring_entries(ctx);
7082 /* if we're handling multiple rings, cap submit size for fairness */
7083 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7084 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7086 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7087 unsigned nr_events = 0;
7088 const struct cred *creds = NULL;
7090 if (ctx->sq_creds != current_cred())
7091 creds = override_creds(ctx->sq_creds);
7093 mutex_lock(&ctx->uring_lock);
7094 if (!list_empty(&ctx->iopoll_list))
7095 io_do_iopoll(ctx, &nr_events, 0);
7098 * Don't submit if refs are dying, good for io_uring_register(),
7099 * but also it is relied upon by io_ring_exit_work()
7101 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7102 !(ctx->flags & IORING_SETUP_R_DISABLED))
7103 ret = io_submit_sqes(ctx, to_submit);
7104 mutex_unlock(&ctx->uring_lock);
7106 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7107 wake_up(&ctx->sqo_sq_wait);
7109 revert_creds(creds);
7115 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7117 struct io_ring_ctx *ctx;
7118 unsigned sq_thread_idle = 0;
7120 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7121 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7122 sqd->sq_thread_idle = sq_thread_idle;
7125 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7127 bool did_sig = false;
7128 struct ksignal ksig;
7130 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7131 signal_pending(current)) {
7132 mutex_unlock(&sqd->lock);
7133 if (signal_pending(current))
7134 did_sig = get_signal(&ksig);
7136 mutex_lock(&sqd->lock);
7138 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7141 static int io_sq_thread(void *data)
7143 struct io_sq_data *sqd = data;
7144 struct io_ring_ctx *ctx;
7145 unsigned long timeout = 0;
7146 char buf[TASK_COMM_LEN];
7149 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7150 set_task_comm(current, buf);
7152 if (sqd->sq_cpu != -1)
7153 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7155 set_cpus_allowed_ptr(current, cpu_online_mask);
7156 current->flags |= PF_NO_SETAFFINITY;
7158 mutex_lock(&sqd->lock);
7160 bool cap_entries, sqt_spin = false;
7162 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7163 if (io_sqd_handle_event(sqd))
7165 timeout = jiffies + sqd->sq_thread_idle;
7168 cap_entries = !list_is_singular(&sqd->ctx_list);
7169 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7170 int ret = __io_sq_thread(ctx, cap_entries);
7172 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7175 if (io_run_task_work())
7178 if (sqt_spin || !time_after(jiffies, timeout)) {
7181 timeout = jiffies + sqd->sq_thread_idle;
7185 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7186 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7187 bool needs_sched = true;
7189 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7190 io_ring_set_wakeup_flag(ctx);
7192 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7193 !list_empty_careful(&ctx->iopoll_list)) {
7194 needs_sched = false;
7197 if (io_sqring_entries(ctx)) {
7198 needs_sched = false;
7204 mutex_unlock(&sqd->lock);
7206 mutex_lock(&sqd->lock);
7208 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7209 io_ring_clear_wakeup_flag(ctx);
7212 finish_wait(&sqd->wait, &wait);
7213 timeout = jiffies + sqd->sq_thread_idle;
7216 io_uring_cancel_generic(true, sqd);
7218 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7219 io_ring_set_wakeup_flag(ctx);
7221 mutex_unlock(&sqd->lock);
7223 complete(&sqd->exited);
7227 struct io_wait_queue {
7228 struct wait_queue_entry wq;
7229 struct io_ring_ctx *ctx;
7231 unsigned nr_timeouts;
7234 static inline bool io_should_wake(struct io_wait_queue *iowq)
7236 struct io_ring_ctx *ctx = iowq->ctx;
7237 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7240 * Wake up if we have enough events, or if a timeout occurred since we
7241 * started waiting. For timeouts, we always want to return to userspace,
7242 * regardless of event count.
7244 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7247 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7248 int wake_flags, void *key)
7250 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7254 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7255 * the task, and the next invocation will do it.
7257 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7258 return autoremove_wake_function(curr, mode, wake_flags, key);
7262 static int io_run_task_work_sig(void)
7264 if (io_run_task_work())
7266 if (!signal_pending(current))
7268 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7269 return -ERESTARTSYS;
7273 /* when returns >0, the caller should retry */
7274 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7275 struct io_wait_queue *iowq,
7276 signed long *timeout)
7280 /* make sure we run task_work before checking for signals */
7281 ret = io_run_task_work_sig();
7282 if (ret || io_should_wake(iowq))
7284 /* let the caller flush overflows, retry */
7285 if (test_bit(0, &ctx->check_cq_overflow))
7288 *timeout = schedule_timeout(*timeout);
7289 return !*timeout ? -ETIME : 1;
7293 * Wait until events become available, if we don't already have some. The
7294 * application must reap them itself, as they reside on the shared cq ring.
7296 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7297 const sigset_t __user *sig, size_t sigsz,
7298 struct __kernel_timespec __user *uts)
7300 struct io_wait_queue iowq;
7301 struct io_rings *rings = ctx->rings;
7302 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7306 io_cqring_overflow_flush(ctx);
7307 if (io_cqring_events(ctx) >= min_events)
7309 if (!io_run_task_work())
7314 #ifdef CONFIG_COMPAT
7315 if (in_compat_syscall())
7316 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7320 ret = set_user_sigmask(sig, sigsz);
7327 struct timespec64 ts;
7329 if (get_timespec64(&ts, uts))
7331 timeout = timespec64_to_jiffies(&ts);
7334 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7335 iowq.wq.private = current;
7336 INIT_LIST_HEAD(&iowq.wq.entry);
7338 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7339 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7341 trace_io_uring_cqring_wait(ctx, min_events);
7343 /* if we can't even flush overflow, don't wait for more */
7344 if (!io_cqring_overflow_flush(ctx)) {
7348 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7349 TASK_INTERRUPTIBLE);
7350 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7351 finish_wait(&ctx->cq_wait, &iowq.wq);
7355 restore_saved_sigmask_unless(ret == -EINTR);
7357 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7360 static void io_free_page_table(void **table, size_t size)
7362 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7364 for (i = 0; i < nr_tables; i++)
7369 static void **io_alloc_page_table(size_t size)
7371 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7372 size_t init_size = size;
7375 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7379 for (i = 0; i < nr_tables; i++) {
7380 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7382 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7384 io_free_page_table(table, init_size);
7392 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7394 percpu_ref_exit(&ref_node->refs);
7398 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7400 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7401 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7402 unsigned long flags;
7403 bool first_add = false;
7405 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7408 while (!list_empty(&ctx->rsrc_ref_list)) {
7409 node = list_first_entry(&ctx->rsrc_ref_list,
7410 struct io_rsrc_node, node);
7411 /* recycle ref nodes in order */
7414 list_del(&node->node);
7415 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7417 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7420 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7423 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7425 struct io_rsrc_node *ref_node;
7427 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7431 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7436 INIT_LIST_HEAD(&ref_node->node);
7437 INIT_LIST_HEAD(&ref_node->rsrc_list);
7438 ref_node->done = false;
7442 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7443 struct io_rsrc_data *data_to_kill)
7445 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7446 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7449 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7451 rsrc_node->rsrc_data = data_to_kill;
7452 spin_lock_irq(&ctx->rsrc_ref_lock);
7453 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7454 spin_unlock_irq(&ctx->rsrc_ref_lock);
7456 atomic_inc(&data_to_kill->refs);
7457 percpu_ref_kill(&rsrc_node->refs);
7458 ctx->rsrc_node = NULL;
7461 if (!ctx->rsrc_node) {
7462 ctx->rsrc_node = ctx->rsrc_backup_node;
7463 ctx->rsrc_backup_node = NULL;
7467 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7469 if (ctx->rsrc_backup_node)
7471 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7472 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7475 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7479 /* As we may drop ->uring_lock, other task may have started quiesce */
7483 data->quiesce = true;
7485 ret = io_rsrc_node_switch_start(ctx);
7488 io_rsrc_node_switch(ctx, data);
7490 /* kill initial ref, already quiesced if zero */
7491 if (atomic_dec_and_test(&data->refs))
7493 mutex_unlock(&ctx->uring_lock);
7494 flush_delayed_work(&ctx->rsrc_put_work);
7495 ret = wait_for_completion_interruptible(&data->done);
7497 mutex_lock(&ctx->uring_lock);
7501 atomic_inc(&data->refs);
7502 /* wait for all works potentially completing data->done */
7503 flush_delayed_work(&ctx->rsrc_put_work);
7504 reinit_completion(&data->done);
7506 ret = io_run_task_work_sig();
7507 mutex_lock(&ctx->uring_lock);
7509 data->quiesce = false;
7514 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7516 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7517 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7519 return &data->tags[table_idx][off];
7522 static void io_rsrc_data_free(struct io_rsrc_data *data)
7524 size_t size = data->nr * sizeof(data->tags[0][0]);
7527 io_free_page_table((void **)data->tags, size);
7531 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7532 u64 __user *utags, unsigned nr,
7533 struct io_rsrc_data **pdata)
7535 struct io_rsrc_data *data;
7539 data = kzalloc(sizeof(*data), GFP_KERNEL);
7542 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7550 data->do_put = do_put;
7553 for (i = 0; i < nr; i++) {
7554 u64 *tag_slot = io_get_tag_slot(data, i);
7556 if (copy_from_user(tag_slot, &utags[i],
7562 atomic_set(&data->refs, 1);
7563 init_completion(&data->done);
7567 io_rsrc_data_free(data);
7571 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7573 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7574 GFP_KERNEL_ACCOUNT);
7575 return !!table->files;
7578 static void io_free_file_tables(struct io_file_table *table)
7580 kvfree(table->files);
7581 table->files = NULL;
7584 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7586 #if defined(CONFIG_UNIX)
7587 if (ctx->ring_sock) {
7588 struct sock *sock = ctx->ring_sock->sk;
7589 struct sk_buff *skb;
7591 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7597 for (i = 0; i < ctx->nr_user_files; i++) {
7600 file = io_file_from_index(ctx, i);
7605 io_free_file_tables(&ctx->file_table);
7606 io_rsrc_data_free(ctx->file_data);
7607 ctx->file_data = NULL;
7608 ctx->nr_user_files = 0;
7611 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7615 if (!ctx->file_data)
7617 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7619 __io_sqe_files_unregister(ctx);
7623 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7624 __releases(&sqd->lock)
7626 WARN_ON_ONCE(sqd->thread == current);
7629 * Do the dance but not conditional clear_bit() because it'd race with
7630 * other threads incrementing park_pending and setting the bit.
7632 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7633 if (atomic_dec_return(&sqd->park_pending))
7634 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7635 mutex_unlock(&sqd->lock);
7638 static void io_sq_thread_park(struct io_sq_data *sqd)
7639 __acquires(&sqd->lock)
7641 WARN_ON_ONCE(sqd->thread == current);
7643 atomic_inc(&sqd->park_pending);
7644 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7645 mutex_lock(&sqd->lock);
7647 wake_up_process(sqd->thread);
7650 static void io_sq_thread_stop(struct io_sq_data *sqd)
7652 WARN_ON_ONCE(sqd->thread == current);
7653 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7655 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7656 mutex_lock(&sqd->lock);
7658 wake_up_process(sqd->thread);
7659 mutex_unlock(&sqd->lock);
7660 wait_for_completion(&sqd->exited);
7663 static void io_put_sq_data(struct io_sq_data *sqd)
7665 if (refcount_dec_and_test(&sqd->refs)) {
7666 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7668 io_sq_thread_stop(sqd);
7673 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7675 struct io_sq_data *sqd = ctx->sq_data;
7678 io_sq_thread_park(sqd);
7679 list_del_init(&ctx->sqd_list);
7680 io_sqd_update_thread_idle(sqd);
7681 io_sq_thread_unpark(sqd);
7683 io_put_sq_data(sqd);
7684 ctx->sq_data = NULL;
7688 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7690 struct io_ring_ctx *ctx_attach;
7691 struct io_sq_data *sqd;
7694 f = fdget(p->wq_fd);
7696 return ERR_PTR(-ENXIO);
7697 if (f.file->f_op != &io_uring_fops) {
7699 return ERR_PTR(-EINVAL);
7702 ctx_attach = f.file->private_data;
7703 sqd = ctx_attach->sq_data;
7706 return ERR_PTR(-EINVAL);
7708 if (sqd->task_tgid != current->tgid) {
7710 return ERR_PTR(-EPERM);
7713 refcount_inc(&sqd->refs);
7718 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7721 struct io_sq_data *sqd;
7724 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7725 sqd = io_attach_sq_data(p);
7730 /* fall through for EPERM case, setup new sqd/task */
7731 if (PTR_ERR(sqd) != -EPERM)
7735 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7737 return ERR_PTR(-ENOMEM);
7739 atomic_set(&sqd->park_pending, 0);
7740 refcount_set(&sqd->refs, 1);
7741 INIT_LIST_HEAD(&sqd->ctx_list);
7742 mutex_init(&sqd->lock);
7743 init_waitqueue_head(&sqd->wait);
7744 init_completion(&sqd->exited);
7748 #if defined(CONFIG_UNIX)
7750 * Ensure the UNIX gc is aware of our file set, so we are certain that
7751 * the io_uring can be safely unregistered on process exit, even if we have
7752 * loops in the file referencing.
7754 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7756 struct sock *sk = ctx->ring_sock->sk;
7757 struct scm_fp_list *fpl;
7758 struct sk_buff *skb;
7761 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7765 skb = alloc_skb(0, GFP_KERNEL);
7774 fpl->user = get_uid(current_user());
7775 for (i = 0; i < nr; i++) {
7776 struct file *file = io_file_from_index(ctx, i + offset);
7780 fpl->fp[nr_files] = get_file(file);
7781 unix_inflight(fpl->user, fpl->fp[nr_files]);
7786 fpl->max = SCM_MAX_FD;
7787 fpl->count = nr_files;
7788 UNIXCB(skb).fp = fpl;
7789 skb->destructor = unix_destruct_scm;
7790 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7791 skb_queue_head(&sk->sk_receive_queue, skb);
7793 for (i = 0; i < nr_files; i++)
7804 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7805 * causes regular reference counting to break down. We rely on the UNIX
7806 * garbage collection to take care of this problem for us.
7808 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7810 unsigned left, total;
7814 left = ctx->nr_user_files;
7816 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7818 ret = __io_sqe_files_scm(ctx, this_files, total);
7822 total += this_files;
7828 while (total < ctx->nr_user_files) {
7829 struct file *file = io_file_from_index(ctx, total);
7839 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7845 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7847 struct file *file = prsrc->file;
7848 #if defined(CONFIG_UNIX)
7849 struct sock *sock = ctx->ring_sock->sk;
7850 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7851 struct sk_buff *skb;
7854 __skb_queue_head_init(&list);
7857 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7858 * remove this entry and rearrange the file array.
7860 skb = skb_dequeue(head);
7862 struct scm_fp_list *fp;
7864 fp = UNIXCB(skb).fp;
7865 for (i = 0; i < fp->count; i++) {
7868 if (fp->fp[i] != file)
7871 unix_notinflight(fp->user, fp->fp[i]);
7872 left = fp->count - 1 - i;
7874 memmove(&fp->fp[i], &fp->fp[i + 1],
7875 left * sizeof(struct file *));
7882 __skb_queue_tail(&list, skb);
7892 __skb_queue_tail(&list, skb);
7894 skb = skb_dequeue(head);
7897 if (skb_peek(&list)) {
7898 spin_lock_irq(&head->lock);
7899 while ((skb = __skb_dequeue(&list)) != NULL)
7900 __skb_queue_tail(head, skb);
7901 spin_unlock_irq(&head->lock);
7908 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7910 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7911 struct io_ring_ctx *ctx = rsrc_data->ctx;
7912 struct io_rsrc_put *prsrc, *tmp;
7914 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7915 list_del(&prsrc->list);
7918 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7920 io_ring_submit_lock(ctx, lock_ring);
7921 spin_lock(&ctx->completion_lock);
7922 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7924 io_commit_cqring(ctx);
7925 spin_unlock(&ctx->completion_lock);
7926 io_cqring_ev_posted(ctx);
7927 io_ring_submit_unlock(ctx, lock_ring);
7930 rsrc_data->do_put(ctx, prsrc);
7934 io_rsrc_node_destroy(ref_node);
7935 if (atomic_dec_and_test(&rsrc_data->refs))
7936 complete(&rsrc_data->done);
7939 static void io_rsrc_put_work(struct work_struct *work)
7941 struct io_ring_ctx *ctx;
7942 struct llist_node *node;
7944 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7945 node = llist_del_all(&ctx->rsrc_put_llist);
7948 struct io_rsrc_node *ref_node;
7949 struct llist_node *next = node->next;
7951 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7952 __io_rsrc_put_work(ref_node);
7957 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7958 unsigned nr_args, u64 __user *tags)
7960 __s32 __user *fds = (__s32 __user *) arg;
7969 if (nr_args > IORING_MAX_FIXED_FILES)
7971 if (nr_args > rlimit(RLIMIT_NOFILE))
7973 ret = io_rsrc_node_switch_start(ctx);
7976 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7982 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7985 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7986 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7990 /* allow sparse sets */
7993 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8000 if (unlikely(!file))
8004 * Don't allow io_uring instances to be registered. If UNIX
8005 * isn't enabled, then this causes a reference cycle and this
8006 * instance can never get freed. If UNIX is enabled we'll
8007 * handle it just fine, but there's still no point in allowing
8008 * a ring fd as it doesn't support regular read/write anyway.
8010 if (file->f_op == &io_uring_fops) {
8014 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8017 ret = io_sqe_files_scm(ctx);
8019 __io_sqe_files_unregister(ctx);
8023 io_rsrc_node_switch(ctx, NULL);
8026 for (i = 0; i < ctx->nr_user_files; i++) {
8027 file = io_file_from_index(ctx, i);
8031 io_free_file_tables(&ctx->file_table);
8032 ctx->nr_user_files = 0;
8034 io_rsrc_data_free(ctx->file_data);
8035 ctx->file_data = NULL;
8039 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8042 #if defined(CONFIG_UNIX)
8043 struct sock *sock = ctx->ring_sock->sk;
8044 struct sk_buff_head *head = &sock->sk_receive_queue;
8045 struct sk_buff *skb;
8048 * See if we can merge this file into an existing skb SCM_RIGHTS
8049 * file set. If there's no room, fall back to allocating a new skb
8050 * and filling it in.
8052 spin_lock_irq(&head->lock);
8053 skb = skb_peek(head);
8055 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8057 if (fpl->count < SCM_MAX_FD) {
8058 __skb_unlink(skb, head);
8059 spin_unlock_irq(&head->lock);
8060 fpl->fp[fpl->count] = get_file(file);
8061 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8063 spin_lock_irq(&head->lock);
8064 __skb_queue_head(head, skb);
8069 spin_unlock_irq(&head->lock);
8076 return __io_sqe_files_scm(ctx, 1, index);
8082 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8083 unsigned int issue_flags, u32 slot_index)
8085 struct io_ring_ctx *ctx = req->ctx;
8086 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8087 struct io_fixed_file *file_slot;
8090 io_ring_submit_lock(ctx, !force_nonblock);
8091 if (file->f_op == &io_uring_fops)
8094 if (!ctx->file_data)
8097 if (slot_index >= ctx->nr_user_files)
8100 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8101 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8103 if (file_slot->file_ptr)
8106 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8107 io_fixed_file_set(file_slot, file);
8108 ret = io_sqe_file_register(ctx, file, slot_index);
8110 file_slot->file_ptr = 0;
8116 io_ring_submit_unlock(ctx, !force_nonblock);
8122 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8123 struct io_rsrc_node *node, void *rsrc)
8125 struct io_rsrc_put *prsrc;
8127 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8131 prsrc->tag = *io_get_tag_slot(data, idx);
8133 list_add(&prsrc->list, &node->rsrc_list);
8137 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8138 struct io_uring_rsrc_update2 *up,
8141 u64 __user *tags = u64_to_user_ptr(up->tags);
8142 __s32 __user *fds = u64_to_user_ptr(up->data);
8143 struct io_rsrc_data *data = ctx->file_data;
8144 struct io_fixed_file *file_slot;
8148 bool needs_switch = false;
8150 if (!ctx->file_data)
8152 if (up->offset + nr_args > ctx->nr_user_files)
8155 for (done = 0; done < nr_args; done++) {
8158 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8159 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8163 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8167 if (fd == IORING_REGISTER_FILES_SKIP)
8170 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8171 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8173 if (file_slot->file_ptr) {
8174 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8175 err = io_queue_rsrc_removal(data, up->offset + done,
8176 ctx->rsrc_node, file);
8179 file_slot->file_ptr = 0;
8180 needs_switch = true;
8189 * Don't allow io_uring instances to be registered. If
8190 * UNIX isn't enabled, then this causes a reference
8191 * cycle and this instance can never get freed. If UNIX
8192 * is enabled we'll handle it just fine, but there's
8193 * still no point in allowing a ring fd as it doesn't
8194 * support regular read/write anyway.
8196 if (file->f_op == &io_uring_fops) {
8201 *io_get_tag_slot(data, up->offset + done) = tag;
8202 io_fixed_file_set(file_slot, file);
8203 err = io_sqe_file_register(ctx, file, i);
8205 file_slot->file_ptr = 0;
8213 io_rsrc_node_switch(ctx, data);
8214 return done ? done : err;
8217 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8218 struct task_struct *task)
8220 struct io_wq_hash *hash;
8221 struct io_wq_data data;
8222 unsigned int concurrency;
8224 mutex_lock(&ctx->uring_lock);
8225 hash = ctx->hash_map;
8227 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8229 mutex_unlock(&ctx->uring_lock);
8230 return ERR_PTR(-ENOMEM);
8232 refcount_set(&hash->refs, 1);
8233 init_waitqueue_head(&hash->wait);
8234 ctx->hash_map = hash;
8236 mutex_unlock(&ctx->uring_lock);
8240 data.free_work = io_wq_free_work;
8241 data.do_work = io_wq_submit_work;
8243 /* Do QD, or 4 * CPUS, whatever is smallest */
8244 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8246 return io_wq_create(concurrency, &data);
8249 static int io_uring_alloc_task_context(struct task_struct *task,
8250 struct io_ring_ctx *ctx)
8252 struct io_uring_task *tctx;
8255 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8256 if (unlikely(!tctx))
8259 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8260 if (unlikely(ret)) {
8265 tctx->io_wq = io_init_wq_offload(ctx, task);
8266 if (IS_ERR(tctx->io_wq)) {
8267 ret = PTR_ERR(tctx->io_wq);
8268 percpu_counter_destroy(&tctx->inflight);
8274 init_waitqueue_head(&tctx->wait);
8275 atomic_set(&tctx->in_idle, 0);
8276 atomic_set(&tctx->inflight_tracked, 0);
8277 task->io_uring = tctx;
8278 spin_lock_init(&tctx->task_lock);
8279 INIT_WQ_LIST(&tctx->task_list);
8280 init_task_work(&tctx->task_work, tctx_task_work);
8284 void __io_uring_free(struct task_struct *tsk)
8286 struct io_uring_task *tctx = tsk->io_uring;
8288 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8289 WARN_ON_ONCE(tctx->io_wq);
8290 WARN_ON_ONCE(tctx->cached_refs);
8292 percpu_counter_destroy(&tctx->inflight);
8294 tsk->io_uring = NULL;
8297 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8298 struct io_uring_params *p)
8302 /* Retain compatibility with failing for an invalid attach attempt */
8303 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8304 IORING_SETUP_ATTACH_WQ) {
8307 f = fdget(p->wq_fd);
8310 if (f.file->f_op != &io_uring_fops) {
8316 if (ctx->flags & IORING_SETUP_SQPOLL) {
8317 struct task_struct *tsk;
8318 struct io_sq_data *sqd;
8321 sqd = io_get_sq_data(p, &attached);
8327 ctx->sq_creds = get_current_cred();
8329 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8330 if (!ctx->sq_thread_idle)
8331 ctx->sq_thread_idle = HZ;
8333 io_sq_thread_park(sqd);
8334 list_add(&ctx->sqd_list, &sqd->ctx_list);
8335 io_sqd_update_thread_idle(sqd);
8336 /* don't attach to a dying SQPOLL thread, would be racy */
8337 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8338 io_sq_thread_unpark(sqd);
8345 if (p->flags & IORING_SETUP_SQ_AFF) {
8346 int cpu = p->sq_thread_cpu;
8349 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8356 sqd->task_pid = current->pid;
8357 sqd->task_tgid = current->tgid;
8358 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8365 ret = io_uring_alloc_task_context(tsk, ctx);
8366 wake_up_new_task(tsk);
8369 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8370 /* Can't have SQ_AFF without SQPOLL */
8377 complete(&ctx->sq_data->exited);
8379 io_sq_thread_finish(ctx);
8383 static inline void __io_unaccount_mem(struct user_struct *user,
8384 unsigned long nr_pages)
8386 atomic_long_sub(nr_pages, &user->locked_vm);
8389 static inline int __io_account_mem(struct user_struct *user,
8390 unsigned long nr_pages)
8392 unsigned long page_limit, cur_pages, new_pages;
8394 /* Don't allow more pages than we can safely lock */
8395 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8398 cur_pages = atomic_long_read(&user->locked_vm);
8399 new_pages = cur_pages + nr_pages;
8400 if (new_pages > page_limit)
8402 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8403 new_pages) != cur_pages);
8408 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8411 __io_unaccount_mem(ctx->user, nr_pages);
8413 if (ctx->mm_account)
8414 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8417 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8422 ret = __io_account_mem(ctx->user, nr_pages);
8427 if (ctx->mm_account)
8428 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8433 static void io_mem_free(void *ptr)
8440 page = virt_to_head_page(ptr);
8441 if (put_page_testzero(page))
8442 free_compound_page(page);
8445 static void *io_mem_alloc(size_t size)
8447 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8448 __GFP_NORETRY | __GFP_ACCOUNT;
8450 return (void *) __get_free_pages(gfp_flags, get_order(size));
8453 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8456 struct io_rings *rings;
8457 size_t off, sq_array_size;
8459 off = struct_size(rings, cqes, cq_entries);
8460 if (off == SIZE_MAX)
8464 off = ALIGN(off, SMP_CACHE_BYTES);
8472 sq_array_size = array_size(sizeof(u32), sq_entries);
8473 if (sq_array_size == SIZE_MAX)
8476 if (check_add_overflow(off, sq_array_size, &off))
8482 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8484 struct io_mapped_ubuf *imu = *slot;
8487 if (imu != ctx->dummy_ubuf) {
8488 for (i = 0; i < imu->nr_bvecs; i++)
8489 unpin_user_page(imu->bvec[i].bv_page);
8490 if (imu->acct_pages)
8491 io_unaccount_mem(ctx, imu->acct_pages);
8497 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8499 io_buffer_unmap(ctx, &prsrc->buf);
8503 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8507 for (i = 0; i < ctx->nr_user_bufs; i++)
8508 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8509 kfree(ctx->user_bufs);
8510 io_rsrc_data_free(ctx->buf_data);
8511 ctx->user_bufs = NULL;
8512 ctx->buf_data = NULL;
8513 ctx->nr_user_bufs = 0;
8516 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8523 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8525 __io_sqe_buffers_unregister(ctx);
8529 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8530 void __user *arg, unsigned index)
8532 struct iovec __user *src;
8534 #ifdef CONFIG_COMPAT
8536 struct compat_iovec __user *ciovs;
8537 struct compat_iovec ciov;
8539 ciovs = (struct compat_iovec __user *) arg;
8540 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8543 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8544 dst->iov_len = ciov.iov_len;
8548 src = (struct iovec __user *) arg;
8549 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8555 * Not super efficient, but this is just a registration time. And we do cache
8556 * the last compound head, so generally we'll only do a full search if we don't
8559 * We check if the given compound head page has already been accounted, to
8560 * avoid double accounting it. This allows us to account the full size of the
8561 * page, not just the constituent pages of a huge page.
8563 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8564 int nr_pages, struct page *hpage)
8568 /* check current page array */
8569 for (i = 0; i < nr_pages; i++) {
8570 if (!PageCompound(pages[i]))
8572 if (compound_head(pages[i]) == hpage)
8576 /* check previously registered pages */
8577 for (i = 0; i < ctx->nr_user_bufs; i++) {
8578 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8580 for (j = 0; j < imu->nr_bvecs; j++) {
8581 if (!PageCompound(imu->bvec[j].bv_page))
8583 if (compound_head(imu->bvec[j].bv_page) == hpage)
8591 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8592 int nr_pages, struct io_mapped_ubuf *imu,
8593 struct page **last_hpage)
8597 imu->acct_pages = 0;
8598 for (i = 0; i < nr_pages; i++) {
8599 if (!PageCompound(pages[i])) {
8604 hpage = compound_head(pages[i]);
8605 if (hpage == *last_hpage)
8607 *last_hpage = hpage;
8608 if (headpage_already_acct(ctx, pages, i, hpage))
8610 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8614 if (!imu->acct_pages)
8617 ret = io_account_mem(ctx, imu->acct_pages);
8619 imu->acct_pages = 0;
8623 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8624 struct io_mapped_ubuf **pimu,
8625 struct page **last_hpage)
8627 struct io_mapped_ubuf *imu = NULL;
8628 struct vm_area_struct **vmas = NULL;
8629 struct page **pages = NULL;
8630 unsigned long off, start, end, ubuf;
8632 int ret, pret, nr_pages, i;
8634 if (!iov->iov_base) {
8635 *pimu = ctx->dummy_ubuf;
8639 ubuf = (unsigned long) iov->iov_base;
8640 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8641 start = ubuf >> PAGE_SHIFT;
8642 nr_pages = end - start;
8647 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8651 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8656 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8661 mmap_read_lock(current->mm);
8662 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8664 if (pret == nr_pages) {
8665 /* don't support file backed memory */
8666 for (i = 0; i < nr_pages; i++) {
8667 struct vm_area_struct *vma = vmas[i];
8669 if (vma_is_shmem(vma))
8672 !is_file_hugepages(vma->vm_file)) {
8678 ret = pret < 0 ? pret : -EFAULT;
8680 mmap_read_unlock(current->mm);
8683 * if we did partial map, or found file backed vmas,
8684 * release any pages we did get
8687 unpin_user_pages(pages, pret);
8691 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8693 unpin_user_pages(pages, pret);
8697 off = ubuf & ~PAGE_MASK;
8698 size = iov->iov_len;
8699 for (i = 0; i < nr_pages; i++) {
8702 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8703 imu->bvec[i].bv_page = pages[i];
8704 imu->bvec[i].bv_len = vec_len;
8705 imu->bvec[i].bv_offset = off;
8709 /* store original address for later verification */
8711 imu->ubuf_end = ubuf + iov->iov_len;
8712 imu->nr_bvecs = nr_pages;
8723 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8725 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8726 return ctx->user_bufs ? 0 : -ENOMEM;
8729 static int io_buffer_validate(struct iovec *iov)
8731 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8734 * Don't impose further limits on the size and buffer
8735 * constraints here, we'll -EINVAL later when IO is
8736 * submitted if they are wrong.
8739 return iov->iov_len ? -EFAULT : 0;
8743 /* arbitrary limit, but we need something */
8744 if (iov->iov_len > SZ_1G)
8747 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8753 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8754 unsigned int nr_args, u64 __user *tags)
8756 struct page *last_hpage = NULL;
8757 struct io_rsrc_data *data;
8763 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8765 ret = io_rsrc_node_switch_start(ctx);
8768 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8771 ret = io_buffers_map_alloc(ctx, nr_args);
8773 io_rsrc_data_free(data);
8777 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8778 ret = io_copy_iov(ctx, &iov, arg, i);
8781 ret = io_buffer_validate(&iov);
8784 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8789 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8795 WARN_ON_ONCE(ctx->buf_data);
8797 ctx->buf_data = data;
8799 __io_sqe_buffers_unregister(ctx);
8801 io_rsrc_node_switch(ctx, NULL);
8805 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8806 struct io_uring_rsrc_update2 *up,
8807 unsigned int nr_args)
8809 u64 __user *tags = u64_to_user_ptr(up->tags);
8810 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8811 struct page *last_hpage = NULL;
8812 bool needs_switch = false;
8818 if (up->offset + nr_args > ctx->nr_user_bufs)
8821 for (done = 0; done < nr_args; done++) {
8822 struct io_mapped_ubuf *imu;
8823 int offset = up->offset + done;
8826 err = io_copy_iov(ctx, &iov, iovs, done);
8829 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8833 err = io_buffer_validate(&iov);
8836 if (!iov.iov_base && tag) {
8840 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8844 i = array_index_nospec(offset, ctx->nr_user_bufs);
8845 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8846 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8847 ctx->rsrc_node, ctx->user_bufs[i]);
8848 if (unlikely(err)) {
8849 io_buffer_unmap(ctx, &imu);
8852 ctx->user_bufs[i] = NULL;
8853 needs_switch = true;
8856 ctx->user_bufs[i] = imu;
8857 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8861 io_rsrc_node_switch(ctx, ctx->buf_data);
8862 return done ? done : err;
8865 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8867 __s32 __user *fds = arg;
8873 if (copy_from_user(&fd, fds, sizeof(*fds)))
8876 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8877 if (IS_ERR(ctx->cq_ev_fd)) {
8878 int ret = PTR_ERR(ctx->cq_ev_fd);
8880 ctx->cq_ev_fd = NULL;
8887 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8889 if (ctx->cq_ev_fd) {
8890 eventfd_ctx_put(ctx->cq_ev_fd);
8891 ctx->cq_ev_fd = NULL;
8898 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8900 struct io_buffer *buf;
8901 unsigned long index;
8903 xa_for_each(&ctx->io_buffers, index, buf)
8904 __io_remove_buffers(ctx, buf, index, -1U);
8907 static void io_req_cache_free(struct list_head *list)
8909 struct io_kiocb *req, *nxt;
8911 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8912 list_del(&req->inflight_entry);
8913 kmem_cache_free(req_cachep, req);
8917 static void io_req_caches_free(struct io_ring_ctx *ctx)
8919 struct io_submit_state *state = &ctx->submit_state;
8921 mutex_lock(&ctx->uring_lock);
8923 if (state->free_reqs) {
8924 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8925 state->free_reqs = 0;
8928 io_flush_cached_locked_reqs(ctx, state);
8929 io_req_cache_free(&state->free_list);
8930 mutex_unlock(&ctx->uring_lock);
8933 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8935 if (data && !atomic_dec_and_test(&data->refs))
8936 wait_for_completion(&data->done);
8939 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8941 io_sq_thread_finish(ctx);
8943 if (ctx->mm_account) {
8944 mmdrop(ctx->mm_account);
8945 ctx->mm_account = NULL;
8948 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8949 io_wait_rsrc_data(ctx->buf_data);
8950 io_wait_rsrc_data(ctx->file_data);
8952 mutex_lock(&ctx->uring_lock);
8954 __io_sqe_buffers_unregister(ctx);
8956 __io_sqe_files_unregister(ctx);
8958 __io_cqring_overflow_flush(ctx, true);
8959 mutex_unlock(&ctx->uring_lock);
8960 io_eventfd_unregister(ctx);
8961 io_destroy_buffers(ctx);
8963 put_cred(ctx->sq_creds);
8965 /* there are no registered resources left, nobody uses it */
8967 io_rsrc_node_destroy(ctx->rsrc_node);
8968 if (ctx->rsrc_backup_node)
8969 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8970 flush_delayed_work(&ctx->rsrc_put_work);
8972 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8973 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8975 #if defined(CONFIG_UNIX)
8976 if (ctx->ring_sock) {
8977 ctx->ring_sock->file = NULL; /* so that iput() is called */
8978 sock_release(ctx->ring_sock);
8981 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
8983 io_mem_free(ctx->rings);
8984 io_mem_free(ctx->sq_sqes);
8986 percpu_ref_exit(&ctx->refs);
8987 free_uid(ctx->user);
8988 io_req_caches_free(ctx);
8990 io_wq_put_hash(ctx->hash_map);
8991 kfree(ctx->cancel_hash);
8992 kfree(ctx->dummy_ubuf);
8996 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8998 struct io_ring_ctx *ctx = file->private_data;
9001 poll_wait(file, &ctx->poll_wait, wait);
9003 * synchronizes with barrier from wq_has_sleeper call in
9007 if (!io_sqring_full(ctx))
9008 mask |= EPOLLOUT | EPOLLWRNORM;
9011 * Don't flush cqring overflow list here, just do a simple check.
9012 * Otherwise there could possible be ABBA deadlock:
9015 * lock(&ctx->uring_lock);
9017 * lock(&ctx->uring_lock);
9020 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9021 * pushs them to do the flush.
9023 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9024 mask |= EPOLLIN | EPOLLRDNORM;
9029 static int io_uring_fasync(int fd, struct file *file, int on)
9031 struct io_ring_ctx *ctx = file->private_data;
9033 return fasync_helper(fd, file, on, &ctx->cq_fasync);
9036 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9038 const struct cred *creds;
9040 creds = xa_erase(&ctx->personalities, id);
9049 struct io_tctx_exit {
9050 struct callback_head task_work;
9051 struct completion completion;
9052 struct io_ring_ctx *ctx;
9055 static void io_tctx_exit_cb(struct callback_head *cb)
9057 struct io_uring_task *tctx = current->io_uring;
9058 struct io_tctx_exit *work;
9060 work = container_of(cb, struct io_tctx_exit, task_work);
9062 * When @in_idle, we're in cancellation and it's racy to remove the
9063 * node. It'll be removed by the end of cancellation, just ignore it.
9065 if (!atomic_read(&tctx->in_idle))
9066 io_uring_del_tctx_node((unsigned long)work->ctx);
9067 complete(&work->completion);
9070 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9072 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9074 return req->ctx == data;
9077 static void io_ring_exit_work(struct work_struct *work)
9079 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9080 unsigned long timeout = jiffies + HZ * 60 * 5;
9081 unsigned long interval = HZ / 20;
9082 struct io_tctx_exit exit;
9083 struct io_tctx_node *node;
9087 * If we're doing polled IO and end up having requests being
9088 * submitted async (out-of-line), then completions can come in while
9089 * we're waiting for refs to drop. We need to reap these manually,
9090 * as nobody else will be looking for them.
9093 io_uring_try_cancel_requests(ctx, NULL, true);
9095 struct io_sq_data *sqd = ctx->sq_data;
9096 struct task_struct *tsk;
9098 io_sq_thread_park(sqd);
9100 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9101 io_wq_cancel_cb(tsk->io_uring->io_wq,
9102 io_cancel_ctx_cb, ctx, true);
9103 io_sq_thread_unpark(sqd);
9106 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9107 /* there is little hope left, don't run it too often */
9110 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9112 init_completion(&exit.completion);
9113 init_task_work(&exit.task_work, io_tctx_exit_cb);
9116 * Some may use context even when all refs and requests have been put,
9117 * and they are free to do so while still holding uring_lock or
9118 * completion_lock, see io_req_task_submit(). Apart from other work,
9119 * this lock/unlock section also waits them to finish.
9121 mutex_lock(&ctx->uring_lock);
9122 while (!list_empty(&ctx->tctx_list)) {
9123 WARN_ON_ONCE(time_after(jiffies, timeout));
9125 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9127 /* don't spin on a single task if cancellation failed */
9128 list_rotate_left(&ctx->tctx_list);
9129 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9130 if (WARN_ON_ONCE(ret))
9132 wake_up_process(node->task);
9134 mutex_unlock(&ctx->uring_lock);
9135 wait_for_completion(&exit.completion);
9136 mutex_lock(&ctx->uring_lock);
9138 mutex_unlock(&ctx->uring_lock);
9139 spin_lock(&ctx->completion_lock);
9140 spin_unlock(&ctx->completion_lock);
9142 io_ring_ctx_free(ctx);
9145 /* Returns true if we found and killed one or more timeouts */
9146 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9149 struct io_kiocb *req, *tmp;
9152 spin_lock(&ctx->completion_lock);
9153 spin_lock_irq(&ctx->timeout_lock);
9154 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9155 if (io_match_task(req, tsk, cancel_all)) {
9156 io_kill_timeout(req, -ECANCELED);
9160 spin_unlock_irq(&ctx->timeout_lock);
9162 io_commit_cqring(ctx);
9163 spin_unlock(&ctx->completion_lock);
9165 io_cqring_ev_posted(ctx);
9166 return canceled != 0;
9169 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9171 unsigned long index;
9172 struct creds *creds;
9174 mutex_lock(&ctx->uring_lock);
9175 percpu_ref_kill(&ctx->refs);
9177 __io_cqring_overflow_flush(ctx, true);
9178 xa_for_each(&ctx->personalities, index, creds)
9179 io_unregister_personality(ctx, index);
9180 mutex_unlock(&ctx->uring_lock);
9182 io_kill_timeouts(ctx, NULL, true);
9183 io_poll_remove_all(ctx, NULL, true);
9185 /* if we failed setting up the ctx, we might not have any rings */
9186 io_iopoll_try_reap_events(ctx);
9188 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9190 * Use system_unbound_wq to avoid spawning tons of event kworkers
9191 * if we're exiting a ton of rings at the same time. It just adds
9192 * noise and overhead, there's no discernable change in runtime
9193 * over using system_wq.
9195 queue_work(system_unbound_wq, &ctx->exit_work);
9198 static int io_uring_release(struct inode *inode, struct file *file)
9200 struct io_ring_ctx *ctx = file->private_data;
9202 file->private_data = NULL;
9203 io_ring_ctx_wait_and_kill(ctx);
9207 struct io_task_cancel {
9208 struct task_struct *task;
9212 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9214 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9215 struct io_task_cancel *cancel = data;
9218 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9219 struct io_ring_ctx *ctx = req->ctx;
9221 /* protect against races with linked timeouts */
9222 spin_lock(&ctx->completion_lock);
9223 ret = io_match_task(req, cancel->task, cancel->all);
9224 spin_unlock(&ctx->completion_lock);
9226 ret = io_match_task(req, cancel->task, cancel->all);
9231 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9232 struct task_struct *task, bool cancel_all)
9234 struct io_defer_entry *de;
9237 spin_lock(&ctx->completion_lock);
9238 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9239 if (io_match_task(de->req, task, cancel_all)) {
9240 list_cut_position(&list, &ctx->defer_list, &de->list);
9244 spin_unlock(&ctx->completion_lock);
9245 if (list_empty(&list))
9248 while (!list_empty(&list)) {
9249 de = list_first_entry(&list, struct io_defer_entry, list);
9250 list_del_init(&de->list);
9251 io_req_complete_failed(de->req, -ECANCELED);
9257 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9259 struct io_tctx_node *node;
9260 enum io_wq_cancel cret;
9263 mutex_lock(&ctx->uring_lock);
9264 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9265 struct io_uring_task *tctx = node->task->io_uring;
9268 * io_wq will stay alive while we hold uring_lock, because it's
9269 * killed after ctx nodes, which requires to take the lock.
9271 if (!tctx || !tctx->io_wq)
9273 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9274 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9276 mutex_unlock(&ctx->uring_lock);
9281 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9282 struct task_struct *task,
9285 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9286 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9289 enum io_wq_cancel cret;
9293 ret |= io_uring_try_cancel_iowq(ctx);
9294 } else if (tctx && tctx->io_wq) {
9296 * Cancels requests of all rings, not only @ctx, but
9297 * it's fine as the task is in exit/exec.
9299 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9301 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9304 /* SQPOLL thread does its own polling */
9305 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9306 (ctx->sq_data && ctx->sq_data->thread == current)) {
9307 while (!list_empty_careful(&ctx->iopoll_list)) {
9308 io_iopoll_try_reap_events(ctx);
9313 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9314 ret |= io_poll_remove_all(ctx, task, cancel_all);
9315 ret |= io_kill_timeouts(ctx, task, cancel_all);
9317 ret |= io_run_task_work();
9324 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9326 struct io_uring_task *tctx = current->io_uring;
9327 struct io_tctx_node *node;
9330 if (unlikely(!tctx)) {
9331 ret = io_uring_alloc_task_context(current, ctx);
9334 tctx = current->io_uring;
9336 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9337 node = kmalloc(sizeof(*node), GFP_KERNEL);
9341 node->task = current;
9343 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9350 mutex_lock(&ctx->uring_lock);
9351 list_add(&node->ctx_node, &ctx->tctx_list);
9352 mutex_unlock(&ctx->uring_lock);
9359 * Note that this task has used io_uring. We use it for cancelation purposes.
9361 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9363 struct io_uring_task *tctx = current->io_uring;
9365 if (likely(tctx && tctx->last == ctx))
9367 return __io_uring_add_tctx_node(ctx);
9371 * Remove this io_uring_file -> task mapping.
9373 static void io_uring_del_tctx_node(unsigned long index)
9375 struct io_uring_task *tctx = current->io_uring;
9376 struct io_tctx_node *node;
9380 node = xa_erase(&tctx->xa, index);
9384 WARN_ON_ONCE(current != node->task);
9385 WARN_ON_ONCE(list_empty(&node->ctx_node));
9387 mutex_lock(&node->ctx->uring_lock);
9388 list_del(&node->ctx_node);
9389 mutex_unlock(&node->ctx->uring_lock);
9391 if (tctx->last == node->ctx)
9396 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9398 struct io_wq *wq = tctx->io_wq;
9399 struct io_tctx_node *node;
9400 unsigned long index;
9402 xa_for_each(&tctx->xa, index, node)
9403 io_uring_del_tctx_node(index);
9406 * Must be after io_uring_del_task_file() (removes nodes under
9407 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9409 io_wq_put_and_exit(wq);
9414 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9417 return atomic_read(&tctx->inflight_tracked);
9418 return percpu_counter_sum(&tctx->inflight);
9421 static void io_uring_drop_tctx_refs(struct task_struct *task)
9423 struct io_uring_task *tctx = task->io_uring;
9424 unsigned int refs = tctx->cached_refs;
9427 tctx->cached_refs = 0;
9428 percpu_counter_sub(&tctx->inflight, refs);
9429 put_task_struct_many(task, refs);
9434 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9435 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9437 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9439 struct io_uring_task *tctx = current->io_uring;
9440 struct io_ring_ctx *ctx;
9444 WARN_ON_ONCE(sqd && sqd->thread != current);
9446 if (!current->io_uring)
9449 io_wq_exit_start(tctx->io_wq);
9451 atomic_inc(&tctx->in_idle);
9453 io_uring_drop_tctx_refs(current);
9454 /* read completions before cancelations */
9455 inflight = tctx_inflight(tctx, !cancel_all);
9460 struct io_tctx_node *node;
9461 unsigned long index;
9463 xa_for_each(&tctx->xa, index, node) {
9464 /* sqpoll task will cancel all its requests */
9465 if (node->ctx->sq_data)
9467 io_uring_try_cancel_requests(node->ctx, current,
9471 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9472 io_uring_try_cancel_requests(ctx, current,
9476 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9477 io_uring_drop_tctx_refs(current);
9479 * If we've seen completions, retry without waiting. This
9480 * avoids a race where a completion comes in before we did
9481 * prepare_to_wait().
9483 if (inflight == tctx_inflight(tctx, !cancel_all))
9485 finish_wait(&tctx->wait, &wait);
9487 atomic_dec(&tctx->in_idle);
9489 io_uring_clean_tctx(tctx);
9491 /* for exec all current's requests should be gone, kill tctx */
9492 __io_uring_free(current);
9496 void __io_uring_cancel(bool cancel_all)
9498 io_uring_cancel_generic(cancel_all, NULL);
9501 static void *io_uring_validate_mmap_request(struct file *file,
9502 loff_t pgoff, size_t sz)
9504 struct io_ring_ctx *ctx = file->private_data;
9505 loff_t offset = pgoff << PAGE_SHIFT;
9510 case IORING_OFF_SQ_RING:
9511 case IORING_OFF_CQ_RING:
9514 case IORING_OFF_SQES:
9518 return ERR_PTR(-EINVAL);
9521 page = virt_to_head_page(ptr);
9522 if (sz > page_size(page))
9523 return ERR_PTR(-EINVAL);
9530 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9532 size_t sz = vma->vm_end - vma->vm_start;
9536 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9538 return PTR_ERR(ptr);
9540 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9541 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9544 #else /* !CONFIG_MMU */
9546 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9548 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9551 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9553 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9556 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9557 unsigned long addr, unsigned long len,
9558 unsigned long pgoff, unsigned long flags)
9562 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9564 return PTR_ERR(ptr);
9566 return (unsigned long) ptr;
9569 #endif /* !CONFIG_MMU */
9571 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9576 if (!io_sqring_full(ctx))
9578 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9580 if (!io_sqring_full(ctx))
9583 } while (!signal_pending(current));
9585 finish_wait(&ctx->sqo_sq_wait, &wait);
9589 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9590 struct __kernel_timespec __user **ts,
9591 const sigset_t __user **sig)
9593 struct io_uring_getevents_arg arg;
9596 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9597 * is just a pointer to the sigset_t.
9599 if (!(flags & IORING_ENTER_EXT_ARG)) {
9600 *sig = (const sigset_t __user *) argp;
9606 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9607 * timespec and sigset_t pointers if good.
9609 if (*argsz != sizeof(arg))
9611 if (copy_from_user(&arg, argp, sizeof(arg)))
9613 *sig = u64_to_user_ptr(arg.sigmask);
9614 *argsz = arg.sigmask_sz;
9615 *ts = u64_to_user_ptr(arg.ts);
9619 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9620 u32, min_complete, u32, flags, const void __user *, argp,
9623 struct io_ring_ctx *ctx;
9630 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9631 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9635 if (unlikely(!f.file))
9639 if (unlikely(f.file->f_op != &io_uring_fops))
9643 ctx = f.file->private_data;
9644 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9648 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9652 * For SQ polling, the thread will do all submissions and completions.
9653 * Just return the requested submit count, and wake the thread if
9657 if (ctx->flags & IORING_SETUP_SQPOLL) {
9658 io_cqring_overflow_flush(ctx);
9660 if (unlikely(ctx->sq_data->thread == NULL)) {
9664 if (flags & IORING_ENTER_SQ_WAKEUP)
9665 wake_up(&ctx->sq_data->wait);
9666 if (flags & IORING_ENTER_SQ_WAIT) {
9667 ret = io_sqpoll_wait_sq(ctx);
9671 submitted = to_submit;
9672 } else if (to_submit) {
9673 ret = io_uring_add_tctx_node(ctx);
9676 mutex_lock(&ctx->uring_lock);
9677 submitted = io_submit_sqes(ctx, to_submit);
9678 mutex_unlock(&ctx->uring_lock);
9680 if (submitted != to_submit)
9683 if (flags & IORING_ENTER_GETEVENTS) {
9684 const sigset_t __user *sig;
9685 struct __kernel_timespec __user *ts;
9687 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9691 min_complete = min(min_complete, ctx->cq_entries);
9694 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9695 * space applications don't need to do io completion events
9696 * polling again, they can rely on io_sq_thread to do polling
9697 * work, which can reduce cpu usage and uring_lock contention.
9699 if (ctx->flags & IORING_SETUP_IOPOLL &&
9700 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9701 ret = io_iopoll_check(ctx, min_complete);
9703 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9708 percpu_ref_put(&ctx->refs);
9711 return submitted ? submitted : ret;
9714 #ifdef CONFIG_PROC_FS
9715 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9716 const struct cred *cred)
9718 struct user_namespace *uns = seq_user_ns(m);
9719 struct group_info *gi;
9724 seq_printf(m, "%5d\n", id);
9725 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9726 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9727 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9728 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9729 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9730 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9731 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9732 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9733 seq_puts(m, "\n\tGroups:\t");
9734 gi = cred->group_info;
9735 for (g = 0; g < gi->ngroups; g++) {
9736 seq_put_decimal_ull(m, g ? " " : "",
9737 from_kgid_munged(uns, gi->gid[g]));
9739 seq_puts(m, "\n\tCapEff:\t");
9740 cap = cred->cap_effective;
9741 CAP_FOR_EACH_U32(__capi)
9742 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9747 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9749 struct io_sq_data *sq = NULL;
9754 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9755 * since fdinfo case grabs it in the opposite direction of normal use
9756 * cases. If we fail to get the lock, we just don't iterate any
9757 * structures that could be going away outside the io_uring mutex.
9759 has_lock = mutex_trylock(&ctx->uring_lock);
9761 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9767 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9768 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9769 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9770 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9771 struct file *f = io_file_from_index(ctx, i);
9774 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9776 seq_printf(m, "%5u: <none>\n", i);
9778 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9779 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9780 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9781 unsigned int len = buf->ubuf_end - buf->ubuf;
9783 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9785 if (has_lock && !xa_empty(&ctx->personalities)) {
9786 unsigned long index;
9787 const struct cred *cred;
9789 seq_printf(m, "Personalities:\n");
9790 xa_for_each(&ctx->personalities, index, cred)
9791 io_uring_show_cred(m, index, cred);
9793 seq_printf(m, "PollList:\n");
9794 spin_lock(&ctx->completion_lock);
9795 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9796 struct hlist_head *list = &ctx->cancel_hash[i];
9797 struct io_kiocb *req;
9799 hlist_for_each_entry(req, list, hash_node)
9800 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9801 req->task->task_works != NULL);
9803 spin_unlock(&ctx->completion_lock);
9805 mutex_unlock(&ctx->uring_lock);
9808 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9810 struct io_ring_ctx *ctx = f->private_data;
9812 if (percpu_ref_tryget(&ctx->refs)) {
9813 __io_uring_show_fdinfo(ctx, m);
9814 percpu_ref_put(&ctx->refs);
9819 static const struct file_operations io_uring_fops = {
9820 .release = io_uring_release,
9821 .mmap = io_uring_mmap,
9823 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9824 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9826 .poll = io_uring_poll,
9827 .fasync = io_uring_fasync,
9828 #ifdef CONFIG_PROC_FS
9829 .show_fdinfo = io_uring_show_fdinfo,
9833 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9834 struct io_uring_params *p)
9836 struct io_rings *rings;
9837 size_t size, sq_array_offset;
9839 /* make sure these are sane, as we already accounted them */
9840 ctx->sq_entries = p->sq_entries;
9841 ctx->cq_entries = p->cq_entries;
9843 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9844 if (size == SIZE_MAX)
9847 rings = io_mem_alloc(size);
9852 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9853 rings->sq_ring_mask = p->sq_entries - 1;
9854 rings->cq_ring_mask = p->cq_entries - 1;
9855 rings->sq_ring_entries = p->sq_entries;
9856 rings->cq_ring_entries = p->cq_entries;
9858 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9859 if (size == SIZE_MAX) {
9860 io_mem_free(ctx->rings);
9865 ctx->sq_sqes = io_mem_alloc(size);
9866 if (!ctx->sq_sqes) {
9867 io_mem_free(ctx->rings);
9875 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9879 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9883 ret = io_uring_add_tctx_node(ctx);
9888 fd_install(fd, file);
9893 * Allocate an anonymous fd, this is what constitutes the application
9894 * visible backing of an io_uring instance. The application mmaps this
9895 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9896 * we have to tie this fd to a socket for file garbage collection purposes.
9898 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9901 #if defined(CONFIG_UNIX)
9904 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9907 return ERR_PTR(ret);
9910 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9911 O_RDWR | O_CLOEXEC);
9912 #if defined(CONFIG_UNIX)
9914 sock_release(ctx->ring_sock);
9915 ctx->ring_sock = NULL;
9917 ctx->ring_sock->file = file;
9923 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9924 struct io_uring_params __user *params)
9926 struct io_ring_ctx *ctx;
9932 if (entries > IORING_MAX_ENTRIES) {
9933 if (!(p->flags & IORING_SETUP_CLAMP))
9935 entries = IORING_MAX_ENTRIES;
9939 * Use twice as many entries for the CQ ring. It's possible for the
9940 * application to drive a higher depth than the size of the SQ ring,
9941 * since the sqes are only used at submission time. This allows for
9942 * some flexibility in overcommitting a bit. If the application has
9943 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9944 * of CQ ring entries manually.
9946 p->sq_entries = roundup_pow_of_two(entries);
9947 if (p->flags & IORING_SETUP_CQSIZE) {
9949 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9950 * to a power-of-two, if it isn't already. We do NOT impose
9951 * any cq vs sq ring sizing.
9955 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9956 if (!(p->flags & IORING_SETUP_CLAMP))
9958 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9960 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9961 if (p->cq_entries < p->sq_entries)
9964 p->cq_entries = 2 * p->sq_entries;
9967 ctx = io_ring_ctx_alloc(p);
9970 ctx->compat = in_compat_syscall();
9971 if (!capable(CAP_IPC_LOCK))
9972 ctx->user = get_uid(current_user());
9975 * This is just grabbed for accounting purposes. When a process exits,
9976 * the mm is exited and dropped before the files, hence we need to hang
9977 * on to this mm purely for the purposes of being able to unaccount
9978 * memory (locked/pinned vm). It's not used for anything else.
9980 mmgrab(current->mm);
9981 ctx->mm_account = current->mm;
9983 ret = io_allocate_scq_urings(ctx, p);
9987 ret = io_sq_offload_create(ctx, p);
9990 /* always set a rsrc node */
9991 ret = io_rsrc_node_switch_start(ctx);
9994 io_rsrc_node_switch(ctx, NULL);
9996 memset(&p->sq_off, 0, sizeof(p->sq_off));
9997 p->sq_off.head = offsetof(struct io_rings, sq.head);
9998 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9999 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10000 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10001 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10002 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10003 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10005 memset(&p->cq_off, 0, sizeof(p->cq_off));
10006 p->cq_off.head = offsetof(struct io_rings, cq.head);
10007 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10008 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10009 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10010 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10011 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10012 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10014 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10015 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10016 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10017 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10018 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10019 IORING_FEAT_RSRC_TAGS;
10021 if (copy_to_user(params, p, sizeof(*p))) {
10026 file = io_uring_get_file(ctx);
10027 if (IS_ERR(file)) {
10028 ret = PTR_ERR(file);
10033 * Install ring fd as the very last thing, so we don't risk someone
10034 * having closed it before we finish setup
10036 ret = io_uring_install_fd(ctx, file);
10038 /* fput will clean it up */
10043 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10046 io_ring_ctx_wait_and_kill(ctx);
10051 * Sets up an aio uring context, and returns the fd. Applications asks for a
10052 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10053 * params structure passed in.
10055 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10057 struct io_uring_params p;
10060 if (copy_from_user(&p, params, sizeof(p)))
10062 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10067 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10068 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10069 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10070 IORING_SETUP_R_DISABLED))
10073 return io_uring_create(entries, &p, params);
10076 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10077 struct io_uring_params __user *, params)
10079 return io_uring_setup(entries, params);
10082 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10084 struct io_uring_probe *p;
10088 size = struct_size(p, ops, nr_args);
10089 if (size == SIZE_MAX)
10091 p = kzalloc(size, GFP_KERNEL);
10096 if (copy_from_user(p, arg, size))
10099 if (memchr_inv(p, 0, size))
10102 p->last_op = IORING_OP_LAST - 1;
10103 if (nr_args > IORING_OP_LAST)
10104 nr_args = IORING_OP_LAST;
10106 for (i = 0; i < nr_args; i++) {
10108 if (!io_op_defs[i].not_supported)
10109 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10114 if (copy_to_user(arg, p, size))
10121 static int io_register_personality(struct io_ring_ctx *ctx)
10123 const struct cred *creds;
10127 creds = get_current_cred();
10129 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10130 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10138 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10139 unsigned int nr_args)
10141 struct io_uring_restriction *res;
10145 /* Restrictions allowed only if rings started disabled */
10146 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10149 /* We allow only a single restrictions registration */
10150 if (ctx->restrictions.registered)
10153 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10156 size = array_size(nr_args, sizeof(*res));
10157 if (size == SIZE_MAX)
10160 res = memdup_user(arg, size);
10162 return PTR_ERR(res);
10166 for (i = 0; i < nr_args; i++) {
10167 switch (res[i].opcode) {
10168 case IORING_RESTRICTION_REGISTER_OP:
10169 if (res[i].register_op >= IORING_REGISTER_LAST) {
10174 __set_bit(res[i].register_op,
10175 ctx->restrictions.register_op);
10177 case IORING_RESTRICTION_SQE_OP:
10178 if (res[i].sqe_op >= IORING_OP_LAST) {
10183 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10185 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10186 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10188 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10189 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10198 /* Reset all restrictions if an error happened */
10200 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10202 ctx->restrictions.registered = true;
10208 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10210 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10213 if (ctx->restrictions.registered)
10214 ctx->restricted = 1;
10216 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10217 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10218 wake_up(&ctx->sq_data->wait);
10222 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10223 struct io_uring_rsrc_update2 *up,
10231 if (check_add_overflow(up->offset, nr_args, &tmp))
10233 err = io_rsrc_node_switch_start(ctx);
10238 case IORING_RSRC_FILE:
10239 return __io_sqe_files_update(ctx, up, nr_args);
10240 case IORING_RSRC_BUFFER:
10241 return __io_sqe_buffers_update(ctx, up, nr_args);
10246 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10249 struct io_uring_rsrc_update2 up;
10253 memset(&up, 0, sizeof(up));
10254 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10256 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10259 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10260 unsigned size, unsigned type)
10262 struct io_uring_rsrc_update2 up;
10264 if (size != sizeof(up))
10266 if (copy_from_user(&up, arg, sizeof(up)))
10268 if (!up.nr || up.resv)
10270 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10273 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10274 unsigned int size, unsigned int type)
10276 struct io_uring_rsrc_register rr;
10278 /* keep it extendible */
10279 if (size != sizeof(rr))
10282 memset(&rr, 0, sizeof(rr));
10283 if (copy_from_user(&rr, arg, size))
10285 if (!rr.nr || rr.resv || rr.resv2)
10289 case IORING_RSRC_FILE:
10290 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10291 rr.nr, u64_to_user_ptr(rr.tags));
10292 case IORING_RSRC_BUFFER:
10293 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10294 rr.nr, u64_to_user_ptr(rr.tags));
10299 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10302 struct io_uring_task *tctx = current->io_uring;
10303 cpumask_var_t new_mask;
10306 if (!tctx || !tctx->io_wq)
10309 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10312 cpumask_clear(new_mask);
10313 if (len > cpumask_size())
10314 len = cpumask_size();
10316 if (copy_from_user(new_mask, arg, len)) {
10317 free_cpumask_var(new_mask);
10321 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10322 free_cpumask_var(new_mask);
10326 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10328 struct io_uring_task *tctx = current->io_uring;
10330 if (!tctx || !tctx->io_wq)
10333 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10336 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10339 struct io_uring_task *tctx = NULL;
10340 struct io_sq_data *sqd = NULL;
10341 __u32 new_count[2];
10344 if (copy_from_user(new_count, arg, sizeof(new_count)))
10346 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10347 if (new_count[i] > INT_MAX)
10350 if (ctx->flags & IORING_SETUP_SQPOLL) {
10351 sqd = ctx->sq_data;
10353 mutex_lock(&sqd->lock);
10354 tctx = sqd->thread->io_uring;
10357 tctx = current->io_uring;
10361 if (!tctx || !tctx->io_wq)
10364 ret = io_wq_max_workers(tctx->io_wq, new_count);
10369 mutex_unlock(&sqd->lock);
10371 if (copy_to_user(arg, new_count, sizeof(new_count)))
10377 mutex_unlock(&sqd->lock);
10381 static bool io_register_op_must_quiesce(int op)
10384 case IORING_REGISTER_BUFFERS:
10385 case IORING_UNREGISTER_BUFFERS:
10386 case IORING_REGISTER_FILES:
10387 case IORING_UNREGISTER_FILES:
10388 case IORING_REGISTER_FILES_UPDATE:
10389 case IORING_REGISTER_PROBE:
10390 case IORING_REGISTER_PERSONALITY:
10391 case IORING_UNREGISTER_PERSONALITY:
10392 case IORING_REGISTER_FILES2:
10393 case IORING_REGISTER_FILES_UPDATE2:
10394 case IORING_REGISTER_BUFFERS2:
10395 case IORING_REGISTER_BUFFERS_UPDATE:
10396 case IORING_REGISTER_IOWQ_AFF:
10397 case IORING_UNREGISTER_IOWQ_AFF:
10398 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10405 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10409 percpu_ref_kill(&ctx->refs);
10412 * Drop uring mutex before waiting for references to exit. If another
10413 * thread is currently inside io_uring_enter() it might need to grab the
10414 * uring_lock to make progress. If we hold it here across the drain
10415 * wait, then we can deadlock. It's safe to drop the mutex here, since
10416 * no new references will come in after we've killed the percpu ref.
10418 mutex_unlock(&ctx->uring_lock);
10420 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10423 ret = io_run_task_work_sig();
10424 } while (ret >= 0);
10425 mutex_lock(&ctx->uring_lock);
10428 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10432 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10433 void __user *arg, unsigned nr_args)
10434 __releases(ctx->uring_lock)
10435 __acquires(ctx->uring_lock)
10440 * We're inside the ring mutex, if the ref is already dying, then
10441 * someone else killed the ctx or is already going through
10442 * io_uring_register().
10444 if (percpu_ref_is_dying(&ctx->refs))
10447 if (ctx->restricted) {
10448 if (opcode >= IORING_REGISTER_LAST)
10450 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10451 if (!test_bit(opcode, ctx->restrictions.register_op))
10455 if (io_register_op_must_quiesce(opcode)) {
10456 ret = io_ctx_quiesce(ctx);
10462 case IORING_REGISTER_BUFFERS:
10463 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10465 case IORING_UNREGISTER_BUFFERS:
10467 if (arg || nr_args)
10469 ret = io_sqe_buffers_unregister(ctx);
10471 case IORING_REGISTER_FILES:
10472 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10474 case IORING_UNREGISTER_FILES:
10476 if (arg || nr_args)
10478 ret = io_sqe_files_unregister(ctx);
10480 case IORING_REGISTER_FILES_UPDATE:
10481 ret = io_register_files_update(ctx, arg, nr_args);
10483 case IORING_REGISTER_EVENTFD:
10484 case IORING_REGISTER_EVENTFD_ASYNC:
10488 ret = io_eventfd_register(ctx, arg);
10491 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10492 ctx->eventfd_async = 1;
10494 ctx->eventfd_async = 0;
10496 case IORING_UNREGISTER_EVENTFD:
10498 if (arg || nr_args)
10500 ret = io_eventfd_unregister(ctx);
10502 case IORING_REGISTER_PROBE:
10504 if (!arg || nr_args > 256)
10506 ret = io_probe(ctx, arg, nr_args);
10508 case IORING_REGISTER_PERSONALITY:
10510 if (arg || nr_args)
10512 ret = io_register_personality(ctx);
10514 case IORING_UNREGISTER_PERSONALITY:
10518 ret = io_unregister_personality(ctx, nr_args);
10520 case IORING_REGISTER_ENABLE_RINGS:
10522 if (arg || nr_args)
10524 ret = io_register_enable_rings(ctx);
10526 case IORING_REGISTER_RESTRICTIONS:
10527 ret = io_register_restrictions(ctx, arg, nr_args);
10529 case IORING_REGISTER_FILES2:
10530 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10532 case IORING_REGISTER_FILES_UPDATE2:
10533 ret = io_register_rsrc_update(ctx, arg, nr_args,
10536 case IORING_REGISTER_BUFFERS2:
10537 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10539 case IORING_REGISTER_BUFFERS_UPDATE:
10540 ret = io_register_rsrc_update(ctx, arg, nr_args,
10541 IORING_RSRC_BUFFER);
10543 case IORING_REGISTER_IOWQ_AFF:
10545 if (!arg || !nr_args)
10547 ret = io_register_iowq_aff(ctx, arg, nr_args);
10549 case IORING_UNREGISTER_IOWQ_AFF:
10551 if (arg || nr_args)
10553 ret = io_unregister_iowq_aff(ctx);
10555 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10557 if (!arg || nr_args != 2)
10559 ret = io_register_iowq_max_workers(ctx, arg);
10566 if (io_register_op_must_quiesce(opcode)) {
10567 /* bring the ctx back to life */
10568 percpu_ref_reinit(&ctx->refs);
10569 reinit_completion(&ctx->ref_comp);
10574 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10575 void __user *, arg, unsigned int, nr_args)
10577 struct io_ring_ctx *ctx;
10586 if (f.file->f_op != &io_uring_fops)
10589 ctx = f.file->private_data;
10591 io_run_task_work();
10593 mutex_lock(&ctx->uring_lock);
10594 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10595 mutex_unlock(&ctx->uring_lock);
10596 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10597 ctx->cq_ev_fd != NULL, ret);
10603 static int __init io_uring_init(void)
10605 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10606 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10607 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10610 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10611 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10612 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10613 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10614 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10615 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10616 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10617 BUILD_BUG_SQE_ELEM(8, __u64, off);
10618 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10619 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10620 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10621 BUILD_BUG_SQE_ELEM(24, __u32, len);
10622 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10623 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10624 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10625 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10626 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10627 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10628 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10629 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10630 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10631 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10632 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10633 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10634 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10635 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10636 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10637 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10638 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10639 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10640 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10641 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10642 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10644 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10645 sizeof(struct io_uring_rsrc_update));
10646 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10647 sizeof(struct io_uring_rsrc_update2));
10649 /* ->buf_index is u16 */
10650 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10652 /* should fit into one byte */
10653 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10655 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10656 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10658 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10662 __initcall(io_uring_init);