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;
674 struct filename *filename;
680 struct filename *oldpath;
681 struct filename *newpath;
688 struct filename *oldpath;
689 struct filename *newpath;
693 struct io_completion {
698 struct io_async_connect {
699 struct sockaddr_storage address;
702 struct io_async_msghdr {
703 struct iovec fast_iov[UIO_FASTIOV];
704 /* points to an allocated iov, if NULL we use fast_iov instead */
705 struct iovec *free_iov;
706 struct sockaddr __user *uaddr;
708 struct sockaddr_storage addr;
712 struct iovec fast_iov[UIO_FASTIOV];
713 const struct iovec *free_iovec;
714 struct iov_iter iter;
716 struct wait_page_queue wpq;
720 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
721 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
722 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
723 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
724 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
725 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
727 /* first byte is taken by user flags, shift it to not overlap */
732 REQ_F_LINK_TIMEOUT_BIT,
733 REQ_F_NEED_CLEANUP_BIT,
735 REQ_F_BUFFER_SELECTED_BIT,
736 REQ_F_COMPLETE_INLINE_BIT,
738 REQ_F_DONT_REISSUE_BIT,
741 REQ_F_ARM_LTIMEOUT_BIT,
742 /* keep async read/write and isreg together and in order */
743 REQ_F_NOWAIT_READ_BIT,
744 REQ_F_NOWAIT_WRITE_BIT,
747 /* not a real bit, just to check we're not overflowing the space */
753 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
754 /* drain existing IO first */
755 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
757 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
758 /* doesn't sever on completion < 0 */
759 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
761 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
762 /* IOSQE_BUFFER_SELECT */
763 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
765 /* fail rest of links */
766 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
767 /* on inflight list, should be cancelled and waited on exit reliably */
768 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
769 /* read/write uses file position */
770 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
771 /* must not punt to workers */
772 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
773 /* has or had linked timeout */
774 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
776 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
777 /* already went through poll handler */
778 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
779 /* buffer already selected */
780 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
781 /* completion is deferred through io_comp_state */
782 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
783 /* caller should reissue async */
784 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
785 /* don't attempt request reissue, see io_rw_reissue() */
786 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
787 /* supports async reads */
788 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
789 /* supports async writes */
790 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
792 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
793 /* has creds assigned */
794 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
795 /* skip refcounting if not set */
796 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
797 /* there is a linked timeout that has to be armed */
798 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
802 struct io_poll_iocb poll;
803 struct io_poll_iocb *double_poll;
806 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
808 struct io_task_work {
810 struct io_wq_work_node node;
811 struct llist_node fallback_node;
813 io_req_tw_func_t func;
817 IORING_RSRC_FILE = 0,
818 IORING_RSRC_BUFFER = 1,
822 * NOTE! Each of the iocb union members has the file pointer
823 * as the first entry in their struct definition. So you can
824 * access the file pointer through any of the sub-structs,
825 * or directly as just 'ki_filp' in this struct.
831 struct io_poll_iocb poll;
832 struct io_poll_update poll_update;
833 struct io_accept accept;
835 struct io_cancel cancel;
836 struct io_timeout timeout;
837 struct io_timeout_rem timeout_rem;
838 struct io_connect connect;
839 struct io_sr_msg sr_msg;
841 struct io_close close;
842 struct io_rsrc_update rsrc_update;
843 struct io_fadvise fadvise;
844 struct io_madvise madvise;
845 struct io_epoll epoll;
846 struct io_splice splice;
847 struct io_provide_buf pbuf;
848 struct io_statx statx;
849 struct io_shutdown shutdown;
850 struct io_rename rename;
851 struct io_unlink unlink;
852 struct io_mkdir mkdir;
853 struct io_symlink symlink;
854 struct io_hardlink hardlink;
855 /* use only after cleaning per-op data, see io_clean_op() */
856 struct io_completion compl;
859 /* opcode allocated if it needs to store data for async defer */
862 /* polled IO has completed */
868 struct io_ring_ctx *ctx;
871 struct task_struct *task;
874 struct io_kiocb *link;
875 struct percpu_ref *fixed_rsrc_refs;
877 /* used with ctx->iopoll_list with reads/writes */
878 struct list_head inflight_entry;
879 struct io_task_work io_task_work;
880 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
881 struct hlist_node hash_node;
882 struct async_poll *apoll;
883 struct io_wq_work work;
884 const struct cred *creds;
886 /* store used ubuf, so we can prevent reloading */
887 struct io_mapped_ubuf *imu;
890 struct io_tctx_node {
891 struct list_head ctx_node;
892 struct task_struct *task;
893 struct io_ring_ctx *ctx;
896 struct io_defer_entry {
897 struct list_head list;
898 struct io_kiocb *req;
903 /* needs req->file assigned */
904 unsigned needs_file : 1;
905 /* hash wq insertion if file is a regular file */
906 unsigned hash_reg_file : 1;
907 /* unbound wq insertion if file is a non-regular file */
908 unsigned unbound_nonreg_file : 1;
909 /* opcode is not supported by this kernel */
910 unsigned not_supported : 1;
911 /* set if opcode supports polled "wait" */
913 unsigned pollout : 1;
914 /* op supports buffer selection */
915 unsigned buffer_select : 1;
916 /* do prep async if is going to be punted */
917 unsigned needs_async_setup : 1;
918 /* should block plug */
920 /* size of async data needed, if any */
921 unsigned short async_size;
924 static const struct io_op_def io_op_defs[] = {
925 [IORING_OP_NOP] = {},
926 [IORING_OP_READV] = {
928 .unbound_nonreg_file = 1,
931 .needs_async_setup = 1,
933 .async_size = sizeof(struct io_async_rw),
935 [IORING_OP_WRITEV] = {
938 .unbound_nonreg_file = 1,
940 .needs_async_setup = 1,
942 .async_size = sizeof(struct io_async_rw),
944 [IORING_OP_FSYNC] = {
947 [IORING_OP_READ_FIXED] = {
949 .unbound_nonreg_file = 1,
952 .async_size = sizeof(struct io_async_rw),
954 [IORING_OP_WRITE_FIXED] = {
957 .unbound_nonreg_file = 1,
960 .async_size = sizeof(struct io_async_rw),
962 [IORING_OP_POLL_ADD] = {
964 .unbound_nonreg_file = 1,
966 [IORING_OP_POLL_REMOVE] = {},
967 [IORING_OP_SYNC_FILE_RANGE] = {
970 [IORING_OP_SENDMSG] = {
972 .unbound_nonreg_file = 1,
974 .needs_async_setup = 1,
975 .async_size = sizeof(struct io_async_msghdr),
977 [IORING_OP_RECVMSG] = {
979 .unbound_nonreg_file = 1,
982 .needs_async_setup = 1,
983 .async_size = sizeof(struct io_async_msghdr),
985 [IORING_OP_TIMEOUT] = {
986 .async_size = sizeof(struct io_timeout_data),
988 [IORING_OP_TIMEOUT_REMOVE] = {
989 /* used by timeout updates' prep() */
991 [IORING_OP_ACCEPT] = {
993 .unbound_nonreg_file = 1,
996 [IORING_OP_ASYNC_CANCEL] = {},
997 [IORING_OP_LINK_TIMEOUT] = {
998 .async_size = sizeof(struct io_timeout_data),
1000 [IORING_OP_CONNECT] = {
1002 .unbound_nonreg_file = 1,
1004 .needs_async_setup = 1,
1005 .async_size = sizeof(struct io_async_connect),
1007 [IORING_OP_FALLOCATE] = {
1010 [IORING_OP_OPENAT] = {},
1011 [IORING_OP_CLOSE] = {},
1012 [IORING_OP_FILES_UPDATE] = {},
1013 [IORING_OP_STATX] = {},
1014 [IORING_OP_READ] = {
1016 .unbound_nonreg_file = 1,
1020 .async_size = sizeof(struct io_async_rw),
1022 [IORING_OP_WRITE] = {
1024 .unbound_nonreg_file = 1,
1027 .async_size = sizeof(struct io_async_rw),
1029 [IORING_OP_FADVISE] = {
1032 [IORING_OP_MADVISE] = {},
1033 [IORING_OP_SEND] = {
1035 .unbound_nonreg_file = 1,
1038 [IORING_OP_RECV] = {
1040 .unbound_nonreg_file = 1,
1044 [IORING_OP_OPENAT2] = {
1046 [IORING_OP_EPOLL_CTL] = {
1047 .unbound_nonreg_file = 1,
1049 [IORING_OP_SPLICE] = {
1052 .unbound_nonreg_file = 1,
1054 [IORING_OP_PROVIDE_BUFFERS] = {},
1055 [IORING_OP_REMOVE_BUFFERS] = {},
1059 .unbound_nonreg_file = 1,
1061 [IORING_OP_SHUTDOWN] = {
1064 [IORING_OP_RENAMEAT] = {},
1065 [IORING_OP_UNLINKAT] = {},
1066 [IORING_OP_MKDIRAT] = {},
1067 [IORING_OP_SYMLINKAT] = {},
1068 [IORING_OP_LINKAT] = {},
1071 /* requests with any of those set should undergo io_disarm_next() */
1072 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1074 static bool io_disarm_next(struct io_kiocb *req);
1075 static void io_uring_del_tctx_node(unsigned long index);
1076 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1077 struct task_struct *task,
1079 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1081 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1082 long res, unsigned int cflags);
1083 static void io_put_req(struct io_kiocb *req);
1084 static void io_put_req_deferred(struct io_kiocb *req);
1085 static void io_dismantle_req(struct io_kiocb *req);
1086 static void io_queue_linked_timeout(struct io_kiocb *req);
1087 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1088 struct io_uring_rsrc_update2 *up,
1090 static void io_clean_op(struct io_kiocb *req);
1091 static struct file *io_file_get(struct io_ring_ctx *ctx,
1092 struct io_kiocb *req, int fd, bool fixed);
1093 static void __io_queue_sqe(struct io_kiocb *req);
1094 static void io_rsrc_put_work(struct work_struct *work);
1096 static void io_req_task_queue(struct io_kiocb *req);
1097 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1098 static int io_req_prep_async(struct io_kiocb *req);
1100 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1101 unsigned int issue_flags, u32 slot_index);
1102 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1104 static struct kmem_cache *req_cachep;
1106 static const struct file_operations io_uring_fops;
1108 struct sock *io_uring_get_socket(struct file *file)
1110 #if defined(CONFIG_UNIX)
1111 if (file->f_op == &io_uring_fops) {
1112 struct io_ring_ctx *ctx = file->private_data;
1114 return ctx->ring_sock->sk;
1119 EXPORT_SYMBOL(io_uring_get_socket);
1121 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1124 mutex_lock(&ctx->uring_lock);
1129 #define io_for_each_link(pos, head) \
1130 for (pos = (head); pos; pos = pos->link)
1133 * Shamelessly stolen from the mm implementation of page reference checking,
1134 * see commit f958d7b528b1 for details.
1136 #define req_ref_zero_or_close_to_overflow(req) \
1137 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1139 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1141 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1142 return atomic_inc_not_zero(&req->refs);
1145 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1147 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1150 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1151 return atomic_dec_and_test(&req->refs);
1154 static inline void req_ref_put(struct io_kiocb *req)
1156 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1157 WARN_ON_ONCE(req_ref_put_and_test(req));
1160 static inline void req_ref_get(struct io_kiocb *req)
1162 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1163 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1164 atomic_inc(&req->refs);
1167 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1169 if (!(req->flags & REQ_F_REFCOUNT)) {
1170 req->flags |= REQ_F_REFCOUNT;
1171 atomic_set(&req->refs, nr);
1175 static inline void io_req_set_refcount(struct io_kiocb *req)
1177 __io_req_set_refcount(req, 1);
1180 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1182 struct io_ring_ctx *ctx = req->ctx;
1184 if (!req->fixed_rsrc_refs) {
1185 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1186 percpu_ref_get(req->fixed_rsrc_refs);
1190 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1192 bool got = percpu_ref_tryget(ref);
1194 /* already at zero, wait for ->release() */
1196 wait_for_completion(compl);
1197 percpu_ref_resurrect(ref);
1199 percpu_ref_put(ref);
1202 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1205 struct io_kiocb *req;
1207 if (task && head->task != task)
1212 io_for_each_link(req, head) {
1213 if (req->flags & REQ_F_INFLIGHT)
1219 static inline void req_set_fail(struct io_kiocb *req)
1221 req->flags |= REQ_F_FAIL;
1224 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1230 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1232 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1234 complete(&ctx->ref_comp);
1237 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1239 return !req->timeout.off;
1242 static void io_fallback_req_func(struct work_struct *work)
1244 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1245 fallback_work.work);
1246 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1247 struct io_kiocb *req, *tmp;
1248 bool locked = false;
1250 percpu_ref_get(&ctx->refs);
1251 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1252 req->io_task_work.func(req, &locked);
1255 if (ctx->submit_state.compl_nr)
1256 io_submit_flush_completions(ctx);
1257 mutex_unlock(&ctx->uring_lock);
1259 percpu_ref_put(&ctx->refs);
1263 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1265 struct io_ring_ctx *ctx;
1268 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1273 * Use 5 bits less than the max cq entries, that should give us around
1274 * 32 entries per hash list if totally full and uniformly spread.
1276 hash_bits = ilog2(p->cq_entries);
1280 ctx->cancel_hash_bits = hash_bits;
1281 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1283 if (!ctx->cancel_hash)
1285 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1287 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1288 if (!ctx->dummy_ubuf)
1290 /* set invalid range, so io_import_fixed() fails meeting it */
1291 ctx->dummy_ubuf->ubuf = -1UL;
1293 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1294 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1297 ctx->flags = p->flags;
1298 init_waitqueue_head(&ctx->sqo_sq_wait);
1299 INIT_LIST_HEAD(&ctx->sqd_list);
1300 init_waitqueue_head(&ctx->poll_wait);
1301 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1302 init_completion(&ctx->ref_comp);
1303 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1304 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1305 mutex_init(&ctx->uring_lock);
1306 init_waitqueue_head(&ctx->cq_wait);
1307 spin_lock_init(&ctx->completion_lock);
1308 spin_lock_init(&ctx->timeout_lock);
1309 INIT_LIST_HEAD(&ctx->iopoll_list);
1310 INIT_LIST_HEAD(&ctx->defer_list);
1311 INIT_LIST_HEAD(&ctx->timeout_list);
1312 INIT_LIST_HEAD(&ctx->ltimeout_list);
1313 spin_lock_init(&ctx->rsrc_ref_lock);
1314 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1315 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1316 init_llist_head(&ctx->rsrc_put_llist);
1317 INIT_LIST_HEAD(&ctx->tctx_list);
1318 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1319 INIT_LIST_HEAD(&ctx->locked_free_list);
1320 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1323 kfree(ctx->dummy_ubuf);
1324 kfree(ctx->cancel_hash);
1329 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1331 struct io_rings *r = ctx->rings;
1333 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1337 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1339 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1340 struct io_ring_ctx *ctx = req->ctx;
1342 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1348 #define FFS_ASYNC_READ 0x1UL
1349 #define FFS_ASYNC_WRITE 0x2UL
1351 #define FFS_ISREG 0x4UL
1353 #define FFS_ISREG 0x0UL
1355 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1357 static inline bool io_req_ffs_set(struct io_kiocb *req)
1359 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1362 static void io_req_track_inflight(struct io_kiocb *req)
1364 if (!(req->flags & REQ_F_INFLIGHT)) {
1365 req->flags |= REQ_F_INFLIGHT;
1366 atomic_inc(¤t->io_uring->inflight_tracked);
1370 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1372 req->flags &= ~REQ_F_LINK_TIMEOUT;
1375 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1377 if (WARN_ON_ONCE(!req->link))
1380 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1381 req->flags |= REQ_F_LINK_TIMEOUT;
1383 /* linked timeouts should have two refs once prep'ed */
1384 io_req_set_refcount(req);
1385 __io_req_set_refcount(req->link, 2);
1389 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1391 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1393 return __io_prep_linked_timeout(req);
1396 static void io_prep_async_work(struct io_kiocb *req)
1398 const struct io_op_def *def = &io_op_defs[req->opcode];
1399 struct io_ring_ctx *ctx = req->ctx;
1401 if (!(req->flags & REQ_F_CREDS)) {
1402 req->flags |= REQ_F_CREDS;
1403 req->creds = get_current_cred();
1406 req->work.list.next = NULL;
1407 req->work.flags = 0;
1408 if (req->flags & REQ_F_FORCE_ASYNC)
1409 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1411 if (req->flags & REQ_F_ISREG) {
1412 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1413 io_wq_hash_work(&req->work, file_inode(req->file));
1414 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1415 if (def->unbound_nonreg_file)
1416 req->work.flags |= IO_WQ_WORK_UNBOUND;
1419 switch (req->opcode) {
1420 case IORING_OP_SPLICE:
1422 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1423 req->work.flags |= IO_WQ_WORK_UNBOUND;
1428 static void io_prep_async_link(struct io_kiocb *req)
1430 struct io_kiocb *cur;
1432 if (req->flags & REQ_F_LINK_TIMEOUT) {
1433 struct io_ring_ctx *ctx = req->ctx;
1435 spin_lock(&ctx->completion_lock);
1436 io_for_each_link(cur, req)
1437 io_prep_async_work(cur);
1438 spin_unlock(&ctx->completion_lock);
1440 io_for_each_link(cur, req)
1441 io_prep_async_work(cur);
1445 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1447 struct io_ring_ctx *ctx = req->ctx;
1448 struct io_kiocb *link = io_prep_linked_timeout(req);
1449 struct io_uring_task *tctx = req->task->io_uring;
1451 /* must not take the lock, NULL it as a precaution */
1455 BUG_ON(!tctx->io_wq);
1457 /* init ->work of the whole link before punting */
1458 io_prep_async_link(req);
1461 * Not expected to happen, but if we do have a bug where this _can_
1462 * happen, catch it here and ensure the request is marked as
1463 * canceled. That will make io-wq go through the usual work cancel
1464 * procedure rather than attempt to run this request (or create a new
1467 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1468 req->work.flags |= IO_WQ_WORK_CANCEL;
1470 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1471 &req->work, req->flags);
1472 io_wq_enqueue(tctx->io_wq, &req->work);
1474 io_queue_linked_timeout(link);
1477 static void io_kill_timeout(struct io_kiocb *req, int status)
1478 __must_hold(&req->ctx->completion_lock)
1479 __must_hold(&req->ctx->timeout_lock)
1481 struct io_timeout_data *io = req->async_data;
1483 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1484 atomic_set(&req->ctx->cq_timeouts,
1485 atomic_read(&req->ctx->cq_timeouts) + 1);
1486 list_del_init(&req->timeout.list);
1487 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1488 io_put_req_deferred(req);
1492 static void io_queue_deferred(struct io_ring_ctx *ctx)
1494 while (!list_empty(&ctx->defer_list)) {
1495 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1496 struct io_defer_entry, list);
1498 if (req_need_defer(de->req, de->seq))
1500 list_del_init(&de->list);
1501 io_req_task_queue(de->req);
1506 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1507 __must_hold(&ctx->completion_lock)
1509 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1511 spin_lock_irq(&ctx->timeout_lock);
1512 while (!list_empty(&ctx->timeout_list)) {
1513 u32 events_needed, events_got;
1514 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1515 struct io_kiocb, timeout.list);
1517 if (io_is_timeout_noseq(req))
1521 * Since seq can easily wrap around over time, subtract
1522 * the last seq at which timeouts were flushed before comparing.
1523 * Assuming not more than 2^31-1 events have happened since,
1524 * these subtractions won't have wrapped, so we can check if
1525 * target is in [last_seq, current_seq] by comparing the two.
1527 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1528 events_got = seq - ctx->cq_last_tm_flush;
1529 if (events_got < events_needed)
1532 list_del_init(&req->timeout.list);
1533 io_kill_timeout(req, 0);
1535 ctx->cq_last_tm_flush = seq;
1536 spin_unlock_irq(&ctx->timeout_lock);
1539 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1541 if (ctx->off_timeout_used)
1542 io_flush_timeouts(ctx);
1543 if (ctx->drain_active)
1544 io_queue_deferred(ctx);
1547 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1549 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1550 __io_commit_cqring_flush(ctx);
1551 /* order cqe stores with ring update */
1552 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1555 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1557 struct io_rings *r = ctx->rings;
1559 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1562 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1564 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1567 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1569 struct io_rings *rings = ctx->rings;
1570 unsigned tail, mask = ctx->cq_entries - 1;
1573 * writes to the cq entry need to come after reading head; the
1574 * control dependency is enough as we're using WRITE_ONCE to
1577 if (__io_cqring_events(ctx) == ctx->cq_entries)
1580 tail = ctx->cached_cq_tail++;
1581 return &rings->cqes[tail & mask];
1584 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1586 if (likely(!ctx->cq_ev_fd))
1588 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1590 return !ctx->eventfd_async || io_wq_current_is_worker();
1594 * This should only get called when at least one event has been posted.
1595 * Some applications rely on the eventfd notification count only changing
1596 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1597 * 1:1 relationship between how many times this function is called (and
1598 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1600 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1603 * wake_up_all() may seem excessive, but io_wake_function() and
1604 * io_should_wake() handle the termination of the loop and only
1605 * wake as many waiters as we need to.
1607 if (wq_has_sleeper(&ctx->cq_wait))
1608 wake_up_all(&ctx->cq_wait);
1609 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1610 wake_up(&ctx->sq_data->wait);
1611 if (io_should_trigger_evfd(ctx))
1612 eventfd_signal(ctx->cq_ev_fd, 1);
1613 if (waitqueue_active(&ctx->poll_wait)) {
1614 wake_up_interruptible(&ctx->poll_wait);
1615 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1619 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1621 if (ctx->flags & IORING_SETUP_SQPOLL) {
1622 if (wq_has_sleeper(&ctx->cq_wait))
1623 wake_up_all(&ctx->cq_wait);
1625 if (io_should_trigger_evfd(ctx))
1626 eventfd_signal(ctx->cq_ev_fd, 1);
1627 if (waitqueue_active(&ctx->poll_wait)) {
1628 wake_up_interruptible(&ctx->poll_wait);
1629 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1633 /* Returns true if there are no backlogged entries after the flush */
1634 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1636 bool all_flushed, posted;
1638 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1642 spin_lock(&ctx->completion_lock);
1643 while (!list_empty(&ctx->cq_overflow_list)) {
1644 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1645 struct io_overflow_cqe *ocqe;
1649 ocqe = list_first_entry(&ctx->cq_overflow_list,
1650 struct io_overflow_cqe, list);
1652 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1654 io_account_cq_overflow(ctx);
1657 list_del(&ocqe->list);
1661 all_flushed = list_empty(&ctx->cq_overflow_list);
1663 clear_bit(0, &ctx->check_cq_overflow);
1664 WRITE_ONCE(ctx->rings->sq_flags,
1665 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1669 io_commit_cqring(ctx);
1670 spin_unlock(&ctx->completion_lock);
1672 io_cqring_ev_posted(ctx);
1676 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1680 if (test_bit(0, &ctx->check_cq_overflow)) {
1681 /* iopoll syncs against uring_lock, not completion_lock */
1682 if (ctx->flags & IORING_SETUP_IOPOLL)
1683 mutex_lock(&ctx->uring_lock);
1684 ret = __io_cqring_overflow_flush(ctx, false);
1685 if (ctx->flags & IORING_SETUP_IOPOLL)
1686 mutex_unlock(&ctx->uring_lock);
1692 /* must to be called somewhat shortly after putting a request */
1693 static inline void io_put_task(struct task_struct *task, int nr)
1695 struct io_uring_task *tctx = task->io_uring;
1697 if (likely(task == current)) {
1698 tctx->cached_refs += nr;
1700 percpu_counter_sub(&tctx->inflight, nr);
1701 if (unlikely(atomic_read(&tctx->in_idle)))
1702 wake_up(&tctx->wait);
1703 put_task_struct_many(task, nr);
1707 static void io_task_refs_refill(struct io_uring_task *tctx)
1709 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1711 percpu_counter_add(&tctx->inflight, refill);
1712 refcount_add(refill, ¤t->usage);
1713 tctx->cached_refs += refill;
1716 static inline void io_get_task_refs(int nr)
1718 struct io_uring_task *tctx = current->io_uring;
1720 tctx->cached_refs -= nr;
1721 if (unlikely(tctx->cached_refs < 0))
1722 io_task_refs_refill(tctx);
1725 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1726 long res, unsigned int cflags)
1728 struct io_overflow_cqe *ocqe;
1730 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1733 * If we're in ring overflow flush mode, or in task cancel mode,
1734 * or cannot allocate an overflow entry, then we need to drop it
1737 io_account_cq_overflow(ctx);
1740 if (list_empty(&ctx->cq_overflow_list)) {
1741 set_bit(0, &ctx->check_cq_overflow);
1742 WRITE_ONCE(ctx->rings->sq_flags,
1743 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1746 ocqe->cqe.user_data = user_data;
1747 ocqe->cqe.res = res;
1748 ocqe->cqe.flags = cflags;
1749 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1753 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1754 long res, unsigned int cflags)
1756 struct io_uring_cqe *cqe;
1758 trace_io_uring_complete(ctx, user_data, res, cflags);
1761 * If we can't get a cq entry, userspace overflowed the
1762 * submission (by quite a lot). Increment the overflow count in
1765 cqe = io_get_cqe(ctx);
1767 WRITE_ONCE(cqe->user_data, user_data);
1768 WRITE_ONCE(cqe->res, res);
1769 WRITE_ONCE(cqe->flags, cflags);
1772 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1775 /* not as hot to bloat with inlining */
1776 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1777 long res, unsigned int cflags)
1779 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1782 static void io_req_complete_post(struct io_kiocb *req, long res,
1783 unsigned int cflags)
1785 struct io_ring_ctx *ctx = req->ctx;
1787 spin_lock(&ctx->completion_lock);
1788 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1790 * If we're the last reference to this request, add to our locked
1793 if (req_ref_put_and_test(req)) {
1794 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1795 if (req->flags & IO_DISARM_MASK)
1796 io_disarm_next(req);
1798 io_req_task_queue(req->link);
1802 io_dismantle_req(req);
1803 io_put_task(req->task, 1);
1804 list_add(&req->inflight_entry, &ctx->locked_free_list);
1805 ctx->locked_free_nr++;
1807 if (!percpu_ref_tryget(&ctx->refs))
1810 io_commit_cqring(ctx);
1811 spin_unlock(&ctx->completion_lock);
1814 io_cqring_ev_posted(ctx);
1815 percpu_ref_put(&ctx->refs);
1819 static inline bool io_req_needs_clean(struct io_kiocb *req)
1821 return req->flags & IO_REQ_CLEAN_FLAGS;
1824 static void io_req_complete_state(struct io_kiocb *req, long res,
1825 unsigned int cflags)
1827 if (io_req_needs_clean(req))
1830 req->compl.cflags = cflags;
1831 req->flags |= REQ_F_COMPLETE_INLINE;
1834 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1835 long res, unsigned cflags)
1837 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1838 io_req_complete_state(req, res, cflags);
1840 io_req_complete_post(req, res, cflags);
1843 static inline void io_req_complete(struct io_kiocb *req, long res)
1845 __io_req_complete(req, 0, res, 0);
1848 static void io_req_complete_failed(struct io_kiocb *req, long res)
1851 io_req_complete_post(req, res, 0);
1855 * Don't initialise the fields below on every allocation, but do that in
1856 * advance and keep them valid across allocations.
1858 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1862 req->async_data = NULL;
1863 /* not necessary, but safer to zero */
1867 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1868 struct io_submit_state *state)
1870 spin_lock(&ctx->completion_lock);
1871 list_splice_init(&ctx->locked_free_list, &state->free_list);
1872 ctx->locked_free_nr = 0;
1873 spin_unlock(&ctx->completion_lock);
1876 /* Returns true IFF there are requests in the cache */
1877 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1879 struct io_submit_state *state = &ctx->submit_state;
1883 * If we have more than a batch's worth of requests in our IRQ side
1884 * locked cache, grab the lock and move them over to our submission
1887 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1888 io_flush_cached_locked_reqs(ctx, state);
1890 nr = state->free_reqs;
1891 while (!list_empty(&state->free_list)) {
1892 struct io_kiocb *req = list_first_entry(&state->free_list,
1893 struct io_kiocb, inflight_entry);
1895 list_del(&req->inflight_entry);
1896 state->reqs[nr++] = req;
1897 if (nr == ARRAY_SIZE(state->reqs))
1901 state->free_reqs = nr;
1906 * A request might get retired back into the request caches even before opcode
1907 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1908 * Because of that, io_alloc_req() should be called only under ->uring_lock
1909 * and with extra caution to not get a request that is still worked on.
1911 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1912 __must_hold(&ctx->uring_lock)
1914 struct io_submit_state *state = &ctx->submit_state;
1915 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1918 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1920 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1923 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1927 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1928 * retry single alloc to be on the safe side.
1930 if (unlikely(ret <= 0)) {
1931 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1932 if (!state->reqs[0])
1937 for (i = 0; i < ret; i++)
1938 io_preinit_req(state->reqs[i], ctx);
1939 state->free_reqs = ret;
1942 return state->reqs[state->free_reqs];
1945 static inline void io_put_file(struct file *file)
1951 static void io_dismantle_req(struct io_kiocb *req)
1953 unsigned int flags = req->flags;
1955 if (io_req_needs_clean(req))
1957 if (!(flags & REQ_F_FIXED_FILE))
1958 io_put_file(req->file);
1959 if (req->fixed_rsrc_refs)
1960 percpu_ref_put(req->fixed_rsrc_refs);
1961 if (req->async_data) {
1962 kfree(req->async_data);
1963 req->async_data = NULL;
1967 static void __io_free_req(struct io_kiocb *req)
1969 struct io_ring_ctx *ctx = req->ctx;
1971 io_dismantle_req(req);
1972 io_put_task(req->task, 1);
1974 spin_lock(&ctx->completion_lock);
1975 list_add(&req->inflight_entry, &ctx->locked_free_list);
1976 ctx->locked_free_nr++;
1977 spin_unlock(&ctx->completion_lock);
1979 percpu_ref_put(&ctx->refs);
1982 static inline void io_remove_next_linked(struct io_kiocb *req)
1984 struct io_kiocb *nxt = req->link;
1986 req->link = nxt->link;
1990 static bool io_kill_linked_timeout(struct io_kiocb *req)
1991 __must_hold(&req->ctx->completion_lock)
1992 __must_hold(&req->ctx->timeout_lock)
1994 struct io_kiocb *link = req->link;
1996 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1997 struct io_timeout_data *io = link->async_data;
1999 io_remove_next_linked(req);
2000 link->timeout.head = NULL;
2001 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2002 list_del(&link->timeout.list);
2003 io_cqring_fill_event(link->ctx, link->user_data,
2005 io_put_req_deferred(link);
2012 static void io_fail_links(struct io_kiocb *req)
2013 __must_hold(&req->ctx->completion_lock)
2015 struct io_kiocb *nxt, *link = req->link;
2019 long res = -ECANCELED;
2021 if (link->flags & REQ_F_FAIL)
2027 trace_io_uring_fail_link(req, link);
2028 io_cqring_fill_event(link->ctx, link->user_data, res, 0);
2029 io_put_req_deferred(link);
2034 static bool io_disarm_next(struct io_kiocb *req)
2035 __must_hold(&req->ctx->completion_lock)
2037 bool posted = false;
2039 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2040 struct io_kiocb *link = req->link;
2042 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2043 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2044 io_remove_next_linked(req);
2045 io_cqring_fill_event(link->ctx, link->user_data,
2047 io_put_req_deferred(link);
2050 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2051 struct io_ring_ctx *ctx = req->ctx;
2053 spin_lock_irq(&ctx->timeout_lock);
2054 posted = io_kill_linked_timeout(req);
2055 spin_unlock_irq(&ctx->timeout_lock);
2057 if (unlikely((req->flags & REQ_F_FAIL) &&
2058 !(req->flags & REQ_F_HARDLINK))) {
2059 posted |= (req->link != NULL);
2065 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2067 struct io_kiocb *nxt;
2070 * If LINK is set, we have dependent requests in this chain. If we
2071 * didn't fail this request, queue the first one up, moving any other
2072 * dependencies to the next request. In case of failure, fail the rest
2075 if (req->flags & IO_DISARM_MASK) {
2076 struct io_ring_ctx *ctx = req->ctx;
2079 spin_lock(&ctx->completion_lock);
2080 posted = io_disarm_next(req);
2082 io_commit_cqring(req->ctx);
2083 spin_unlock(&ctx->completion_lock);
2085 io_cqring_ev_posted(ctx);
2092 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2094 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2096 return __io_req_find_next(req);
2099 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2104 if (ctx->submit_state.compl_nr)
2105 io_submit_flush_completions(ctx);
2106 mutex_unlock(&ctx->uring_lock);
2109 percpu_ref_put(&ctx->refs);
2112 static void tctx_task_work(struct callback_head *cb)
2114 bool locked = false;
2115 struct io_ring_ctx *ctx = NULL;
2116 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2120 struct io_wq_work_node *node;
2122 spin_lock_irq(&tctx->task_lock);
2123 node = tctx->task_list.first;
2124 INIT_WQ_LIST(&tctx->task_list);
2126 tctx->task_running = false;
2127 spin_unlock_irq(&tctx->task_lock);
2132 struct io_wq_work_node *next = node->next;
2133 struct io_kiocb *req = container_of(node, struct io_kiocb,
2136 if (req->ctx != ctx) {
2137 ctx_flush_and_put(ctx, &locked);
2139 /* if not contended, grab and improve batching */
2140 locked = mutex_trylock(&ctx->uring_lock);
2141 percpu_ref_get(&ctx->refs);
2143 req->io_task_work.func(req, &locked);
2150 ctx_flush_and_put(ctx, &locked);
2153 static void io_req_task_work_add(struct io_kiocb *req)
2155 struct task_struct *tsk = req->task;
2156 struct io_uring_task *tctx = tsk->io_uring;
2157 enum task_work_notify_mode notify;
2158 struct io_wq_work_node *node;
2159 unsigned long flags;
2162 WARN_ON_ONCE(!tctx);
2164 spin_lock_irqsave(&tctx->task_lock, flags);
2165 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2166 running = tctx->task_running;
2168 tctx->task_running = true;
2169 spin_unlock_irqrestore(&tctx->task_lock, flags);
2171 /* task_work already pending, we're done */
2176 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2177 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2178 * processing task_work. There's no reliable way to tell if TWA_RESUME
2181 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2182 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2183 wake_up_process(tsk);
2187 spin_lock_irqsave(&tctx->task_lock, flags);
2188 tctx->task_running = false;
2189 node = tctx->task_list.first;
2190 INIT_WQ_LIST(&tctx->task_list);
2191 spin_unlock_irqrestore(&tctx->task_lock, flags);
2194 req = container_of(node, struct io_kiocb, io_task_work.node);
2196 if (llist_add(&req->io_task_work.fallback_node,
2197 &req->ctx->fallback_llist))
2198 schedule_delayed_work(&req->ctx->fallback_work, 1);
2202 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2204 struct io_ring_ctx *ctx = req->ctx;
2206 /* not needed for normal modes, but SQPOLL depends on it */
2207 io_tw_lock(ctx, locked);
2208 io_req_complete_failed(req, req->result);
2211 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2213 struct io_ring_ctx *ctx = req->ctx;
2215 io_tw_lock(ctx, locked);
2216 /* req->task == current here, checking PF_EXITING is safe */
2217 if (likely(!(req->task->flags & PF_EXITING)))
2218 __io_queue_sqe(req);
2220 io_req_complete_failed(req, -EFAULT);
2223 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2226 req->io_task_work.func = io_req_task_cancel;
2227 io_req_task_work_add(req);
2230 static void io_req_task_queue(struct io_kiocb *req)
2232 req->io_task_work.func = io_req_task_submit;
2233 io_req_task_work_add(req);
2236 static void io_req_task_queue_reissue(struct io_kiocb *req)
2238 req->io_task_work.func = io_queue_async_work;
2239 io_req_task_work_add(req);
2242 static inline void io_queue_next(struct io_kiocb *req)
2244 struct io_kiocb *nxt = io_req_find_next(req);
2247 io_req_task_queue(nxt);
2250 static void io_free_req(struct io_kiocb *req)
2256 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2262 struct task_struct *task;
2267 static inline void io_init_req_batch(struct req_batch *rb)
2274 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2275 struct req_batch *rb)
2278 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2280 io_put_task(rb->task, rb->task_refs);
2283 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2284 struct io_submit_state *state)
2287 io_dismantle_req(req);
2289 if (req->task != rb->task) {
2291 io_put_task(rb->task, rb->task_refs);
2292 rb->task = req->task;
2298 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2299 state->reqs[state->free_reqs++] = req;
2301 list_add(&req->inflight_entry, &state->free_list);
2304 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2305 __must_hold(&ctx->uring_lock)
2307 struct io_submit_state *state = &ctx->submit_state;
2308 int i, nr = state->compl_nr;
2309 struct req_batch rb;
2311 spin_lock(&ctx->completion_lock);
2312 for (i = 0; i < nr; i++) {
2313 struct io_kiocb *req = state->compl_reqs[i];
2315 __io_cqring_fill_event(ctx, req->user_data, req->result,
2318 io_commit_cqring(ctx);
2319 spin_unlock(&ctx->completion_lock);
2320 io_cqring_ev_posted(ctx);
2322 io_init_req_batch(&rb);
2323 for (i = 0; i < nr; i++) {
2324 struct io_kiocb *req = state->compl_reqs[i];
2326 if (req_ref_put_and_test(req))
2327 io_req_free_batch(&rb, req, &ctx->submit_state);
2330 io_req_free_batch_finish(ctx, &rb);
2331 state->compl_nr = 0;
2335 * Drop reference to request, return next in chain (if there is one) if this
2336 * was the last reference to this request.
2338 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2340 struct io_kiocb *nxt = NULL;
2342 if (req_ref_put_and_test(req)) {
2343 nxt = io_req_find_next(req);
2349 static inline void io_put_req(struct io_kiocb *req)
2351 if (req_ref_put_and_test(req))
2355 static inline void io_put_req_deferred(struct io_kiocb *req)
2357 if (req_ref_put_and_test(req)) {
2358 req->io_task_work.func = io_free_req_work;
2359 io_req_task_work_add(req);
2363 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2365 /* See comment at the top of this file */
2367 return __io_cqring_events(ctx);
2370 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2372 struct io_rings *rings = ctx->rings;
2374 /* make sure SQ entry isn't read before tail */
2375 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2378 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2380 unsigned int cflags;
2382 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2383 cflags |= IORING_CQE_F_BUFFER;
2384 req->flags &= ~REQ_F_BUFFER_SELECTED;
2389 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2391 struct io_buffer *kbuf;
2393 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2395 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2396 return io_put_kbuf(req, kbuf);
2399 static inline bool io_run_task_work(void)
2401 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2402 __set_current_state(TASK_RUNNING);
2403 tracehook_notify_signal();
2411 * Find and free completed poll iocbs
2413 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2414 struct list_head *done)
2416 struct req_batch rb;
2417 struct io_kiocb *req;
2419 /* order with ->result store in io_complete_rw_iopoll() */
2422 io_init_req_batch(&rb);
2423 while (!list_empty(done)) {
2424 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2425 list_del(&req->inflight_entry);
2427 if (READ_ONCE(req->result) == -EAGAIN &&
2428 !(req->flags & REQ_F_DONT_REISSUE)) {
2429 req->iopoll_completed = 0;
2430 io_req_task_queue_reissue(req);
2434 __io_cqring_fill_event(ctx, req->user_data, req->result,
2435 io_put_rw_kbuf(req));
2438 if (req_ref_put_and_test(req))
2439 io_req_free_batch(&rb, req, &ctx->submit_state);
2442 io_commit_cqring(ctx);
2443 io_cqring_ev_posted_iopoll(ctx);
2444 io_req_free_batch_finish(ctx, &rb);
2447 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2450 struct io_kiocb *req, *tmp;
2455 * Only spin for completions if we don't have multiple devices hanging
2456 * off our complete list, and we're under the requested amount.
2458 spin = !ctx->poll_multi_queue && *nr_events < min;
2460 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2461 struct kiocb *kiocb = &req->rw.kiocb;
2465 * Move completed and retryable entries to our local lists.
2466 * If we find a request that requires polling, break out
2467 * and complete those lists first, if we have entries there.
2469 if (READ_ONCE(req->iopoll_completed)) {
2470 list_move_tail(&req->inflight_entry, &done);
2473 if (!list_empty(&done))
2476 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2477 if (unlikely(ret < 0))
2482 /* iopoll may have completed current req */
2483 if (READ_ONCE(req->iopoll_completed))
2484 list_move_tail(&req->inflight_entry, &done);
2487 if (!list_empty(&done))
2488 io_iopoll_complete(ctx, nr_events, &done);
2494 * We can't just wait for polled events to come to us, we have to actively
2495 * find and complete them.
2497 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2499 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2502 mutex_lock(&ctx->uring_lock);
2503 while (!list_empty(&ctx->iopoll_list)) {
2504 unsigned int nr_events = 0;
2506 io_do_iopoll(ctx, &nr_events, 0);
2508 /* let it sleep and repeat later if can't complete a request */
2512 * Ensure we allow local-to-the-cpu processing to take place,
2513 * in this case we need to ensure that we reap all events.
2514 * Also let task_work, etc. to progress by releasing the mutex
2516 if (need_resched()) {
2517 mutex_unlock(&ctx->uring_lock);
2519 mutex_lock(&ctx->uring_lock);
2522 mutex_unlock(&ctx->uring_lock);
2525 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2527 unsigned int nr_events = 0;
2531 * We disallow the app entering submit/complete with polling, but we
2532 * still need to lock the ring to prevent racing with polled issue
2533 * that got punted to a workqueue.
2535 mutex_lock(&ctx->uring_lock);
2537 * Don't enter poll loop if we already have events pending.
2538 * If we do, we can potentially be spinning for commands that
2539 * already triggered a CQE (eg in error).
2541 if (test_bit(0, &ctx->check_cq_overflow))
2542 __io_cqring_overflow_flush(ctx, false);
2543 if (io_cqring_events(ctx))
2547 * If a submit got punted to a workqueue, we can have the
2548 * application entering polling for a command before it gets
2549 * issued. That app will hold the uring_lock for the duration
2550 * of the poll right here, so we need to take a breather every
2551 * now and then to ensure that the issue has a chance to add
2552 * the poll to the issued list. Otherwise we can spin here
2553 * forever, while the workqueue is stuck trying to acquire the
2556 if (list_empty(&ctx->iopoll_list)) {
2557 u32 tail = ctx->cached_cq_tail;
2559 mutex_unlock(&ctx->uring_lock);
2561 mutex_lock(&ctx->uring_lock);
2563 /* some requests don't go through iopoll_list */
2564 if (tail != ctx->cached_cq_tail ||
2565 list_empty(&ctx->iopoll_list))
2568 ret = io_do_iopoll(ctx, &nr_events, min);
2569 } while (!ret && nr_events < min && !need_resched());
2571 mutex_unlock(&ctx->uring_lock);
2575 static void kiocb_end_write(struct io_kiocb *req)
2578 * Tell lockdep we inherited freeze protection from submission
2581 if (req->flags & REQ_F_ISREG) {
2582 struct super_block *sb = file_inode(req->file)->i_sb;
2584 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2590 static bool io_resubmit_prep(struct io_kiocb *req)
2592 struct io_async_rw *rw = req->async_data;
2595 return !io_req_prep_async(req);
2596 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2597 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2601 static bool io_rw_should_reissue(struct io_kiocb *req)
2603 umode_t mode = file_inode(req->file)->i_mode;
2604 struct io_ring_ctx *ctx = req->ctx;
2606 if (!S_ISBLK(mode) && !S_ISREG(mode))
2608 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2609 !(ctx->flags & IORING_SETUP_IOPOLL)))
2612 * If ref is dying, we might be running poll reap from the exit work.
2613 * Don't attempt to reissue from that path, just let it fail with
2616 if (percpu_ref_is_dying(&ctx->refs))
2619 * Play it safe and assume not safe to re-import and reissue if we're
2620 * not in the original thread group (or in task context).
2622 if (!same_thread_group(req->task, current) || !in_task())
2627 static bool io_resubmit_prep(struct io_kiocb *req)
2631 static bool io_rw_should_reissue(struct io_kiocb *req)
2637 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2639 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2640 kiocb_end_write(req);
2641 if (res != req->result) {
2642 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2643 io_rw_should_reissue(req)) {
2644 req->flags |= REQ_F_REISSUE;
2653 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2655 unsigned int cflags = io_put_rw_kbuf(req);
2656 long res = req->result;
2659 struct io_ring_ctx *ctx = req->ctx;
2660 struct io_submit_state *state = &ctx->submit_state;
2662 io_req_complete_state(req, res, cflags);
2663 state->compl_reqs[state->compl_nr++] = req;
2664 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2665 io_submit_flush_completions(ctx);
2667 io_req_complete_post(req, res, cflags);
2671 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2672 unsigned int issue_flags)
2674 if (__io_complete_rw_common(req, res))
2676 __io_req_complete(req, 0, req->result, io_put_rw_kbuf(req));
2679 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2681 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2683 if (__io_complete_rw_common(req, res))
2686 req->io_task_work.func = io_req_task_complete;
2687 io_req_task_work_add(req);
2690 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2692 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2694 if (kiocb->ki_flags & IOCB_WRITE)
2695 kiocb_end_write(req);
2696 if (unlikely(res != req->result)) {
2697 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2698 io_resubmit_prep(req))) {
2700 req->flags |= REQ_F_DONT_REISSUE;
2704 WRITE_ONCE(req->result, res);
2705 /* order with io_iopoll_complete() checking ->result */
2707 WRITE_ONCE(req->iopoll_completed, 1);
2711 * After the iocb has been issued, it's safe to be found on the poll list.
2712 * Adding the kiocb to the list AFTER submission ensures that we don't
2713 * find it from a io_do_iopoll() thread before the issuer is done
2714 * accessing the kiocb cookie.
2716 static void io_iopoll_req_issued(struct io_kiocb *req)
2718 struct io_ring_ctx *ctx = req->ctx;
2719 const bool in_async = io_wq_current_is_worker();
2721 /* workqueue context doesn't hold uring_lock, grab it now */
2722 if (unlikely(in_async))
2723 mutex_lock(&ctx->uring_lock);
2726 * Track whether we have multiple files in our lists. This will impact
2727 * how we do polling eventually, not spinning if we're on potentially
2728 * different devices.
2730 if (list_empty(&ctx->iopoll_list)) {
2731 ctx->poll_multi_queue = false;
2732 } else if (!ctx->poll_multi_queue) {
2733 struct io_kiocb *list_req;
2734 unsigned int queue_num0, queue_num1;
2736 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2739 if (list_req->file != req->file) {
2740 ctx->poll_multi_queue = true;
2742 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2743 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2744 if (queue_num0 != queue_num1)
2745 ctx->poll_multi_queue = true;
2750 * For fast devices, IO may have already completed. If it has, add
2751 * it to the front so we find it first.
2753 if (READ_ONCE(req->iopoll_completed))
2754 list_add(&req->inflight_entry, &ctx->iopoll_list);
2756 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2758 if (unlikely(in_async)) {
2760 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2761 * in sq thread task context or in io worker task context. If
2762 * current task context is sq thread, we don't need to check
2763 * whether should wake up sq thread.
2765 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2766 wq_has_sleeper(&ctx->sq_data->wait))
2767 wake_up(&ctx->sq_data->wait);
2769 mutex_unlock(&ctx->uring_lock);
2773 static bool io_bdev_nowait(struct block_device *bdev)
2775 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2779 * If we tracked the file through the SCM inflight mechanism, we could support
2780 * any file. For now, just ensure that anything potentially problematic is done
2783 static bool __io_file_supports_nowait(struct file *file, int rw)
2785 umode_t mode = file_inode(file)->i_mode;
2787 if (S_ISBLK(mode)) {
2788 if (IS_ENABLED(CONFIG_BLOCK) &&
2789 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2795 if (S_ISREG(mode)) {
2796 if (IS_ENABLED(CONFIG_BLOCK) &&
2797 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2798 file->f_op != &io_uring_fops)
2803 /* any ->read/write should understand O_NONBLOCK */
2804 if (file->f_flags & O_NONBLOCK)
2807 if (!(file->f_mode & FMODE_NOWAIT))
2811 return file->f_op->read_iter != NULL;
2813 return file->f_op->write_iter != NULL;
2816 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2818 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2820 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2823 return __io_file_supports_nowait(req->file, rw);
2826 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2828 struct io_ring_ctx *ctx = req->ctx;
2829 struct kiocb *kiocb = &req->rw.kiocb;
2830 struct file *file = req->file;
2834 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2835 req->flags |= REQ_F_ISREG;
2837 kiocb->ki_pos = READ_ONCE(sqe->off);
2838 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2839 req->flags |= REQ_F_CUR_POS;
2840 kiocb->ki_pos = file->f_pos;
2842 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2843 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2844 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2848 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2849 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2850 req->flags |= REQ_F_NOWAIT;
2852 ioprio = READ_ONCE(sqe->ioprio);
2854 ret = ioprio_check_cap(ioprio);
2858 kiocb->ki_ioprio = ioprio;
2860 kiocb->ki_ioprio = get_current_ioprio();
2862 if (ctx->flags & IORING_SETUP_IOPOLL) {
2863 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2864 !kiocb->ki_filp->f_op->iopoll)
2867 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2868 kiocb->ki_complete = io_complete_rw_iopoll;
2869 req->iopoll_completed = 0;
2871 if (kiocb->ki_flags & IOCB_HIPRI)
2873 kiocb->ki_complete = io_complete_rw;
2876 if (req->opcode == IORING_OP_READ_FIXED ||
2877 req->opcode == IORING_OP_WRITE_FIXED) {
2879 io_req_set_rsrc_node(req);
2882 req->rw.addr = READ_ONCE(sqe->addr);
2883 req->rw.len = READ_ONCE(sqe->len);
2884 req->buf_index = READ_ONCE(sqe->buf_index);
2888 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2894 case -ERESTARTNOINTR:
2895 case -ERESTARTNOHAND:
2896 case -ERESTART_RESTARTBLOCK:
2898 * We can't just restart the syscall, since previously
2899 * submitted sqes may already be in progress. Just fail this
2905 kiocb->ki_complete(kiocb, ret, 0);
2909 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2910 unsigned int issue_flags)
2912 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2913 struct io_async_rw *io = req->async_data;
2914 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2916 /* add previously done IO, if any */
2917 if (io && io->bytes_done > 0) {
2919 ret = io->bytes_done;
2921 ret += io->bytes_done;
2924 if (req->flags & REQ_F_CUR_POS)
2925 req->file->f_pos = kiocb->ki_pos;
2926 if (ret >= 0 && check_reissue)
2927 __io_complete_rw(req, ret, 0, issue_flags);
2929 io_rw_done(kiocb, ret);
2931 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2932 req->flags &= ~REQ_F_REISSUE;
2933 if (io_resubmit_prep(req)) {
2934 io_req_task_queue_reissue(req);
2937 __io_req_complete(req, issue_flags, ret,
2938 io_put_rw_kbuf(req));
2943 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2944 struct io_mapped_ubuf *imu)
2946 size_t len = req->rw.len;
2947 u64 buf_end, buf_addr = req->rw.addr;
2950 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2952 /* not inside the mapped region */
2953 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2957 * May not be a start of buffer, set size appropriately
2958 * and advance us to the beginning.
2960 offset = buf_addr - imu->ubuf;
2961 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2965 * Don't use iov_iter_advance() here, as it's really slow for
2966 * using the latter parts of a big fixed buffer - it iterates
2967 * over each segment manually. We can cheat a bit here, because
2970 * 1) it's a BVEC iter, we set it up
2971 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2972 * first and last bvec
2974 * So just find our index, and adjust the iterator afterwards.
2975 * If the offset is within the first bvec (or the whole first
2976 * bvec, just use iov_iter_advance(). This makes it easier
2977 * since we can just skip the first segment, which may not
2978 * be PAGE_SIZE aligned.
2980 const struct bio_vec *bvec = imu->bvec;
2982 if (offset <= bvec->bv_len) {
2983 iov_iter_advance(iter, offset);
2985 unsigned long seg_skip;
2987 /* skip first vec */
2988 offset -= bvec->bv_len;
2989 seg_skip = 1 + (offset >> PAGE_SHIFT);
2991 iter->bvec = bvec + seg_skip;
2992 iter->nr_segs -= seg_skip;
2993 iter->count -= bvec->bv_len + offset;
2994 iter->iov_offset = offset & ~PAGE_MASK;
3001 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3003 struct io_ring_ctx *ctx = req->ctx;
3004 struct io_mapped_ubuf *imu = req->imu;
3005 u16 index, buf_index = req->buf_index;
3008 if (unlikely(buf_index >= ctx->nr_user_bufs))
3010 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3011 imu = READ_ONCE(ctx->user_bufs[index]);
3014 return __io_import_fixed(req, rw, iter, imu);
3017 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3020 mutex_unlock(&ctx->uring_lock);
3023 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3026 * "Normal" inline submissions always hold the uring_lock, since we
3027 * grab it from the system call. Same is true for the SQPOLL offload.
3028 * The only exception is when we've detached the request and issue it
3029 * from an async worker thread, grab the lock for that case.
3032 mutex_lock(&ctx->uring_lock);
3035 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3036 int bgid, struct io_buffer *kbuf,
3039 struct io_buffer *head;
3041 if (req->flags & REQ_F_BUFFER_SELECTED)
3044 io_ring_submit_lock(req->ctx, needs_lock);
3046 lockdep_assert_held(&req->ctx->uring_lock);
3048 head = xa_load(&req->ctx->io_buffers, bgid);
3050 if (!list_empty(&head->list)) {
3051 kbuf = list_last_entry(&head->list, struct io_buffer,
3053 list_del(&kbuf->list);
3056 xa_erase(&req->ctx->io_buffers, bgid);
3058 if (*len > kbuf->len)
3061 kbuf = ERR_PTR(-ENOBUFS);
3064 io_ring_submit_unlock(req->ctx, needs_lock);
3069 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3072 struct io_buffer *kbuf;
3075 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3076 bgid = req->buf_index;
3077 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3080 req->rw.addr = (u64) (unsigned long) kbuf;
3081 req->flags |= REQ_F_BUFFER_SELECTED;
3082 return u64_to_user_ptr(kbuf->addr);
3085 #ifdef CONFIG_COMPAT
3086 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3089 struct compat_iovec __user *uiov;
3090 compat_ssize_t clen;
3094 uiov = u64_to_user_ptr(req->rw.addr);
3095 if (!access_ok(uiov, sizeof(*uiov)))
3097 if (__get_user(clen, &uiov->iov_len))
3103 buf = io_rw_buffer_select(req, &len, needs_lock);
3105 return PTR_ERR(buf);
3106 iov[0].iov_base = buf;
3107 iov[0].iov_len = (compat_size_t) len;
3112 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3115 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3119 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3122 len = iov[0].iov_len;
3125 buf = io_rw_buffer_select(req, &len, needs_lock);
3127 return PTR_ERR(buf);
3128 iov[0].iov_base = buf;
3129 iov[0].iov_len = len;
3133 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3136 if (req->flags & REQ_F_BUFFER_SELECTED) {
3137 struct io_buffer *kbuf;
3139 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3140 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3141 iov[0].iov_len = kbuf->len;
3144 if (req->rw.len != 1)
3147 #ifdef CONFIG_COMPAT
3148 if (req->ctx->compat)
3149 return io_compat_import(req, iov, needs_lock);
3152 return __io_iov_buffer_select(req, iov, needs_lock);
3155 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3156 struct iov_iter *iter, bool needs_lock)
3158 void __user *buf = u64_to_user_ptr(req->rw.addr);
3159 size_t sqe_len = req->rw.len;
3160 u8 opcode = req->opcode;
3163 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3165 return io_import_fixed(req, rw, iter);
3168 /* buffer index only valid with fixed read/write, or buffer select */
3169 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3172 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3173 if (req->flags & REQ_F_BUFFER_SELECT) {
3174 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3176 return PTR_ERR(buf);
3177 req->rw.len = sqe_len;
3180 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3185 if (req->flags & REQ_F_BUFFER_SELECT) {
3186 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3188 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3193 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3197 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3199 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3203 * For files that don't have ->read_iter() and ->write_iter(), handle them
3204 * by looping over ->read() or ->write() manually.
3206 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3208 struct kiocb *kiocb = &req->rw.kiocb;
3209 struct file *file = req->file;
3213 * Don't support polled IO through this interface, and we can't
3214 * support non-blocking either. For the latter, this just causes
3215 * the kiocb to be handled from an async context.
3217 if (kiocb->ki_flags & IOCB_HIPRI)
3219 if (kiocb->ki_flags & IOCB_NOWAIT)
3222 while (iov_iter_count(iter)) {
3226 if (!iov_iter_is_bvec(iter)) {
3227 iovec = iov_iter_iovec(iter);
3229 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3230 iovec.iov_len = req->rw.len;
3234 nr = file->f_op->read(file, iovec.iov_base,
3235 iovec.iov_len, io_kiocb_ppos(kiocb));
3237 nr = file->f_op->write(file, iovec.iov_base,
3238 iovec.iov_len, io_kiocb_ppos(kiocb));
3247 if (nr != iovec.iov_len)
3251 iov_iter_advance(iter, nr);
3257 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3258 const struct iovec *fast_iov, struct iov_iter *iter)
3260 struct io_async_rw *rw = req->async_data;
3262 memcpy(&rw->iter, iter, sizeof(*iter));
3263 rw->free_iovec = iovec;
3265 /* can only be fixed buffers, no need to do anything */
3266 if (iov_iter_is_bvec(iter))
3269 unsigned iov_off = 0;
3271 rw->iter.iov = rw->fast_iov;
3272 if (iter->iov != fast_iov) {
3273 iov_off = iter->iov - fast_iov;
3274 rw->iter.iov += iov_off;
3276 if (rw->fast_iov != fast_iov)
3277 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3278 sizeof(struct iovec) * iter->nr_segs);
3280 req->flags |= REQ_F_NEED_CLEANUP;
3284 static inline int io_alloc_async_data(struct io_kiocb *req)
3286 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3287 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3288 return req->async_data == NULL;
3291 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3292 const struct iovec *fast_iov,
3293 struct iov_iter *iter, bool force)
3295 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3297 if (!req->async_data) {
3298 if (io_alloc_async_data(req)) {
3303 io_req_map_rw(req, iovec, fast_iov, iter);
3308 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3310 struct io_async_rw *iorw = req->async_data;
3311 struct iovec *iov = iorw->fast_iov;
3314 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3315 if (unlikely(ret < 0))
3318 iorw->bytes_done = 0;
3319 iorw->free_iovec = iov;
3321 req->flags |= REQ_F_NEED_CLEANUP;
3325 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3327 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3329 return io_prep_rw(req, sqe);
3333 * This is our waitqueue callback handler, registered through lock_page_async()
3334 * when we initially tried to do the IO with the iocb armed our waitqueue.
3335 * This gets called when the page is unlocked, and we generally expect that to
3336 * happen when the page IO is completed and the page is now uptodate. This will
3337 * queue a task_work based retry of the operation, attempting to copy the data
3338 * again. If the latter fails because the page was NOT uptodate, then we will
3339 * do a thread based blocking retry of the operation. That's the unexpected
3342 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3343 int sync, void *arg)
3345 struct wait_page_queue *wpq;
3346 struct io_kiocb *req = wait->private;
3347 struct wait_page_key *key = arg;
3349 wpq = container_of(wait, struct wait_page_queue, wait);
3351 if (!wake_page_match(wpq, key))
3354 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3355 list_del_init(&wait->entry);
3356 io_req_task_queue(req);
3361 * This controls whether a given IO request should be armed for async page
3362 * based retry. If we return false here, the request is handed to the async
3363 * worker threads for retry. If we're doing buffered reads on a regular file,
3364 * we prepare a private wait_page_queue entry and retry the operation. This
3365 * will either succeed because the page is now uptodate and unlocked, or it
3366 * will register a callback when the page is unlocked at IO completion. Through
3367 * that callback, io_uring uses task_work to setup a retry of the operation.
3368 * That retry will attempt the buffered read again. The retry will generally
3369 * succeed, or in rare cases where it fails, we then fall back to using the
3370 * async worker threads for a blocking retry.
3372 static bool io_rw_should_retry(struct io_kiocb *req)
3374 struct io_async_rw *rw = req->async_data;
3375 struct wait_page_queue *wait = &rw->wpq;
3376 struct kiocb *kiocb = &req->rw.kiocb;
3378 /* never retry for NOWAIT, we just complete with -EAGAIN */
3379 if (req->flags & REQ_F_NOWAIT)
3382 /* Only for buffered IO */
3383 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3387 * just use poll if we can, and don't attempt if the fs doesn't
3388 * support callback based unlocks
3390 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3393 wait->wait.func = io_async_buf_func;
3394 wait->wait.private = req;
3395 wait->wait.flags = 0;
3396 INIT_LIST_HEAD(&wait->wait.entry);
3397 kiocb->ki_flags |= IOCB_WAITQ;
3398 kiocb->ki_flags &= ~IOCB_NOWAIT;
3399 kiocb->ki_waitq = wait;
3403 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3405 if (req->file->f_op->read_iter)
3406 return call_read_iter(req->file, &req->rw.kiocb, iter);
3407 else if (req->file->f_op->read)
3408 return loop_rw_iter(READ, req, iter);
3413 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3415 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3416 struct kiocb *kiocb = &req->rw.kiocb;
3417 struct iov_iter __iter, *iter = &__iter;
3418 struct io_async_rw *rw = req->async_data;
3419 ssize_t io_size, ret, ret2;
3420 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3426 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3430 io_size = iov_iter_count(iter);
3431 req->result = io_size;
3433 /* Ensure we clear previously set non-block flag */
3434 if (!force_nonblock)
3435 kiocb->ki_flags &= ~IOCB_NOWAIT;
3437 kiocb->ki_flags |= IOCB_NOWAIT;
3439 /* If the file doesn't support async, just async punt */
3440 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3441 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3442 return ret ?: -EAGAIN;
3445 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3446 if (unlikely(ret)) {
3451 ret = io_iter_do_read(req, iter);
3453 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3454 req->flags &= ~REQ_F_REISSUE;
3455 /* IOPOLL retry should happen for io-wq threads */
3456 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3458 /* no retry on NONBLOCK nor RWF_NOWAIT */
3459 if (req->flags & REQ_F_NOWAIT)
3461 /* some cases will consume bytes even on error returns */
3462 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3464 } else if (ret == -EIOCBQUEUED) {
3466 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3467 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3468 /* read all, failed, already did sync or don't want to retry */
3472 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3477 rw = req->async_data;
3478 /* now use our persistent iterator, if we aren't already */
3483 rw->bytes_done += ret;
3484 /* if we can retry, do so with the callbacks armed */
3485 if (!io_rw_should_retry(req)) {
3486 kiocb->ki_flags &= ~IOCB_WAITQ;
3491 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3492 * we get -EIOCBQUEUED, then we'll get a notification when the
3493 * desired page gets unlocked. We can also get a partial read
3494 * here, and if we do, then just retry at the new offset.
3496 ret = io_iter_do_read(req, iter);
3497 if (ret == -EIOCBQUEUED)
3499 /* we got some bytes, but not all. retry. */
3500 kiocb->ki_flags &= ~IOCB_WAITQ;
3501 } while (ret > 0 && ret < io_size);
3503 kiocb_done(kiocb, ret, issue_flags);
3505 /* it's faster to check here then delegate to kfree */
3511 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3513 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3515 return io_prep_rw(req, sqe);
3518 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3520 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3521 struct kiocb *kiocb = &req->rw.kiocb;
3522 struct iov_iter __iter, *iter = &__iter;
3523 struct io_async_rw *rw = req->async_data;
3524 ssize_t ret, ret2, io_size;
3525 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3531 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3535 io_size = iov_iter_count(iter);
3536 req->result = io_size;
3538 /* Ensure we clear previously set non-block flag */
3539 if (!force_nonblock)
3540 kiocb->ki_flags &= ~IOCB_NOWAIT;
3542 kiocb->ki_flags |= IOCB_NOWAIT;
3544 /* If the file doesn't support async, just async punt */
3545 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3548 /* file path doesn't support NOWAIT for non-direct_IO */
3549 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3550 (req->flags & REQ_F_ISREG))
3553 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3558 * Open-code file_start_write here to grab freeze protection,
3559 * which will be released by another thread in
3560 * io_complete_rw(). Fool lockdep by telling it the lock got
3561 * released so that it doesn't complain about the held lock when
3562 * we return to userspace.
3564 if (req->flags & REQ_F_ISREG) {
3565 sb_start_write(file_inode(req->file)->i_sb);
3566 __sb_writers_release(file_inode(req->file)->i_sb,
3569 kiocb->ki_flags |= IOCB_WRITE;
3571 if (req->file->f_op->write_iter)
3572 ret2 = call_write_iter(req->file, kiocb, iter);
3573 else if (req->file->f_op->write)
3574 ret2 = loop_rw_iter(WRITE, req, iter);
3578 if (req->flags & REQ_F_REISSUE) {
3579 req->flags &= ~REQ_F_REISSUE;
3584 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3585 * retry them without IOCB_NOWAIT.
3587 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3589 /* no retry on NONBLOCK nor RWF_NOWAIT */
3590 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3592 if (!force_nonblock || ret2 != -EAGAIN) {
3593 /* IOPOLL retry should happen for io-wq threads */
3594 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3597 kiocb_done(kiocb, ret2, issue_flags);
3600 /* some cases will consume bytes even on error returns */
3601 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3602 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3603 return ret ?: -EAGAIN;
3606 /* it's reportedly faster than delegating the null check to kfree() */
3612 static int io_renameat_prep(struct io_kiocb *req,
3613 const struct io_uring_sqe *sqe)
3615 struct io_rename *ren = &req->rename;
3616 const char __user *oldf, *newf;
3618 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3620 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3622 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3625 ren->old_dfd = READ_ONCE(sqe->fd);
3626 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3627 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3628 ren->new_dfd = READ_ONCE(sqe->len);
3629 ren->flags = READ_ONCE(sqe->rename_flags);
3631 ren->oldpath = getname(oldf);
3632 if (IS_ERR(ren->oldpath))
3633 return PTR_ERR(ren->oldpath);
3635 ren->newpath = getname(newf);
3636 if (IS_ERR(ren->newpath)) {
3637 putname(ren->oldpath);
3638 return PTR_ERR(ren->newpath);
3641 req->flags |= REQ_F_NEED_CLEANUP;
3645 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3647 struct io_rename *ren = &req->rename;
3650 if (issue_flags & IO_URING_F_NONBLOCK)
3653 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3654 ren->newpath, ren->flags);
3656 req->flags &= ~REQ_F_NEED_CLEANUP;
3659 io_req_complete(req, ret);
3663 static int io_unlinkat_prep(struct io_kiocb *req,
3664 const struct io_uring_sqe *sqe)
3666 struct io_unlink *un = &req->unlink;
3667 const char __user *fname;
3669 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3671 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3674 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3677 un->dfd = READ_ONCE(sqe->fd);
3679 un->flags = READ_ONCE(sqe->unlink_flags);
3680 if (un->flags & ~AT_REMOVEDIR)
3683 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3684 un->filename = getname(fname);
3685 if (IS_ERR(un->filename))
3686 return PTR_ERR(un->filename);
3688 req->flags |= REQ_F_NEED_CLEANUP;
3692 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3694 struct io_unlink *un = &req->unlink;
3697 if (issue_flags & IO_URING_F_NONBLOCK)
3700 if (un->flags & AT_REMOVEDIR)
3701 ret = do_rmdir(un->dfd, un->filename);
3703 ret = do_unlinkat(un->dfd, un->filename);
3705 req->flags &= ~REQ_F_NEED_CLEANUP;
3708 io_req_complete(req, ret);
3712 static int io_mkdirat_prep(struct io_kiocb *req,
3713 const struct io_uring_sqe *sqe)
3715 struct io_mkdir *mkd = &req->mkdir;
3716 const char __user *fname;
3718 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3720 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3723 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3726 mkd->dfd = READ_ONCE(sqe->fd);
3727 mkd->mode = READ_ONCE(sqe->len);
3729 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3730 mkd->filename = getname(fname);
3731 if (IS_ERR(mkd->filename))
3732 return PTR_ERR(mkd->filename);
3734 req->flags |= REQ_F_NEED_CLEANUP;
3738 static int io_mkdirat(struct io_kiocb *req, int issue_flags)
3740 struct io_mkdir *mkd = &req->mkdir;
3743 if (issue_flags & IO_URING_F_NONBLOCK)
3746 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3748 req->flags &= ~REQ_F_NEED_CLEANUP;
3751 io_req_complete(req, ret);
3755 static int io_symlinkat_prep(struct io_kiocb *req,
3756 const struct io_uring_sqe *sqe)
3758 struct io_symlink *sl = &req->symlink;
3759 const char __user *oldpath, *newpath;
3761 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3763 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3766 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3769 sl->new_dfd = READ_ONCE(sqe->fd);
3770 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3771 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3773 sl->oldpath = getname(oldpath);
3774 if (IS_ERR(sl->oldpath))
3775 return PTR_ERR(sl->oldpath);
3777 sl->newpath = getname(newpath);
3778 if (IS_ERR(sl->newpath)) {
3779 putname(sl->oldpath);
3780 return PTR_ERR(sl->newpath);
3783 req->flags |= REQ_F_NEED_CLEANUP;
3787 static int io_symlinkat(struct io_kiocb *req, int issue_flags)
3789 struct io_symlink *sl = &req->symlink;
3792 if (issue_flags & IO_URING_F_NONBLOCK)
3795 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
3797 req->flags &= ~REQ_F_NEED_CLEANUP;
3800 io_req_complete(req, ret);
3804 static int io_linkat_prep(struct io_kiocb *req,
3805 const struct io_uring_sqe *sqe)
3807 struct io_hardlink *lnk = &req->hardlink;
3808 const char __user *oldf, *newf;
3810 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3812 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
3814 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3817 lnk->old_dfd = READ_ONCE(sqe->fd);
3818 lnk->new_dfd = READ_ONCE(sqe->len);
3819 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3820 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3821 lnk->flags = READ_ONCE(sqe->hardlink_flags);
3823 lnk->oldpath = getname(oldf);
3824 if (IS_ERR(lnk->oldpath))
3825 return PTR_ERR(lnk->oldpath);
3827 lnk->newpath = getname(newf);
3828 if (IS_ERR(lnk->newpath)) {
3829 putname(lnk->oldpath);
3830 return PTR_ERR(lnk->newpath);
3833 req->flags |= REQ_F_NEED_CLEANUP;
3837 static int io_linkat(struct io_kiocb *req, int issue_flags)
3839 struct io_hardlink *lnk = &req->hardlink;
3842 if (issue_flags & IO_URING_F_NONBLOCK)
3845 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
3846 lnk->newpath, lnk->flags);
3848 req->flags &= ~REQ_F_NEED_CLEANUP;
3851 io_req_complete(req, ret);
3855 static int io_shutdown_prep(struct io_kiocb *req,
3856 const struct io_uring_sqe *sqe)
3858 #if defined(CONFIG_NET)
3859 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3861 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3862 sqe->buf_index || sqe->splice_fd_in))
3865 req->shutdown.how = READ_ONCE(sqe->len);
3872 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3874 #if defined(CONFIG_NET)
3875 struct socket *sock;
3878 if (issue_flags & IO_URING_F_NONBLOCK)
3881 sock = sock_from_file(req->file);
3882 if (unlikely(!sock))
3885 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3888 io_req_complete(req, ret);
3895 static int __io_splice_prep(struct io_kiocb *req,
3896 const struct io_uring_sqe *sqe)
3898 struct io_splice *sp = &req->splice;
3899 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3901 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3905 sp->len = READ_ONCE(sqe->len);
3906 sp->flags = READ_ONCE(sqe->splice_flags);
3908 if (unlikely(sp->flags & ~valid_flags))
3911 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3912 (sp->flags & SPLICE_F_FD_IN_FIXED));
3915 req->flags |= REQ_F_NEED_CLEANUP;
3919 static int io_tee_prep(struct io_kiocb *req,
3920 const struct io_uring_sqe *sqe)
3922 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3924 return __io_splice_prep(req, sqe);
3927 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3929 struct io_splice *sp = &req->splice;
3930 struct file *in = sp->file_in;
3931 struct file *out = sp->file_out;
3932 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3935 if (issue_flags & IO_URING_F_NONBLOCK)
3938 ret = do_tee(in, out, sp->len, flags);
3940 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3942 req->flags &= ~REQ_F_NEED_CLEANUP;
3946 io_req_complete(req, ret);
3950 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3952 struct io_splice *sp = &req->splice;
3954 sp->off_in = READ_ONCE(sqe->splice_off_in);
3955 sp->off_out = READ_ONCE(sqe->off);
3956 return __io_splice_prep(req, sqe);
3959 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3961 struct io_splice *sp = &req->splice;
3962 struct file *in = sp->file_in;
3963 struct file *out = sp->file_out;
3964 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3965 loff_t *poff_in, *poff_out;
3968 if (issue_flags & IO_URING_F_NONBLOCK)
3971 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3972 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3975 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3977 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3979 req->flags &= ~REQ_F_NEED_CLEANUP;
3983 io_req_complete(req, ret);
3988 * IORING_OP_NOP just posts a completion event, nothing else.
3990 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3992 struct io_ring_ctx *ctx = req->ctx;
3994 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3997 __io_req_complete(req, issue_flags, 0, 0);
4001 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4003 struct io_ring_ctx *ctx = req->ctx;
4008 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4010 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4014 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4015 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4018 req->sync.off = READ_ONCE(sqe->off);
4019 req->sync.len = READ_ONCE(sqe->len);
4023 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4025 loff_t end = req->sync.off + req->sync.len;
4028 /* fsync always requires a blocking context */
4029 if (issue_flags & IO_URING_F_NONBLOCK)
4032 ret = vfs_fsync_range(req->file, req->sync.off,
4033 end > 0 ? end : LLONG_MAX,
4034 req->sync.flags & IORING_FSYNC_DATASYNC);
4037 io_req_complete(req, ret);
4041 static int io_fallocate_prep(struct io_kiocb *req,
4042 const struct io_uring_sqe *sqe)
4044 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4047 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4050 req->sync.off = READ_ONCE(sqe->off);
4051 req->sync.len = READ_ONCE(sqe->addr);
4052 req->sync.mode = READ_ONCE(sqe->len);
4056 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4060 /* fallocate always requiring blocking context */
4061 if (issue_flags & IO_URING_F_NONBLOCK)
4063 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4067 io_req_complete(req, ret);
4071 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4073 const char __user *fname;
4076 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4078 if (unlikely(sqe->ioprio || sqe->buf_index))
4080 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4083 /* open.how should be already initialised */
4084 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4085 req->open.how.flags |= O_LARGEFILE;
4087 req->open.dfd = READ_ONCE(sqe->fd);
4088 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4089 req->open.filename = getname(fname);
4090 if (IS_ERR(req->open.filename)) {
4091 ret = PTR_ERR(req->open.filename);
4092 req->open.filename = NULL;
4096 req->open.file_slot = READ_ONCE(sqe->file_index);
4097 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4100 req->open.nofile = rlimit(RLIMIT_NOFILE);
4101 req->flags |= REQ_F_NEED_CLEANUP;
4105 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4107 u64 mode = READ_ONCE(sqe->len);
4108 u64 flags = READ_ONCE(sqe->open_flags);
4110 req->open.how = build_open_how(flags, mode);
4111 return __io_openat_prep(req, sqe);
4114 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4116 struct open_how __user *how;
4120 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4121 len = READ_ONCE(sqe->len);
4122 if (len < OPEN_HOW_SIZE_VER0)
4125 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4130 return __io_openat_prep(req, sqe);
4133 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4135 struct open_flags op;
4137 bool resolve_nonblock, nonblock_set;
4138 bool fixed = !!req->open.file_slot;
4141 ret = build_open_flags(&req->open.how, &op);
4144 nonblock_set = op.open_flag & O_NONBLOCK;
4145 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4146 if (issue_flags & IO_URING_F_NONBLOCK) {
4148 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4149 * it'll always -EAGAIN
4151 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4153 op.lookup_flags |= LOOKUP_CACHED;
4154 op.open_flag |= O_NONBLOCK;
4158 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4163 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4166 * We could hang on to this 'fd' on retrying, but seems like
4167 * marginal gain for something that is now known to be a slower
4168 * path. So just put it, and we'll get a new one when we retry.
4173 ret = PTR_ERR(file);
4174 /* only retry if RESOLVE_CACHED wasn't already set by application */
4175 if (ret == -EAGAIN &&
4176 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4181 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4182 file->f_flags &= ~O_NONBLOCK;
4183 fsnotify_open(file);
4186 fd_install(ret, file);
4188 ret = io_install_fixed_file(req, file, issue_flags,
4189 req->open.file_slot - 1);
4191 putname(req->open.filename);
4192 req->flags &= ~REQ_F_NEED_CLEANUP;
4195 __io_req_complete(req, issue_flags, ret, 0);
4199 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4201 return io_openat2(req, issue_flags);
4204 static int io_remove_buffers_prep(struct io_kiocb *req,
4205 const struct io_uring_sqe *sqe)
4207 struct io_provide_buf *p = &req->pbuf;
4210 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4214 tmp = READ_ONCE(sqe->fd);
4215 if (!tmp || tmp > USHRT_MAX)
4218 memset(p, 0, sizeof(*p));
4220 p->bgid = READ_ONCE(sqe->buf_group);
4224 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4225 int bgid, unsigned nbufs)
4229 /* shouldn't happen */
4233 /* the head kbuf is the list itself */
4234 while (!list_empty(&buf->list)) {
4235 struct io_buffer *nxt;
4237 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4238 list_del(&nxt->list);
4245 xa_erase(&ctx->io_buffers, bgid);
4250 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4252 struct io_provide_buf *p = &req->pbuf;
4253 struct io_ring_ctx *ctx = req->ctx;
4254 struct io_buffer *head;
4256 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4258 io_ring_submit_lock(ctx, !force_nonblock);
4260 lockdep_assert_held(&ctx->uring_lock);
4263 head = xa_load(&ctx->io_buffers, p->bgid);
4265 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4269 /* complete before unlock, IOPOLL may need the lock */
4270 __io_req_complete(req, issue_flags, ret, 0);
4271 io_ring_submit_unlock(ctx, !force_nonblock);
4275 static int io_provide_buffers_prep(struct io_kiocb *req,
4276 const struct io_uring_sqe *sqe)
4278 unsigned long size, tmp_check;
4279 struct io_provide_buf *p = &req->pbuf;
4282 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4285 tmp = READ_ONCE(sqe->fd);
4286 if (!tmp || tmp > USHRT_MAX)
4289 p->addr = READ_ONCE(sqe->addr);
4290 p->len = READ_ONCE(sqe->len);
4292 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4295 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4298 size = (unsigned long)p->len * p->nbufs;
4299 if (!access_ok(u64_to_user_ptr(p->addr), size))
4302 p->bgid = READ_ONCE(sqe->buf_group);
4303 tmp = READ_ONCE(sqe->off);
4304 if (tmp > USHRT_MAX)
4310 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4312 struct io_buffer *buf;
4313 u64 addr = pbuf->addr;
4314 int i, bid = pbuf->bid;
4316 for (i = 0; i < pbuf->nbufs; i++) {
4317 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4322 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4327 INIT_LIST_HEAD(&buf->list);
4330 list_add_tail(&buf->list, &(*head)->list);
4334 return i ? i : -ENOMEM;
4337 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4339 struct io_provide_buf *p = &req->pbuf;
4340 struct io_ring_ctx *ctx = req->ctx;
4341 struct io_buffer *head, *list;
4343 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4345 io_ring_submit_lock(ctx, !force_nonblock);
4347 lockdep_assert_held(&ctx->uring_lock);
4349 list = head = xa_load(&ctx->io_buffers, p->bgid);
4351 ret = io_add_buffers(p, &head);
4352 if (ret >= 0 && !list) {
4353 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4355 __io_remove_buffers(ctx, head, p->bgid, -1U);
4359 /* complete before unlock, IOPOLL may need the lock */
4360 __io_req_complete(req, issue_flags, ret, 0);
4361 io_ring_submit_unlock(ctx, !force_nonblock);
4365 static int io_epoll_ctl_prep(struct io_kiocb *req,
4366 const struct io_uring_sqe *sqe)
4368 #if defined(CONFIG_EPOLL)
4369 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4371 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4374 req->epoll.epfd = READ_ONCE(sqe->fd);
4375 req->epoll.op = READ_ONCE(sqe->len);
4376 req->epoll.fd = READ_ONCE(sqe->off);
4378 if (ep_op_has_event(req->epoll.op)) {
4379 struct epoll_event __user *ev;
4381 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4382 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4392 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4394 #if defined(CONFIG_EPOLL)
4395 struct io_epoll *ie = &req->epoll;
4397 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4399 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4400 if (force_nonblock && ret == -EAGAIN)
4405 __io_req_complete(req, issue_flags, ret, 0);
4412 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4414 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4415 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4417 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4420 req->madvise.addr = READ_ONCE(sqe->addr);
4421 req->madvise.len = READ_ONCE(sqe->len);
4422 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4429 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4431 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4432 struct io_madvise *ma = &req->madvise;
4435 if (issue_flags & IO_URING_F_NONBLOCK)
4438 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4441 io_req_complete(req, ret);
4448 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4450 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4452 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4455 req->fadvise.offset = READ_ONCE(sqe->off);
4456 req->fadvise.len = READ_ONCE(sqe->len);
4457 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4461 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4463 struct io_fadvise *fa = &req->fadvise;
4466 if (issue_flags & IO_URING_F_NONBLOCK) {
4467 switch (fa->advice) {
4468 case POSIX_FADV_NORMAL:
4469 case POSIX_FADV_RANDOM:
4470 case POSIX_FADV_SEQUENTIAL:
4477 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4480 __io_req_complete(req, issue_flags, ret, 0);
4484 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4486 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4488 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4490 if (req->flags & REQ_F_FIXED_FILE)
4493 req->statx.dfd = READ_ONCE(sqe->fd);
4494 req->statx.mask = READ_ONCE(sqe->len);
4495 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4496 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4497 req->statx.flags = READ_ONCE(sqe->statx_flags);
4502 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4504 struct io_statx *ctx = &req->statx;
4507 if (issue_flags & IO_URING_F_NONBLOCK)
4510 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4515 io_req_complete(req, ret);
4519 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4521 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4523 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4524 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4526 if (req->flags & REQ_F_FIXED_FILE)
4529 req->close.fd = READ_ONCE(sqe->fd);
4533 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4535 struct files_struct *files = current->files;
4536 struct io_close *close = &req->close;
4537 struct fdtable *fdt;
4538 struct file *file = NULL;
4541 spin_lock(&files->file_lock);
4542 fdt = files_fdtable(files);
4543 if (close->fd >= fdt->max_fds) {
4544 spin_unlock(&files->file_lock);
4547 file = fdt->fd[close->fd];
4548 if (!file || file->f_op == &io_uring_fops) {
4549 spin_unlock(&files->file_lock);
4554 /* if the file has a flush method, be safe and punt to async */
4555 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4556 spin_unlock(&files->file_lock);
4560 ret = __close_fd_get_file(close->fd, &file);
4561 spin_unlock(&files->file_lock);
4568 /* No ->flush() or already async, safely close from here */
4569 ret = filp_close(file, current->files);
4575 __io_req_complete(req, issue_flags, ret, 0);
4579 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4581 struct io_ring_ctx *ctx = req->ctx;
4583 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4585 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4589 req->sync.off = READ_ONCE(sqe->off);
4590 req->sync.len = READ_ONCE(sqe->len);
4591 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4595 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4599 /* sync_file_range always requires a blocking context */
4600 if (issue_flags & IO_URING_F_NONBLOCK)
4603 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4607 io_req_complete(req, ret);
4611 #if defined(CONFIG_NET)
4612 static int io_setup_async_msg(struct io_kiocb *req,
4613 struct io_async_msghdr *kmsg)
4615 struct io_async_msghdr *async_msg = req->async_data;
4619 if (io_alloc_async_data(req)) {
4620 kfree(kmsg->free_iov);
4623 async_msg = req->async_data;
4624 req->flags |= REQ_F_NEED_CLEANUP;
4625 memcpy(async_msg, kmsg, sizeof(*kmsg));
4626 async_msg->msg.msg_name = &async_msg->addr;
4627 /* if were using fast_iov, set it to the new one */
4628 if (!async_msg->free_iov)
4629 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4634 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4635 struct io_async_msghdr *iomsg)
4637 iomsg->msg.msg_name = &iomsg->addr;
4638 iomsg->free_iov = iomsg->fast_iov;
4639 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4640 req->sr_msg.msg_flags, &iomsg->free_iov);
4643 static int io_sendmsg_prep_async(struct io_kiocb *req)
4647 ret = io_sendmsg_copy_hdr(req, req->async_data);
4649 req->flags |= REQ_F_NEED_CLEANUP;
4653 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4655 struct io_sr_msg *sr = &req->sr_msg;
4657 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4660 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4661 sr->len = READ_ONCE(sqe->len);
4662 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4663 if (sr->msg_flags & MSG_DONTWAIT)
4664 req->flags |= REQ_F_NOWAIT;
4666 #ifdef CONFIG_COMPAT
4667 if (req->ctx->compat)
4668 sr->msg_flags |= MSG_CMSG_COMPAT;
4673 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4675 struct io_async_msghdr iomsg, *kmsg;
4676 struct socket *sock;
4681 sock = sock_from_file(req->file);
4682 if (unlikely(!sock))
4685 kmsg = req->async_data;
4687 ret = io_sendmsg_copy_hdr(req, &iomsg);
4693 flags = req->sr_msg.msg_flags;
4694 if (issue_flags & IO_URING_F_NONBLOCK)
4695 flags |= MSG_DONTWAIT;
4696 if (flags & MSG_WAITALL)
4697 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4699 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4700 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4701 return io_setup_async_msg(req, kmsg);
4702 if (ret == -ERESTARTSYS)
4705 /* fast path, check for non-NULL to avoid function call */
4707 kfree(kmsg->free_iov);
4708 req->flags &= ~REQ_F_NEED_CLEANUP;
4711 __io_req_complete(req, issue_flags, ret, 0);
4715 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4717 struct io_sr_msg *sr = &req->sr_msg;
4720 struct socket *sock;
4725 sock = sock_from_file(req->file);
4726 if (unlikely(!sock))
4729 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4733 msg.msg_name = NULL;
4734 msg.msg_control = NULL;
4735 msg.msg_controllen = 0;
4736 msg.msg_namelen = 0;
4738 flags = req->sr_msg.msg_flags;
4739 if (issue_flags & IO_URING_F_NONBLOCK)
4740 flags |= MSG_DONTWAIT;
4741 if (flags & MSG_WAITALL)
4742 min_ret = iov_iter_count(&msg.msg_iter);
4744 msg.msg_flags = flags;
4745 ret = sock_sendmsg(sock, &msg);
4746 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4748 if (ret == -ERESTARTSYS)
4753 __io_req_complete(req, issue_flags, ret, 0);
4757 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4758 struct io_async_msghdr *iomsg)
4760 struct io_sr_msg *sr = &req->sr_msg;
4761 struct iovec __user *uiov;
4765 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4766 &iomsg->uaddr, &uiov, &iov_len);
4770 if (req->flags & REQ_F_BUFFER_SELECT) {
4773 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4775 sr->len = iomsg->fast_iov[0].iov_len;
4776 iomsg->free_iov = NULL;
4778 iomsg->free_iov = iomsg->fast_iov;
4779 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4780 &iomsg->free_iov, &iomsg->msg.msg_iter,
4789 #ifdef CONFIG_COMPAT
4790 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4791 struct io_async_msghdr *iomsg)
4793 struct io_sr_msg *sr = &req->sr_msg;
4794 struct compat_iovec __user *uiov;
4799 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4804 uiov = compat_ptr(ptr);
4805 if (req->flags & REQ_F_BUFFER_SELECT) {
4806 compat_ssize_t clen;
4810 if (!access_ok(uiov, sizeof(*uiov)))
4812 if (__get_user(clen, &uiov->iov_len))
4817 iomsg->free_iov = NULL;
4819 iomsg->free_iov = iomsg->fast_iov;
4820 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4821 UIO_FASTIOV, &iomsg->free_iov,
4822 &iomsg->msg.msg_iter, true);
4831 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4832 struct io_async_msghdr *iomsg)
4834 iomsg->msg.msg_name = &iomsg->addr;
4836 #ifdef CONFIG_COMPAT
4837 if (req->ctx->compat)
4838 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4841 return __io_recvmsg_copy_hdr(req, iomsg);
4844 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4847 struct io_sr_msg *sr = &req->sr_msg;
4848 struct io_buffer *kbuf;
4850 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4855 req->flags |= REQ_F_BUFFER_SELECTED;
4859 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4861 return io_put_kbuf(req, req->sr_msg.kbuf);
4864 static int io_recvmsg_prep_async(struct io_kiocb *req)
4868 ret = io_recvmsg_copy_hdr(req, req->async_data);
4870 req->flags |= REQ_F_NEED_CLEANUP;
4874 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4876 struct io_sr_msg *sr = &req->sr_msg;
4878 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4881 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4882 sr->len = READ_ONCE(sqe->len);
4883 sr->bgid = READ_ONCE(sqe->buf_group);
4884 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4885 if (sr->msg_flags & MSG_DONTWAIT)
4886 req->flags |= REQ_F_NOWAIT;
4888 #ifdef CONFIG_COMPAT
4889 if (req->ctx->compat)
4890 sr->msg_flags |= MSG_CMSG_COMPAT;
4895 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4897 struct io_async_msghdr iomsg, *kmsg;
4898 struct socket *sock;
4899 struct io_buffer *kbuf;
4902 int ret, cflags = 0;
4903 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4905 sock = sock_from_file(req->file);
4906 if (unlikely(!sock))
4909 kmsg = req->async_data;
4911 ret = io_recvmsg_copy_hdr(req, &iomsg);
4917 if (req->flags & REQ_F_BUFFER_SELECT) {
4918 kbuf = io_recv_buffer_select(req, !force_nonblock);
4920 return PTR_ERR(kbuf);
4921 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4922 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4923 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4924 1, req->sr_msg.len);
4927 flags = req->sr_msg.msg_flags;
4929 flags |= MSG_DONTWAIT;
4930 if (flags & MSG_WAITALL)
4931 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4933 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4934 kmsg->uaddr, flags);
4935 if (force_nonblock && ret == -EAGAIN)
4936 return io_setup_async_msg(req, kmsg);
4937 if (ret == -ERESTARTSYS)
4940 if (req->flags & REQ_F_BUFFER_SELECTED)
4941 cflags = io_put_recv_kbuf(req);
4942 /* fast path, check for non-NULL to avoid function call */
4944 kfree(kmsg->free_iov);
4945 req->flags &= ~REQ_F_NEED_CLEANUP;
4946 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4948 __io_req_complete(req, issue_flags, ret, cflags);
4952 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4954 struct io_buffer *kbuf;
4955 struct io_sr_msg *sr = &req->sr_msg;
4957 void __user *buf = sr->buf;
4958 struct socket *sock;
4962 int ret, cflags = 0;
4963 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4965 sock = sock_from_file(req->file);
4966 if (unlikely(!sock))
4969 if (req->flags & REQ_F_BUFFER_SELECT) {
4970 kbuf = io_recv_buffer_select(req, !force_nonblock);
4972 return PTR_ERR(kbuf);
4973 buf = u64_to_user_ptr(kbuf->addr);
4976 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4980 msg.msg_name = NULL;
4981 msg.msg_control = NULL;
4982 msg.msg_controllen = 0;
4983 msg.msg_namelen = 0;
4984 msg.msg_iocb = NULL;
4987 flags = req->sr_msg.msg_flags;
4989 flags |= MSG_DONTWAIT;
4990 if (flags & MSG_WAITALL)
4991 min_ret = iov_iter_count(&msg.msg_iter);
4993 ret = sock_recvmsg(sock, &msg, flags);
4994 if (force_nonblock && ret == -EAGAIN)
4996 if (ret == -ERESTARTSYS)
4999 if (req->flags & REQ_F_BUFFER_SELECTED)
5000 cflags = io_put_recv_kbuf(req);
5001 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5003 __io_req_complete(req, issue_flags, ret, cflags);
5007 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5009 struct io_accept *accept = &req->accept;
5011 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5013 if (sqe->ioprio || sqe->len || sqe->buf_index)
5016 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5017 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5018 accept->flags = READ_ONCE(sqe->accept_flags);
5019 accept->nofile = rlimit(RLIMIT_NOFILE);
5021 accept->file_slot = READ_ONCE(sqe->file_index);
5022 if (accept->file_slot && ((req->open.how.flags & O_CLOEXEC) ||
5023 (accept->flags & SOCK_CLOEXEC)))
5025 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5027 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5028 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5032 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5034 struct io_accept *accept = &req->accept;
5035 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5036 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5037 bool fixed = !!accept->file_slot;
5041 if (req->file->f_flags & O_NONBLOCK)
5042 req->flags |= REQ_F_NOWAIT;
5045 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5046 if (unlikely(fd < 0))
5049 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5054 ret = PTR_ERR(file);
5055 if (ret == -EAGAIN && force_nonblock)
5057 if (ret == -ERESTARTSYS)
5060 } else if (!fixed) {
5061 fd_install(fd, file);
5064 ret = io_install_fixed_file(req, file, issue_flags,
5065 accept->file_slot - 1);
5067 __io_req_complete(req, issue_flags, ret, 0);
5071 static int io_connect_prep_async(struct io_kiocb *req)
5073 struct io_async_connect *io = req->async_data;
5074 struct io_connect *conn = &req->connect;
5076 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5079 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5081 struct io_connect *conn = &req->connect;
5083 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5085 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5089 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5090 conn->addr_len = READ_ONCE(sqe->addr2);
5094 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5096 struct io_async_connect __io, *io;
5097 unsigned file_flags;
5099 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5101 if (req->async_data) {
5102 io = req->async_data;
5104 ret = move_addr_to_kernel(req->connect.addr,
5105 req->connect.addr_len,
5112 file_flags = force_nonblock ? O_NONBLOCK : 0;
5114 ret = __sys_connect_file(req->file, &io->address,
5115 req->connect.addr_len, file_flags);
5116 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5117 if (req->async_data)
5119 if (io_alloc_async_data(req)) {
5123 memcpy(req->async_data, &__io, sizeof(__io));
5126 if (ret == -ERESTARTSYS)
5131 __io_req_complete(req, issue_flags, ret, 0);
5134 #else /* !CONFIG_NET */
5135 #define IO_NETOP_FN(op) \
5136 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5138 return -EOPNOTSUPP; \
5141 #define IO_NETOP_PREP(op) \
5143 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5145 return -EOPNOTSUPP; \
5148 #define IO_NETOP_PREP_ASYNC(op) \
5150 static int io_##op##_prep_async(struct io_kiocb *req) \
5152 return -EOPNOTSUPP; \
5155 IO_NETOP_PREP_ASYNC(sendmsg);
5156 IO_NETOP_PREP_ASYNC(recvmsg);
5157 IO_NETOP_PREP_ASYNC(connect);
5158 IO_NETOP_PREP(accept);
5161 #endif /* CONFIG_NET */
5163 struct io_poll_table {
5164 struct poll_table_struct pt;
5165 struct io_kiocb *req;
5170 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
5171 __poll_t mask, io_req_tw_func_t func)
5173 /* for instances that support it check for an event match first: */
5174 if (mask && !(mask & poll->events))
5177 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5179 list_del_init(&poll->wait.entry);
5182 req->io_task_work.func = func;
5185 * If this fails, then the task is exiting. When a task exits, the
5186 * work gets canceled, so just cancel this request as well instead
5187 * of executing it. We can't safely execute it anyway, as we may not
5188 * have the needed state needed for it anyway.
5190 io_req_task_work_add(req);
5194 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
5195 __acquires(&req->ctx->completion_lock)
5197 struct io_ring_ctx *ctx = req->ctx;
5199 /* req->task == current here, checking PF_EXITING is safe */
5200 if (unlikely(req->task->flags & PF_EXITING))
5201 WRITE_ONCE(poll->canceled, true);
5203 if (!req->result && !READ_ONCE(poll->canceled)) {
5204 struct poll_table_struct pt = { ._key = poll->events };
5206 req->result = vfs_poll(req->file, &pt) & poll->events;
5209 spin_lock(&ctx->completion_lock);
5210 if (!req->result && !READ_ONCE(poll->canceled)) {
5211 add_wait_queue(poll->head, &poll->wait);
5218 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5220 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5221 if (req->opcode == IORING_OP_POLL_ADD)
5222 return req->async_data;
5223 return req->apoll->double_poll;
5226 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5228 if (req->opcode == IORING_OP_POLL_ADD)
5230 return &req->apoll->poll;
5233 static void io_poll_remove_double(struct io_kiocb *req)
5234 __must_hold(&req->ctx->completion_lock)
5236 struct io_poll_iocb *poll = io_poll_get_double(req);
5238 lockdep_assert_held(&req->ctx->completion_lock);
5240 if (poll && poll->head) {
5241 struct wait_queue_head *head = poll->head;
5243 spin_lock_irq(&head->lock);
5244 list_del_init(&poll->wait.entry);
5245 if (poll->wait.private)
5248 spin_unlock_irq(&head->lock);
5252 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5253 __must_hold(&req->ctx->completion_lock)
5255 struct io_ring_ctx *ctx = req->ctx;
5256 unsigned flags = IORING_CQE_F_MORE;
5259 if (READ_ONCE(req->poll.canceled)) {
5261 req->poll.events |= EPOLLONESHOT;
5263 error = mangle_poll(mask);
5265 if (req->poll.events & EPOLLONESHOT)
5267 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5268 req->poll.done = true;
5271 if (flags & IORING_CQE_F_MORE)
5274 io_commit_cqring(ctx);
5275 return !(flags & IORING_CQE_F_MORE);
5278 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5280 struct io_ring_ctx *ctx = req->ctx;
5281 struct io_kiocb *nxt;
5283 if (io_poll_rewait(req, &req->poll)) {
5284 spin_unlock(&ctx->completion_lock);
5288 done = io_poll_complete(req, req->result);
5290 io_poll_remove_double(req);
5291 hash_del(&req->hash_node);
5294 add_wait_queue(req->poll.head, &req->poll.wait);
5296 spin_unlock(&ctx->completion_lock);
5297 io_cqring_ev_posted(ctx);
5300 nxt = io_put_req_find_next(req);
5302 io_req_task_submit(nxt, locked);
5307 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5308 int sync, void *key)
5310 struct io_kiocb *req = wait->private;
5311 struct io_poll_iocb *poll = io_poll_get_single(req);
5312 __poll_t mask = key_to_poll(key);
5313 unsigned long flags;
5315 /* for instances that support it check for an event match first: */
5316 if (mask && !(mask & poll->events))
5318 if (!(poll->events & EPOLLONESHOT))
5319 return poll->wait.func(&poll->wait, mode, sync, key);
5321 list_del_init(&wait->entry);
5326 spin_lock_irqsave(&poll->head->lock, flags);
5327 done = list_empty(&poll->wait.entry);
5329 list_del_init(&poll->wait.entry);
5330 /* make sure double remove sees this as being gone */
5331 wait->private = NULL;
5332 spin_unlock_irqrestore(&poll->head->lock, flags);
5334 /* use wait func handler, so it matches the rq type */
5335 poll->wait.func(&poll->wait, mode, sync, key);
5342 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5343 wait_queue_func_t wake_func)
5347 poll->canceled = false;
5348 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5349 /* mask in events that we always want/need */
5350 poll->events = events | IO_POLL_UNMASK;
5351 INIT_LIST_HEAD(&poll->wait.entry);
5352 init_waitqueue_func_entry(&poll->wait, wake_func);
5355 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5356 struct wait_queue_head *head,
5357 struct io_poll_iocb **poll_ptr)
5359 struct io_kiocb *req = pt->req;
5362 * The file being polled uses multiple waitqueues for poll handling
5363 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5366 if (unlikely(pt->nr_entries)) {
5367 struct io_poll_iocb *poll_one = poll;
5369 /* double add on the same waitqueue head, ignore */
5370 if (poll_one->head == head)
5372 /* already have a 2nd entry, fail a third attempt */
5374 if ((*poll_ptr)->head == head)
5376 pt->error = -EINVAL;
5380 * Can't handle multishot for double wait for now, turn it
5381 * into one-shot mode.
5383 if (!(poll_one->events & EPOLLONESHOT))
5384 poll_one->events |= EPOLLONESHOT;
5385 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5387 pt->error = -ENOMEM;
5390 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5392 poll->wait.private = req;
5399 if (poll->events & EPOLLEXCLUSIVE)
5400 add_wait_queue_exclusive(head, &poll->wait);
5402 add_wait_queue(head, &poll->wait);
5405 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5406 struct poll_table_struct *p)
5408 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5409 struct async_poll *apoll = pt->req->apoll;
5411 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5414 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5416 struct async_poll *apoll = req->apoll;
5417 struct io_ring_ctx *ctx = req->ctx;
5419 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5421 if (io_poll_rewait(req, &apoll->poll)) {
5422 spin_unlock(&ctx->completion_lock);
5426 hash_del(&req->hash_node);
5427 io_poll_remove_double(req);
5428 spin_unlock(&ctx->completion_lock);
5430 if (!READ_ONCE(apoll->poll.canceled))
5431 io_req_task_submit(req, locked);
5433 io_req_complete_failed(req, -ECANCELED);
5436 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5439 struct io_kiocb *req = wait->private;
5440 struct io_poll_iocb *poll = &req->apoll->poll;
5442 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5445 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5448 static void io_poll_req_insert(struct io_kiocb *req)
5450 struct io_ring_ctx *ctx = req->ctx;
5451 struct hlist_head *list;
5453 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5454 hlist_add_head(&req->hash_node, list);
5457 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5458 struct io_poll_iocb *poll,
5459 struct io_poll_table *ipt, __poll_t mask,
5460 wait_queue_func_t wake_func)
5461 __acquires(&ctx->completion_lock)
5463 struct io_ring_ctx *ctx = req->ctx;
5464 bool cancel = false;
5466 INIT_HLIST_NODE(&req->hash_node);
5467 io_init_poll_iocb(poll, mask, wake_func);
5468 poll->file = req->file;
5469 poll->wait.private = req;
5471 ipt->pt._key = mask;
5474 ipt->nr_entries = 0;
5476 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5477 if (unlikely(!ipt->nr_entries) && !ipt->error)
5478 ipt->error = -EINVAL;
5480 spin_lock(&ctx->completion_lock);
5481 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5482 io_poll_remove_double(req);
5483 if (likely(poll->head)) {
5484 spin_lock_irq(&poll->head->lock);
5485 if (unlikely(list_empty(&poll->wait.entry))) {
5491 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5492 list_del_init(&poll->wait.entry);
5494 WRITE_ONCE(poll->canceled, true);
5495 else if (!poll->done) /* actually waiting for an event */
5496 io_poll_req_insert(req);
5497 spin_unlock_irq(&poll->head->lock);
5509 static int io_arm_poll_handler(struct io_kiocb *req)
5511 const struct io_op_def *def = &io_op_defs[req->opcode];
5512 struct io_ring_ctx *ctx = req->ctx;
5513 struct async_poll *apoll;
5514 struct io_poll_table ipt;
5515 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5518 if (!req->file || !file_can_poll(req->file))
5519 return IO_APOLL_ABORTED;
5520 if (req->flags & REQ_F_POLLED)
5521 return IO_APOLL_ABORTED;
5522 if (!def->pollin && !def->pollout)
5523 return IO_APOLL_ABORTED;
5527 mask |= POLLIN | POLLRDNORM;
5529 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5530 if ((req->opcode == IORING_OP_RECVMSG) &&
5531 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5535 mask |= POLLOUT | POLLWRNORM;
5538 /* if we can't nonblock try, then no point in arming a poll handler */
5539 if (!io_file_supports_nowait(req, rw))
5540 return IO_APOLL_ABORTED;
5542 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5543 if (unlikely(!apoll))
5544 return IO_APOLL_ABORTED;
5545 apoll->double_poll = NULL;
5547 req->flags |= REQ_F_POLLED;
5548 ipt.pt._qproc = io_async_queue_proc;
5549 io_req_set_refcount(req);
5551 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5553 spin_unlock(&ctx->completion_lock);
5554 if (ret || ipt.error)
5555 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5557 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5558 mask, apoll->poll.events);
5562 static bool __io_poll_remove_one(struct io_kiocb *req,
5563 struct io_poll_iocb *poll, bool do_cancel)
5564 __must_hold(&req->ctx->completion_lock)
5566 bool do_complete = false;
5570 spin_lock_irq(&poll->head->lock);
5572 WRITE_ONCE(poll->canceled, true);
5573 if (!list_empty(&poll->wait.entry)) {
5574 list_del_init(&poll->wait.entry);
5577 spin_unlock_irq(&poll->head->lock);
5578 hash_del(&req->hash_node);
5582 static bool io_poll_remove_one(struct io_kiocb *req)
5583 __must_hold(&req->ctx->completion_lock)
5587 io_poll_remove_double(req);
5588 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5591 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5592 io_commit_cqring(req->ctx);
5594 io_put_req_deferred(req);
5600 * Returns true if we found and killed one or more poll requests
5602 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5605 struct hlist_node *tmp;
5606 struct io_kiocb *req;
5609 spin_lock(&ctx->completion_lock);
5610 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5611 struct hlist_head *list;
5613 list = &ctx->cancel_hash[i];
5614 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5615 if (io_match_task(req, tsk, cancel_all))
5616 posted += io_poll_remove_one(req);
5619 spin_unlock(&ctx->completion_lock);
5622 io_cqring_ev_posted(ctx);
5627 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5629 __must_hold(&ctx->completion_lock)
5631 struct hlist_head *list;
5632 struct io_kiocb *req;
5634 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5635 hlist_for_each_entry(req, list, hash_node) {
5636 if (sqe_addr != req->user_data)
5638 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5645 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5647 __must_hold(&ctx->completion_lock)
5649 struct io_kiocb *req;
5651 req = io_poll_find(ctx, sqe_addr, poll_only);
5654 if (io_poll_remove_one(req))
5660 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5665 events = READ_ONCE(sqe->poll32_events);
5667 events = swahw32(events);
5669 if (!(flags & IORING_POLL_ADD_MULTI))
5670 events |= EPOLLONESHOT;
5671 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5674 static int io_poll_update_prep(struct io_kiocb *req,
5675 const struct io_uring_sqe *sqe)
5677 struct io_poll_update *upd = &req->poll_update;
5680 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5682 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5684 flags = READ_ONCE(sqe->len);
5685 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5686 IORING_POLL_ADD_MULTI))
5688 /* meaningless without update */
5689 if (flags == IORING_POLL_ADD_MULTI)
5692 upd->old_user_data = READ_ONCE(sqe->addr);
5693 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5694 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5696 upd->new_user_data = READ_ONCE(sqe->off);
5697 if (!upd->update_user_data && upd->new_user_data)
5699 if (upd->update_events)
5700 upd->events = io_poll_parse_events(sqe, flags);
5701 else if (sqe->poll32_events)
5707 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5710 struct io_kiocb *req = wait->private;
5711 struct io_poll_iocb *poll = &req->poll;
5713 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5716 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5717 struct poll_table_struct *p)
5719 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5721 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5724 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5726 struct io_poll_iocb *poll = &req->poll;
5729 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5731 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5733 flags = READ_ONCE(sqe->len);
5734 if (flags & ~IORING_POLL_ADD_MULTI)
5737 io_req_set_refcount(req);
5738 poll->events = io_poll_parse_events(sqe, flags);
5742 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5744 struct io_poll_iocb *poll = &req->poll;
5745 struct io_ring_ctx *ctx = req->ctx;
5746 struct io_poll_table ipt;
5749 ipt.pt._qproc = io_poll_queue_proc;
5751 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5754 if (mask) { /* no async, we'd stolen it */
5756 io_poll_complete(req, mask);
5758 spin_unlock(&ctx->completion_lock);
5761 io_cqring_ev_posted(ctx);
5762 if (poll->events & EPOLLONESHOT)
5768 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5770 struct io_ring_ctx *ctx = req->ctx;
5771 struct io_kiocb *preq;
5775 spin_lock(&ctx->completion_lock);
5776 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5782 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5784 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5789 * Don't allow racy completion with singleshot, as we cannot safely
5790 * update those. For multishot, if we're racing with completion, just
5791 * let completion re-add it.
5793 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5794 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5798 /* we now have a detached poll request. reissue. */
5802 spin_unlock(&ctx->completion_lock);
5804 io_req_complete(req, ret);
5807 /* only mask one event flags, keep behavior flags */
5808 if (req->poll_update.update_events) {
5809 preq->poll.events &= ~0xffff;
5810 preq->poll.events |= req->poll_update.events & 0xffff;
5811 preq->poll.events |= IO_POLL_UNMASK;
5813 if (req->poll_update.update_user_data)
5814 preq->user_data = req->poll_update.new_user_data;
5815 spin_unlock(&ctx->completion_lock);
5817 /* complete update request, we're done with it */
5818 io_req_complete(req, ret);
5821 ret = io_poll_add(preq, issue_flags);
5824 io_req_complete(preq, ret);
5830 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5833 io_req_complete_post(req, -ETIME, 0);
5836 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5838 struct io_timeout_data *data = container_of(timer,
5839 struct io_timeout_data, timer);
5840 struct io_kiocb *req = data->req;
5841 struct io_ring_ctx *ctx = req->ctx;
5842 unsigned long flags;
5844 spin_lock_irqsave(&ctx->timeout_lock, flags);
5845 list_del_init(&req->timeout.list);
5846 atomic_set(&req->ctx->cq_timeouts,
5847 atomic_read(&req->ctx->cq_timeouts) + 1);
5848 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5850 req->io_task_work.func = io_req_task_timeout;
5851 io_req_task_work_add(req);
5852 return HRTIMER_NORESTART;
5855 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5857 __must_hold(&ctx->timeout_lock)
5859 struct io_timeout_data *io;
5860 struct io_kiocb *req;
5863 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5864 found = user_data == req->user_data;
5869 return ERR_PTR(-ENOENT);
5871 io = req->async_data;
5872 if (hrtimer_try_to_cancel(&io->timer) == -1)
5873 return ERR_PTR(-EALREADY);
5874 list_del_init(&req->timeout.list);
5878 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5879 __must_hold(&ctx->completion_lock)
5880 __must_hold(&ctx->timeout_lock)
5882 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5885 return PTR_ERR(req);
5888 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5889 io_put_req_deferred(req);
5893 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5895 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5896 case IORING_TIMEOUT_BOOTTIME:
5897 return CLOCK_BOOTTIME;
5898 case IORING_TIMEOUT_REALTIME:
5899 return CLOCK_REALTIME;
5901 /* can't happen, vetted at prep time */
5905 return CLOCK_MONOTONIC;
5909 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5910 struct timespec64 *ts, enum hrtimer_mode mode)
5911 __must_hold(&ctx->timeout_lock)
5913 struct io_timeout_data *io;
5914 struct io_kiocb *req;
5917 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5918 found = user_data == req->user_data;
5925 io = req->async_data;
5926 if (hrtimer_try_to_cancel(&io->timer) == -1)
5928 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5929 io->timer.function = io_link_timeout_fn;
5930 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
5934 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5935 struct timespec64 *ts, enum hrtimer_mode mode)
5936 __must_hold(&ctx->timeout_lock)
5938 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5939 struct io_timeout_data *data;
5942 return PTR_ERR(req);
5944 req->timeout.off = 0; /* noseq */
5945 data = req->async_data;
5946 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5947 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
5948 data->timer.function = io_timeout_fn;
5949 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5953 static int io_timeout_remove_prep(struct io_kiocb *req,
5954 const struct io_uring_sqe *sqe)
5956 struct io_timeout_rem *tr = &req->timeout_rem;
5958 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5960 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5962 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5965 tr->ltimeout = false;
5966 tr->addr = READ_ONCE(sqe->addr);
5967 tr->flags = READ_ONCE(sqe->timeout_flags);
5968 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
5969 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5971 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
5972 tr->ltimeout = true;
5973 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
5975 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5977 } else if (tr->flags) {
5978 /* timeout removal doesn't support flags */
5985 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5987 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5992 * Remove or update an existing timeout command
5994 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5996 struct io_timeout_rem *tr = &req->timeout_rem;
5997 struct io_ring_ctx *ctx = req->ctx;
6000 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6001 spin_lock(&ctx->completion_lock);
6002 spin_lock_irq(&ctx->timeout_lock);
6003 ret = io_timeout_cancel(ctx, tr->addr);
6004 spin_unlock_irq(&ctx->timeout_lock);
6005 spin_unlock(&ctx->completion_lock);
6007 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6009 spin_lock_irq(&ctx->timeout_lock);
6011 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6013 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6014 spin_unlock_irq(&ctx->timeout_lock);
6019 io_req_complete_post(req, ret, 0);
6023 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6024 bool is_timeout_link)
6026 struct io_timeout_data *data;
6028 u32 off = READ_ONCE(sqe->off);
6030 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6032 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6035 if (off && is_timeout_link)
6037 flags = READ_ONCE(sqe->timeout_flags);
6038 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6040 /* more than one clock specified is invalid, obviously */
6041 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6044 INIT_LIST_HEAD(&req->timeout.list);
6045 req->timeout.off = off;
6046 if (unlikely(off && !req->ctx->off_timeout_used))
6047 req->ctx->off_timeout_used = true;
6049 if (!req->async_data && io_alloc_async_data(req))
6052 data = req->async_data;
6054 data->flags = flags;
6056 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6059 data->mode = io_translate_timeout_mode(flags);
6060 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6062 if (is_timeout_link) {
6063 struct io_submit_link *link = &req->ctx->submit_state.link;
6067 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6069 req->timeout.head = link->last;
6070 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6075 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6077 struct io_ring_ctx *ctx = req->ctx;
6078 struct io_timeout_data *data = req->async_data;
6079 struct list_head *entry;
6080 u32 tail, off = req->timeout.off;
6082 spin_lock_irq(&ctx->timeout_lock);
6085 * sqe->off holds how many events that need to occur for this
6086 * timeout event to be satisfied. If it isn't set, then this is
6087 * a pure timeout request, sequence isn't used.
6089 if (io_is_timeout_noseq(req)) {
6090 entry = ctx->timeout_list.prev;
6094 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6095 req->timeout.target_seq = tail + off;
6097 /* Update the last seq here in case io_flush_timeouts() hasn't.
6098 * This is safe because ->completion_lock is held, and submissions
6099 * and completions are never mixed in the same ->completion_lock section.
6101 ctx->cq_last_tm_flush = tail;
6104 * Insertion sort, ensuring the first entry in the list is always
6105 * the one we need first.
6107 list_for_each_prev(entry, &ctx->timeout_list) {
6108 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6111 if (io_is_timeout_noseq(nxt))
6113 /* nxt.seq is behind @tail, otherwise would've been completed */
6114 if (off >= nxt->timeout.target_seq - tail)
6118 list_add(&req->timeout.list, entry);
6119 data->timer.function = io_timeout_fn;
6120 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6121 spin_unlock_irq(&ctx->timeout_lock);
6125 struct io_cancel_data {
6126 struct io_ring_ctx *ctx;
6130 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6132 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6133 struct io_cancel_data *cd = data;
6135 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6138 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6139 struct io_ring_ctx *ctx)
6141 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6142 enum io_wq_cancel cancel_ret;
6145 if (!tctx || !tctx->io_wq)
6148 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6149 switch (cancel_ret) {
6150 case IO_WQ_CANCEL_OK:
6153 case IO_WQ_CANCEL_RUNNING:
6156 case IO_WQ_CANCEL_NOTFOUND:
6164 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6166 struct io_ring_ctx *ctx = req->ctx;
6169 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6171 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6175 spin_lock(&ctx->completion_lock);
6176 spin_lock_irq(&ctx->timeout_lock);
6177 ret = io_timeout_cancel(ctx, sqe_addr);
6178 spin_unlock_irq(&ctx->timeout_lock);
6181 ret = io_poll_cancel(ctx, sqe_addr, false);
6183 spin_unlock(&ctx->completion_lock);
6187 static int io_async_cancel_prep(struct io_kiocb *req,
6188 const struct io_uring_sqe *sqe)
6190 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6192 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6194 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6198 req->cancel.addr = READ_ONCE(sqe->addr);
6202 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6204 struct io_ring_ctx *ctx = req->ctx;
6205 u64 sqe_addr = req->cancel.addr;
6206 struct io_tctx_node *node;
6209 ret = io_try_cancel_userdata(req, sqe_addr);
6213 /* slow path, try all io-wq's */
6214 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6216 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6217 struct io_uring_task *tctx = node->task->io_uring;
6219 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6223 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6227 io_req_complete_post(req, ret, 0);
6231 static int io_rsrc_update_prep(struct io_kiocb *req,
6232 const struct io_uring_sqe *sqe)
6234 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6236 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6239 req->rsrc_update.offset = READ_ONCE(sqe->off);
6240 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6241 if (!req->rsrc_update.nr_args)
6243 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6247 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6249 struct io_ring_ctx *ctx = req->ctx;
6250 struct io_uring_rsrc_update2 up;
6253 if (issue_flags & IO_URING_F_NONBLOCK)
6256 up.offset = req->rsrc_update.offset;
6257 up.data = req->rsrc_update.arg;
6262 mutex_lock(&ctx->uring_lock);
6263 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6264 &up, req->rsrc_update.nr_args);
6265 mutex_unlock(&ctx->uring_lock);
6269 __io_req_complete(req, issue_flags, ret, 0);
6273 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6275 switch (req->opcode) {
6278 case IORING_OP_READV:
6279 case IORING_OP_READ_FIXED:
6280 case IORING_OP_READ:
6281 return io_read_prep(req, sqe);
6282 case IORING_OP_WRITEV:
6283 case IORING_OP_WRITE_FIXED:
6284 case IORING_OP_WRITE:
6285 return io_write_prep(req, sqe);
6286 case IORING_OP_POLL_ADD:
6287 return io_poll_add_prep(req, sqe);
6288 case IORING_OP_POLL_REMOVE:
6289 return io_poll_update_prep(req, sqe);
6290 case IORING_OP_FSYNC:
6291 return io_fsync_prep(req, sqe);
6292 case IORING_OP_SYNC_FILE_RANGE:
6293 return io_sfr_prep(req, sqe);
6294 case IORING_OP_SENDMSG:
6295 case IORING_OP_SEND:
6296 return io_sendmsg_prep(req, sqe);
6297 case IORING_OP_RECVMSG:
6298 case IORING_OP_RECV:
6299 return io_recvmsg_prep(req, sqe);
6300 case IORING_OP_CONNECT:
6301 return io_connect_prep(req, sqe);
6302 case IORING_OP_TIMEOUT:
6303 return io_timeout_prep(req, sqe, false);
6304 case IORING_OP_TIMEOUT_REMOVE:
6305 return io_timeout_remove_prep(req, sqe);
6306 case IORING_OP_ASYNC_CANCEL:
6307 return io_async_cancel_prep(req, sqe);
6308 case IORING_OP_LINK_TIMEOUT:
6309 return io_timeout_prep(req, sqe, true);
6310 case IORING_OP_ACCEPT:
6311 return io_accept_prep(req, sqe);
6312 case IORING_OP_FALLOCATE:
6313 return io_fallocate_prep(req, sqe);
6314 case IORING_OP_OPENAT:
6315 return io_openat_prep(req, sqe);
6316 case IORING_OP_CLOSE:
6317 return io_close_prep(req, sqe);
6318 case IORING_OP_FILES_UPDATE:
6319 return io_rsrc_update_prep(req, sqe);
6320 case IORING_OP_STATX:
6321 return io_statx_prep(req, sqe);
6322 case IORING_OP_FADVISE:
6323 return io_fadvise_prep(req, sqe);
6324 case IORING_OP_MADVISE:
6325 return io_madvise_prep(req, sqe);
6326 case IORING_OP_OPENAT2:
6327 return io_openat2_prep(req, sqe);
6328 case IORING_OP_EPOLL_CTL:
6329 return io_epoll_ctl_prep(req, sqe);
6330 case IORING_OP_SPLICE:
6331 return io_splice_prep(req, sqe);
6332 case IORING_OP_PROVIDE_BUFFERS:
6333 return io_provide_buffers_prep(req, sqe);
6334 case IORING_OP_REMOVE_BUFFERS:
6335 return io_remove_buffers_prep(req, sqe);
6337 return io_tee_prep(req, sqe);
6338 case IORING_OP_SHUTDOWN:
6339 return io_shutdown_prep(req, sqe);
6340 case IORING_OP_RENAMEAT:
6341 return io_renameat_prep(req, sqe);
6342 case IORING_OP_UNLINKAT:
6343 return io_unlinkat_prep(req, sqe);
6344 case IORING_OP_MKDIRAT:
6345 return io_mkdirat_prep(req, sqe);
6346 case IORING_OP_SYMLINKAT:
6347 return io_symlinkat_prep(req, sqe);
6348 case IORING_OP_LINKAT:
6349 return io_linkat_prep(req, sqe);
6352 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6357 static int io_req_prep_async(struct io_kiocb *req)
6359 if (!io_op_defs[req->opcode].needs_async_setup)
6361 if (WARN_ON_ONCE(req->async_data))
6363 if (io_alloc_async_data(req))
6366 switch (req->opcode) {
6367 case IORING_OP_READV:
6368 return io_rw_prep_async(req, READ);
6369 case IORING_OP_WRITEV:
6370 return io_rw_prep_async(req, WRITE);
6371 case IORING_OP_SENDMSG:
6372 return io_sendmsg_prep_async(req);
6373 case IORING_OP_RECVMSG:
6374 return io_recvmsg_prep_async(req);
6375 case IORING_OP_CONNECT:
6376 return io_connect_prep_async(req);
6378 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6383 static u32 io_get_sequence(struct io_kiocb *req)
6385 u32 seq = req->ctx->cached_sq_head;
6387 /* need original cached_sq_head, but it was increased for each req */
6388 io_for_each_link(req, req)
6393 static bool io_drain_req(struct io_kiocb *req)
6395 struct io_kiocb *pos;
6396 struct io_ring_ctx *ctx = req->ctx;
6397 struct io_defer_entry *de;
6402 * If we need to drain a request in the middle of a link, drain the
6403 * head request and the next request/link after the current link.
6404 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6405 * maintained for every request of our link.
6407 if (ctx->drain_next) {
6408 req->flags |= REQ_F_IO_DRAIN;
6409 ctx->drain_next = false;
6411 /* not interested in head, start from the first linked */
6412 io_for_each_link(pos, req->link) {
6413 if (pos->flags & REQ_F_IO_DRAIN) {
6414 ctx->drain_next = true;
6415 req->flags |= REQ_F_IO_DRAIN;
6420 /* Still need defer if there is pending req in defer list. */
6421 if (likely(list_empty_careful(&ctx->defer_list) &&
6422 !(req->flags & REQ_F_IO_DRAIN))) {
6423 ctx->drain_active = false;
6427 seq = io_get_sequence(req);
6428 /* Still a chance to pass the sequence check */
6429 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6432 ret = io_req_prep_async(req);
6435 io_prep_async_link(req);
6436 de = kmalloc(sizeof(*de), GFP_KERNEL);
6440 io_req_complete_failed(req, ret);
6444 spin_lock(&ctx->completion_lock);
6445 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6446 spin_unlock(&ctx->completion_lock);
6448 io_queue_async_work(req, NULL);
6452 trace_io_uring_defer(ctx, req, req->user_data);
6455 list_add_tail(&de->list, &ctx->defer_list);
6456 spin_unlock(&ctx->completion_lock);
6460 static void io_clean_op(struct io_kiocb *req)
6462 if (req->flags & REQ_F_BUFFER_SELECTED) {
6463 switch (req->opcode) {
6464 case IORING_OP_READV:
6465 case IORING_OP_READ_FIXED:
6466 case IORING_OP_READ:
6467 kfree((void *)(unsigned long)req->rw.addr);
6469 case IORING_OP_RECVMSG:
6470 case IORING_OP_RECV:
6471 kfree(req->sr_msg.kbuf);
6476 if (req->flags & REQ_F_NEED_CLEANUP) {
6477 switch (req->opcode) {
6478 case IORING_OP_READV:
6479 case IORING_OP_READ_FIXED:
6480 case IORING_OP_READ:
6481 case IORING_OP_WRITEV:
6482 case IORING_OP_WRITE_FIXED:
6483 case IORING_OP_WRITE: {
6484 struct io_async_rw *io = req->async_data;
6486 kfree(io->free_iovec);
6489 case IORING_OP_RECVMSG:
6490 case IORING_OP_SENDMSG: {
6491 struct io_async_msghdr *io = req->async_data;
6493 kfree(io->free_iov);
6496 case IORING_OP_SPLICE:
6498 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6499 io_put_file(req->splice.file_in);
6501 case IORING_OP_OPENAT:
6502 case IORING_OP_OPENAT2:
6503 if (req->open.filename)
6504 putname(req->open.filename);
6506 case IORING_OP_RENAMEAT:
6507 putname(req->rename.oldpath);
6508 putname(req->rename.newpath);
6510 case IORING_OP_UNLINKAT:
6511 putname(req->unlink.filename);
6513 case IORING_OP_MKDIRAT:
6514 putname(req->mkdir.filename);
6516 case IORING_OP_SYMLINKAT:
6517 putname(req->symlink.oldpath);
6518 putname(req->symlink.newpath);
6520 case IORING_OP_LINKAT:
6521 putname(req->hardlink.oldpath);
6522 putname(req->hardlink.newpath);
6526 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6527 kfree(req->apoll->double_poll);
6531 if (req->flags & REQ_F_INFLIGHT) {
6532 struct io_uring_task *tctx = req->task->io_uring;
6534 atomic_dec(&tctx->inflight_tracked);
6536 if (req->flags & REQ_F_CREDS)
6537 put_cred(req->creds);
6539 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6542 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6544 struct io_ring_ctx *ctx = req->ctx;
6545 const struct cred *creds = NULL;
6548 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6549 creds = override_creds(req->creds);
6551 switch (req->opcode) {
6553 ret = io_nop(req, issue_flags);
6555 case IORING_OP_READV:
6556 case IORING_OP_READ_FIXED:
6557 case IORING_OP_READ:
6558 ret = io_read(req, issue_flags);
6560 case IORING_OP_WRITEV:
6561 case IORING_OP_WRITE_FIXED:
6562 case IORING_OP_WRITE:
6563 ret = io_write(req, issue_flags);
6565 case IORING_OP_FSYNC:
6566 ret = io_fsync(req, issue_flags);
6568 case IORING_OP_POLL_ADD:
6569 ret = io_poll_add(req, issue_flags);
6571 case IORING_OP_POLL_REMOVE:
6572 ret = io_poll_update(req, issue_flags);
6574 case IORING_OP_SYNC_FILE_RANGE:
6575 ret = io_sync_file_range(req, issue_flags);
6577 case IORING_OP_SENDMSG:
6578 ret = io_sendmsg(req, issue_flags);
6580 case IORING_OP_SEND:
6581 ret = io_send(req, issue_flags);
6583 case IORING_OP_RECVMSG:
6584 ret = io_recvmsg(req, issue_flags);
6586 case IORING_OP_RECV:
6587 ret = io_recv(req, issue_flags);
6589 case IORING_OP_TIMEOUT:
6590 ret = io_timeout(req, issue_flags);
6592 case IORING_OP_TIMEOUT_REMOVE:
6593 ret = io_timeout_remove(req, issue_flags);
6595 case IORING_OP_ACCEPT:
6596 ret = io_accept(req, issue_flags);
6598 case IORING_OP_CONNECT:
6599 ret = io_connect(req, issue_flags);
6601 case IORING_OP_ASYNC_CANCEL:
6602 ret = io_async_cancel(req, issue_flags);
6604 case IORING_OP_FALLOCATE:
6605 ret = io_fallocate(req, issue_flags);
6607 case IORING_OP_OPENAT:
6608 ret = io_openat(req, issue_flags);
6610 case IORING_OP_CLOSE:
6611 ret = io_close(req, issue_flags);
6613 case IORING_OP_FILES_UPDATE:
6614 ret = io_files_update(req, issue_flags);
6616 case IORING_OP_STATX:
6617 ret = io_statx(req, issue_flags);
6619 case IORING_OP_FADVISE:
6620 ret = io_fadvise(req, issue_flags);
6622 case IORING_OP_MADVISE:
6623 ret = io_madvise(req, issue_flags);
6625 case IORING_OP_OPENAT2:
6626 ret = io_openat2(req, issue_flags);
6628 case IORING_OP_EPOLL_CTL:
6629 ret = io_epoll_ctl(req, issue_flags);
6631 case IORING_OP_SPLICE:
6632 ret = io_splice(req, issue_flags);
6634 case IORING_OP_PROVIDE_BUFFERS:
6635 ret = io_provide_buffers(req, issue_flags);
6637 case IORING_OP_REMOVE_BUFFERS:
6638 ret = io_remove_buffers(req, issue_flags);
6641 ret = io_tee(req, issue_flags);
6643 case IORING_OP_SHUTDOWN:
6644 ret = io_shutdown(req, issue_flags);
6646 case IORING_OP_RENAMEAT:
6647 ret = io_renameat(req, issue_flags);
6649 case IORING_OP_UNLINKAT:
6650 ret = io_unlinkat(req, issue_flags);
6652 case IORING_OP_MKDIRAT:
6653 ret = io_mkdirat(req, issue_flags);
6655 case IORING_OP_SYMLINKAT:
6656 ret = io_symlinkat(req, issue_flags);
6658 case IORING_OP_LINKAT:
6659 ret = io_linkat(req, issue_flags);
6667 revert_creds(creds);
6670 /* If the op doesn't have a file, we're not polling for it */
6671 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6672 io_iopoll_req_issued(req);
6677 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6679 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6681 req = io_put_req_find_next(req);
6682 return req ? &req->work : NULL;
6685 static void io_wq_submit_work(struct io_wq_work *work)
6687 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6688 struct io_kiocb *timeout;
6691 /* one will be dropped by ->io_free_work() after returning to io-wq */
6692 if (!(req->flags & REQ_F_REFCOUNT))
6693 __io_req_set_refcount(req, 2);
6697 timeout = io_prep_linked_timeout(req);
6699 io_queue_linked_timeout(timeout);
6701 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6702 if (work->flags & IO_WQ_WORK_CANCEL)
6707 ret = io_issue_sqe(req, 0);
6709 * We can get EAGAIN for polled IO even though we're
6710 * forcing a sync submission from here, since we can't
6711 * wait for request slots on the block side.
6719 /* avoid locking problems by failing it from a clean context */
6721 io_req_task_queue_fail(req, ret);
6724 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6727 return &table->files[i];
6730 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6733 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6735 return (struct file *) (slot->file_ptr & FFS_MASK);
6738 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6740 unsigned long file_ptr = (unsigned long) file;
6742 if (__io_file_supports_nowait(file, READ))
6743 file_ptr |= FFS_ASYNC_READ;
6744 if (__io_file_supports_nowait(file, WRITE))
6745 file_ptr |= FFS_ASYNC_WRITE;
6746 if (S_ISREG(file_inode(file)->i_mode))
6747 file_ptr |= FFS_ISREG;
6748 file_slot->file_ptr = file_ptr;
6751 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6752 struct io_kiocb *req, int fd)
6755 unsigned long file_ptr;
6757 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6759 fd = array_index_nospec(fd, ctx->nr_user_files);
6760 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6761 file = (struct file *) (file_ptr & FFS_MASK);
6762 file_ptr &= ~FFS_MASK;
6763 /* mask in overlapping REQ_F and FFS bits */
6764 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6765 io_req_set_rsrc_node(req);
6769 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6770 struct io_kiocb *req, int fd)
6772 struct file *file = fget(fd);
6774 trace_io_uring_file_get(ctx, fd);
6776 /* we don't allow fixed io_uring files */
6777 if (file && unlikely(file->f_op == &io_uring_fops))
6778 io_req_track_inflight(req);
6782 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6783 struct io_kiocb *req, int fd, bool fixed)
6786 return io_file_get_fixed(ctx, req, fd);
6788 return io_file_get_normal(ctx, req, fd);
6791 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6793 struct io_kiocb *prev = req->timeout.prev;
6797 ret = io_try_cancel_userdata(req, prev->user_data);
6798 io_req_complete_post(req, ret ?: -ETIME, 0);
6801 io_req_complete_post(req, -ETIME, 0);
6805 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6807 struct io_timeout_data *data = container_of(timer,
6808 struct io_timeout_data, timer);
6809 struct io_kiocb *prev, *req = data->req;
6810 struct io_ring_ctx *ctx = req->ctx;
6811 unsigned long flags;
6813 spin_lock_irqsave(&ctx->timeout_lock, flags);
6814 prev = req->timeout.head;
6815 req->timeout.head = NULL;
6818 * We don't expect the list to be empty, that will only happen if we
6819 * race with the completion of the linked work.
6822 io_remove_next_linked(prev);
6823 if (!req_ref_inc_not_zero(prev))
6826 list_del(&req->timeout.list);
6827 req->timeout.prev = prev;
6828 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6830 req->io_task_work.func = io_req_task_link_timeout;
6831 io_req_task_work_add(req);
6832 return HRTIMER_NORESTART;
6835 static void io_queue_linked_timeout(struct io_kiocb *req)
6837 struct io_ring_ctx *ctx = req->ctx;
6839 spin_lock_irq(&ctx->timeout_lock);
6841 * If the back reference is NULL, then our linked request finished
6842 * before we got a chance to setup the timer
6844 if (req->timeout.head) {
6845 struct io_timeout_data *data = req->async_data;
6847 data->timer.function = io_link_timeout_fn;
6848 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6850 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6852 spin_unlock_irq(&ctx->timeout_lock);
6853 /* drop submission reference */
6857 static void __io_queue_sqe(struct io_kiocb *req)
6858 __must_hold(&req->ctx->uring_lock)
6860 struct io_kiocb *linked_timeout;
6864 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6867 * We async punt it if the file wasn't marked NOWAIT, or if the file
6868 * doesn't support non-blocking read/write attempts
6871 if (req->flags & REQ_F_COMPLETE_INLINE) {
6872 struct io_ring_ctx *ctx = req->ctx;
6873 struct io_submit_state *state = &ctx->submit_state;
6875 state->compl_reqs[state->compl_nr++] = req;
6876 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6877 io_submit_flush_completions(ctx);
6881 linked_timeout = io_prep_linked_timeout(req);
6883 io_queue_linked_timeout(linked_timeout);
6884 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6885 linked_timeout = io_prep_linked_timeout(req);
6887 switch (io_arm_poll_handler(req)) {
6888 case IO_APOLL_READY:
6890 io_unprep_linked_timeout(req);
6892 case IO_APOLL_ABORTED:
6894 * Queued up for async execution, worker will release
6895 * submit reference when the iocb is actually submitted.
6897 io_queue_async_work(req, NULL);
6902 io_queue_linked_timeout(linked_timeout);
6904 io_req_complete_failed(req, ret);
6908 static inline void io_queue_sqe(struct io_kiocb *req)
6909 __must_hold(&req->ctx->uring_lock)
6911 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6914 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6915 __io_queue_sqe(req);
6916 } else if (req->flags & REQ_F_FAIL) {
6917 io_req_complete_failed(req, req->result);
6919 int ret = io_req_prep_async(req);
6922 io_req_complete_failed(req, ret);
6924 io_queue_async_work(req, NULL);
6929 * Check SQE restrictions (opcode and flags).
6931 * Returns 'true' if SQE is allowed, 'false' otherwise.
6933 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6934 struct io_kiocb *req,
6935 unsigned int sqe_flags)
6937 if (likely(!ctx->restricted))
6940 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6943 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6944 ctx->restrictions.sqe_flags_required)
6947 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6948 ctx->restrictions.sqe_flags_required))
6954 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6955 const struct io_uring_sqe *sqe)
6956 __must_hold(&ctx->uring_lock)
6958 struct io_submit_state *state;
6959 unsigned int sqe_flags;
6960 int personality, ret = 0;
6962 /* req is partially pre-initialised, see io_preinit_req() */
6963 req->opcode = READ_ONCE(sqe->opcode);
6964 /* same numerical values with corresponding REQ_F_*, safe to copy */
6965 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6966 req->user_data = READ_ONCE(sqe->user_data);
6968 req->fixed_rsrc_refs = NULL;
6969 req->task = current;
6971 /* enforce forwards compatibility on users */
6972 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6974 if (unlikely(req->opcode >= IORING_OP_LAST))
6976 if (!io_check_restriction(ctx, req, sqe_flags))
6979 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6980 !io_op_defs[req->opcode].buffer_select)
6982 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6983 ctx->drain_active = true;
6985 personality = READ_ONCE(sqe->personality);
6987 req->creds = xa_load(&ctx->personalities, personality);
6990 get_cred(req->creds);
6991 req->flags |= REQ_F_CREDS;
6993 state = &ctx->submit_state;
6996 * Plug now if we have more than 1 IO left after this, and the target
6997 * is potentially a read/write to block based storage.
6999 if (!state->plug_started && state->ios_left > 1 &&
7000 io_op_defs[req->opcode].plug) {
7001 blk_start_plug(&state->plug);
7002 state->plug_started = true;
7005 if (io_op_defs[req->opcode].needs_file) {
7006 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7007 (sqe_flags & IOSQE_FIXED_FILE));
7008 if (unlikely(!req->file))
7016 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7017 const struct io_uring_sqe *sqe)
7018 __must_hold(&ctx->uring_lock)
7020 struct io_submit_link *link = &ctx->submit_state.link;
7023 ret = io_init_req(ctx, req, sqe);
7024 if (unlikely(ret)) {
7026 /* fail even hard links since we don't submit */
7029 * we can judge a link req is failed or cancelled by if
7030 * REQ_F_FAIL is set, but the head is an exception since
7031 * it may be set REQ_F_FAIL because of other req's failure
7032 * so let's leverage req->result to distinguish if a head
7033 * is set REQ_F_FAIL because of its failure or other req's
7034 * failure so that we can set the correct ret code for it.
7035 * init result here to avoid affecting the normal path.
7037 if (!(link->head->flags & REQ_F_FAIL))
7038 req_fail_link_node(link->head, -ECANCELED);
7039 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7041 * the current req is a normal req, we should return
7042 * error and thus break the submittion loop.
7044 io_req_complete_failed(req, ret);
7047 req_fail_link_node(req, ret);
7049 ret = io_req_prep(req, sqe);
7054 /* don't need @sqe from now on */
7055 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7057 ctx->flags & IORING_SETUP_SQPOLL);
7060 * If we already have a head request, queue this one for async
7061 * submittal once the head completes. If we don't have a head but
7062 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7063 * submitted sync once the chain is complete. If none of those
7064 * conditions are true (normal request), then just queue it.
7067 struct io_kiocb *head = link->head;
7069 if (!(req->flags & REQ_F_FAIL)) {
7070 ret = io_req_prep_async(req);
7071 if (unlikely(ret)) {
7072 req_fail_link_node(req, ret);
7073 if (!(head->flags & REQ_F_FAIL))
7074 req_fail_link_node(head, -ECANCELED);
7077 trace_io_uring_link(ctx, req, head);
7078 link->last->link = req;
7081 /* last request of a link, enqueue the link */
7082 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7087 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7099 * Batched submission is done, ensure local IO is flushed out.
7101 static void io_submit_state_end(struct io_submit_state *state,
7102 struct io_ring_ctx *ctx)
7104 if (state->link.head)
7105 io_queue_sqe(state->link.head);
7106 if (state->compl_nr)
7107 io_submit_flush_completions(ctx);
7108 if (state->plug_started)
7109 blk_finish_plug(&state->plug);
7113 * Start submission side cache.
7115 static void io_submit_state_start(struct io_submit_state *state,
7116 unsigned int max_ios)
7118 state->plug_started = false;
7119 state->ios_left = max_ios;
7120 /* set only head, no need to init link_last in advance */
7121 state->link.head = NULL;
7124 static void io_commit_sqring(struct io_ring_ctx *ctx)
7126 struct io_rings *rings = ctx->rings;
7129 * Ensure any loads from the SQEs are done at this point,
7130 * since once we write the new head, the application could
7131 * write new data to them.
7133 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7137 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7138 * that is mapped by userspace. This means that care needs to be taken to
7139 * ensure that reads are stable, as we cannot rely on userspace always
7140 * being a good citizen. If members of the sqe are validated and then later
7141 * used, it's important that those reads are done through READ_ONCE() to
7142 * prevent a re-load down the line.
7144 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7146 unsigned head, mask = ctx->sq_entries - 1;
7147 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7150 * The cached sq head (or cq tail) serves two purposes:
7152 * 1) allows us to batch the cost of updating the user visible
7154 * 2) allows the kernel side to track the head on its own, even
7155 * though the application is the one updating it.
7157 head = READ_ONCE(ctx->sq_array[sq_idx]);
7158 if (likely(head < ctx->sq_entries))
7159 return &ctx->sq_sqes[head];
7161 /* drop invalid entries */
7163 WRITE_ONCE(ctx->rings->sq_dropped,
7164 READ_ONCE(ctx->rings->sq_dropped) + 1);
7168 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7169 __must_hold(&ctx->uring_lock)
7173 /* make sure SQ entry isn't read before tail */
7174 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7175 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7177 io_get_task_refs(nr);
7179 io_submit_state_start(&ctx->submit_state, nr);
7180 while (submitted < nr) {
7181 const struct io_uring_sqe *sqe;
7182 struct io_kiocb *req;
7184 req = io_alloc_req(ctx);
7185 if (unlikely(!req)) {
7187 submitted = -EAGAIN;
7190 sqe = io_get_sqe(ctx);
7191 if (unlikely(!sqe)) {
7192 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7195 /* will complete beyond this point, count as submitted */
7197 if (io_submit_sqe(ctx, req, sqe))
7201 if (unlikely(submitted != nr)) {
7202 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7203 int unused = nr - ref_used;
7205 current->io_uring->cached_refs += unused;
7206 percpu_ref_put_many(&ctx->refs, unused);
7209 io_submit_state_end(&ctx->submit_state, ctx);
7210 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7211 io_commit_sqring(ctx);
7216 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7218 return READ_ONCE(sqd->state);
7221 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7223 /* Tell userspace we may need a wakeup call */
7224 spin_lock(&ctx->completion_lock);
7225 WRITE_ONCE(ctx->rings->sq_flags,
7226 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7227 spin_unlock(&ctx->completion_lock);
7230 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7232 spin_lock(&ctx->completion_lock);
7233 WRITE_ONCE(ctx->rings->sq_flags,
7234 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7235 spin_unlock(&ctx->completion_lock);
7238 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7240 unsigned int to_submit;
7243 to_submit = io_sqring_entries(ctx);
7244 /* if we're handling multiple rings, cap submit size for fairness */
7245 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7246 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7248 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7249 unsigned nr_events = 0;
7250 const struct cred *creds = NULL;
7252 if (ctx->sq_creds != current_cred())
7253 creds = override_creds(ctx->sq_creds);
7255 mutex_lock(&ctx->uring_lock);
7256 if (!list_empty(&ctx->iopoll_list))
7257 io_do_iopoll(ctx, &nr_events, 0);
7260 * Don't submit if refs are dying, good for io_uring_register(),
7261 * but also it is relied upon by io_ring_exit_work()
7263 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7264 !(ctx->flags & IORING_SETUP_R_DISABLED))
7265 ret = io_submit_sqes(ctx, to_submit);
7266 mutex_unlock(&ctx->uring_lock);
7268 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7269 wake_up(&ctx->sqo_sq_wait);
7271 revert_creds(creds);
7277 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7279 struct io_ring_ctx *ctx;
7280 unsigned sq_thread_idle = 0;
7282 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7283 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7284 sqd->sq_thread_idle = sq_thread_idle;
7287 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7289 bool did_sig = false;
7290 struct ksignal ksig;
7292 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7293 signal_pending(current)) {
7294 mutex_unlock(&sqd->lock);
7295 if (signal_pending(current))
7296 did_sig = get_signal(&ksig);
7298 mutex_lock(&sqd->lock);
7300 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7303 static int io_sq_thread(void *data)
7305 struct io_sq_data *sqd = data;
7306 struct io_ring_ctx *ctx;
7307 unsigned long timeout = 0;
7308 char buf[TASK_COMM_LEN];
7311 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7312 set_task_comm(current, buf);
7314 if (sqd->sq_cpu != -1)
7315 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7317 set_cpus_allowed_ptr(current, cpu_online_mask);
7318 current->flags |= PF_NO_SETAFFINITY;
7320 mutex_lock(&sqd->lock);
7322 bool cap_entries, sqt_spin = false;
7324 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7325 if (io_sqd_handle_event(sqd))
7327 timeout = jiffies + sqd->sq_thread_idle;
7330 cap_entries = !list_is_singular(&sqd->ctx_list);
7331 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7332 int ret = __io_sq_thread(ctx, cap_entries);
7334 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7337 if (io_run_task_work())
7340 if (sqt_spin || !time_after(jiffies, timeout)) {
7343 timeout = jiffies + sqd->sq_thread_idle;
7347 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7348 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7349 bool needs_sched = true;
7351 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7352 io_ring_set_wakeup_flag(ctx);
7354 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7355 !list_empty_careful(&ctx->iopoll_list)) {
7356 needs_sched = false;
7359 if (io_sqring_entries(ctx)) {
7360 needs_sched = false;
7366 mutex_unlock(&sqd->lock);
7368 mutex_lock(&sqd->lock);
7370 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7371 io_ring_clear_wakeup_flag(ctx);
7374 finish_wait(&sqd->wait, &wait);
7375 timeout = jiffies + sqd->sq_thread_idle;
7378 io_uring_cancel_generic(true, sqd);
7380 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7381 io_ring_set_wakeup_flag(ctx);
7383 mutex_unlock(&sqd->lock);
7385 complete(&sqd->exited);
7389 struct io_wait_queue {
7390 struct wait_queue_entry wq;
7391 struct io_ring_ctx *ctx;
7393 unsigned nr_timeouts;
7396 static inline bool io_should_wake(struct io_wait_queue *iowq)
7398 struct io_ring_ctx *ctx = iowq->ctx;
7399 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7402 * Wake up if we have enough events, or if a timeout occurred since we
7403 * started waiting. For timeouts, we always want to return to userspace,
7404 * regardless of event count.
7406 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7409 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7410 int wake_flags, void *key)
7412 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7416 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7417 * the task, and the next invocation will do it.
7419 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7420 return autoremove_wake_function(curr, mode, wake_flags, key);
7424 static int io_run_task_work_sig(void)
7426 if (io_run_task_work())
7428 if (!signal_pending(current))
7430 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7431 return -ERESTARTSYS;
7435 /* when returns >0, the caller should retry */
7436 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7437 struct io_wait_queue *iowq,
7438 signed long *timeout)
7442 /* make sure we run task_work before checking for signals */
7443 ret = io_run_task_work_sig();
7444 if (ret || io_should_wake(iowq))
7446 /* let the caller flush overflows, retry */
7447 if (test_bit(0, &ctx->check_cq_overflow))
7450 *timeout = schedule_timeout(*timeout);
7451 return !*timeout ? -ETIME : 1;
7455 * Wait until events become available, if we don't already have some. The
7456 * application must reap them itself, as they reside on the shared cq ring.
7458 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7459 const sigset_t __user *sig, size_t sigsz,
7460 struct __kernel_timespec __user *uts)
7462 struct io_wait_queue iowq;
7463 struct io_rings *rings = ctx->rings;
7464 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7468 io_cqring_overflow_flush(ctx);
7469 if (io_cqring_events(ctx) >= min_events)
7471 if (!io_run_task_work())
7476 #ifdef CONFIG_COMPAT
7477 if (in_compat_syscall())
7478 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7482 ret = set_user_sigmask(sig, sigsz);
7489 struct timespec64 ts;
7491 if (get_timespec64(&ts, uts))
7493 timeout = timespec64_to_jiffies(&ts);
7496 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7497 iowq.wq.private = current;
7498 INIT_LIST_HEAD(&iowq.wq.entry);
7500 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7501 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7503 trace_io_uring_cqring_wait(ctx, min_events);
7505 /* if we can't even flush overflow, don't wait for more */
7506 if (!io_cqring_overflow_flush(ctx)) {
7510 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7511 TASK_INTERRUPTIBLE);
7512 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7513 finish_wait(&ctx->cq_wait, &iowq.wq);
7517 restore_saved_sigmask_unless(ret == -EINTR);
7519 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7522 static void io_free_page_table(void **table, size_t size)
7524 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7526 for (i = 0; i < nr_tables; i++)
7531 static void **io_alloc_page_table(size_t size)
7533 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7534 size_t init_size = size;
7537 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7541 for (i = 0; i < nr_tables; i++) {
7542 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7544 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7546 io_free_page_table(table, init_size);
7554 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7556 percpu_ref_exit(&ref_node->refs);
7560 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7562 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7563 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7564 unsigned long flags;
7565 bool first_add = false;
7567 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7570 while (!list_empty(&ctx->rsrc_ref_list)) {
7571 node = list_first_entry(&ctx->rsrc_ref_list,
7572 struct io_rsrc_node, node);
7573 /* recycle ref nodes in order */
7576 list_del(&node->node);
7577 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7579 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7582 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7585 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7587 struct io_rsrc_node *ref_node;
7589 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7593 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7598 INIT_LIST_HEAD(&ref_node->node);
7599 INIT_LIST_HEAD(&ref_node->rsrc_list);
7600 ref_node->done = false;
7604 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7605 struct io_rsrc_data *data_to_kill)
7607 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7608 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7611 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7613 rsrc_node->rsrc_data = data_to_kill;
7614 spin_lock_irq(&ctx->rsrc_ref_lock);
7615 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7616 spin_unlock_irq(&ctx->rsrc_ref_lock);
7618 atomic_inc(&data_to_kill->refs);
7619 percpu_ref_kill(&rsrc_node->refs);
7620 ctx->rsrc_node = NULL;
7623 if (!ctx->rsrc_node) {
7624 ctx->rsrc_node = ctx->rsrc_backup_node;
7625 ctx->rsrc_backup_node = NULL;
7629 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7631 if (ctx->rsrc_backup_node)
7633 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7634 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7637 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7641 /* As we may drop ->uring_lock, other task may have started quiesce */
7645 data->quiesce = true;
7647 ret = io_rsrc_node_switch_start(ctx);
7650 io_rsrc_node_switch(ctx, data);
7652 /* kill initial ref, already quiesced if zero */
7653 if (atomic_dec_and_test(&data->refs))
7655 mutex_unlock(&ctx->uring_lock);
7656 flush_delayed_work(&ctx->rsrc_put_work);
7657 ret = wait_for_completion_interruptible(&data->done);
7659 mutex_lock(&ctx->uring_lock);
7663 atomic_inc(&data->refs);
7664 /* wait for all works potentially completing data->done */
7665 flush_delayed_work(&ctx->rsrc_put_work);
7666 reinit_completion(&data->done);
7668 ret = io_run_task_work_sig();
7669 mutex_lock(&ctx->uring_lock);
7671 data->quiesce = false;
7676 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7678 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7679 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7681 return &data->tags[table_idx][off];
7684 static void io_rsrc_data_free(struct io_rsrc_data *data)
7686 size_t size = data->nr * sizeof(data->tags[0][0]);
7689 io_free_page_table((void **)data->tags, size);
7693 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7694 u64 __user *utags, unsigned nr,
7695 struct io_rsrc_data **pdata)
7697 struct io_rsrc_data *data;
7701 data = kzalloc(sizeof(*data), GFP_KERNEL);
7704 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7712 data->do_put = do_put;
7715 for (i = 0; i < nr; i++) {
7716 u64 *tag_slot = io_get_tag_slot(data, i);
7718 if (copy_from_user(tag_slot, &utags[i],
7724 atomic_set(&data->refs, 1);
7725 init_completion(&data->done);
7729 io_rsrc_data_free(data);
7733 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7735 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7736 GFP_KERNEL_ACCOUNT);
7737 return !!table->files;
7740 static void io_free_file_tables(struct io_file_table *table)
7742 kvfree(table->files);
7743 table->files = NULL;
7746 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7748 #if defined(CONFIG_UNIX)
7749 if (ctx->ring_sock) {
7750 struct sock *sock = ctx->ring_sock->sk;
7751 struct sk_buff *skb;
7753 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7759 for (i = 0; i < ctx->nr_user_files; i++) {
7762 file = io_file_from_index(ctx, i);
7767 io_free_file_tables(&ctx->file_table);
7768 io_rsrc_data_free(ctx->file_data);
7769 ctx->file_data = NULL;
7770 ctx->nr_user_files = 0;
7773 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7777 if (!ctx->file_data)
7779 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7781 __io_sqe_files_unregister(ctx);
7785 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7786 __releases(&sqd->lock)
7788 WARN_ON_ONCE(sqd->thread == current);
7791 * Do the dance but not conditional clear_bit() because it'd race with
7792 * other threads incrementing park_pending and setting the bit.
7794 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7795 if (atomic_dec_return(&sqd->park_pending))
7796 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7797 mutex_unlock(&sqd->lock);
7800 static void io_sq_thread_park(struct io_sq_data *sqd)
7801 __acquires(&sqd->lock)
7803 WARN_ON_ONCE(sqd->thread == current);
7805 atomic_inc(&sqd->park_pending);
7806 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7807 mutex_lock(&sqd->lock);
7809 wake_up_process(sqd->thread);
7812 static void io_sq_thread_stop(struct io_sq_data *sqd)
7814 WARN_ON_ONCE(sqd->thread == current);
7815 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7817 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7818 mutex_lock(&sqd->lock);
7820 wake_up_process(sqd->thread);
7821 mutex_unlock(&sqd->lock);
7822 wait_for_completion(&sqd->exited);
7825 static void io_put_sq_data(struct io_sq_data *sqd)
7827 if (refcount_dec_and_test(&sqd->refs)) {
7828 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7830 io_sq_thread_stop(sqd);
7835 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7837 struct io_sq_data *sqd = ctx->sq_data;
7840 io_sq_thread_park(sqd);
7841 list_del_init(&ctx->sqd_list);
7842 io_sqd_update_thread_idle(sqd);
7843 io_sq_thread_unpark(sqd);
7845 io_put_sq_data(sqd);
7846 ctx->sq_data = NULL;
7850 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7852 struct io_ring_ctx *ctx_attach;
7853 struct io_sq_data *sqd;
7856 f = fdget(p->wq_fd);
7858 return ERR_PTR(-ENXIO);
7859 if (f.file->f_op != &io_uring_fops) {
7861 return ERR_PTR(-EINVAL);
7864 ctx_attach = f.file->private_data;
7865 sqd = ctx_attach->sq_data;
7868 return ERR_PTR(-EINVAL);
7870 if (sqd->task_tgid != current->tgid) {
7872 return ERR_PTR(-EPERM);
7875 refcount_inc(&sqd->refs);
7880 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7883 struct io_sq_data *sqd;
7886 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7887 sqd = io_attach_sq_data(p);
7892 /* fall through for EPERM case, setup new sqd/task */
7893 if (PTR_ERR(sqd) != -EPERM)
7897 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7899 return ERR_PTR(-ENOMEM);
7901 atomic_set(&sqd->park_pending, 0);
7902 refcount_set(&sqd->refs, 1);
7903 INIT_LIST_HEAD(&sqd->ctx_list);
7904 mutex_init(&sqd->lock);
7905 init_waitqueue_head(&sqd->wait);
7906 init_completion(&sqd->exited);
7910 #if defined(CONFIG_UNIX)
7912 * Ensure the UNIX gc is aware of our file set, so we are certain that
7913 * the io_uring can be safely unregistered on process exit, even if we have
7914 * loops in the file referencing.
7916 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7918 struct sock *sk = ctx->ring_sock->sk;
7919 struct scm_fp_list *fpl;
7920 struct sk_buff *skb;
7923 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7927 skb = alloc_skb(0, GFP_KERNEL);
7936 fpl->user = get_uid(current_user());
7937 for (i = 0; i < nr; i++) {
7938 struct file *file = io_file_from_index(ctx, i + offset);
7942 fpl->fp[nr_files] = get_file(file);
7943 unix_inflight(fpl->user, fpl->fp[nr_files]);
7948 fpl->max = SCM_MAX_FD;
7949 fpl->count = nr_files;
7950 UNIXCB(skb).fp = fpl;
7951 skb->destructor = unix_destruct_scm;
7952 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7953 skb_queue_head(&sk->sk_receive_queue, skb);
7955 for (i = 0; i < nr_files; i++)
7966 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7967 * causes regular reference counting to break down. We rely on the UNIX
7968 * garbage collection to take care of this problem for us.
7970 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7972 unsigned left, total;
7976 left = ctx->nr_user_files;
7978 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7980 ret = __io_sqe_files_scm(ctx, this_files, total);
7984 total += this_files;
7990 while (total < ctx->nr_user_files) {
7991 struct file *file = io_file_from_index(ctx, total);
8001 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8007 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8009 struct file *file = prsrc->file;
8010 #if defined(CONFIG_UNIX)
8011 struct sock *sock = ctx->ring_sock->sk;
8012 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8013 struct sk_buff *skb;
8016 __skb_queue_head_init(&list);
8019 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8020 * remove this entry and rearrange the file array.
8022 skb = skb_dequeue(head);
8024 struct scm_fp_list *fp;
8026 fp = UNIXCB(skb).fp;
8027 for (i = 0; i < fp->count; i++) {
8030 if (fp->fp[i] != file)
8033 unix_notinflight(fp->user, fp->fp[i]);
8034 left = fp->count - 1 - i;
8036 memmove(&fp->fp[i], &fp->fp[i + 1],
8037 left * sizeof(struct file *));
8044 __skb_queue_tail(&list, skb);
8054 __skb_queue_tail(&list, skb);
8056 skb = skb_dequeue(head);
8059 if (skb_peek(&list)) {
8060 spin_lock_irq(&head->lock);
8061 while ((skb = __skb_dequeue(&list)) != NULL)
8062 __skb_queue_tail(head, skb);
8063 spin_unlock_irq(&head->lock);
8070 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8072 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8073 struct io_ring_ctx *ctx = rsrc_data->ctx;
8074 struct io_rsrc_put *prsrc, *tmp;
8076 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8077 list_del(&prsrc->list);
8080 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8082 io_ring_submit_lock(ctx, lock_ring);
8083 spin_lock(&ctx->completion_lock);
8084 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
8086 io_commit_cqring(ctx);
8087 spin_unlock(&ctx->completion_lock);
8088 io_cqring_ev_posted(ctx);
8089 io_ring_submit_unlock(ctx, lock_ring);
8092 rsrc_data->do_put(ctx, prsrc);
8096 io_rsrc_node_destroy(ref_node);
8097 if (atomic_dec_and_test(&rsrc_data->refs))
8098 complete(&rsrc_data->done);
8101 static void io_rsrc_put_work(struct work_struct *work)
8103 struct io_ring_ctx *ctx;
8104 struct llist_node *node;
8106 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8107 node = llist_del_all(&ctx->rsrc_put_llist);
8110 struct io_rsrc_node *ref_node;
8111 struct llist_node *next = node->next;
8113 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8114 __io_rsrc_put_work(ref_node);
8119 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8120 unsigned nr_args, u64 __user *tags)
8122 __s32 __user *fds = (__s32 __user *) arg;
8131 if (nr_args > IORING_MAX_FIXED_FILES)
8133 if (nr_args > rlimit(RLIMIT_NOFILE))
8135 ret = io_rsrc_node_switch_start(ctx);
8138 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8144 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8147 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8148 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8152 /* allow sparse sets */
8155 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8162 if (unlikely(!file))
8166 * Don't allow io_uring instances to be registered. If UNIX
8167 * isn't enabled, then this causes a reference cycle and this
8168 * instance can never get freed. If UNIX is enabled we'll
8169 * handle it just fine, but there's still no point in allowing
8170 * a ring fd as it doesn't support regular read/write anyway.
8172 if (file->f_op == &io_uring_fops) {
8176 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8179 ret = io_sqe_files_scm(ctx);
8181 __io_sqe_files_unregister(ctx);
8185 io_rsrc_node_switch(ctx, NULL);
8188 for (i = 0; i < ctx->nr_user_files; i++) {
8189 file = io_file_from_index(ctx, i);
8193 io_free_file_tables(&ctx->file_table);
8194 ctx->nr_user_files = 0;
8196 io_rsrc_data_free(ctx->file_data);
8197 ctx->file_data = NULL;
8201 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8204 #if defined(CONFIG_UNIX)
8205 struct sock *sock = ctx->ring_sock->sk;
8206 struct sk_buff_head *head = &sock->sk_receive_queue;
8207 struct sk_buff *skb;
8210 * See if we can merge this file into an existing skb SCM_RIGHTS
8211 * file set. If there's no room, fall back to allocating a new skb
8212 * and filling it in.
8214 spin_lock_irq(&head->lock);
8215 skb = skb_peek(head);
8217 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8219 if (fpl->count < SCM_MAX_FD) {
8220 __skb_unlink(skb, head);
8221 spin_unlock_irq(&head->lock);
8222 fpl->fp[fpl->count] = get_file(file);
8223 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8225 spin_lock_irq(&head->lock);
8226 __skb_queue_head(head, skb);
8231 spin_unlock_irq(&head->lock);
8238 return __io_sqe_files_scm(ctx, 1, index);
8244 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8245 unsigned int issue_flags, u32 slot_index)
8247 struct io_ring_ctx *ctx = req->ctx;
8248 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8249 struct io_fixed_file *file_slot;
8252 io_ring_submit_lock(ctx, !force_nonblock);
8253 if (file->f_op == &io_uring_fops)
8256 if (!ctx->file_data)
8259 if (slot_index >= ctx->nr_user_files)
8262 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8263 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8265 if (file_slot->file_ptr)
8268 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8269 io_fixed_file_set(file_slot, file);
8270 ret = io_sqe_file_register(ctx, file, slot_index);
8272 file_slot->file_ptr = 0;
8278 io_ring_submit_unlock(ctx, !force_nonblock);
8284 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8285 struct io_rsrc_node *node, void *rsrc)
8287 struct io_rsrc_put *prsrc;
8289 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8293 prsrc->tag = *io_get_tag_slot(data, idx);
8295 list_add(&prsrc->list, &node->rsrc_list);
8299 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8300 struct io_uring_rsrc_update2 *up,
8303 u64 __user *tags = u64_to_user_ptr(up->tags);
8304 __s32 __user *fds = u64_to_user_ptr(up->data);
8305 struct io_rsrc_data *data = ctx->file_data;
8306 struct io_fixed_file *file_slot;
8310 bool needs_switch = false;
8312 if (!ctx->file_data)
8314 if (up->offset + nr_args > ctx->nr_user_files)
8317 for (done = 0; done < nr_args; done++) {
8320 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8321 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8325 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8329 if (fd == IORING_REGISTER_FILES_SKIP)
8332 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8333 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8335 if (file_slot->file_ptr) {
8336 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8337 err = io_queue_rsrc_removal(data, up->offset + done,
8338 ctx->rsrc_node, file);
8341 file_slot->file_ptr = 0;
8342 needs_switch = true;
8351 * Don't allow io_uring instances to be registered. If
8352 * UNIX isn't enabled, then this causes a reference
8353 * cycle and this instance can never get freed. If UNIX
8354 * is enabled we'll handle it just fine, but there's
8355 * still no point in allowing a ring fd as it doesn't
8356 * support regular read/write anyway.
8358 if (file->f_op == &io_uring_fops) {
8363 *io_get_tag_slot(data, up->offset + done) = tag;
8364 io_fixed_file_set(file_slot, file);
8365 err = io_sqe_file_register(ctx, file, i);
8367 file_slot->file_ptr = 0;
8375 io_rsrc_node_switch(ctx, data);
8376 return done ? done : err;
8379 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8380 struct task_struct *task)
8382 struct io_wq_hash *hash;
8383 struct io_wq_data data;
8384 unsigned int concurrency;
8386 mutex_lock(&ctx->uring_lock);
8387 hash = ctx->hash_map;
8389 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8391 mutex_unlock(&ctx->uring_lock);
8392 return ERR_PTR(-ENOMEM);
8394 refcount_set(&hash->refs, 1);
8395 init_waitqueue_head(&hash->wait);
8396 ctx->hash_map = hash;
8398 mutex_unlock(&ctx->uring_lock);
8402 data.free_work = io_wq_free_work;
8403 data.do_work = io_wq_submit_work;
8405 /* Do QD, or 4 * CPUS, whatever is smallest */
8406 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8408 return io_wq_create(concurrency, &data);
8411 static int io_uring_alloc_task_context(struct task_struct *task,
8412 struct io_ring_ctx *ctx)
8414 struct io_uring_task *tctx;
8417 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8418 if (unlikely(!tctx))
8421 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8422 if (unlikely(ret)) {
8427 tctx->io_wq = io_init_wq_offload(ctx, task);
8428 if (IS_ERR(tctx->io_wq)) {
8429 ret = PTR_ERR(tctx->io_wq);
8430 percpu_counter_destroy(&tctx->inflight);
8436 init_waitqueue_head(&tctx->wait);
8437 atomic_set(&tctx->in_idle, 0);
8438 atomic_set(&tctx->inflight_tracked, 0);
8439 task->io_uring = tctx;
8440 spin_lock_init(&tctx->task_lock);
8441 INIT_WQ_LIST(&tctx->task_list);
8442 init_task_work(&tctx->task_work, tctx_task_work);
8446 void __io_uring_free(struct task_struct *tsk)
8448 struct io_uring_task *tctx = tsk->io_uring;
8450 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8451 WARN_ON_ONCE(tctx->io_wq);
8452 WARN_ON_ONCE(tctx->cached_refs);
8454 percpu_counter_destroy(&tctx->inflight);
8456 tsk->io_uring = NULL;
8459 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8460 struct io_uring_params *p)
8464 /* Retain compatibility with failing for an invalid attach attempt */
8465 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8466 IORING_SETUP_ATTACH_WQ) {
8469 f = fdget(p->wq_fd);
8472 if (f.file->f_op != &io_uring_fops) {
8478 if (ctx->flags & IORING_SETUP_SQPOLL) {
8479 struct task_struct *tsk;
8480 struct io_sq_data *sqd;
8483 sqd = io_get_sq_data(p, &attached);
8489 ctx->sq_creds = get_current_cred();
8491 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8492 if (!ctx->sq_thread_idle)
8493 ctx->sq_thread_idle = HZ;
8495 io_sq_thread_park(sqd);
8496 list_add(&ctx->sqd_list, &sqd->ctx_list);
8497 io_sqd_update_thread_idle(sqd);
8498 /* don't attach to a dying SQPOLL thread, would be racy */
8499 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8500 io_sq_thread_unpark(sqd);
8507 if (p->flags & IORING_SETUP_SQ_AFF) {
8508 int cpu = p->sq_thread_cpu;
8511 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8518 sqd->task_pid = current->pid;
8519 sqd->task_tgid = current->tgid;
8520 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8527 ret = io_uring_alloc_task_context(tsk, ctx);
8528 wake_up_new_task(tsk);
8531 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8532 /* Can't have SQ_AFF without SQPOLL */
8539 complete(&ctx->sq_data->exited);
8541 io_sq_thread_finish(ctx);
8545 static inline void __io_unaccount_mem(struct user_struct *user,
8546 unsigned long nr_pages)
8548 atomic_long_sub(nr_pages, &user->locked_vm);
8551 static inline int __io_account_mem(struct user_struct *user,
8552 unsigned long nr_pages)
8554 unsigned long page_limit, cur_pages, new_pages;
8556 /* Don't allow more pages than we can safely lock */
8557 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8560 cur_pages = atomic_long_read(&user->locked_vm);
8561 new_pages = cur_pages + nr_pages;
8562 if (new_pages > page_limit)
8564 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8565 new_pages) != cur_pages);
8570 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8573 __io_unaccount_mem(ctx->user, nr_pages);
8575 if (ctx->mm_account)
8576 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8579 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8584 ret = __io_account_mem(ctx->user, nr_pages);
8589 if (ctx->mm_account)
8590 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8595 static void io_mem_free(void *ptr)
8602 page = virt_to_head_page(ptr);
8603 if (put_page_testzero(page))
8604 free_compound_page(page);
8607 static void *io_mem_alloc(size_t size)
8609 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8610 __GFP_NORETRY | __GFP_ACCOUNT;
8612 return (void *) __get_free_pages(gfp_flags, get_order(size));
8615 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8618 struct io_rings *rings;
8619 size_t off, sq_array_size;
8621 off = struct_size(rings, cqes, cq_entries);
8622 if (off == SIZE_MAX)
8626 off = ALIGN(off, SMP_CACHE_BYTES);
8634 sq_array_size = array_size(sizeof(u32), sq_entries);
8635 if (sq_array_size == SIZE_MAX)
8638 if (check_add_overflow(off, sq_array_size, &off))
8644 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8646 struct io_mapped_ubuf *imu = *slot;
8649 if (imu != ctx->dummy_ubuf) {
8650 for (i = 0; i < imu->nr_bvecs; i++)
8651 unpin_user_page(imu->bvec[i].bv_page);
8652 if (imu->acct_pages)
8653 io_unaccount_mem(ctx, imu->acct_pages);
8659 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8661 io_buffer_unmap(ctx, &prsrc->buf);
8665 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8669 for (i = 0; i < ctx->nr_user_bufs; i++)
8670 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8671 kfree(ctx->user_bufs);
8672 io_rsrc_data_free(ctx->buf_data);
8673 ctx->user_bufs = NULL;
8674 ctx->buf_data = NULL;
8675 ctx->nr_user_bufs = 0;
8678 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8685 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8687 __io_sqe_buffers_unregister(ctx);
8691 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8692 void __user *arg, unsigned index)
8694 struct iovec __user *src;
8696 #ifdef CONFIG_COMPAT
8698 struct compat_iovec __user *ciovs;
8699 struct compat_iovec ciov;
8701 ciovs = (struct compat_iovec __user *) arg;
8702 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8705 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8706 dst->iov_len = ciov.iov_len;
8710 src = (struct iovec __user *) arg;
8711 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8717 * Not super efficient, but this is just a registration time. And we do cache
8718 * the last compound head, so generally we'll only do a full search if we don't
8721 * We check if the given compound head page has already been accounted, to
8722 * avoid double accounting it. This allows us to account the full size of the
8723 * page, not just the constituent pages of a huge page.
8725 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8726 int nr_pages, struct page *hpage)
8730 /* check current page array */
8731 for (i = 0; i < nr_pages; i++) {
8732 if (!PageCompound(pages[i]))
8734 if (compound_head(pages[i]) == hpage)
8738 /* check previously registered pages */
8739 for (i = 0; i < ctx->nr_user_bufs; i++) {
8740 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8742 for (j = 0; j < imu->nr_bvecs; j++) {
8743 if (!PageCompound(imu->bvec[j].bv_page))
8745 if (compound_head(imu->bvec[j].bv_page) == hpage)
8753 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8754 int nr_pages, struct io_mapped_ubuf *imu,
8755 struct page **last_hpage)
8759 imu->acct_pages = 0;
8760 for (i = 0; i < nr_pages; i++) {
8761 if (!PageCompound(pages[i])) {
8766 hpage = compound_head(pages[i]);
8767 if (hpage == *last_hpage)
8769 *last_hpage = hpage;
8770 if (headpage_already_acct(ctx, pages, i, hpage))
8772 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8776 if (!imu->acct_pages)
8779 ret = io_account_mem(ctx, imu->acct_pages);
8781 imu->acct_pages = 0;
8785 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8786 struct io_mapped_ubuf **pimu,
8787 struct page **last_hpage)
8789 struct io_mapped_ubuf *imu = NULL;
8790 struct vm_area_struct **vmas = NULL;
8791 struct page **pages = NULL;
8792 unsigned long off, start, end, ubuf;
8794 int ret, pret, nr_pages, i;
8796 if (!iov->iov_base) {
8797 *pimu = ctx->dummy_ubuf;
8801 ubuf = (unsigned long) iov->iov_base;
8802 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8803 start = ubuf >> PAGE_SHIFT;
8804 nr_pages = end - start;
8809 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8813 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8818 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8823 mmap_read_lock(current->mm);
8824 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8826 if (pret == nr_pages) {
8827 /* don't support file backed memory */
8828 for (i = 0; i < nr_pages; i++) {
8829 struct vm_area_struct *vma = vmas[i];
8831 if (vma_is_shmem(vma))
8834 !is_file_hugepages(vma->vm_file)) {
8840 ret = pret < 0 ? pret : -EFAULT;
8842 mmap_read_unlock(current->mm);
8845 * if we did partial map, or found file backed vmas,
8846 * release any pages we did get
8849 unpin_user_pages(pages, pret);
8853 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8855 unpin_user_pages(pages, pret);
8859 off = ubuf & ~PAGE_MASK;
8860 size = iov->iov_len;
8861 for (i = 0; i < nr_pages; i++) {
8864 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8865 imu->bvec[i].bv_page = pages[i];
8866 imu->bvec[i].bv_len = vec_len;
8867 imu->bvec[i].bv_offset = off;
8871 /* store original address for later verification */
8873 imu->ubuf_end = ubuf + iov->iov_len;
8874 imu->nr_bvecs = nr_pages;
8885 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8887 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8888 return ctx->user_bufs ? 0 : -ENOMEM;
8891 static int io_buffer_validate(struct iovec *iov)
8893 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8896 * Don't impose further limits on the size and buffer
8897 * constraints here, we'll -EINVAL later when IO is
8898 * submitted if they are wrong.
8901 return iov->iov_len ? -EFAULT : 0;
8905 /* arbitrary limit, but we need something */
8906 if (iov->iov_len > SZ_1G)
8909 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8915 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8916 unsigned int nr_args, u64 __user *tags)
8918 struct page *last_hpage = NULL;
8919 struct io_rsrc_data *data;
8925 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8927 ret = io_rsrc_node_switch_start(ctx);
8930 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8933 ret = io_buffers_map_alloc(ctx, nr_args);
8935 io_rsrc_data_free(data);
8939 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8940 ret = io_copy_iov(ctx, &iov, arg, i);
8943 ret = io_buffer_validate(&iov);
8946 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8951 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8957 WARN_ON_ONCE(ctx->buf_data);
8959 ctx->buf_data = data;
8961 __io_sqe_buffers_unregister(ctx);
8963 io_rsrc_node_switch(ctx, NULL);
8967 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8968 struct io_uring_rsrc_update2 *up,
8969 unsigned int nr_args)
8971 u64 __user *tags = u64_to_user_ptr(up->tags);
8972 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8973 struct page *last_hpage = NULL;
8974 bool needs_switch = false;
8980 if (up->offset + nr_args > ctx->nr_user_bufs)
8983 for (done = 0; done < nr_args; done++) {
8984 struct io_mapped_ubuf *imu;
8985 int offset = up->offset + done;
8988 err = io_copy_iov(ctx, &iov, iovs, done);
8991 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8995 err = io_buffer_validate(&iov);
8998 if (!iov.iov_base && tag) {
9002 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9006 i = array_index_nospec(offset, ctx->nr_user_bufs);
9007 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9008 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9009 ctx->rsrc_node, ctx->user_bufs[i]);
9010 if (unlikely(err)) {
9011 io_buffer_unmap(ctx, &imu);
9014 ctx->user_bufs[i] = NULL;
9015 needs_switch = true;
9018 ctx->user_bufs[i] = imu;
9019 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9023 io_rsrc_node_switch(ctx, ctx->buf_data);
9024 return done ? done : err;
9027 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9029 __s32 __user *fds = arg;
9035 if (copy_from_user(&fd, fds, sizeof(*fds)))
9038 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9039 if (IS_ERR(ctx->cq_ev_fd)) {
9040 int ret = PTR_ERR(ctx->cq_ev_fd);
9042 ctx->cq_ev_fd = NULL;
9049 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9051 if (ctx->cq_ev_fd) {
9052 eventfd_ctx_put(ctx->cq_ev_fd);
9053 ctx->cq_ev_fd = NULL;
9060 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9062 struct io_buffer *buf;
9063 unsigned long index;
9065 xa_for_each(&ctx->io_buffers, index, buf)
9066 __io_remove_buffers(ctx, buf, index, -1U);
9069 static void io_req_cache_free(struct list_head *list)
9071 struct io_kiocb *req, *nxt;
9073 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9074 list_del(&req->inflight_entry);
9075 kmem_cache_free(req_cachep, req);
9079 static void io_req_caches_free(struct io_ring_ctx *ctx)
9081 struct io_submit_state *state = &ctx->submit_state;
9083 mutex_lock(&ctx->uring_lock);
9085 if (state->free_reqs) {
9086 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9087 state->free_reqs = 0;
9090 io_flush_cached_locked_reqs(ctx, state);
9091 io_req_cache_free(&state->free_list);
9092 mutex_unlock(&ctx->uring_lock);
9095 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9097 if (data && !atomic_dec_and_test(&data->refs))
9098 wait_for_completion(&data->done);
9101 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9103 io_sq_thread_finish(ctx);
9105 if (ctx->mm_account) {
9106 mmdrop(ctx->mm_account);
9107 ctx->mm_account = NULL;
9110 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9111 io_wait_rsrc_data(ctx->buf_data);
9112 io_wait_rsrc_data(ctx->file_data);
9114 mutex_lock(&ctx->uring_lock);
9116 __io_sqe_buffers_unregister(ctx);
9118 __io_sqe_files_unregister(ctx);
9120 __io_cqring_overflow_flush(ctx, true);
9121 mutex_unlock(&ctx->uring_lock);
9122 io_eventfd_unregister(ctx);
9123 io_destroy_buffers(ctx);
9125 put_cred(ctx->sq_creds);
9127 /* there are no registered resources left, nobody uses it */
9129 io_rsrc_node_destroy(ctx->rsrc_node);
9130 if (ctx->rsrc_backup_node)
9131 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9132 flush_delayed_work(&ctx->rsrc_put_work);
9134 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9135 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9137 #if defined(CONFIG_UNIX)
9138 if (ctx->ring_sock) {
9139 ctx->ring_sock->file = NULL; /* so that iput() is called */
9140 sock_release(ctx->ring_sock);
9143 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9145 io_mem_free(ctx->rings);
9146 io_mem_free(ctx->sq_sqes);
9148 percpu_ref_exit(&ctx->refs);
9149 free_uid(ctx->user);
9150 io_req_caches_free(ctx);
9152 io_wq_put_hash(ctx->hash_map);
9153 kfree(ctx->cancel_hash);
9154 kfree(ctx->dummy_ubuf);
9158 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9160 struct io_ring_ctx *ctx = file->private_data;
9163 poll_wait(file, &ctx->poll_wait, wait);
9165 * synchronizes with barrier from wq_has_sleeper call in
9169 if (!io_sqring_full(ctx))
9170 mask |= EPOLLOUT | EPOLLWRNORM;
9173 * Don't flush cqring overflow list here, just do a simple check.
9174 * Otherwise there could possible be ABBA deadlock:
9177 * lock(&ctx->uring_lock);
9179 * lock(&ctx->uring_lock);
9182 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9183 * pushs them to do the flush.
9185 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9186 mask |= EPOLLIN | EPOLLRDNORM;
9191 static int io_uring_fasync(int fd, struct file *file, int on)
9193 struct io_ring_ctx *ctx = file->private_data;
9195 return fasync_helper(fd, file, on, &ctx->cq_fasync);
9198 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9200 const struct cred *creds;
9202 creds = xa_erase(&ctx->personalities, id);
9211 struct io_tctx_exit {
9212 struct callback_head task_work;
9213 struct completion completion;
9214 struct io_ring_ctx *ctx;
9217 static void io_tctx_exit_cb(struct callback_head *cb)
9219 struct io_uring_task *tctx = current->io_uring;
9220 struct io_tctx_exit *work;
9222 work = container_of(cb, struct io_tctx_exit, task_work);
9224 * When @in_idle, we're in cancellation and it's racy to remove the
9225 * node. It'll be removed by the end of cancellation, just ignore it.
9227 if (!atomic_read(&tctx->in_idle))
9228 io_uring_del_tctx_node((unsigned long)work->ctx);
9229 complete(&work->completion);
9232 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9234 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9236 return req->ctx == data;
9239 static void io_ring_exit_work(struct work_struct *work)
9241 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9242 unsigned long timeout = jiffies + HZ * 60 * 5;
9243 unsigned long interval = HZ / 20;
9244 struct io_tctx_exit exit;
9245 struct io_tctx_node *node;
9249 * If we're doing polled IO and end up having requests being
9250 * submitted async (out-of-line), then completions can come in while
9251 * we're waiting for refs to drop. We need to reap these manually,
9252 * as nobody else will be looking for them.
9255 io_uring_try_cancel_requests(ctx, NULL, true);
9257 struct io_sq_data *sqd = ctx->sq_data;
9258 struct task_struct *tsk;
9260 io_sq_thread_park(sqd);
9262 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9263 io_wq_cancel_cb(tsk->io_uring->io_wq,
9264 io_cancel_ctx_cb, ctx, true);
9265 io_sq_thread_unpark(sqd);
9268 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9269 /* there is little hope left, don't run it too often */
9272 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9274 init_completion(&exit.completion);
9275 init_task_work(&exit.task_work, io_tctx_exit_cb);
9278 * Some may use context even when all refs and requests have been put,
9279 * and they are free to do so while still holding uring_lock or
9280 * completion_lock, see io_req_task_submit(). Apart from other work,
9281 * this lock/unlock section also waits them to finish.
9283 mutex_lock(&ctx->uring_lock);
9284 while (!list_empty(&ctx->tctx_list)) {
9285 WARN_ON_ONCE(time_after(jiffies, timeout));
9287 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9289 /* don't spin on a single task if cancellation failed */
9290 list_rotate_left(&ctx->tctx_list);
9291 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9292 if (WARN_ON_ONCE(ret))
9294 wake_up_process(node->task);
9296 mutex_unlock(&ctx->uring_lock);
9297 wait_for_completion(&exit.completion);
9298 mutex_lock(&ctx->uring_lock);
9300 mutex_unlock(&ctx->uring_lock);
9301 spin_lock(&ctx->completion_lock);
9302 spin_unlock(&ctx->completion_lock);
9304 io_ring_ctx_free(ctx);
9307 /* Returns true if we found and killed one or more timeouts */
9308 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9311 struct io_kiocb *req, *tmp;
9314 spin_lock(&ctx->completion_lock);
9315 spin_lock_irq(&ctx->timeout_lock);
9316 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9317 if (io_match_task(req, tsk, cancel_all)) {
9318 io_kill_timeout(req, -ECANCELED);
9322 spin_unlock_irq(&ctx->timeout_lock);
9324 io_commit_cqring(ctx);
9325 spin_unlock(&ctx->completion_lock);
9327 io_cqring_ev_posted(ctx);
9328 return canceled != 0;
9331 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9333 unsigned long index;
9334 struct creds *creds;
9336 mutex_lock(&ctx->uring_lock);
9337 percpu_ref_kill(&ctx->refs);
9339 __io_cqring_overflow_flush(ctx, true);
9340 xa_for_each(&ctx->personalities, index, creds)
9341 io_unregister_personality(ctx, index);
9342 mutex_unlock(&ctx->uring_lock);
9344 io_kill_timeouts(ctx, NULL, true);
9345 io_poll_remove_all(ctx, NULL, true);
9347 /* if we failed setting up the ctx, we might not have any rings */
9348 io_iopoll_try_reap_events(ctx);
9350 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9352 * Use system_unbound_wq to avoid spawning tons of event kworkers
9353 * if we're exiting a ton of rings at the same time. It just adds
9354 * noise and overhead, there's no discernable change in runtime
9355 * over using system_wq.
9357 queue_work(system_unbound_wq, &ctx->exit_work);
9360 static int io_uring_release(struct inode *inode, struct file *file)
9362 struct io_ring_ctx *ctx = file->private_data;
9364 file->private_data = NULL;
9365 io_ring_ctx_wait_and_kill(ctx);
9369 struct io_task_cancel {
9370 struct task_struct *task;
9374 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9376 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9377 struct io_task_cancel *cancel = data;
9380 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
9381 struct io_ring_ctx *ctx = req->ctx;
9383 /* protect against races with linked timeouts */
9384 spin_lock(&ctx->completion_lock);
9385 ret = io_match_task(req, cancel->task, cancel->all);
9386 spin_unlock(&ctx->completion_lock);
9388 ret = io_match_task(req, cancel->task, cancel->all);
9393 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9394 struct task_struct *task, bool cancel_all)
9396 struct io_defer_entry *de;
9399 spin_lock(&ctx->completion_lock);
9400 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9401 if (io_match_task(de->req, task, cancel_all)) {
9402 list_cut_position(&list, &ctx->defer_list, &de->list);
9406 spin_unlock(&ctx->completion_lock);
9407 if (list_empty(&list))
9410 while (!list_empty(&list)) {
9411 de = list_first_entry(&list, struct io_defer_entry, list);
9412 list_del_init(&de->list);
9413 io_req_complete_failed(de->req, -ECANCELED);
9419 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9421 struct io_tctx_node *node;
9422 enum io_wq_cancel cret;
9425 mutex_lock(&ctx->uring_lock);
9426 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9427 struct io_uring_task *tctx = node->task->io_uring;
9430 * io_wq will stay alive while we hold uring_lock, because it's
9431 * killed after ctx nodes, which requires to take the lock.
9433 if (!tctx || !tctx->io_wq)
9435 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9436 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9438 mutex_unlock(&ctx->uring_lock);
9443 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9444 struct task_struct *task,
9447 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9448 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9451 enum io_wq_cancel cret;
9455 ret |= io_uring_try_cancel_iowq(ctx);
9456 } else if (tctx && tctx->io_wq) {
9458 * Cancels requests of all rings, not only @ctx, but
9459 * it's fine as the task is in exit/exec.
9461 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9463 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9466 /* SQPOLL thread does its own polling */
9467 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9468 (ctx->sq_data && ctx->sq_data->thread == current)) {
9469 while (!list_empty_careful(&ctx->iopoll_list)) {
9470 io_iopoll_try_reap_events(ctx);
9475 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9476 ret |= io_poll_remove_all(ctx, task, cancel_all);
9477 ret |= io_kill_timeouts(ctx, task, cancel_all);
9479 ret |= io_run_task_work();
9486 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9488 struct io_uring_task *tctx = current->io_uring;
9489 struct io_tctx_node *node;
9492 if (unlikely(!tctx)) {
9493 ret = io_uring_alloc_task_context(current, ctx);
9496 tctx = current->io_uring;
9498 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9499 node = kmalloc(sizeof(*node), GFP_KERNEL);
9503 node->task = current;
9505 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9512 mutex_lock(&ctx->uring_lock);
9513 list_add(&node->ctx_node, &ctx->tctx_list);
9514 mutex_unlock(&ctx->uring_lock);
9521 * Note that this task has used io_uring. We use it for cancelation purposes.
9523 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9525 struct io_uring_task *tctx = current->io_uring;
9527 if (likely(tctx && tctx->last == ctx))
9529 return __io_uring_add_tctx_node(ctx);
9533 * Remove this io_uring_file -> task mapping.
9535 static void io_uring_del_tctx_node(unsigned long index)
9537 struct io_uring_task *tctx = current->io_uring;
9538 struct io_tctx_node *node;
9542 node = xa_erase(&tctx->xa, index);
9546 WARN_ON_ONCE(current != node->task);
9547 WARN_ON_ONCE(list_empty(&node->ctx_node));
9549 mutex_lock(&node->ctx->uring_lock);
9550 list_del(&node->ctx_node);
9551 mutex_unlock(&node->ctx->uring_lock);
9553 if (tctx->last == node->ctx)
9558 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9560 struct io_wq *wq = tctx->io_wq;
9561 struct io_tctx_node *node;
9562 unsigned long index;
9564 xa_for_each(&tctx->xa, index, node)
9565 io_uring_del_tctx_node(index);
9568 * Must be after io_uring_del_task_file() (removes nodes under
9569 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9571 io_wq_put_and_exit(wq);
9576 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9579 return atomic_read(&tctx->inflight_tracked);
9580 return percpu_counter_sum(&tctx->inflight);
9583 static void io_uring_drop_tctx_refs(struct task_struct *task)
9585 struct io_uring_task *tctx = task->io_uring;
9586 unsigned int refs = tctx->cached_refs;
9589 tctx->cached_refs = 0;
9590 percpu_counter_sub(&tctx->inflight, refs);
9591 put_task_struct_many(task, refs);
9596 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9597 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9599 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9601 struct io_uring_task *tctx = current->io_uring;
9602 struct io_ring_ctx *ctx;
9606 WARN_ON_ONCE(sqd && sqd->thread != current);
9608 if (!current->io_uring)
9611 io_wq_exit_start(tctx->io_wq);
9613 atomic_inc(&tctx->in_idle);
9615 io_uring_drop_tctx_refs(current);
9616 /* read completions before cancelations */
9617 inflight = tctx_inflight(tctx, !cancel_all);
9622 struct io_tctx_node *node;
9623 unsigned long index;
9625 xa_for_each(&tctx->xa, index, node) {
9626 /* sqpoll task will cancel all its requests */
9627 if (node->ctx->sq_data)
9629 io_uring_try_cancel_requests(node->ctx, current,
9633 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9634 io_uring_try_cancel_requests(ctx, current,
9638 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9639 io_uring_drop_tctx_refs(current);
9641 * If we've seen completions, retry without waiting. This
9642 * avoids a race where a completion comes in before we did
9643 * prepare_to_wait().
9645 if (inflight == tctx_inflight(tctx, !cancel_all))
9647 finish_wait(&tctx->wait, &wait);
9649 atomic_dec(&tctx->in_idle);
9651 io_uring_clean_tctx(tctx);
9653 /* for exec all current's requests should be gone, kill tctx */
9654 __io_uring_free(current);
9658 void __io_uring_cancel(bool cancel_all)
9660 io_uring_cancel_generic(cancel_all, NULL);
9663 static void *io_uring_validate_mmap_request(struct file *file,
9664 loff_t pgoff, size_t sz)
9666 struct io_ring_ctx *ctx = file->private_data;
9667 loff_t offset = pgoff << PAGE_SHIFT;
9672 case IORING_OFF_SQ_RING:
9673 case IORING_OFF_CQ_RING:
9676 case IORING_OFF_SQES:
9680 return ERR_PTR(-EINVAL);
9683 page = virt_to_head_page(ptr);
9684 if (sz > page_size(page))
9685 return ERR_PTR(-EINVAL);
9692 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9694 size_t sz = vma->vm_end - vma->vm_start;
9698 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9700 return PTR_ERR(ptr);
9702 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9703 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9706 #else /* !CONFIG_MMU */
9708 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9710 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9713 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9715 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9718 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9719 unsigned long addr, unsigned long len,
9720 unsigned long pgoff, unsigned long flags)
9724 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9726 return PTR_ERR(ptr);
9728 return (unsigned long) ptr;
9731 #endif /* !CONFIG_MMU */
9733 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9738 if (!io_sqring_full(ctx))
9740 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9742 if (!io_sqring_full(ctx))
9745 } while (!signal_pending(current));
9747 finish_wait(&ctx->sqo_sq_wait, &wait);
9751 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9752 struct __kernel_timespec __user **ts,
9753 const sigset_t __user **sig)
9755 struct io_uring_getevents_arg arg;
9758 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9759 * is just a pointer to the sigset_t.
9761 if (!(flags & IORING_ENTER_EXT_ARG)) {
9762 *sig = (const sigset_t __user *) argp;
9768 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9769 * timespec and sigset_t pointers if good.
9771 if (*argsz != sizeof(arg))
9773 if (copy_from_user(&arg, argp, sizeof(arg)))
9775 *sig = u64_to_user_ptr(arg.sigmask);
9776 *argsz = arg.sigmask_sz;
9777 *ts = u64_to_user_ptr(arg.ts);
9781 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9782 u32, min_complete, u32, flags, const void __user *, argp,
9785 struct io_ring_ctx *ctx;
9792 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9793 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9797 if (unlikely(!f.file))
9801 if (unlikely(f.file->f_op != &io_uring_fops))
9805 ctx = f.file->private_data;
9806 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9810 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9814 * For SQ polling, the thread will do all submissions and completions.
9815 * Just return the requested submit count, and wake the thread if
9819 if (ctx->flags & IORING_SETUP_SQPOLL) {
9820 io_cqring_overflow_flush(ctx);
9822 if (unlikely(ctx->sq_data->thread == NULL)) {
9826 if (flags & IORING_ENTER_SQ_WAKEUP)
9827 wake_up(&ctx->sq_data->wait);
9828 if (flags & IORING_ENTER_SQ_WAIT) {
9829 ret = io_sqpoll_wait_sq(ctx);
9833 submitted = to_submit;
9834 } else if (to_submit) {
9835 ret = io_uring_add_tctx_node(ctx);
9838 mutex_lock(&ctx->uring_lock);
9839 submitted = io_submit_sqes(ctx, to_submit);
9840 mutex_unlock(&ctx->uring_lock);
9842 if (submitted != to_submit)
9845 if (flags & IORING_ENTER_GETEVENTS) {
9846 const sigset_t __user *sig;
9847 struct __kernel_timespec __user *ts;
9849 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9853 min_complete = min(min_complete, ctx->cq_entries);
9856 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9857 * space applications don't need to do io completion events
9858 * polling again, they can rely on io_sq_thread to do polling
9859 * work, which can reduce cpu usage and uring_lock contention.
9861 if (ctx->flags & IORING_SETUP_IOPOLL &&
9862 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9863 ret = io_iopoll_check(ctx, min_complete);
9865 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9870 percpu_ref_put(&ctx->refs);
9873 return submitted ? submitted : ret;
9876 #ifdef CONFIG_PROC_FS
9877 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9878 const struct cred *cred)
9880 struct user_namespace *uns = seq_user_ns(m);
9881 struct group_info *gi;
9886 seq_printf(m, "%5d\n", id);
9887 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9888 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9889 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9890 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9891 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9892 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9893 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9894 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9895 seq_puts(m, "\n\tGroups:\t");
9896 gi = cred->group_info;
9897 for (g = 0; g < gi->ngroups; g++) {
9898 seq_put_decimal_ull(m, g ? " " : "",
9899 from_kgid_munged(uns, gi->gid[g]));
9901 seq_puts(m, "\n\tCapEff:\t");
9902 cap = cred->cap_effective;
9903 CAP_FOR_EACH_U32(__capi)
9904 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9909 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9911 struct io_sq_data *sq = NULL;
9916 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9917 * since fdinfo case grabs it in the opposite direction of normal use
9918 * cases. If we fail to get the lock, we just don't iterate any
9919 * structures that could be going away outside the io_uring mutex.
9921 has_lock = mutex_trylock(&ctx->uring_lock);
9923 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9929 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9930 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9931 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9932 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9933 struct file *f = io_file_from_index(ctx, i);
9936 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9938 seq_printf(m, "%5u: <none>\n", i);
9940 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9941 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9942 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9943 unsigned int len = buf->ubuf_end - buf->ubuf;
9945 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9947 if (has_lock && !xa_empty(&ctx->personalities)) {
9948 unsigned long index;
9949 const struct cred *cred;
9951 seq_printf(m, "Personalities:\n");
9952 xa_for_each(&ctx->personalities, index, cred)
9953 io_uring_show_cred(m, index, cred);
9955 seq_printf(m, "PollList:\n");
9956 spin_lock(&ctx->completion_lock);
9957 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9958 struct hlist_head *list = &ctx->cancel_hash[i];
9959 struct io_kiocb *req;
9961 hlist_for_each_entry(req, list, hash_node)
9962 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9963 req->task->task_works != NULL);
9965 spin_unlock(&ctx->completion_lock);
9967 mutex_unlock(&ctx->uring_lock);
9970 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9972 struct io_ring_ctx *ctx = f->private_data;
9974 if (percpu_ref_tryget(&ctx->refs)) {
9975 __io_uring_show_fdinfo(ctx, m);
9976 percpu_ref_put(&ctx->refs);
9981 static const struct file_operations io_uring_fops = {
9982 .release = io_uring_release,
9983 .mmap = io_uring_mmap,
9985 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9986 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9988 .poll = io_uring_poll,
9989 .fasync = io_uring_fasync,
9990 #ifdef CONFIG_PROC_FS
9991 .show_fdinfo = io_uring_show_fdinfo,
9995 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9996 struct io_uring_params *p)
9998 struct io_rings *rings;
9999 size_t size, sq_array_offset;
10001 /* make sure these are sane, as we already accounted them */
10002 ctx->sq_entries = p->sq_entries;
10003 ctx->cq_entries = p->cq_entries;
10005 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10006 if (size == SIZE_MAX)
10009 rings = io_mem_alloc(size);
10013 ctx->rings = rings;
10014 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10015 rings->sq_ring_mask = p->sq_entries - 1;
10016 rings->cq_ring_mask = p->cq_entries - 1;
10017 rings->sq_ring_entries = p->sq_entries;
10018 rings->cq_ring_entries = p->cq_entries;
10020 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10021 if (size == SIZE_MAX) {
10022 io_mem_free(ctx->rings);
10027 ctx->sq_sqes = io_mem_alloc(size);
10028 if (!ctx->sq_sqes) {
10029 io_mem_free(ctx->rings);
10037 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10041 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10045 ret = io_uring_add_tctx_node(ctx);
10050 fd_install(fd, file);
10055 * Allocate an anonymous fd, this is what constitutes the application
10056 * visible backing of an io_uring instance. The application mmaps this
10057 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10058 * we have to tie this fd to a socket for file garbage collection purposes.
10060 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10063 #if defined(CONFIG_UNIX)
10066 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10069 return ERR_PTR(ret);
10072 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10073 O_RDWR | O_CLOEXEC);
10074 #if defined(CONFIG_UNIX)
10075 if (IS_ERR(file)) {
10076 sock_release(ctx->ring_sock);
10077 ctx->ring_sock = NULL;
10079 ctx->ring_sock->file = file;
10085 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10086 struct io_uring_params __user *params)
10088 struct io_ring_ctx *ctx;
10094 if (entries > IORING_MAX_ENTRIES) {
10095 if (!(p->flags & IORING_SETUP_CLAMP))
10097 entries = IORING_MAX_ENTRIES;
10101 * Use twice as many entries for the CQ ring. It's possible for the
10102 * application to drive a higher depth than the size of the SQ ring,
10103 * since the sqes are only used at submission time. This allows for
10104 * some flexibility in overcommitting a bit. If the application has
10105 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10106 * of CQ ring entries manually.
10108 p->sq_entries = roundup_pow_of_two(entries);
10109 if (p->flags & IORING_SETUP_CQSIZE) {
10111 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10112 * to a power-of-two, if it isn't already. We do NOT impose
10113 * any cq vs sq ring sizing.
10115 if (!p->cq_entries)
10117 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10118 if (!(p->flags & IORING_SETUP_CLAMP))
10120 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10122 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10123 if (p->cq_entries < p->sq_entries)
10126 p->cq_entries = 2 * p->sq_entries;
10129 ctx = io_ring_ctx_alloc(p);
10132 ctx->compat = in_compat_syscall();
10133 if (!capable(CAP_IPC_LOCK))
10134 ctx->user = get_uid(current_user());
10137 * This is just grabbed for accounting purposes. When a process exits,
10138 * the mm is exited and dropped before the files, hence we need to hang
10139 * on to this mm purely for the purposes of being able to unaccount
10140 * memory (locked/pinned vm). It's not used for anything else.
10142 mmgrab(current->mm);
10143 ctx->mm_account = current->mm;
10145 ret = io_allocate_scq_urings(ctx, p);
10149 ret = io_sq_offload_create(ctx, p);
10152 /* always set a rsrc node */
10153 ret = io_rsrc_node_switch_start(ctx);
10156 io_rsrc_node_switch(ctx, NULL);
10158 memset(&p->sq_off, 0, sizeof(p->sq_off));
10159 p->sq_off.head = offsetof(struct io_rings, sq.head);
10160 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10161 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10162 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10163 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10164 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10165 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10167 memset(&p->cq_off, 0, sizeof(p->cq_off));
10168 p->cq_off.head = offsetof(struct io_rings, cq.head);
10169 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10170 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10171 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10172 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10173 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10174 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10176 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10177 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10178 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10179 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10180 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10181 IORING_FEAT_RSRC_TAGS;
10183 if (copy_to_user(params, p, sizeof(*p))) {
10188 file = io_uring_get_file(ctx);
10189 if (IS_ERR(file)) {
10190 ret = PTR_ERR(file);
10195 * Install ring fd as the very last thing, so we don't risk someone
10196 * having closed it before we finish setup
10198 ret = io_uring_install_fd(ctx, file);
10200 /* fput will clean it up */
10205 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10208 io_ring_ctx_wait_and_kill(ctx);
10213 * Sets up an aio uring context, and returns the fd. Applications asks for a
10214 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10215 * params structure passed in.
10217 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10219 struct io_uring_params p;
10222 if (copy_from_user(&p, params, sizeof(p)))
10224 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10229 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10230 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10231 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10232 IORING_SETUP_R_DISABLED))
10235 return io_uring_create(entries, &p, params);
10238 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10239 struct io_uring_params __user *, params)
10241 return io_uring_setup(entries, params);
10244 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10246 struct io_uring_probe *p;
10250 size = struct_size(p, ops, nr_args);
10251 if (size == SIZE_MAX)
10253 p = kzalloc(size, GFP_KERNEL);
10258 if (copy_from_user(p, arg, size))
10261 if (memchr_inv(p, 0, size))
10264 p->last_op = IORING_OP_LAST - 1;
10265 if (nr_args > IORING_OP_LAST)
10266 nr_args = IORING_OP_LAST;
10268 for (i = 0; i < nr_args; i++) {
10270 if (!io_op_defs[i].not_supported)
10271 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10276 if (copy_to_user(arg, p, size))
10283 static int io_register_personality(struct io_ring_ctx *ctx)
10285 const struct cred *creds;
10289 creds = get_current_cred();
10291 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10292 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10300 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10301 unsigned int nr_args)
10303 struct io_uring_restriction *res;
10307 /* Restrictions allowed only if rings started disabled */
10308 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10311 /* We allow only a single restrictions registration */
10312 if (ctx->restrictions.registered)
10315 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10318 size = array_size(nr_args, sizeof(*res));
10319 if (size == SIZE_MAX)
10322 res = memdup_user(arg, size);
10324 return PTR_ERR(res);
10328 for (i = 0; i < nr_args; i++) {
10329 switch (res[i].opcode) {
10330 case IORING_RESTRICTION_REGISTER_OP:
10331 if (res[i].register_op >= IORING_REGISTER_LAST) {
10336 __set_bit(res[i].register_op,
10337 ctx->restrictions.register_op);
10339 case IORING_RESTRICTION_SQE_OP:
10340 if (res[i].sqe_op >= IORING_OP_LAST) {
10345 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10347 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10348 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10350 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10351 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10360 /* Reset all restrictions if an error happened */
10362 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10364 ctx->restrictions.registered = true;
10370 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10372 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10375 if (ctx->restrictions.registered)
10376 ctx->restricted = 1;
10378 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10379 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10380 wake_up(&ctx->sq_data->wait);
10384 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10385 struct io_uring_rsrc_update2 *up,
10393 if (check_add_overflow(up->offset, nr_args, &tmp))
10395 err = io_rsrc_node_switch_start(ctx);
10400 case IORING_RSRC_FILE:
10401 return __io_sqe_files_update(ctx, up, nr_args);
10402 case IORING_RSRC_BUFFER:
10403 return __io_sqe_buffers_update(ctx, up, nr_args);
10408 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10411 struct io_uring_rsrc_update2 up;
10415 memset(&up, 0, sizeof(up));
10416 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10418 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10421 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10422 unsigned size, unsigned type)
10424 struct io_uring_rsrc_update2 up;
10426 if (size != sizeof(up))
10428 if (copy_from_user(&up, arg, sizeof(up)))
10430 if (!up.nr || up.resv)
10432 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10435 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10436 unsigned int size, unsigned int type)
10438 struct io_uring_rsrc_register rr;
10440 /* keep it extendible */
10441 if (size != sizeof(rr))
10444 memset(&rr, 0, sizeof(rr));
10445 if (copy_from_user(&rr, arg, size))
10447 if (!rr.nr || rr.resv || rr.resv2)
10451 case IORING_RSRC_FILE:
10452 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10453 rr.nr, u64_to_user_ptr(rr.tags));
10454 case IORING_RSRC_BUFFER:
10455 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10456 rr.nr, u64_to_user_ptr(rr.tags));
10461 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10464 struct io_uring_task *tctx = current->io_uring;
10465 cpumask_var_t new_mask;
10468 if (!tctx || !tctx->io_wq)
10471 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10474 cpumask_clear(new_mask);
10475 if (len > cpumask_size())
10476 len = cpumask_size();
10478 if (copy_from_user(new_mask, arg, len)) {
10479 free_cpumask_var(new_mask);
10483 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10484 free_cpumask_var(new_mask);
10488 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10490 struct io_uring_task *tctx = current->io_uring;
10492 if (!tctx || !tctx->io_wq)
10495 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10498 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10501 struct io_uring_task *tctx = current->io_uring;
10502 __u32 new_count[2];
10505 if (!tctx || !tctx->io_wq)
10507 if (copy_from_user(new_count, arg, sizeof(new_count)))
10509 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10510 if (new_count[i] > INT_MAX)
10513 ret = io_wq_max_workers(tctx->io_wq, new_count);
10517 if (copy_to_user(arg, new_count, sizeof(new_count)))
10523 static bool io_register_op_must_quiesce(int op)
10526 case IORING_REGISTER_BUFFERS:
10527 case IORING_UNREGISTER_BUFFERS:
10528 case IORING_REGISTER_FILES:
10529 case IORING_UNREGISTER_FILES:
10530 case IORING_REGISTER_FILES_UPDATE:
10531 case IORING_REGISTER_PROBE:
10532 case IORING_REGISTER_PERSONALITY:
10533 case IORING_UNREGISTER_PERSONALITY:
10534 case IORING_REGISTER_FILES2:
10535 case IORING_REGISTER_FILES_UPDATE2:
10536 case IORING_REGISTER_BUFFERS2:
10537 case IORING_REGISTER_BUFFERS_UPDATE:
10538 case IORING_REGISTER_IOWQ_AFF:
10539 case IORING_UNREGISTER_IOWQ_AFF:
10540 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10547 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10551 percpu_ref_kill(&ctx->refs);
10554 * Drop uring mutex before waiting for references to exit. If another
10555 * thread is currently inside io_uring_enter() it might need to grab the
10556 * uring_lock to make progress. If we hold it here across the drain
10557 * wait, then we can deadlock. It's safe to drop the mutex here, since
10558 * no new references will come in after we've killed the percpu ref.
10560 mutex_unlock(&ctx->uring_lock);
10562 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10565 ret = io_run_task_work_sig();
10566 } while (ret >= 0);
10567 mutex_lock(&ctx->uring_lock);
10570 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10574 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10575 void __user *arg, unsigned nr_args)
10576 __releases(ctx->uring_lock)
10577 __acquires(ctx->uring_lock)
10582 * We're inside the ring mutex, if the ref is already dying, then
10583 * someone else killed the ctx or is already going through
10584 * io_uring_register().
10586 if (percpu_ref_is_dying(&ctx->refs))
10589 if (ctx->restricted) {
10590 if (opcode >= IORING_REGISTER_LAST)
10592 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10593 if (!test_bit(opcode, ctx->restrictions.register_op))
10597 if (io_register_op_must_quiesce(opcode)) {
10598 ret = io_ctx_quiesce(ctx);
10604 case IORING_REGISTER_BUFFERS:
10605 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10607 case IORING_UNREGISTER_BUFFERS:
10609 if (arg || nr_args)
10611 ret = io_sqe_buffers_unregister(ctx);
10613 case IORING_REGISTER_FILES:
10614 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10616 case IORING_UNREGISTER_FILES:
10618 if (arg || nr_args)
10620 ret = io_sqe_files_unregister(ctx);
10622 case IORING_REGISTER_FILES_UPDATE:
10623 ret = io_register_files_update(ctx, arg, nr_args);
10625 case IORING_REGISTER_EVENTFD:
10626 case IORING_REGISTER_EVENTFD_ASYNC:
10630 ret = io_eventfd_register(ctx, arg);
10633 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10634 ctx->eventfd_async = 1;
10636 ctx->eventfd_async = 0;
10638 case IORING_UNREGISTER_EVENTFD:
10640 if (arg || nr_args)
10642 ret = io_eventfd_unregister(ctx);
10644 case IORING_REGISTER_PROBE:
10646 if (!arg || nr_args > 256)
10648 ret = io_probe(ctx, arg, nr_args);
10650 case IORING_REGISTER_PERSONALITY:
10652 if (arg || nr_args)
10654 ret = io_register_personality(ctx);
10656 case IORING_UNREGISTER_PERSONALITY:
10660 ret = io_unregister_personality(ctx, nr_args);
10662 case IORING_REGISTER_ENABLE_RINGS:
10664 if (arg || nr_args)
10666 ret = io_register_enable_rings(ctx);
10668 case IORING_REGISTER_RESTRICTIONS:
10669 ret = io_register_restrictions(ctx, arg, nr_args);
10671 case IORING_REGISTER_FILES2:
10672 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10674 case IORING_REGISTER_FILES_UPDATE2:
10675 ret = io_register_rsrc_update(ctx, arg, nr_args,
10678 case IORING_REGISTER_BUFFERS2:
10679 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10681 case IORING_REGISTER_BUFFERS_UPDATE:
10682 ret = io_register_rsrc_update(ctx, arg, nr_args,
10683 IORING_RSRC_BUFFER);
10685 case IORING_REGISTER_IOWQ_AFF:
10687 if (!arg || !nr_args)
10689 ret = io_register_iowq_aff(ctx, arg, nr_args);
10691 case IORING_UNREGISTER_IOWQ_AFF:
10693 if (arg || nr_args)
10695 ret = io_unregister_iowq_aff(ctx);
10697 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10699 if (!arg || nr_args != 2)
10701 ret = io_register_iowq_max_workers(ctx, arg);
10708 if (io_register_op_must_quiesce(opcode)) {
10709 /* bring the ctx back to life */
10710 percpu_ref_reinit(&ctx->refs);
10711 reinit_completion(&ctx->ref_comp);
10716 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10717 void __user *, arg, unsigned int, nr_args)
10719 struct io_ring_ctx *ctx;
10728 if (f.file->f_op != &io_uring_fops)
10731 ctx = f.file->private_data;
10733 io_run_task_work();
10735 mutex_lock(&ctx->uring_lock);
10736 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10737 mutex_unlock(&ctx->uring_lock);
10738 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10739 ctx->cq_ev_fd != NULL, ret);
10745 static int __init io_uring_init(void)
10747 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10748 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10749 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10752 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10753 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10754 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10755 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10756 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10757 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10758 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10759 BUILD_BUG_SQE_ELEM(8, __u64, off);
10760 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10761 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10762 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10763 BUILD_BUG_SQE_ELEM(24, __u32, len);
10764 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10765 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10766 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10767 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10768 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10769 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10770 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10771 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10772 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10773 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10774 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10775 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10776 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10777 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10778 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10779 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10780 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10781 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10782 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10783 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10784 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10786 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10787 sizeof(struct io_uring_rsrc_update));
10788 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10789 sizeof(struct io_uring_rsrc_update2));
10791 /* ->buf_index is u16 */
10792 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
10794 /* should fit into one byte */
10795 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10797 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10798 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10800 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10804 __initcall(io_uring_init);