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
95 /* 512 entries per page on 64-bit archs, 64 pages max */
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 9
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 cq_overflow_list;
379 struct xarray io_buffers;
380 struct xarray personalities;
382 unsigned sq_thread_idle;
383 } ____cacheline_aligned_in_smp;
385 /* IRQ completion list, under ->completion_lock */
386 struct list_head locked_free_list;
387 unsigned int locked_free_nr;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
395 unsigned long check_cq_overflow;
398 unsigned cached_cq_tail;
400 struct eventfd_ctx *cq_ev_fd;
401 struct wait_queue_head poll_wait;
402 struct wait_queue_head cq_wait;
404 atomic_t cq_timeouts;
405 struct fasync_struct *cq_fasync;
406 unsigned cq_last_tm_flush;
407 } ____cacheline_aligned_in_smp;
410 spinlock_t completion_lock;
412 spinlock_t timeout_lock;
415 * ->iopoll_list is protected by the ctx->uring_lock for
416 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417 * For SQPOLL, only the single threaded io_sq_thread() will
418 * manipulate the list, hence no extra locking is needed there.
420 struct list_head iopoll_list;
421 struct hlist_head *cancel_hash;
422 unsigned cancel_hash_bits;
423 bool poll_multi_queue;
424 } ____cacheline_aligned_in_smp;
426 struct io_restriction restrictions;
428 /* slow path rsrc auxilary data, used by update/register */
430 struct io_rsrc_node *rsrc_backup_node;
431 struct io_mapped_ubuf *dummy_ubuf;
432 struct io_rsrc_data *file_data;
433 struct io_rsrc_data *buf_data;
435 struct delayed_work rsrc_put_work;
436 struct llist_head rsrc_put_llist;
437 struct list_head rsrc_ref_list;
438 spinlock_t rsrc_ref_lock;
441 /* Keep this last, we don't need it for the fast path */
443 #if defined(CONFIG_UNIX)
444 struct socket *ring_sock;
446 /* hashed buffered write serialization */
447 struct io_wq_hash *hash_map;
449 /* Only used for accounting purposes */
450 struct user_struct *user;
451 struct mm_struct *mm_account;
453 /* ctx exit and cancelation */
454 struct llist_head fallback_llist;
455 struct delayed_work fallback_work;
456 struct work_struct exit_work;
457 struct list_head tctx_list;
458 struct completion ref_comp;
462 struct io_uring_task {
463 /* submission side */
466 struct wait_queue_head wait;
467 const struct io_ring_ctx *last;
469 struct percpu_counter inflight;
470 atomic_t inflight_tracked;
473 spinlock_t task_lock;
474 struct io_wq_work_list task_list;
475 struct callback_head task_work;
480 * First field must be the file pointer in all the
481 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
483 struct io_poll_iocb {
485 struct wait_queue_head *head;
489 struct wait_queue_entry wait;
492 struct io_poll_update {
498 bool update_user_data;
506 struct io_timeout_data {
507 struct io_kiocb *req;
508 struct hrtimer timer;
509 struct timespec64 ts;
510 enum hrtimer_mode mode;
515 struct sockaddr __user *addr;
516 int __user *addr_len;
518 unsigned long nofile;
538 struct list_head list;
539 /* head of the link, used by linked timeouts only */
540 struct io_kiocb *head;
543 struct io_timeout_rem {
548 struct timespec64 ts;
553 /* NOTE: kiocb has the file as the first member, so don't do it here */
561 struct sockaddr __user *addr;
568 struct compat_msghdr __user *umsg_compat;
569 struct user_msghdr __user *umsg;
575 struct io_buffer *kbuf;
581 struct filename *filename;
583 unsigned long nofile;
586 struct io_rsrc_update {
612 struct epoll_event event;
616 struct file *file_out;
617 struct file *file_in;
624 struct io_provide_buf {
638 const char __user *filename;
639 struct statx __user *buffer;
651 struct filename *oldpath;
652 struct filename *newpath;
660 struct filename *filename;
663 struct io_completion {
668 struct io_async_connect {
669 struct sockaddr_storage address;
672 struct io_async_msghdr {
673 struct iovec fast_iov[UIO_FASTIOV];
674 /* points to an allocated iov, if NULL we use fast_iov instead */
675 struct iovec *free_iov;
676 struct sockaddr __user *uaddr;
678 struct sockaddr_storage addr;
682 struct iovec fast_iov[UIO_FASTIOV];
683 const struct iovec *free_iovec;
684 struct iov_iter iter;
686 struct wait_page_queue wpq;
690 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
691 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
692 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
693 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
694 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
695 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
697 /* first byte is taken by user flags, shift it to not overlap */
702 REQ_F_LINK_TIMEOUT_BIT,
703 REQ_F_NEED_CLEANUP_BIT,
705 REQ_F_BUFFER_SELECTED_BIT,
706 REQ_F_LTIMEOUT_ACTIVE_BIT,
707 REQ_F_COMPLETE_INLINE_BIT,
709 REQ_F_DONT_REISSUE_BIT,
711 /* keep async read/write and isreg together and in order */
712 REQ_F_NOWAIT_READ_BIT,
713 REQ_F_NOWAIT_WRITE_BIT,
716 /* not a real bit, just to check we're not overflowing the space */
722 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
723 /* drain existing IO first */
724 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
726 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
727 /* doesn't sever on completion < 0 */
728 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
730 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
731 /* IOSQE_BUFFER_SELECT */
732 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
734 /* fail rest of links */
735 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
736 /* on inflight list, should be cancelled and waited on exit reliably */
737 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
738 /* read/write uses file position */
739 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
740 /* must not punt to workers */
741 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
742 /* has or had linked timeout */
743 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
745 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
746 /* already went through poll handler */
747 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
748 /* buffer already selected */
749 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
750 /* linked timeout is active, i.e. prepared by link's head */
751 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
752 /* completion is deferred through io_comp_state */
753 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
754 /* caller should reissue async */
755 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
756 /* don't attempt request reissue, see io_rw_reissue() */
757 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
758 /* supports async reads */
759 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
760 /* supports async writes */
761 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
763 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
764 /* has creds assigned */
765 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
769 struct io_poll_iocb poll;
770 struct io_poll_iocb *double_poll;
773 typedef void (*io_req_tw_func_t)(struct io_kiocb *req);
775 struct io_task_work {
777 struct io_wq_work_node node;
778 struct llist_node fallback_node;
780 io_req_tw_func_t func;
784 IORING_RSRC_FILE = 0,
785 IORING_RSRC_BUFFER = 1,
789 * NOTE! Each of the iocb union members has the file pointer
790 * as the first entry in their struct definition. So you can
791 * access the file pointer through any of the sub-structs,
792 * or directly as just 'ki_filp' in this struct.
798 struct io_poll_iocb poll;
799 struct io_poll_update poll_update;
800 struct io_accept accept;
802 struct io_cancel cancel;
803 struct io_timeout timeout;
804 struct io_timeout_rem timeout_rem;
805 struct io_connect connect;
806 struct io_sr_msg sr_msg;
808 struct io_close close;
809 struct io_rsrc_update rsrc_update;
810 struct io_fadvise fadvise;
811 struct io_madvise madvise;
812 struct io_epoll epoll;
813 struct io_splice splice;
814 struct io_provide_buf pbuf;
815 struct io_statx statx;
816 struct io_shutdown shutdown;
817 struct io_rename rename;
818 struct io_unlink unlink;
819 /* use only after cleaning per-op data, see io_clean_op() */
820 struct io_completion compl;
823 /* opcode allocated if it needs to store data for async defer */
826 /* polled IO has completed */
832 struct io_ring_ctx *ctx;
835 struct task_struct *task;
838 struct io_kiocb *link;
839 struct percpu_ref *fixed_rsrc_refs;
841 /* used with ctx->iopoll_list with reads/writes */
842 struct list_head inflight_entry;
843 struct io_task_work io_task_work;
844 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
845 struct hlist_node hash_node;
846 struct async_poll *apoll;
847 struct io_wq_work work;
848 const struct cred *creds;
850 /* store used ubuf, so we can prevent reloading */
851 struct io_mapped_ubuf *imu;
854 struct io_tctx_node {
855 struct list_head ctx_node;
856 struct task_struct *task;
857 struct io_ring_ctx *ctx;
860 struct io_defer_entry {
861 struct list_head list;
862 struct io_kiocb *req;
867 /* needs req->file assigned */
868 unsigned needs_file : 1;
869 /* hash wq insertion if file is a regular file */
870 unsigned hash_reg_file : 1;
871 /* unbound wq insertion if file is a non-regular file */
872 unsigned unbound_nonreg_file : 1;
873 /* opcode is not supported by this kernel */
874 unsigned not_supported : 1;
875 /* set if opcode supports polled "wait" */
877 unsigned pollout : 1;
878 /* op supports buffer selection */
879 unsigned buffer_select : 1;
880 /* do prep async if is going to be punted */
881 unsigned needs_async_setup : 1;
882 /* should block plug */
884 /* size of async data needed, if any */
885 unsigned short async_size;
888 static const struct io_op_def io_op_defs[] = {
889 [IORING_OP_NOP] = {},
890 [IORING_OP_READV] = {
892 .unbound_nonreg_file = 1,
895 .needs_async_setup = 1,
897 .async_size = sizeof(struct io_async_rw),
899 [IORING_OP_WRITEV] = {
902 .unbound_nonreg_file = 1,
904 .needs_async_setup = 1,
906 .async_size = sizeof(struct io_async_rw),
908 [IORING_OP_FSYNC] = {
911 [IORING_OP_READ_FIXED] = {
913 .unbound_nonreg_file = 1,
916 .async_size = sizeof(struct io_async_rw),
918 [IORING_OP_WRITE_FIXED] = {
921 .unbound_nonreg_file = 1,
924 .async_size = sizeof(struct io_async_rw),
926 [IORING_OP_POLL_ADD] = {
928 .unbound_nonreg_file = 1,
930 [IORING_OP_POLL_REMOVE] = {},
931 [IORING_OP_SYNC_FILE_RANGE] = {
934 [IORING_OP_SENDMSG] = {
936 .unbound_nonreg_file = 1,
938 .needs_async_setup = 1,
939 .async_size = sizeof(struct io_async_msghdr),
941 [IORING_OP_RECVMSG] = {
943 .unbound_nonreg_file = 1,
946 .needs_async_setup = 1,
947 .async_size = sizeof(struct io_async_msghdr),
949 [IORING_OP_TIMEOUT] = {
950 .async_size = sizeof(struct io_timeout_data),
952 [IORING_OP_TIMEOUT_REMOVE] = {
953 /* used by timeout updates' prep() */
955 [IORING_OP_ACCEPT] = {
957 .unbound_nonreg_file = 1,
960 [IORING_OP_ASYNC_CANCEL] = {},
961 [IORING_OP_LINK_TIMEOUT] = {
962 .async_size = sizeof(struct io_timeout_data),
964 [IORING_OP_CONNECT] = {
966 .unbound_nonreg_file = 1,
968 .needs_async_setup = 1,
969 .async_size = sizeof(struct io_async_connect),
971 [IORING_OP_FALLOCATE] = {
974 [IORING_OP_OPENAT] = {},
975 [IORING_OP_CLOSE] = {},
976 [IORING_OP_FILES_UPDATE] = {},
977 [IORING_OP_STATX] = {},
980 .unbound_nonreg_file = 1,
984 .async_size = sizeof(struct io_async_rw),
986 [IORING_OP_WRITE] = {
988 .unbound_nonreg_file = 1,
991 .async_size = sizeof(struct io_async_rw),
993 [IORING_OP_FADVISE] = {
996 [IORING_OP_MADVISE] = {},
999 .unbound_nonreg_file = 1,
1002 [IORING_OP_RECV] = {
1004 .unbound_nonreg_file = 1,
1008 [IORING_OP_OPENAT2] = {
1010 [IORING_OP_EPOLL_CTL] = {
1011 .unbound_nonreg_file = 1,
1013 [IORING_OP_SPLICE] = {
1016 .unbound_nonreg_file = 1,
1018 [IORING_OP_PROVIDE_BUFFERS] = {},
1019 [IORING_OP_REMOVE_BUFFERS] = {},
1023 .unbound_nonreg_file = 1,
1025 [IORING_OP_SHUTDOWN] = {
1028 [IORING_OP_RENAMEAT] = {},
1029 [IORING_OP_UNLINKAT] = {},
1032 static bool io_disarm_next(struct io_kiocb *req);
1033 static void io_uring_del_tctx_node(unsigned long index);
1034 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1035 struct task_struct *task,
1037 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1039 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1040 long res, unsigned int cflags);
1041 static void io_put_req(struct io_kiocb *req);
1042 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1043 static void io_dismantle_req(struct io_kiocb *req);
1044 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1045 static void io_queue_linked_timeout(struct io_kiocb *req);
1046 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1047 struct io_uring_rsrc_update2 *up,
1049 static void io_clean_op(struct io_kiocb *req);
1050 static struct file *io_file_get(struct io_ring_ctx *ctx,
1051 struct io_kiocb *req, int fd, bool fixed);
1052 static void __io_queue_sqe(struct io_kiocb *req);
1053 static void io_rsrc_put_work(struct work_struct *work);
1055 static void io_req_task_queue(struct io_kiocb *req);
1056 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1057 static int io_req_prep_async(struct io_kiocb *req);
1059 static struct kmem_cache *req_cachep;
1061 static const struct file_operations io_uring_fops;
1063 struct sock *io_uring_get_socket(struct file *file)
1065 #if defined(CONFIG_UNIX)
1066 if (file->f_op == &io_uring_fops) {
1067 struct io_ring_ctx *ctx = file->private_data;
1069 return ctx->ring_sock->sk;
1074 EXPORT_SYMBOL(io_uring_get_socket);
1076 #define io_for_each_link(pos, head) \
1077 for (pos = (head); pos; pos = pos->link)
1079 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1081 struct io_ring_ctx *ctx = req->ctx;
1083 if (!req->fixed_rsrc_refs) {
1084 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1085 percpu_ref_get(req->fixed_rsrc_refs);
1089 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1091 bool got = percpu_ref_tryget(ref);
1093 /* already at zero, wait for ->release() */
1095 wait_for_completion(compl);
1096 percpu_ref_resurrect(ref);
1098 percpu_ref_put(ref);
1101 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1104 struct io_kiocb *req;
1106 if (task && head->task != task)
1111 io_for_each_link(req, head) {
1112 if (req->flags & REQ_F_INFLIGHT)
1118 static inline void req_set_fail(struct io_kiocb *req)
1120 req->flags |= REQ_F_FAIL;
1123 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1125 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1127 complete(&ctx->ref_comp);
1130 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1132 return !req->timeout.off;
1135 static void io_fallback_req_func(struct work_struct *work)
1137 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1138 fallback_work.work);
1139 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1140 struct io_kiocb *req, *tmp;
1142 percpu_ref_get(&ctx->refs);
1143 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1144 req->io_task_work.func(req);
1145 percpu_ref_put(&ctx->refs);
1148 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1150 struct io_ring_ctx *ctx;
1153 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1158 * Use 5 bits less than the max cq entries, that should give us around
1159 * 32 entries per hash list if totally full and uniformly spread.
1161 hash_bits = ilog2(p->cq_entries);
1165 ctx->cancel_hash_bits = hash_bits;
1166 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1168 if (!ctx->cancel_hash)
1170 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1172 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1173 if (!ctx->dummy_ubuf)
1175 /* set invalid range, so io_import_fixed() fails meeting it */
1176 ctx->dummy_ubuf->ubuf = -1UL;
1178 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1179 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1182 ctx->flags = p->flags;
1183 init_waitqueue_head(&ctx->sqo_sq_wait);
1184 INIT_LIST_HEAD(&ctx->sqd_list);
1185 init_waitqueue_head(&ctx->poll_wait);
1186 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1187 init_completion(&ctx->ref_comp);
1188 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1189 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1190 mutex_init(&ctx->uring_lock);
1191 init_waitqueue_head(&ctx->cq_wait);
1192 spin_lock_init(&ctx->completion_lock);
1193 spin_lock_init(&ctx->timeout_lock);
1194 INIT_LIST_HEAD(&ctx->iopoll_list);
1195 INIT_LIST_HEAD(&ctx->defer_list);
1196 INIT_LIST_HEAD(&ctx->timeout_list);
1197 spin_lock_init(&ctx->rsrc_ref_lock);
1198 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1199 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1200 init_llist_head(&ctx->rsrc_put_llist);
1201 INIT_LIST_HEAD(&ctx->tctx_list);
1202 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1203 INIT_LIST_HEAD(&ctx->locked_free_list);
1204 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1207 kfree(ctx->dummy_ubuf);
1208 kfree(ctx->cancel_hash);
1213 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1215 struct io_rings *r = ctx->rings;
1217 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1221 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1223 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1224 struct io_ring_ctx *ctx = req->ctx;
1226 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1232 #define FFS_ASYNC_READ 0x1UL
1233 #define FFS_ASYNC_WRITE 0x2UL
1235 #define FFS_ISREG 0x4UL
1237 #define FFS_ISREG 0x0UL
1239 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1241 static inline bool io_req_ffs_set(struct io_kiocb *req)
1243 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1246 static void io_req_track_inflight(struct io_kiocb *req)
1248 if (!(req->flags & REQ_F_INFLIGHT)) {
1249 req->flags |= REQ_F_INFLIGHT;
1250 atomic_inc(¤t->io_uring->inflight_tracked);
1254 static void io_prep_async_work(struct io_kiocb *req)
1256 const struct io_op_def *def = &io_op_defs[req->opcode];
1257 struct io_ring_ctx *ctx = req->ctx;
1259 if (!(req->flags & REQ_F_CREDS)) {
1260 req->flags |= REQ_F_CREDS;
1261 req->creds = get_current_cred();
1264 req->work.list.next = NULL;
1265 req->work.flags = 0;
1266 if (req->flags & REQ_F_FORCE_ASYNC)
1267 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1269 if (req->flags & REQ_F_ISREG) {
1270 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1271 io_wq_hash_work(&req->work, file_inode(req->file));
1272 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1273 if (def->unbound_nonreg_file)
1274 req->work.flags |= IO_WQ_WORK_UNBOUND;
1277 switch (req->opcode) {
1278 case IORING_OP_SPLICE:
1280 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1281 req->work.flags |= IO_WQ_WORK_UNBOUND;
1286 static void io_prep_async_link(struct io_kiocb *req)
1288 struct io_kiocb *cur;
1290 if (req->flags & REQ_F_LINK_TIMEOUT) {
1291 struct io_ring_ctx *ctx = req->ctx;
1293 spin_lock_irq(&ctx->completion_lock);
1294 io_for_each_link(cur, req)
1295 io_prep_async_work(cur);
1296 spin_unlock_irq(&ctx->completion_lock);
1298 io_for_each_link(cur, req)
1299 io_prep_async_work(cur);
1303 static void io_queue_async_work(struct io_kiocb *req)
1305 struct io_ring_ctx *ctx = req->ctx;
1306 struct io_kiocb *link = io_prep_linked_timeout(req);
1307 struct io_uring_task *tctx = req->task->io_uring;
1310 BUG_ON(!tctx->io_wq);
1312 /* init ->work of the whole link before punting */
1313 io_prep_async_link(req);
1316 * Not expected to happen, but if we do have a bug where this _can_
1317 * happen, catch it here and ensure the request is marked as
1318 * canceled. That will make io-wq go through the usual work cancel
1319 * procedure rather than attempt to run this request (or create a new
1322 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1323 req->work.flags |= IO_WQ_WORK_CANCEL;
1325 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1326 &req->work, req->flags);
1327 io_wq_enqueue(tctx->io_wq, &req->work);
1329 io_queue_linked_timeout(link);
1332 static void io_kill_timeout(struct io_kiocb *req, int status)
1333 __must_hold(&req->ctx->completion_lock)
1334 __must_hold(&req->ctx->timeout_lock)
1336 struct io_timeout_data *io = req->async_data;
1338 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1339 atomic_set(&req->ctx->cq_timeouts,
1340 atomic_read(&req->ctx->cq_timeouts) + 1);
1341 list_del_init(&req->timeout.list);
1342 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1343 io_put_req_deferred(req, 1);
1347 static void io_queue_deferred(struct io_ring_ctx *ctx)
1349 while (!list_empty(&ctx->defer_list)) {
1350 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1351 struct io_defer_entry, list);
1353 if (req_need_defer(de->req, de->seq))
1355 list_del_init(&de->list);
1356 io_req_task_queue(de->req);
1361 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1362 __must_hold(&ctx->completion_lock)
1364 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1365 unsigned long flags;
1367 spin_lock_irqsave(&ctx->timeout_lock, flags);
1368 while (!list_empty(&ctx->timeout_list)) {
1369 u32 events_needed, events_got;
1370 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1371 struct io_kiocb, timeout.list);
1373 if (io_is_timeout_noseq(req))
1377 * Since seq can easily wrap around over time, subtract
1378 * the last seq at which timeouts were flushed before comparing.
1379 * Assuming not more than 2^31-1 events have happened since,
1380 * these subtractions won't have wrapped, so we can check if
1381 * target is in [last_seq, current_seq] by comparing the two.
1383 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1384 events_got = seq - ctx->cq_last_tm_flush;
1385 if (events_got < events_needed)
1388 list_del_init(&req->timeout.list);
1389 io_kill_timeout(req, 0);
1391 ctx->cq_last_tm_flush = seq;
1392 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
1395 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1397 if (ctx->off_timeout_used)
1398 io_flush_timeouts(ctx);
1399 if (ctx->drain_active)
1400 io_queue_deferred(ctx);
1403 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1405 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1406 __io_commit_cqring_flush(ctx);
1407 /* order cqe stores with ring update */
1408 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1411 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1413 struct io_rings *r = ctx->rings;
1415 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1418 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1420 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1423 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1425 struct io_rings *rings = ctx->rings;
1426 unsigned tail, mask = ctx->cq_entries - 1;
1429 * writes to the cq entry need to come after reading head; the
1430 * control dependency is enough as we're using WRITE_ONCE to
1433 if (__io_cqring_events(ctx) == ctx->cq_entries)
1436 tail = ctx->cached_cq_tail++;
1437 return &rings->cqes[tail & mask];
1440 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1442 if (likely(!ctx->cq_ev_fd))
1444 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1446 return !ctx->eventfd_async || io_wq_current_is_worker();
1449 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1452 * wake_up_all() may seem excessive, but io_wake_function() and
1453 * io_should_wake() handle the termination of the loop and only
1454 * wake as many waiters as we need to.
1456 if (wq_has_sleeper(&ctx->cq_wait))
1457 wake_up_all(&ctx->cq_wait);
1458 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1459 wake_up(&ctx->sq_data->wait);
1460 if (io_should_trigger_evfd(ctx))
1461 eventfd_signal(ctx->cq_ev_fd, 1);
1462 if (waitqueue_active(&ctx->poll_wait)) {
1463 wake_up_interruptible(&ctx->poll_wait);
1464 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1468 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1470 if (ctx->flags & IORING_SETUP_SQPOLL) {
1471 if (wq_has_sleeper(&ctx->cq_wait))
1472 wake_up_all(&ctx->cq_wait);
1474 if (io_should_trigger_evfd(ctx))
1475 eventfd_signal(ctx->cq_ev_fd, 1);
1476 if (waitqueue_active(&ctx->poll_wait)) {
1477 wake_up_interruptible(&ctx->poll_wait);
1478 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1482 /* Returns true if there are no backlogged entries after the flush */
1483 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1485 unsigned long flags;
1486 bool all_flushed, posted;
1488 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1492 spin_lock_irqsave(&ctx->completion_lock, flags);
1493 while (!list_empty(&ctx->cq_overflow_list)) {
1494 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1495 struct io_overflow_cqe *ocqe;
1499 ocqe = list_first_entry(&ctx->cq_overflow_list,
1500 struct io_overflow_cqe, list);
1502 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1504 io_account_cq_overflow(ctx);
1507 list_del(&ocqe->list);
1511 all_flushed = list_empty(&ctx->cq_overflow_list);
1513 clear_bit(0, &ctx->check_cq_overflow);
1514 WRITE_ONCE(ctx->rings->sq_flags,
1515 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1519 io_commit_cqring(ctx);
1520 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1522 io_cqring_ev_posted(ctx);
1526 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1530 if (test_bit(0, &ctx->check_cq_overflow)) {
1531 /* iopoll syncs against uring_lock, not completion_lock */
1532 if (ctx->flags & IORING_SETUP_IOPOLL)
1533 mutex_lock(&ctx->uring_lock);
1534 ret = __io_cqring_overflow_flush(ctx, false);
1535 if (ctx->flags & IORING_SETUP_IOPOLL)
1536 mutex_unlock(&ctx->uring_lock);
1543 * Shamelessly stolen from the mm implementation of page reference checking,
1544 * see commit f958d7b528b1 for details.
1546 #define req_ref_zero_or_close_to_overflow(req) \
1547 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1549 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1551 return atomic_inc_not_zero(&req->refs);
1554 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1556 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1557 return atomic_sub_and_test(refs, &req->refs);
1560 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1562 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1563 return atomic_dec_and_test(&req->refs);
1566 static inline void req_ref_put(struct io_kiocb *req)
1568 WARN_ON_ONCE(req_ref_put_and_test(req));
1571 static inline void req_ref_get(struct io_kiocb *req)
1573 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1574 atomic_inc(&req->refs);
1577 /* must to be called somewhat shortly after putting a request */
1578 static inline void io_put_task(struct task_struct *task, int nr)
1580 struct io_uring_task *tctx = task->io_uring;
1582 percpu_counter_sub(&tctx->inflight, nr);
1583 if (unlikely(atomic_read(&tctx->in_idle)))
1584 wake_up(&tctx->wait);
1585 put_task_struct_many(task, nr);
1588 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1589 long res, unsigned int cflags)
1591 struct io_overflow_cqe *ocqe;
1593 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1596 * If we're in ring overflow flush mode, or in task cancel mode,
1597 * or cannot allocate an overflow entry, then we need to drop it
1600 io_account_cq_overflow(ctx);
1603 if (list_empty(&ctx->cq_overflow_list)) {
1604 set_bit(0, &ctx->check_cq_overflow);
1605 WRITE_ONCE(ctx->rings->sq_flags,
1606 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1609 ocqe->cqe.user_data = user_data;
1610 ocqe->cqe.res = res;
1611 ocqe->cqe.flags = cflags;
1612 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1616 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1617 long res, unsigned int cflags)
1619 struct io_uring_cqe *cqe;
1621 trace_io_uring_complete(ctx, user_data, res, cflags);
1624 * If we can't get a cq entry, userspace overflowed the
1625 * submission (by quite a lot). Increment the overflow count in
1628 cqe = io_get_cqe(ctx);
1630 WRITE_ONCE(cqe->user_data, user_data);
1631 WRITE_ONCE(cqe->res, res);
1632 WRITE_ONCE(cqe->flags, cflags);
1635 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1638 /* not as hot to bloat with inlining */
1639 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1640 long res, unsigned int cflags)
1642 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1645 static void io_req_complete_post(struct io_kiocb *req, long res,
1646 unsigned int cflags)
1648 struct io_ring_ctx *ctx = req->ctx;
1649 unsigned long flags;
1651 spin_lock_irqsave(&ctx->completion_lock, flags);
1652 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1654 * If we're the last reference to this request, add to our locked
1657 if (req_ref_put_and_test(req)) {
1658 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1659 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL))
1660 io_disarm_next(req);
1662 io_req_task_queue(req->link);
1666 io_dismantle_req(req);
1667 io_put_task(req->task, 1);
1668 list_add(&req->inflight_entry, &ctx->locked_free_list);
1669 ctx->locked_free_nr++;
1671 if (!percpu_ref_tryget(&ctx->refs))
1674 io_commit_cqring(ctx);
1675 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1678 io_cqring_ev_posted(ctx);
1679 percpu_ref_put(&ctx->refs);
1683 static inline bool io_req_needs_clean(struct io_kiocb *req)
1685 return req->flags & IO_REQ_CLEAN_FLAGS;
1688 static void io_req_complete_state(struct io_kiocb *req, long res,
1689 unsigned int cflags)
1691 if (io_req_needs_clean(req))
1694 req->compl.cflags = cflags;
1695 req->flags |= REQ_F_COMPLETE_INLINE;
1698 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1699 long res, unsigned cflags)
1701 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1702 io_req_complete_state(req, res, cflags);
1704 io_req_complete_post(req, res, cflags);
1707 static inline void io_req_complete(struct io_kiocb *req, long res)
1709 __io_req_complete(req, 0, res, 0);
1712 static void io_req_complete_failed(struct io_kiocb *req, long res)
1716 io_req_complete_post(req, res, 0);
1720 * Don't initialise the fields below on every allocation, but do that in
1721 * advance and keep them valid across allocations.
1723 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1727 req->async_data = NULL;
1728 /* not necessary, but safer to zero */
1732 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1733 struct io_submit_state *state)
1735 spin_lock_irq(&ctx->completion_lock);
1736 list_splice_init(&ctx->locked_free_list, &state->free_list);
1737 ctx->locked_free_nr = 0;
1738 spin_unlock_irq(&ctx->completion_lock);
1741 /* Returns true IFF there are requests in the cache */
1742 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1744 struct io_submit_state *state = &ctx->submit_state;
1748 * If we have more than a batch's worth of requests in our IRQ side
1749 * locked cache, grab the lock and move them over to our submission
1752 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1753 io_flush_cached_locked_reqs(ctx, state);
1755 nr = state->free_reqs;
1756 while (!list_empty(&state->free_list)) {
1757 struct io_kiocb *req = list_first_entry(&state->free_list,
1758 struct io_kiocb, inflight_entry);
1760 list_del(&req->inflight_entry);
1761 state->reqs[nr++] = req;
1762 if (nr == ARRAY_SIZE(state->reqs))
1766 state->free_reqs = nr;
1770 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1772 struct io_submit_state *state = &ctx->submit_state;
1773 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1776 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1778 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1781 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1785 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1786 * retry single alloc to be on the safe side.
1788 if (unlikely(ret <= 0)) {
1789 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1790 if (!state->reqs[0])
1795 for (i = 0; i < ret; i++)
1796 io_preinit_req(state->reqs[i], ctx);
1797 state->free_reqs = ret;
1800 return state->reqs[state->free_reqs];
1803 static inline void io_put_file(struct file *file)
1809 static void io_dismantle_req(struct io_kiocb *req)
1811 unsigned int flags = req->flags;
1813 if (io_req_needs_clean(req))
1815 if (!(flags & REQ_F_FIXED_FILE))
1816 io_put_file(req->file);
1817 if (req->fixed_rsrc_refs)
1818 percpu_ref_put(req->fixed_rsrc_refs);
1819 if (req->async_data) {
1820 kfree(req->async_data);
1821 req->async_data = NULL;
1825 static void __io_free_req(struct io_kiocb *req)
1827 struct io_ring_ctx *ctx = req->ctx;
1828 unsigned long flags;
1830 io_dismantle_req(req);
1831 io_put_task(req->task, 1);
1833 spin_lock_irqsave(&ctx->completion_lock, flags);
1834 list_add(&req->inflight_entry, &ctx->locked_free_list);
1835 ctx->locked_free_nr++;
1836 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1838 percpu_ref_put(&ctx->refs);
1841 static inline void io_remove_next_linked(struct io_kiocb *req)
1843 struct io_kiocb *nxt = req->link;
1845 req->link = nxt->link;
1849 static bool io_kill_linked_timeout(struct io_kiocb *req)
1850 __must_hold(&req->ctx->completion_lock)
1852 struct io_kiocb *link = req->link;
1855 * Can happen if a linked timeout fired and link had been like
1856 * req -> link t-out -> link t-out [-> ...]
1858 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1859 struct io_timeout_data *io = link->async_data;
1861 io_remove_next_linked(req);
1862 link->timeout.head = NULL;
1863 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1864 io_cqring_fill_event(link->ctx, link->user_data,
1866 io_put_req_deferred(link, 1);
1873 static void io_fail_links(struct io_kiocb *req)
1874 __must_hold(&req->ctx->completion_lock)
1876 struct io_kiocb *nxt, *link = req->link;
1883 trace_io_uring_fail_link(req, link);
1884 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1885 io_put_req_deferred(link, 2);
1890 static bool io_disarm_next(struct io_kiocb *req)
1891 __must_hold(&req->ctx->completion_lock)
1893 bool posted = false;
1895 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1896 posted = io_kill_linked_timeout(req);
1897 if (unlikely((req->flags & REQ_F_FAIL) &&
1898 !(req->flags & REQ_F_HARDLINK))) {
1899 posted |= (req->link != NULL);
1905 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1907 struct io_kiocb *nxt;
1910 * If LINK is set, we have dependent requests in this chain. If we
1911 * didn't fail this request, queue the first one up, moving any other
1912 * dependencies to the next request. In case of failure, fail the rest
1915 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL)) {
1916 struct io_ring_ctx *ctx = req->ctx;
1917 unsigned long flags;
1920 spin_lock_irqsave(&ctx->completion_lock, flags);
1921 posted = io_disarm_next(req);
1923 io_commit_cqring(req->ctx);
1924 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1926 io_cqring_ev_posted(ctx);
1933 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1935 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1937 return __io_req_find_next(req);
1940 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1944 if (ctx->submit_state.compl_nr) {
1945 mutex_lock(&ctx->uring_lock);
1946 io_submit_flush_completions(ctx);
1947 mutex_unlock(&ctx->uring_lock);
1949 percpu_ref_put(&ctx->refs);
1952 static void tctx_task_work(struct callback_head *cb)
1954 struct io_ring_ctx *ctx = NULL;
1955 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1959 struct io_wq_work_node *node;
1961 spin_lock_irq(&tctx->task_lock);
1962 node = tctx->task_list.first;
1963 INIT_WQ_LIST(&tctx->task_list);
1965 tctx->task_running = false;
1966 spin_unlock_irq(&tctx->task_lock);
1971 struct io_wq_work_node *next = node->next;
1972 struct io_kiocb *req = container_of(node, struct io_kiocb,
1975 if (req->ctx != ctx) {
1976 ctx_flush_and_put(ctx);
1978 percpu_ref_get(&ctx->refs);
1980 req->io_task_work.func(req);
1987 ctx_flush_and_put(ctx);
1990 static void io_req_task_work_add(struct io_kiocb *req)
1992 struct task_struct *tsk = req->task;
1993 struct io_uring_task *tctx = tsk->io_uring;
1994 enum task_work_notify_mode notify;
1995 struct io_wq_work_node *node;
1996 unsigned long flags;
1999 WARN_ON_ONCE(!tctx);
2001 spin_lock_irqsave(&tctx->task_lock, flags);
2002 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2003 running = tctx->task_running;
2005 tctx->task_running = true;
2006 spin_unlock_irqrestore(&tctx->task_lock, flags);
2008 /* task_work already pending, we're done */
2013 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2014 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2015 * processing task_work. There's no reliable way to tell if TWA_RESUME
2018 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2019 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2020 wake_up_process(tsk);
2024 spin_lock_irqsave(&tctx->task_lock, flags);
2025 tctx->task_running = false;
2026 node = tctx->task_list.first;
2027 INIT_WQ_LIST(&tctx->task_list);
2028 spin_unlock_irqrestore(&tctx->task_lock, flags);
2031 req = container_of(node, struct io_kiocb, io_task_work.node);
2033 if (llist_add(&req->io_task_work.fallback_node,
2034 &req->ctx->fallback_llist))
2035 schedule_delayed_work(&req->ctx->fallback_work, 1);
2039 static void io_req_task_cancel(struct io_kiocb *req)
2041 struct io_ring_ctx *ctx = req->ctx;
2043 /* ctx is guaranteed to stay alive while we hold uring_lock */
2044 mutex_lock(&ctx->uring_lock);
2045 io_req_complete_failed(req, req->result);
2046 mutex_unlock(&ctx->uring_lock);
2049 static void io_req_task_submit(struct io_kiocb *req)
2051 struct io_ring_ctx *ctx = req->ctx;
2053 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2054 mutex_lock(&ctx->uring_lock);
2055 if (likely(!(req->task->flags & PF_EXITING)))
2056 __io_queue_sqe(req);
2058 io_req_complete_failed(req, -EFAULT);
2059 mutex_unlock(&ctx->uring_lock);
2062 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2065 req->io_task_work.func = io_req_task_cancel;
2066 io_req_task_work_add(req);
2069 static void io_req_task_queue(struct io_kiocb *req)
2071 req->io_task_work.func = io_req_task_submit;
2072 io_req_task_work_add(req);
2075 static void io_req_task_queue_reissue(struct io_kiocb *req)
2077 req->io_task_work.func = io_queue_async_work;
2078 io_req_task_work_add(req);
2081 static inline void io_queue_next(struct io_kiocb *req)
2083 struct io_kiocb *nxt = io_req_find_next(req);
2086 io_req_task_queue(nxt);
2089 static void io_free_req(struct io_kiocb *req)
2096 struct task_struct *task;
2101 static inline void io_init_req_batch(struct req_batch *rb)
2108 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2109 struct req_batch *rb)
2112 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2113 if (rb->task == current)
2114 current->io_uring->cached_refs += rb->task_refs;
2116 io_put_task(rb->task, rb->task_refs);
2119 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2120 struct io_submit_state *state)
2123 io_dismantle_req(req);
2125 if (req->task != rb->task) {
2127 io_put_task(rb->task, rb->task_refs);
2128 rb->task = req->task;
2134 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2135 state->reqs[state->free_reqs++] = req;
2137 list_add(&req->inflight_entry, &state->free_list);
2140 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2141 __must_hold(&req->ctx->uring_lock)
2143 struct io_submit_state *state = &ctx->submit_state;
2144 int i, nr = state->compl_nr;
2145 struct req_batch rb;
2147 spin_lock_irq(&ctx->completion_lock);
2148 for (i = 0; i < nr; i++) {
2149 struct io_kiocb *req = state->compl_reqs[i];
2151 __io_cqring_fill_event(ctx, req->user_data, req->result,
2154 io_commit_cqring(ctx);
2155 spin_unlock_irq(&ctx->completion_lock);
2156 io_cqring_ev_posted(ctx);
2158 io_init_req_batch(&rb);
2159 for (i = 0; i < nr; i++) {
2160 struct io_kiocb *req = state->compl_reqs[i];
2162 /* submission and completion refs */
2163 if (req_ref_sub_and_test(req, 2))
2164 io_req_free_batch(&rb, req, &ctx->submit_state);
2167 io_req_free_batch_finish(ctx, &rb);
2168 state->compl_nr = 0;
2172 * Drop reference to request, return next in chain (if there is one) if this
2173 * was the last reference to this request.
2175 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2177 struct io_kiocb *nxt = NULL;
2179 if (req_ref_put_and_test(req)) {
2180 nxt = io_req_find_next(req);
2186 static inline void io_put_req(struct io_kiocb *req)
2188 if (req_ref_put_and_test(req))
2192 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2194 if (req_ref_sub_and_test(req, refs)) {
2195 req->io_task_work.func = io_free_req;
2196 io_req_task_work_add(req);
2200 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2202 /* See comment at the top of this file */
2204 return __io_cqring_events(ctx);
2207 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2209 struct io_rings *rings = ctx->rings;
2211 /* make sure SQ entry isn't read before tail */
2212 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2215 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2217 unsigned int cflags;
2219 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2220 cflags |= IORING_CQE_F_BUFFER;
2221 req->flags &= ~REQ_F_BUFFER_SELECTED;
2226 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2228 struct io_buffer *kbuf;
2230 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2231 return io_put_kbuf(req, kbuf);
2234 static inline bool io_run_task_work(void)
2236 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2237 __set_current_state(TASK_RUNNING);
2238 tracehook_notify_signal();
2246 * Find and free completed poll iocbs
2248 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2249 struct list_head *done, bool resubmit)
2251 struct req_batch rb;
2252 struct io_kiocb *req;
2254 /* order with ->result store in io_complete_rw_iopoll() */
2257 io_init_req_batch(&rb);
2258 while (!list_empty(done)) {
2261 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2262 list_del(&req->inflight_entry);
2264 if (READ_ONCE(req->result) == -EAGAIN && resubmit &&
2265 !(req->flags & REQ_F_DONT_REISSUE)) {
2266 req->iopoll_completed = 0;
2268 io_req_task_queue_reissue(req);
2272 if (req->flags & REQ_F_BUFFER_SELECTED)
2273 cflags = io_put_rw_kbuf(req);
2275 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2278 if (req_ref_put_and_test(req))
2279 io_req_free_batch(&rb, req, &ctx->submit_state);
2282 io_commit_cqring(ctx);
2283 io_cqring_ev_posted_iopoll(ctx);
2284 io_req_free_batch_finish(ctx, &rb);
2287 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2288 long min, bool resubmit)
2290 struct io_kiocb *req, *tmp;
2295 * Only spin for completions if we don't have multiple devices hanging
2296 * off our complete list, and we're under the requested amount.
2298 spin = !ctx->poll_multi_queue && *nr_events < min;
2300 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2301 struct kiocb *kiocb = &req->rw.kiocb;
2305 * Move completed and retryable entries to our local lists.
2306 * If we find a request that requires polling, break out
2307 * and complete those lists first, if we have entries there.
2309 if (READ_ONCE(req->iopoll_completed)) {
2310 list_move_tail(&req->inflight_entry, &done);
2313 if (!list_empty(&done))
2316 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2317 if (unlikely(ret < 0))
2322 /* iopoll may have completed current req */
2323 if (READ_ONCE(req->iopoll_completed))
2324 list_move_tail(&req->inflight_entry, &done);
2327 if (!list_empty(&done))
2328 io_iopoll_complete(ctx, nr_events, &done, resubmit);
2334 * We can't just wait for polled events to come to us, we have to actively
2335 * find and complete them.
2337 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2339 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2342 mutex_lock(&ctx->uring_lock);
2343 while (!list_empty(&ctx->iopoll_list)) {
2344 unsigned int nr_events = 0;
2346 io_do_iopoll(ctx, &nr_events, 0, false);
2348 /* let it sleep and repeat later if can't complete a request */
2352 * Ensure we allow local-to-the-cpu processing to take place,
2353 * in this case we need to ensure that we reap all events.
2354 * Also let task_work, etc. to progress by releasing the mutex
2356 if (need_resched()) {
2357 mutex_unlock(&ctx->uring_lock);
2359 mutex_lock(&ctx->uring_lock);
2362 mutex_unlock(&ctx->uring_lock);
2365 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2367 unsigned int nr_events = 0;
2371 * We disallow the app entering submit/complete with polling, but we
2372 * still need to lock the ring to prevent racing with polled issue
2373 * that got punted to a workqueue.
2375 mutex_lock(&ctx->uring_lock);
2377 * Don't enter poll loop if we already have events pending.
2378 * If we do, we can potentially be spinning for commands that
2379 * already triggered a CQE (eg in error).
2381 if (test_bit(0, &ctx->check_cq_overflow))
2382 __io_cqring_overflow_flush(ctx, false);
2383 if (io_cqring_events(ctx))
2387 * If a submit got punted to a workqueue, we can have the
2388 * application entering polling for a command before it gets
2389 * issued. That app will hold the uring_lock for the duration
2390 * of the poll right here, so we need to take a breather every
2391 * now and then to ensure that the issue has a chance to add
2392 * the poll to the issued list. Otherwise we can spin here
2393 * forever, while the workqueue is stuck trying to acquire the
2396 if (list_empty(&ctx->iopoll_list)) {
2397 u32 tail = ctx->cached_cq_tail;
2399 mutex_unlock(&ctx->uring_lock);
2401 mutex_lock(&ctx->uring_lock);
2403 /* some requests don't go through iopoll_list */
2404 if (tail != ctx->cached_cq_tail ||
2405 list_empty(&ctx->iopoll_list))
2408 ret = io_do_iopoll(ctx, &nr_events, min, true);
2409 } while (!ret && nr_events < min && !need_resched());
2411 mutex_unlock(&ctx->uring_lock);
2415 static void kiocb_end_write(struct io_kiocb *req)
2418 * Tell lockdep we inherited freeze protection from submission
2421 if (req->flags & REQ_F_ISREG) {
2422 struct super_block *sb = file_inode(req->file)->i_sb;
2424 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2430 static bool io_resubmit_prep(struct io_kiocb *req)
2432 struct io_async_rw *rw = req->async_data;
2435 return !io_req_prep_async(req);
2436 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2437 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2441 static bool io_rw_should_reissue(struct io_kiocb *req)
2443 umode_t mode = file_inode(req->file)->i_mode;
2444 struct io_ring_ctx *ctx = req->ctx;
2446 if (!S_ISBLK(mode) && !S_ISREG(mode))
2448 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2449 !(ctx->flags & IORING_SETUP_IOPOLL)))
2452 * If ref is dying, we might be running poll reap from the exit work.
2453 * Don't attempt to reissue from that path, just let it fail with
2456 if (percpu_ref_is_dying(&ctx->refs))
2459 * Play it safe and assume not safe to re-import and reissue if we're
2460 * not in the original thread group (or in task context).
2462 if (!same_thread_group(req->task, current) || !in_task())
2467 static bool io_resubmit_prep(struct io_kiocb *req)
2471 static bool io_rw_should_reissue(struct io_kiocb *req)
2477 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2478 unsigned int issue_flags)
2482 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2483 kiocb_end_write(req);
2484 if (res != req->result) {
2485 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2486 io_rw_should_reissue(req)) {
2487 req->flags |= REQ_F_REISSUE;
2492 if (req->flags & REQ_F_BUFFER_SELECTED)
2493 cflags = io_put_rw_kbuf(req);
2494 __io_req_complete(req, issue_flags, res, cflags);
2497 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2499 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2501 __io_complete_rw(req, res, res2, 0);
2504 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2506 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2508 if (kiocb->ki_flags & IOCB_WRITE)
2509 kiocb_end_write(req);
2510 if (unlikely(res != req->result)) {
2511 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2512 io_resubmit_prep(req))) {
2514 req->flags |= REQ_F_DONT_REISSUE;
2518 WRITE_ONCE(req->result, res);
2519 /* order with io_iopoll_complete() checking ->result */
2521 WRITE_ONCE(req->iopoll_completed, 1);
2525 * After the iocb has been issued, it's safe to be found on the poll list.
2526 * Adding the kiocb to the list AFTER submission ensures that we don't
2527 * find it from a io_do_iopoll() thread before the issuer is done
2528 * accessing the kiocb cookie.
2530 static void io_iopoll_req_issued(struct io_kiocb *req)
2532 struct io_ring_ctx *ctx = req->ctx;
2533 const bool in_async = io_wq_current_is_worker();
2535 /* workqueue context doesn't hold uring_lock, grab it now */
2536 if (unlikely(in_async))
2537 mutex_lock(&ctx->uring_lock);
2540 * Track whether we have multiple files in our lists. This will impact
2541 * how we do polling eventually, not spinning if we're on potentially
2542 * different devices.
2544 if (list_empty(&ctx->iopoll_list)) {
2545 ctx->poll_multi_queue = false;
2546 } else if (!ctx->poll_multi_queue) {
2547 struct io_kiocb *list_req;
2548 unsigned int queue_num0, queue_num1;
2550 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2553 if (list_req->file != req->file) {
2554 ctx->poll_multi_queue = true;
2556 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2557 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2558 if (queue_num0 != queue_num1)
2559 ctx->poll_multi_queue = true;
2564 * For fast devices, IO may have already completed. If it has, add
2565 * it to the front so we find it first.
2567 if (READ_ONCE(req->iopoll_completed))
2568 list_add(&req->inflight_entry, &ctx->iopoll_list);
2570 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2572 if (unlikely(in_async)) {
2574 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2575 * in sq thread task context or in io worker task context. If
2576 * current task context is sq thread, we don't need to check
2577 * whether should wake up sq thread.
2579 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2580 wq_has_sleeper(&ctx->sq_data->wait))
2581 wake_up(&ctx->sq_data->wait);
2583 mutex_unlock(&ctx->uring_lock);
2587 static bool io_bdev_nowait(struct block_device *bdev)
2589 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2593 * If we tracked the file through the SCM inflight mechanism, we could support
2594 * any file. For now, just ensure that anything potentially problematic is done
2597 static bool __io_file_supports_nowait(struct file *file, int rw)
2599 umode_t mode = file_inode(file)->i_mode;
2601 if (S_ISBLK(mode)) {
2602 if (IS_ENABLED(CONFIG_BLOCK) &&
2603 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2609 if (S_ISREG(mode)) {
2610 if (IS_ENABLED(CONFIG_BLOCK) &&
2611 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2612 file->f_op != &io_uring_fops)
2617 /* any ->read/write should understand O_NONBLOCK */
2618 if (file->f_flags & O_NONBLOCK)
2621 if (!(file->f_mode & FMODE_NOWAIT))
2625 return file->f_op->read_iter != NULL;
2627 return file->f_op->write_iter != NULL;
2630 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2632 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2634 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2637 return __io_file_supports_nowait(req->file, rw);
2640 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2642 struct io_ring_ctx *ctx = req->ctx;
2643 struct kiocb *kiocb = &req->rw.kiocb;
2644 struct file *file = req->file;
2648 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2649 req->flags |= REQ_F_ISREG;
2651 kiocb->ki_pos = READ_ONCE(sqe->off);
2652 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2653 req->flags |= REQ_F_CUR_POS;
2654 kiocb->ki_pos = file->f_pos;
2656 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2657 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2658 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2662 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2663 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2664 req->flags |= REQ_F_NOWAIT;
2666 ioprio = READ_ONCE(sqe->ioprio);
2668 ret = ioprio_check_cap(ioprio);
2672 kiocb->ki_ioprio = ioprio;
2674 kiocb->ki_ioprio = get_current_ioprio();
2676 if (ctx->flags & IORING_SETUP_IOPOLL) {
2677 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2678 !kiocb->ki_filp->f_op->iopoll)
2681 kiocb->ki_flags |= IOCB_HIPRI;
2682 kiocb->ki_complete = io_complete_rw_iopoll;
2683 req->iopoll_completed = 0;
2685 if (kiocb->ki_flags & IOCB_HIPRI)
2687 kiocb->ki_complete = io_complete_rw;
2690 if (req->opcode == IORING_OP_READ_FIXED ||
2691 req->opcode == IORING_OP_WRITE_FIXED) {
2693 io_req_set_rsrc_node(req);
2696 req->rw.addr = READ_ONCE(sqe->addr);
2697 req->rw.len = READ_ONCE(sqe->len);
2698 req->buf_index = READ_ONCE(sqe->buf_index);
2702 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2708 case -ERESTARTNOINTR:
2709 case -ERESTARTNOHAND:
2710 case -ERESTART_RESTARTBLOCK:
2712 * We can't just restart the syscall, since previously
2713 * submitted sqes may already be in progress. Just fail this
2719 kiocb->ki_complete(kiocb, ret, 0);
2723 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2724 unsigned int issue_flags)
2726 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2727 struct io_async_rw *io = req->async_data;
2728 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2730 /* add previously done IO, if any */
2731 if (io && io->bytes_done > 0) {
2733 ret = io->bytes_done;
2735 ret += io->bytes_done;
2738 if (req->flags & REQ_F_CUR_POS)
2739 req->file->f_pos = kiocb->ki_pos;
2740 if (ret >= 0 && check_reissue)
2741 __io_complete_rw(req, ret, 0, issue_flags);
2743 io_rw_done(kiocb, ret);
2745 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2746 req->flags &= ~REQ_F_REISSUE;
2747 if (io_resubmit_prep(req)) {
2749 io_req_task_queue_reissue(req);
2754 if (req->flags & REQ_F_BUFFER_SELECTED)
2755 cflags = io_put_rw_kbuf(req);
2756 __io_req_complete(req, issue_flags, ret, cflags);
2761 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2762 struct io_mapped_ubuf *imu)
2764 size_t len = req->rw.len;
2765 u64 buf_end, buf_addr = req->rw.addr;
2768 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2770 /* not inside the mapped region */
2771 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2775 * May not be a start of buffer, set size appropriately
2776 * and advance us to the beginning.
2778 offset = buf_addr - imu->ubuf;
2779 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2783 * Don't use iov_iter_advance() here, as it's really slow for
2784 * using the latter parts of a big fixed buffer - it iterates
2785 * over each segment manually. We can cheat a bit here, because
2788 * 1) it's a BVEC iter, we set it up
2789 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2790 * first and last bvec
2792 * So just find our index, and adjust the iterator afterwards.
2793 * If the offset is within the first bvec (or the whole first
2794 * bvec, just use iov_iter_advance(). This makes it easier
2795 * since we can just skip the first segment, which may not
2796 * be PAGE_SIZE aligned.
2798 const struct bio_vec *bvec = imu->bvec;
2800 if (offset <= bvec->bv_len) {
2801 iov_iter_advance(iter, offset);
2803 unsigned long seg_skip;
2805 /* skip first vec */
2806 offset -= bvec->bv_len;
2807 seg_skip = 1 + (offset >> PAGE_SHIFT);
2809 iter->bvec = bvec + seg_skip;
2810 iter->nr_segs -= seg_skip;
2811 iter->count -= bvec->bv_len + offset;
2812 iter->iov_offset = offset & ~PAGE_MASK;
2819 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2821 struct io_ring_ctx *ctx = req->ctx;
2822 struct io_mapped_ubuf *imu = req->imu;
2823 u16 index, buf_index = req->buf_index;
2826 if (unlikely(buf_index >= ctx->nr_user_bufs))
2828 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2829 imu = READ_ONCE(ctx->user_bufs[index]);
2832 return __io_import_fixed(req, rw, iter, imu);
2835 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2838 mutex_unlock(&ctx->uring_lock);
2841 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2844 * "Normal" inline submissions always hold the uring_lock, since we
2845 * grab it from the system call. Same is true for the SQPOLL offload.
2846 * The only exception is when we've detached the request and issue it
2847 * from an async worker thread, grab the lock for that case.
2850 mutex_lock(&ctx->uring_lock);
2853 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2854 int bgid, struct io_buffer *kbuf,
2857 struct io_buffer *head;
2859 if (req->flags & REQ_F_BUFFER_SELECTED)
2862 io_ring_submit_lock(req->ctx, needs_lock);
2864 lockdep_assert_held(&req->ctx->uring_lock);
2866 head = xa_load(&req->ctx->io_buffers, bgid);
2868 if (!list_empty(&head->list)) {
2869 kbuf = list_last_entry(&head->list, struct io_buffer,
2871 list_del(&kbuf->list);
2874 xa_erase(&req->ctx->io_buffers, bgid);
2876 if (*len > kbuf->len)
2879 kbuf = ERR_PTR(-ENOBUFS);
2882 io_ring_submit_unlock(req->ctx, needs_lock);
2887 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2890 struct io_buffer *kbuf;
2893 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2894 bgid = req->buf_index;
2895 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2898 req->rw.addr = (u64) (unsigned long) kbuf;
2899 req->flags |= REQ_F_BUFFER_SELECTED;
2900 return u64_to_user_ptr(kbuf->addr);
2903 #ifdef CONFIG_COMPAT
2904 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2907 struct compat_iovec __user *uiov;
2908 compat_ssize_t clen;
2912 uiov = u64_to_user_ptr(req->rw.addr);
2913 if (!access_ok(uiov, sizeof(*uiov)))
2915 if (__get_user(clen, &uiov->iov_len))
2921 buf = io_rw_buffer_select(req, &len, needs_lock);
2923 return PTR_ERR(buf);
2924 iov[0].iov_base = buf;
2925 iov[0].iov_len = (compat_size_t) len;
2930 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2933 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2937 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2940 len = iov[0].iov_len;
2943 buf = io_rw_buffer_select(req, &len, needs_lock);
2945 return PTR_ERR(buf);
2946 iov[0].iov_base = buf;
2947 iov[0].iov_len = len;
2951 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2954 if (req->flags & REQ_F_BUFFER_SELECTED) {
2955 struct io_buffer *kbuf;
2957 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2958 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2959 iov[0].iov_len = kbuf->len;
2962 if (req->rw.len != 1)
2965 #ifdef CONFIG_COMPAT
2966 if (req->ctx->compat)
2967 return io_compat_import(req, iov, needs_lock);
2970 return __io_iov_buffer_select(req, iov, needs_lock);
2973 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2974 struct iov_iter *iter, bool needs_lock)
2976 void __user *buf = u64_to_user_ptr(req->rw.addr);
2977 size_t sqe_len = req->rw.len;
2978 u8 opcode = req->opcode;
2981 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2983 return io_import_fixed(req, rw, iter);
2986 /* buffer index only valid with fixed read/write, or buffer select */
2987 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2990 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2991 if (req->flags & REQ_F_BUFFER_SELECT) {
2992 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2994 return PTR_ERR(buf);
2995 req->rw.len = sqe_len;
2998 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3003 if (req->flags & REQ_F_BUFFER_SELECT) {
3004 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3006 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3011 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3015 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3017 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3021 * For files that don't have ->read_iter() and ->write_iter(), handle them
3022 * by looping over ->read() or ->write() manually.
3024 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3026 struct kiocb *kiocb = &req->rw.kiocb;
3027 struct file *file = req->file;
3031 * Don't support polled IO through this interface, and we can't
3032 * support non-blocking either. For the latter, this just causes
3033 * the kiocb to be handled from an async context.
3035 if (kiocb->ki_flags & IOCB_HIPRI)
3037 if (kiocb->ki_flags & IOCB_NOWAIT)
3040 while (iov_iter_count(iter)) {
3044 if (!iov_iter_is_bvec(iter)) {
3045 iovec = iov_iter_iovec(iter);
3047 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3048 iovec.iov_len = req->rw.len;
3052 nr = file->f_op->read(file, iovec.iov_base,
3053 iovec.iov_len, io_kiocb_ppos(kiocb));
3055 nr = file->f_op->write(file, iovec.iov_base,
3056 iovec.iov_len, io_kiocb_ppos(kiocb));
3065 if (nr != iovec.iov_len)
3069 iov_iter_advance(iter, nr);
3075 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3076 const struct iovec *fast_iov, struct iov_iter *iter)
3078 struct io_async_rw *rw = req->async_data;
3080 memcpy(&rw->iter, iter, sizeof(*iter));
3081 rw->free_iovec = iovec;
3083 /* can only be fixed buffers, no need to do anything */
3084 if (iov_iter_is_bvec(iter))
3087 unsigned iov_off = 0;
3089 rw->iter.iov = rw->fast_iov;
3090 if (iter->iov != fast_iov) {
3091 iov_off = iter->iov - fast_iov;
3092 rw->iter.iov += iov_off;
3094 if (rw->fast_iov != fast_iov)
3095 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3096 sizeof(struct iovec) * iter->nr_segs);
3098 req->flags |= REQ_F_NEED_CLEANUP;
3102 static inline int io_alloc_async_data(struct io_kiocb *req)
3104 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3105 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3106 return req->async_data == NULL;
3109 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3110 const struct iovec *fast_iov,
3111 struct iov_iter *iter, bool force)
3113 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3115 if (!req->async_data) {
3116 if (io_alloc_async_data(req)) {
3121 io_req_map_rw(req, iovec, fast_iov, iter);
3126 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3128 struct io_async_rw *iorw = req->async_data;
3129 struct iovec *iov = iorw->fast_iov;
3132 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3133 if (unlikely(ret < 0))
3136 iorw->bytes_done = 0;
3137 iorw->free_iovec = iov;
3139 req->flags |= REQ_F_NEED_CLEANUP;
3143 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3145 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3147 return io_prep_rw(req, sqe);
3151 * This is our waitqueue callback handler, registered through lock_page_async()
3152 * when we initially tried to do the IO with the iocb armed our waitqueue.
3153 * This gets called when the page is unlocked, and we generally expect that to
3154 * happen when the page IO is completed and the page is now uptodate. This will
3155 * queue a task_work based retry of the operation, attempting to copy the data
3156 * again. If the latter fails because the page was NOT uptodate, then we will
3157 * do a thread based blocking retry of the operation. That's the unexpected
3160 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3161 int sync, void *arg)
3163 struct wait_page_queue *wpq;
3164 struct io_kiocb *req = wait->private;
3165 struct wait_page_key *key = arg;
3167 wpq = container_of(wait, struct wait_page_queue, wait);
3169 if (!wake_page_match(wpq, key))
3172 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3173 list_del_init(&wait->entry);
3175 /* submit ref gets dropped, acquire a new one */
3177 io_req_task_queue(req);
3182 * This controls whether a given IO request should be armed for async page
3183 * based retry. If we return false here, the request is handed to the async
3184 * worker threads for retry. If we're doing buffered reads on a regular file,
3185 * we prepare a private wait_page_queue entry and retry the operation. This
3186 * will either succeed because the page is now uptodate and unlocked, or it
3187 * will register a callback when the page is unlocked at IO completion. Through
3188 * that callback, io_uring uses task_work to setup a retry of the operation.
3189 * That retry will attempt the buffered read again. The retry will generally
3190 * succeed, or in rare cases where it fails, we then fall back to using the
3191 * async worker threads for a blocking retry.
3193 static bool io_rw_should_retry(struct io_kiocb *req)
3195 struct io_async_rw *rw = req->async_data;
3196 struct wait_page_queue *wait = &rw->wpq;
3197 struct kiocb *kiocb = &req->rw.kiocb;
3199 /* never retry for NOWAIT, we just complete with -EAGAIN */
3200 if (req->flags & REQ_F_NOWAIT)
3203 /* Only for buffered IO */
3204 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3208 * just use poll if we can, and don't attempt if the fs doesn't
3209 * support callback based unlocks
3211 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3214 wait->wait.func = io_async_buf_func;
3215 wait->wait.private = req;
3216 wait->wait.flags = 0;
3217 INIT_LIST_HEAD(&wait->wait.entry);
3218 kiocb->ki_flags |= IOCB_WAITQ;
3219 kiocb->ki_flags &= ~IOCB_NOWAIT;
3220 kiocb->ki_waitq = wait;
3224 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3226 if (req->file->f_op->read_iter)
3227 return call_read_iter(req->file, &req->rw.kiocb, iter);
3228 else if (req->file->f_op->read)
3229 return loop_rw_iter(READ, req, iter);
3234 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3236 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3237 struct kiocb *kiocb = &req->rw.kiocb;
3238 struct iov_iter __iter, *iter = &__iter;
3239 struct io_async_rw *rw = req->async_data;
3240 ssize_t io_size, ret, ret2;
3241 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3247 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3251 io_size = iov_iter_count(iter);
3252 req->result = io_size;
3254 /* Ensure we clear previously set non-block flag */
3255 if (!force_nonblock)
3256 kiocb->ki_flags &= ~IOCB_NOWAIT;
3258 kiocb->ki_flags |= IOCB_NOWAIT;
3260 /* If the file doesn't support async, just async punt */
3261 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3262 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3263 return ret ?: -EAGAIN;
3266 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3267 if (unlikely(ret)) {
3272 ret = io_iter_do_read(req, iter);
3274 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3275 req->flags &= ~REQ_F_REISSUE;
3276 /* IOPOLL retry should happen for io-wq threads */
3277 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3279 /* no retry on NONBLOCK nor RWF_NOWAIT */
3280 if (req->flags & REQ_F_NOWAIT)
3282 /* some cases will consume bytes even on error returns */
3283 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3285 } else if (ret == -EIOCBQUEUED) {
3287 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3288 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3289 /* read all, failed, already did sync or don't want to retry */
3293 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3298 rw = req->async_data;
3299 /* now use our persistent iterator, if we aren't already */
3304 rw->bytes_done += ret;
3305 /* if we can retry, do so with the callbacks armed */
3306 if (!io_rw_should_retry(req)) {
3307 kiocb->ki_flags &= ~IOCB_WAITQ;
3312 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3313 * we get -EIOCBQUEUED, then we'll get a notification when the
3314 * desired page gets unlocked. We can also get a partial read
3315 * here, and if we do, then just retry at the new offset.
3317 ret = io_iter_do_read(req, iter);
3318 if (ret == -EIOCBQUEUED)
3320 /* we got some bytes, but not all. retry. */
3321 kiocb->ki_flags &= ~IOCB_WAITQ;
3322 } while (ret > 0 && ret < io_size);
3324 kiocb_done(kiocb, ret, issue_flags);
3326 /* it's faster to check here then delegate to kfree */
3332 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3334 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3336 return io_prep_rw(req, sqe);
3339 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3341 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3342 struct kiocb *kiocb = &req->rw.kiocb;
3343 struct iov_iter __iter, *iter = &__iter;
3344 struct io_async_rw *rw = req->async_data;
3345 ssize_t ret, ret2, io_size;
3346 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3352 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3356 io_size = iov_iter_count(iter);
3357 req->result = io_size;
3359 /* Ensure we clear previously set non-block flag */
3360 if (!force_nonblock)
3361 kiocb->ki_flags &= ~IOCB_NOWAIT;
3363 kiocb->ki_flags |= IOCB_NOWAIT;
3365 /* If the file doesn't support async, just async punt */
3366 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3369 /* file path doesn't support NOWAIT for non-direct_IO */
3370 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3371 (req->flags & REQ_F_ISREG))
3374 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3379 * Open-code file_start_write here to grab freeze protection,
3380 * which will be released by another thread in
3381 * io_complete_rw(). Fool lockdep by telling it the lock got
3382 * released so that it doesn't complain about the held lock when
3383 * we return to userspace.
3385 if (req->flags & REQ_F_ISREG) {
3386 sb_start_write(file_inode(req->file)->i_sb);
3387 __sb_writers_release(file_inode(req->file)->i_sb,
3390 kiocb->ki_flags |= IOCB_WRITE;
3392 if (req->file->f_op->write_iter)
3393 ret2 = call_write_iter(req->file, kiocb, iter);
3394 else if (req->file->f_op->write)
3395 ret2 = loop_rw_iter(WRITE, req, iter);
3399 if (req->flags & REQ_F_REISSUE) {
3400 req->flags &= ~REQ_F_REISSUE;
3405 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3406 * retry them without IOCB_NOWAIT.
3408 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3410 /* no retry on NONBLOCK nor RWF_NOWAIT */
3411 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3413 if (!force_nonblock || ret2 != -EAGAIN) {
3414 /* IOPOLL retry should happen for io-wq threads */
3415 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3418 kiocb_done(kiocb, ret2, issue_flags);
3421 /* some cases will consume bytes even on error returns */
3422 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3423 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3424 return ret ?: -EAGAIN;
3427 /* it's reportedly faster than delegating the null check to kfree() */
3433 static int io_renameat_prep(struct io_kiocb *req,
3434 const struct io_uring_sqe *sqe)
3436 struct io_rename *ren = &req->rename;
3437 const char __user *oldf, *newf;
3439 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3441 if (sqe->ioprio || sqe->buf_index)
3443 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3446 ren->old_dfd = READ_ONCE(sqe->fd);
3447 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3448 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3449 ren->new_dfd = READ_ONCE(sqe->len);
3450 ren->flags = READ_ONCE(sqe->rename_flags);
3452 ren->oldpath = getname(oldf);
3453 if (IS_ERR(ren->oldpath))
3454 return PTR_ERR(ren->oldpath);
3456 ren->newpath = getname(newf);
3457 if (IS_ERR(ren->newpath)) {
3458 putname(ren->oldpath);
3459 return PTR_ERR(ren->newpath);
3462 req->flags |= REQ_F_NEED_CLEANUP;
3466 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3468 struct io_rename *ren = &req->rename;
3471 if (issue_flags & IO_URING_F_NONBLOCK)
3474 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3475 ren->newpath, ren->flags);
3477 req->flags &= ~REQ_F_NEED_CLEANUP;
3480 io_req_complete(req, ret);
3484 static int io_unlinkat_prep(struct io_kiocb *req,
3485 const struct io_uring_sqe *sqe)
3487 struct io_unlink *un = &req->unlink;
3488 const char __user *fname;
3490 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3492 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3494 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3497 un->dfd = READ_ONCE(sqe->fd);
3499 un->flags = READ_ONCE(sqe->unlink_flags);
3500 if (un->flags & ~AT_REMOVEDIR)
3503 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3504 un->filename = getname(fname);
3505 if (IS_ERR(un->filename))
3506 return PTR_ERR(un->filename);
3508 req->flags |= REQ_F_NEED_CLEANUP;
3512 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3514 struct io_unlink *un = &req->unlink;
3517 if (issue_flags & IO_URING_F_NONBLOCK)
3520 if (un->flags & AT_REMOVEDIR)
3521 ret = do_rmdir(un->dfd, un->filename);
3523 ret = do_unlinkat(un->dfd, un->filename);
3525 req->flags &= ~REQ_F_NEED_CLEANUP;
3528 io_req_complete(req, ret);
3532 static int io_shutdown_prep(struct io_kiocb *req,
3533 const struct io_uring_sqe *sqe)
3535 #if defined(CONFIG_NET)
3536 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3538 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3542 req->shutdown.how = READ_ONCE(sqe->len);
3549 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3551 #if defined(CONFIG_NET)
3552 struct socket *sock;
3555 if (issue_flags & IO_URING_F_NONBLOCK)
3558 sock = sock_from_file(req->file);
3559 if (unlikely(!sock))
3562 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3565 io_req_complete(req, ret);
3572 static int __io_splice_prep(struct io_kiocb *req,
3573 const struct io_uring_sqe *sqe)
3575 struct io_splice *sp = &req->splice;
3576 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3578 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3582 sp->len = READ_ONCE(sqe->len);
3583 sp->flags = READ_ONCE(sqe->splice_flags);
3585 if (unlikely(sp->flags & ~valid_flags))
3588 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3589 (sp->flags & SPLICE_F_FD_IN_FIXED));
3592 req->flags |= REQ_F_NEED_CLEANUP;
3596 static int io_tee_prep(struct io_kiocb *req,
3597 const struct io_uring_sqe *sqe)
3599 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3601 return __io_splice_prep(req, sqe);
3604 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3606 struct io_splice *sp = &req->splice;
3607 struct file *in = sp->file_in;
3608 struct file *out = sp->file_out;
3609 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3612 if (issue_flags & IO_URING_F_NONBLOCK)
3615 ret = do_tee(in, out, sp->len, flags);
3617 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3619 req->flags &= ~REQ_F_NEED_CLEANUP;
3623 io_req_complete(req, ret);
3627 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3629 struct io_splice *sp = &req->splice;
3631 sp->off_in = READ_ONCE(sqe->splice_off_in);
3632 sp->off_out = READ_ONCE(sqe->off);
3633 return __io_splice_prep(req, sqe);
3636 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3638 struct io_splice *sp = &req->splice;
3639 struct file *in = sp->file_in;
3640 struct file *out = sp->file_out;
3641 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3642 loff_t *poff_in, *poff_out;
3645 if (issue_flags & IO_URING_F_NONBLOCK)
3648 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3649 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3652 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3654 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3656 req->flags &= ~REQ_F_NEED_CLEANUP;
3660 io_req_complete(req, ret);
3665 * IORING_OP_NOP just posts a completion event, nothing else.
3667 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3669 struct io_ring_ctx *ctx = req->ctx;
3671 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3674 __io_req_complete(req, issue_flags, 0, 0);
3678 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3680 struct io_ring_ctx *ctx = req->ctx;
3685 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3687 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3690 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3691 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3694 req->sync.off = READ_ONCE(sqe->off);
3695 req->sync.len = READ_ONCE(sqe->len);
3699 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3701 loff_t end = req->sync.off + req->sync.len;
3704 /* fsync always requires a blocking context */
3705 if (issue_flags & IO_URING_F_NONBLOCK)
3708 ret = vfs_fsync_range(req->file, req->sync.off,
3709 end > 0 ? end : LLONG_MAX,
3710 req->sync.flags & IORING_FSYNC_DATASYNC);
3713 io_req_complete(req, ret);
3717 static int io_fallocate_prep(struct io_kiocb *req,
3718 const struct io_uring_sqe *sqe)
3720 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3722 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3725 req->sync.off = READ_ONCE(sqe->off);
3726 req->sync.len = READ_ONCE(sqe->addr);
3727 req->sync.mode = READ_ONCE(sqe->len);
3731 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3735 /* fallocate always requiring blocking context */
3736 if (issue_flags & IO_URING_F_NONBLOCK)
3738 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3742 io_req_complete(req, ret);
3746 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3748 const char __user *fname;
3751 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3753 if (unlikely(sqe->ioprio || sqe->buf_index))
3755 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3758 /* open.how should be already initialised */
3759 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3760 req->open.how.flags |= O_LARGEFILE;
3762 req->open.dfd = READ_ONCE(sqe->fd);
3763 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3764 req->open.filename = getname(fname);
3765 if (IS_ERR(req->open.filename)) {
3766 ret = PTR_ERR(req->open.filename);
3767 req->open.filename = NULL;
3770 req->open.nofile = rlimit(RLIMIT_NOFILE);
3771 req->flags |= REQ_F_NEED_CLEANUP;
3775 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3777 u64 mode = READ_ONCE(sqe->len);
3778 u64 flags = READ_ONCE(sqe->open_flags);
3780 req->open.how = build_open_how(flags, mode);
3781 return __io_openat_prep(req, sqe);
3784 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3786 struct open_how __user *how;
3790 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3791 len = READ_ONCE(sqe->len);
3792 if (len < OPEN_HOW_SIZE_VER0)
3795 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3800 return __io_openat_prep(req, sqe);
3803 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3805 struct open_flags op;
3808 bool resolve_nonblock;
3811 ret = build_open_flags(&req->open.how, &op);
3814 nonblock_set = op.open_flag & O_NONBLOCK;
3815 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3816 if (issue_flags & IO_URING_F_NONBLOCK) {
3818 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3819 * it'll always -EAGAIN
3821 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3823 op.lookup_flags |= LOOKUP_CACHED;
3824 op.open_flag |= O_NONBLOCK;
3827 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3831 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3834 * We could hang on to this 'fd' on retrying, but seems like
3835 * marginal gain for something that is now known to be a slower
3836 * path. So just put it, and we'll get a new one when we retry.
3840 ret = PTR_ERR(file);
3841 /* only retry if RESOLVE_CACHED wasn't already set by application */
3842 if (ret == -EAGAIN &&
3843 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3848 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3849 file->f_flags &= ~O_NONBLOCK;
3850 fsnotify_open(file);
3851 fd_install(ret, file);
3853 putname(req->open.filename);
3854 req->flags &= ~REQ_F_NEED_CLEANUP;
3857 __io_req_complete(req, issue_flags, ret, 0);
3861 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3863 return io_openat2(req, issue_flags);
3866 static int io_remove_buffers_prep(struct io_kiocb *req,
3867 const struct io_uring_sqe *sqe)
3869 struct io_provide_buf *p = &req->pbuf;
3872 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3875 tmp = READ_ONCE(sqe->fd);
3876 if (!tmp || tmp > USHRT_MAX)
3879 memset(p, 0, sizeof(*p));
3881 p->bgid = READ_ONCE(sqe->buf_group);
3885 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3886 int bgid, unsigned nbufs)
3890 /* shouldn't happen */
3894 /* the head kbuf is the list itself */
3895 while (!list_empty(&buf->list)) {
3896 struct io_buffer *nxt;
3898 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3899 list_del(&nxt->list);
3906 xa_erase(&ctx->io_buffers, bgid);
3911 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3913 struct io_provide_buf *p = &req->pbuf;
3914 struct io_ring_ctx *ctx = req->ctx;
3915 struct io_buffer *head;
3917 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3919 io_ring_submit_lock(ctx, !force_nonblock);
3921 lockdep_assert_held(&ctx->uring_lock);
3924 head = xa_load(&ctx->io_buffers, p->bgid);
3926 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3930 /* complete before unlock, IOPOLL may need the lock */
3931 __io_req_complete(req, issue_flags, ret, 0);
3932 io_ring_submit_unlock(ctx, !force_nonblock);
3936 static int io_provide_buffers_prep(struct io_kiocb *req,
3937 const struct io_uring_sqe *sqe)
3939 unsigned long size, tmp_check;
3940 struct io_provide_buf *p = &req->pbuf;
3943 if (sqe->ioprio || sqe->rw_flags)
3946 tmp = READ_ONCE(sqe->fd);
3947 if (!tmp || tmp > USHRT_MAX)
3950 p->addr = READ_ONCE(sqe->addr);
3951 p->len = READ_ONCE(sqe->len);
3953 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3956 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3959 size = (unsigned long)p->len * p->nbufs;
3960 if (!access_ok(u64_to_user_ptr(p->addr), size))
3963 p->bgid = READ_ONCE(sqe->buf_group);
3964 tmp = READ_ONCE(sqe->off);
3965 if (tmp > USHRT_MAX)
3971 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3973 struct io_buffer *buf;
3974 u64 addr = pbuf->addr;
3975 int i, bid = pbuf->bid;
3977 for (i = 0; i < pbuf->nbufs; i++) {
3978 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3983 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3988 INIT_LIST_HEAD(&buf->list);
3991 list_add_tail(&buf->list, &(*head)->list);
3995 return i ? i : -ENOMEM;
3998 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4000 struct io_provide_buf *p = &req->pbuf;
4001 struct io_ring_ctx *ctx = req->ctx;
4002 struct io_buffer *head, *list;
4004 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4006 io_ring_submit_lock(ctx, !force_nonblock);
4008 lockdep_assert_held(&ctx->uring_lock);
4010 list = head = xa_load(&ctx->io_buffers, p->bgid);
4012 ret = io_add_buffers(p, &head);
4013 if (ret >= 0 && !list) {
4014 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4016 __io_remove_buffers(ctx, head, p->bgid, -1U);
4020 /* complete before unlock, IOPOLL may need the lock */
4021 __io_req_complete(req, issue_flags, ret, 0);
4022 io_ring_submit_unlock(ctx, !force_nonblock);
4026 static int io_epoll_ctl_prep(struct io_kiocb *req,
4027 const struct io_uring_sqe *sqe)
4029 #if defined(CONFIG_EPOLL)
4030 if (sqe->ioprio || sqe->buf_index)
4032 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4035 req->epoll.epfd = READ_ONCE(sqe->fd);
4036 req->epoll.op = READ_ONCE(sqe->len);
4037 req->epoll.fd = READ_ONCE(sqe->off);
4039 if (ep_op_has_event(req->epoll.op)) {
4040 struct epoll_event __user *ev;
4042 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4043 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4053 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4055 #if defined(CONFIG_EPOLL)
4056 struct io_epoll *ie = &req->epoll;
4058 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4060 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4061 if (force_nonblock && ret == -EAGAIN)
4066 __io_req_complete(req, issue_flags, ret, 0);
4073 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4075 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4076 if (sqe->ioprio || sqe->buf_index || sqe->off)
4078 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4081 req->madvise.addr = READ_ONCE(sqe->addr);
4082 req->madvise.len = READ_ONCE(sqe->len);
4083 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4090 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4092 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4093 struct io_madvise *ma = &req->madvise;
4096 if (issue_flags & IO_URING_F_NONBLOCK)
4099 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4102 io_req_complete(req, ret);
4109 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4111 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4113 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4116 req->fadvise.offset = READ_ONCE(sqe->off);
4117 req->fadvise.len = READ_ONCE(sqe->len);
4118 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4122 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4124 struct io_fadvise *fa = &req->fadvise;
4127 if (issue_flags & IO_URING_F_NONBLOCK) {
4128 switch (fa->advice) {
4129 case POSIX_FADV_NORMAL:
4130 case POSIX_FADV_RANDOM:
4131 case POSIX_FADV_SEQUENTIAL:
4138 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4141 __io_req_complete(req, issue_flags, ret, 0);
4145 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4147 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4149 if (sqe->ioprio || sqe->buf_index)
4151 if (req->flags & REQ_F_FIXED_FILE)
4154 req->statx.dfd = READ_ONCE(sqe->fd);
4155 req->statx.mask = READ_ONCE(sqe->len);
4156 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4157 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4158 req->statx.flags = READ_ONCE(sqe->statx_flags);
4163 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4165 struct io_statx *ctx = &req->statx;
4168 if (issue_flags & IO_URING_F_NONBLOCK)
4171 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4176 io_req_complete(req, ret);
4180 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4182 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4184 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4185 sqe->rw_flags || sqe->buf_index)
4187 if (req->flags & REQ_F_FIXED_FILE)
4190 req->close.fd = READ_ONCE(sqe->fd);
4194 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4196 struct files_struct *files = current->files;
4197 struct io_close *close = &req->close;
4198 struct fdtable *fdt;
4199 struct file *file = NULL;
4202 spin_lock(&files->file_lock);
4203 fdt = files_fdtable(files);
4204 if (close->fd >= fdt->max_fds) {
4205 spin_unlock(&files->file_lock);
4208 file = fdt->fd[close->fd];
4209 if (!file || file->f_op == &io_uring_fops) {
4210 spin_unlock(&files->file_lock);
4215 /* if the file has a flush method, be safe and punt to async */
4216 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4217 spin_unlock(&files->file_lock);
4221 ret = __close_fd_get_file(close->fd, &file);
4222 spin_unlock(&files->file_lock);
4229 /* No ->flush() or already async, safely close from here */
4230 ret = filp_close(file, current->files);
4236 __io_req_complete(req, issue_flags, ret, 0);
4240 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4242 struct io_ring_ctx *ctx = req->ctx;
4244 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4246 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4249 req->sync.off = READ_ONCE(sqe->off);
4250 req->sync.len = READ_ONCE(sqe->len);
4251 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4255 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4259 /* sync_file_range always requires a blocking context */
4260 if (issue_flags & IO_URING_F_NONBLOCK)
4263 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4267 io_req_complete(req, ret);
4271 #if defined(CONFIG_NET)
4272 static int io_setup_async_msg(struct io_kiocb *req,
4273 struct io_async_msghdr *kmsg)
4275 struct io_async_msghdr *async_msg = req->async_data;
4279 if (io_alloc_async_data(req)) {
4280 kfree(kmsg->free_iov);
4283 async_msg = req->async_data;
4284 req->flags |= REQ_F_NEED_CLEANUP;
4285 memcpy(async_msg, kmsg, sizeof(*kmsg));
4286 async_msg->msg.msg_name = &async_msg->addr;
4287 /* if were using fast_iov, set it to the new one */
4288 if (!async_msg->free_iov)
4289 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4294 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4295 struct io_async_msghdr *iomsg)
4297 iomsg->msg.msg_name = &iomsg->addr;
4298 iomsg->free_iov = iomsg->fast_iov;
4299 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4300 req->sr_msg.msg_flags, &iomsg->free_iov);
4303 static int io_sendmsg_prep_async(struct io_kiocb *req)
4307 ret = io_sendmsg_copy_hdr(req, req->async_data);
4309 req->flags |= REQ_F_NEED_CLEANUP;
4313 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4315 struct io_sr_msg *sr = &req->sr_msg;
4317 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4320 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4321 sr->len = READ_ONCE(sqe->len);
4322 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4323 if (sr->msg_flags & MSG_DONTWAIT)
4324 req->flags |= REQ_F_NOWAIT;
4326 #ifdef CONFIG_COMPAT
4327 if (req->ctx->compat)
4328 sr->msg_flags |= MSG_CMSG_COMPAT;
4333 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4335 struct io_async_msghdr iomsg, *kmsg;
4336 struct socket *sock;
4341 sock = sock_from_file(req->file);
4342 if (unlikely(!sock))
4345 kmsg = req->async_data;
4347 ret = io_sendmsg_copy_hdr(req, &iomsg);
4353 flags = req->sr_msg.msg_flags;
4354 if (issue_flags & IO_URING_F_NONBLOCK)
4355 flags |= MSG_DONTWAIT;
4356 if (flags & MSG_WAITALL)
4357 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4359 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4360 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4361 return io_setup_async_msg(req, kmsg);
4362 if (ret == -ERESTARTSYS)
4365 /* fast path, check for non-NULL to avoid function call */
4367 kfree(kmsg->free_iov);
4368 req->flags &= ~REQ_F_NEED_CLEANUP;
4371 __io_req_complete(req, issue_flags, ret, 0);
4375 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4377 struct io_sr_msg *sr = &req->sr_msg;
4380 struct socket *sock;
4385 sock = sock_from_file(req->file);
4386 if (unlikely(!sock))
4389 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4393 msg.msg_name = NULL;
4394 msg.msg_control = NULL;
4395 msg.msg_controllen = 0;
4396 msg.msg_namelen = 0;
4398 flags = req->sr_msg.msg_flags;
4399 if (issue_flags & IO_URING_F_NONBLOCK)
4400 flags |= MSG_DONTWAIT;
4401 if (flags & MSG_WAITALL)
4402 min_ret = iov_iter_count(&msg.msg_iter);
4404 msg.msg_flags = flags;
4405 ret = sock_sendmsg(sock, &msg);
4406 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4408 if (ret == -ERESTARTSYS)
4413 __io_req_complete(req, issue_flags, ret, 0);
4417 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4418 struct io_async_msghdr *iomsg)
4420 struct io_sr_msg *sr = &req->sr_msg;
4421 struct iovec __user *uiov;
4425 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4426 &iomsg->uaddr, &uiov, &iov_len);
4430 if (req->flags & REQ_F_BUFFER_SELECT) {
4433 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4435 sr->len = iomsg->fast_iov[0].iov_len;
4436 iomsg->free_iov = NULL;
4438 iomsg->free_iov = iomsg->fast_iov;
4439 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4440 &iomsg->free_iov, &iomsg->msg.msg_iter,
4449 #ifdef CONFIG_COMPAT
4450 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4451 struct io_async_msghdr *iomsg)
4453 struct io_sr_msg *sr = &req->sr_msg;
4454 struct compat_iovec __user *uiov;
4459 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4464 uiov = compat_ptr(ptr);
4465 if (req->flags & REQ_F_BUFFER_SELECT) {
4466 compat_ssize_t clen;
4470 if (!access_ok(uiov, sizeof(*uiov)))
4472 if (__get_user(clen, &uiov->iov_len))
4477 iomsg->free_iov = NULL;
4479 iomsg->free_iov = iomsg->fast_iov;
4480 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4481 UIO_FASTIOV, &iomsg->free_iov,
4482 &iomsg->msg.msg_iter, true);
4491 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4492 struct io_async_msghdr *iomsg)
4494 iomsg->msg.msg_name = &iomsg->addr;
4496 #ifdef CONFIG_COMPAT
4497 if (req->ctx->compat)
4498 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4501 return __io_recvmsg_copy_hdr(req, iomsg);
4504 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4507 struct io_sr_msg *sr = &req->sr_msg;
4508 struct io_buffer *kbuf;
4510 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4515 req->flags |= REQ_F_BUFFER_SELECTED;
4519 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4521 return io_put_kbuf(req, req->sr_msg.kbuf);
4524 static int io_recvmsg_prep_async(struct io_kiocb *req)
4528 ret = io_recvmsg_copy_hdr(req, req->async_data);
4530 req->flags |= REQ_F_NEED_CLEANUP;
4534 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4536 struct io_sr_msg *sr = &req->sr_msg;
4538 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4541 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4542 sr->len = READ_ONCE(sqe->len);
4543 sr->bgid = READ_ONCE(sqe->buf_group);
4544 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4545 if (sr->msg_flags & MSG_DONTWAIT)
4546 req->flags |= REQ_F_NOWAIT;
4548 #ifdef CONFIG_COMPAT
4549 if (req->ctx->compat)
4550 sr->msg_flags |= MSG_CMSG_COMPAT;
4555 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4557 struct io_async_msghdr iomsg, *kmsg;
4558 struct socket *sock;
4559 struct io_buffer *kbuf;
4562 int ret, cflags = 0;
4563 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4565 sock = sock_from_file(req->file);
4566 if (unlikely(!sock))
4569 kmsg = req->async_data;
4571 ret = io_recvmsg_copy_hdr(req, &iomsg);
4577 if (req->flags & REQ_F_BUFFER_SELECT) {
4578 kbuf = io_recv_buffer_select(req, !force_nonblock);
4580 return PTR_ERR(kbuf);
4581 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4582 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4583 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4584 1, req->sr_msg.len);
4587 flags = req->sr_msg.msg_flags;
4589 flags |= MSG_DONTWAIT;
4590 if (flags & MSG_WAITALL)
4591 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4593 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4594 kmsg->uaddr, flags);
4595 if (force_nonblock && ret == -EAGAIN)
4596 return io_setup_async_msg(req, kmsg);
4597 if (ret == -ERESTARTSYS)
4600 if (req->flags & REQ_F_BUFFER_SELECTED)
4601 cflags = io_put_recv_kbuf(req);
4602 /* fast path, check for non-NULL to avoid function call */
4604 kfree(kmsg->free_iov);
4605 req->flags &= ~REQ_F_NEED_CLEANUP;
4606 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4608 __io_req_complete(req, issue_flags, ret, cflags);
4612 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4614 struct io_buffer *kbuf;
4615 struct io_sr_msg *sr = &req->sr_msg;
4617 void __user *buf = sr->buf;
4618 struct socket *sock;
4622 int ret, cflags = 0;
4623 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4625 sock = sock_from_file(req->file);
4626 if (unlikely(!sock))
4629 if (req->flags & REQ_F_BUFFER_SELECT) {
4630 kbuf = io_recv_buffer_select(req, !force_nonblock);
4632 return PTR_ERR(kbuf);
4633 buf = u64_to_user_ptr(kbuf->addr);
4636 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4640 msg.msg_name = NULL;
4641 msg.msg_control = NULL;
4642 msg.msg_controllen = 0;
4643 msg.msg_namelen = 0;
4644 msg.msg_iocb = NULL;
4647 flags = req->sr_msg.msg_flags;
4649 flags |= MSG_DONTWAIT;
4650 if (flags & MSG_WAITALL)
4651 min_ret = iov_iter_count(&msg.msg_iter);
4653 ret = sock_recvmsg(sock, &msg, flags);
4654 if (force_nonblock && ret == -EAGAIN)
4656 if (ret == -ERESTARTSYS)
4659 if (req->flags & REQ_F_BUFFER_SELECTED)
4660 cflags = io_put_recv_kbuf(req);
4661 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4663 __io_req_complete(req, issue_flags, ret, cflags);
4667 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4669 struct io_accept *accept = &req->accept;
4671 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4673 if (sqe->ioprio || sqe->len || sqe->buf_index)
4676 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4677 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4678 accept->flags = READ_ONCE(sqe->accept_flags);
4679 accept->nofile = rlimit(RLIMIT_NOFILE);
4683 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4685 struct io_accept *accept = &req->accept;
4686 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4687 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4690 if (req->file->f_flags & O_NONBLOCK)
4691 req->flags |= REQ_F_NOWAIT;
4693 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4694 accept->addr_len, accept->flags,
4696 if (ret == -EAGAIN && force_nonblock)
4699 if (ret == -ERESTARTSYS)
4703 __io_req_complete(req, issue_flags, ret, 0);
4707 static int io_connect_prep_async(struct io_kiocb *req)
4709 struct io_async_connect *io = req->async_data;
4710 struct io_connect *conn = &req->connect;
4712 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4715 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4717 struct io_connect *conn = &req->connect;
4719 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4721 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4724 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4725 conn->addr_len = READ_ONCE(sqe->addr2);
4729 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4731 struct io_async_connect __io, *io;
4732 unsigned file_flags;
4734 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4736 if (req->async_data) {
4737 io = req->async_data;
4739 ret = move_addr_to_kernel(req->connect.addr,
4740 req->connect.addr_len,
4747 file_flags = force_nonblock ? O_NONBLOCK : 0;
4749 ret = __sys_connect_file(req->file, &io->address,
4750 req->connect.addr_len, file_flags);
4751 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4752 if (req->async_data)
4754 if (io_alloc_async_data(req)) {
4758 memcpy(req->async_data, &__io, sizeof(__io));
4761 if (ret == -ERESTARTSYS)
4766 __io_req_complete(req, issue_flags, ret, 0);
4769 #else /* !CONFIG_NET */
4770 #define IO_NETOP_FN(op) \
4771 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4773 return -EOPNOTSUPP; \
4776 #define IO_NETOP_PREP(op) \
4778 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4780 return -EOPNOTSUPP; \
4783 #define IO_NETOP_PREP_ASYNC(op) \
4785 static int io_##op##_prep_async(struct io_kiocb *req) \
4787 return -EOPNOTSUPP; \
4790 IO_NETOP_PREP_ASYNC(sendmsg);
4791 IO_NETOP_PREP_ASYNC(recvmsg);
4792 IO_NETOP_PREP_ASYNC(connect);
4793 IO_NETOP_PREP(accept);
4796 #endif /* CONFIG_NET */
4798 struct io_poll_table {
4799 struct poll_table_struct pt;
4800 struct io_kiocb *req;
4805 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4806 __poll_t mask, io_req_tw_func_t func)
4808 /* for instances that support it check for an event match first: */
4809 if (mask && !(mask & poll->events))
4812 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4814 list_del_init(&poll->wait.entry);
4817 req->io_task_work.func = func;
4820 * If this fails, then the task is exiting. When a task exits, the
4821 * work gets canceled, so just cancel this request as well instead
4822 * of executing it. We can't safely execute it anyway, as we may not
4823 * have the needed state needed for it anyway.
4825 io_req_task_work_add(req);
4829 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4830 __acquires(&req->ctx->completion_lock)
4832 struct io_ring_ctx *ctx = req->ctx;
4834 if (unlikely(req->task->flags & PF_EXITING))
4835 WRITE_ONCE(poll->canceled, true);
4837 if (!req->result && !READ_ONCE(poll->canceled)) {
4838 struct poll_table_struct pt = { ._key = poll->events };
4840 req->result = vfs_poll(req->file, &pt) & poll->events;
4843 spin_lock_irq(&ctx->completion_lock);
4844 if (!req->result && !READ_ONCE(poll->canceled)) {
4845 add_wait_queue(poll->head, &poll->wait);
4852 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4854 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4855 if (req->opcode == IORING_OP_POLL_ADD)
4856 return req->async_data;
4857 return req->apoll->double_poll;
4860 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4862 if (req->opcode == IORING_OP_POLL_ADD)
4864 return &req->apoll->poll;
4867 static void io_poll_remove_double(struct io_kiocb *req)
4868 __must_hold(&req->ctx->completion_lock)
4870 struct io_poll_iocb *poll = io_poll_get_double(req);
4872 lockdep_assert_held(&req->ctx->completion_lock);
4874 if (poll && poll->head) {
4875 struct wait_queue_head *head = poll->head;
4877 spin_lock(&head->lock);
4878 list_del_init(&poll->wait.entry);
4879 if (poll->wait.private)
4882 spin_unlock(&head->lock);
4886 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4887 __must_hold(&req->ctx->completion_lock)
4889 struct io_ring_ctx *ctx = req->ctx;
4890 unsigned flags = IORING_CQE_F_MORE;
4893 if (READ_ONCE(req->poll.canceled)) {
4895 req->poll.events |= EPOLLONESHOT;
4897 error = mangle_poll(mask);
4899 if (req->poll.events & EPOLLONESHOT)
4901 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4902 req->poll.done = true;
4905 if (flags & IORING_CQE_F_MORE)
4908 io_commit_cqring(ctx);
4909 return !(flags & IORING_CQE_F_MORE);
4912 static void io_poll_task_func(struct io_kiocb *req)
4914 struct io_ring_ctx *ctx = req->ctx;
4915 struct io_kiocb *nxt;
4917 if (io_poll_rewait(req, &req->poll)) {
4918 spin_unlock_irq(&ctx->completion_lock);
4922 done = io_poll_complete(req, req->result);
4924 io_poll_remove_double(req);
4925 hash_del(&req->hash_node);
4928 add_wait_queue(req->poll.head, &req->poll.wait);
4930 spin_unlock_irq(&ctx->completion_lock);
4931 io_cqring_ev_posted(ctx);
4934 nxt = io_put_req_find_next(req);
4936 io_req_task_submit(nxt);
4941 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4942 int sync, void *key)
4944 struct io_kiocb *req = wait->private;
4945 struct io_poll_iocb *poll = io_poll_get_single(req);
4946 __poll_t mask = key_to_poll(key);
4948 /* for instances that support it check for an event match first: */
4949 if (mask && !(mask & poll->events))
4951 if (!(poll->events & EPOLLONESHOT))
4952 return poll->wait.func(&poll->wait, mode, sync, key);
4954 list_del_init(&wait->entry);
4959 spin_lock(&poll->head->lock);
4960 done = list_empty(&poll->wait.entry);
4962 list_del_init(&poll->wait.entry);
4963 /* make sure double remove sees this as being gone */
4964 wait->private = NULL;
4965 spin_unlock(&poll->head->lock);
4967 /* use wait func handler, so it matches the rq type */
4968 poll->wait.func(&poll->wait, mode, sync, key);
4975 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4976 wait_queue_func_t wake_func)
4980 poll->canceled = false;
4981 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4982 /* mask in events that we always want/need */
4983 poll->events = events | IO_POLL_UNMASK;
4984 INIT_LIST_HEAD(&poll->wait.entry);
4985 init_waitqueue_func_entry(&poll->wait, wake_func);
4988 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4989 struct wait_queue_head *head,
4990 struct io_poll_iocb **poll_ptr)
4992 struct io_kiocb *req = pt->req;
4995 * The file being polled uses multiple waitqueues for poll handling
4996 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
4999 if (unlikely(pt->nr_entries)) {
5000 struct io_poll_iocb *poll_one = poll;
5002 /* already have a 2nd entry, fail a third attempt */
5004 pt->error = -EINVAL;
5008 * Can't handle multishot for double wait for now, turn it
5009 * into one-shot mode.
5011 if (!(poll_one->events & EPOLLONESHOT))
5012 poll_one->events |= EPOLLONESHOT;
5013 /* double add on the same waitqueue head, ignore */
5014 if (poll_one->head == head)
5016 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5018 pt->error = -ENOMEM;
5021 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5023 poll->wait.private = req;
5030 if (poll->events & EPOLLEXCLUSIVE)
5031 add_wait_queue_exclusive(head, &poll->wait);
5033 add_wait_queue(head, &poll->wait);
5036 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5037 struct poll_table_struct *p)
5039 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5040 struct async_poll *apoll = pt->req->apoll;
5042 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5045 static void io_async_task_func(struct io_kiocb *req)
5047 struct async_poll *apoll = req->apoll;
5048 struct io_ring_ctx *ctx = req->ctx;
5050 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5052 if (io_poll_rewait(req, &apoll->poll)) {
5053 spin_unlock_irq(&ctx->completion_lock);
5057 hash_del(&req->hash_node);
5058 io_poll_remove_double(req);
5059 spin_unlock_irq(&ctx->completion_lock);
5061 if (!READ_ONCE(apoll->poll.canceled))
5062 io_req_task_submit(req);
5064 io_req_complete_failed(req, -ECANCELED);
5067 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5070 struct io_kiocb *req = wait->private;
5071 struct io_poll_iocb *poll = &req->apoll->poll;
5073 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5076 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5079 static void io_poll_req_insert(struct io_kiocb *req)
5081 struct io_ring_ctx *ctx = req->ctx;
5082 struct hlist_head *list;
5084 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5085 hlist_add_head(&req->hash_node, list);
5088 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5089 struct io_poll_iocb *poll,
5090 struct io_poll_table *ipt, __poll_t mask,
5091 wait_queue_func_t wake_func)
5092 __acquires(&ctx->completion_lock)
5094 struct io_ring_ctx *ctx = req->ctx;
5095 bool cancel = false;
5097 INIT_HLIST_NODE(&req->hash_node);
5098 io_init_poll_iocb(poll, mask, wake_func);
5099 poll->file = req->file;
5100 poll->wait.private = req;
5102 ipt->pt._key = mask;
5105 ipt->nr_entries = 0;
5107 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5108 if (unlikely(!ipt->nr_entries) && !ipt->error)
5109 ipt->error = -EINVAL;
5111 spin_lock_irq(&ctx->completion_lock);
5112 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5113 io_poll_remove_double(req);
5114 if (likely(poll->head)) {
5115 spin_lock(&poll->head->lock);
5116 if (unlikely(list_empty(&poll->wait.entry))) {
5122 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5123 list_del_init(&poll->wait.entry);
5125 WRITE_ONCE(poll->canceled, true);
5126 else if (!poll->done) /* actually waiting for an event */
5127 io_poll_req_insert(req);
5128 spin_unlock(&poll->head->lock);
5140 static int io_arm_poll_handler(struct io_kiocb *req)
5142 const struct io_op_def *def = &io_op_defs[req->opcode];
5143 struct io_ring_ctx *ctx = req->ctx;
5144 struct async_poll *apoll;
5145 struct io_poll_table ipt;
5146 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5149 if (!req->file || !file_can_poll(req->file))
5150 return IO_APOLL_ABORTED;
5151 if (req->flags & REQ_F_POLLED)
5152 return IO_APOLL_ABORTED;
5153 if (!def->pollin && !def->pollout)
5154 return IO_APOLL_ABORTED;
5158 mask |= POLLIN | POLLRDNORM;
5160 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5161 if ((req->opcode == IORING_OP_RECVMSG) &&
5162 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5166 mask |= POLLOUT | POLLWRNORM;
5169 /* if we can't nonblock try, then no point in arming a poll handler */
5170 if (!io_file_supports_nowait(req, rw))
5171 return IO_APOLL_ABORTED;
5173 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5174 if (unlikely(!apoll))
5175 return IO_APOLL_ABORTED;
5176 apoll->double_poll = NULL;
5178 req->flags |= REQ_F_POLLED;
5179 ipt.pt._qproc = io_async_queue_proc;
5181 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5183 if (ret || ipt.error) {
5184 spin_unlock_irq(&ctx->completion_lock);
5186 return IO_APOLL_READY;
5187 return IO_APOLL_ABORTED;
5189 spin_unlock_irq(&ctx->completion_lock);
5190 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5191 mask, apoll->poll.events);
5195 static bool __io_poll_remove_one(struct io_kiocb *req,
5196 struct io_poll_iocb *poll, bool do_cancel)
5197 __must_hold(&req->ctx->completion_lock)
5199 bool do_complete = false;
5203 spin_lock(&poll->head->lock);
5205 WRITE_ONCE(poll->canceled, true);
5206 if (!list_empty(&poll->wait.entry)) {
5207 list_del_init(&poll->wait.entry);
5210 spin_unlock(&poll->head->lock);
5211 hash_del(&req->hash_node);
5215 static bool io_poll_remove_one(struct io_kiocb *req)
5216 __must_hold(&req->ctx->completion_lock)
5221 io_poll_remove_double(req);
5222 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5225 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5226 io_commit_cqring(req->ctx);
5229 /* non-poll requests have submit ref still */
5230 refs = 1 + (req->opcode != IORING_OP_POLL_ADD);
5231 io_put_req_deferred(req, refs);
5237 * Returns true if we found and killed one or more poll requests
5239 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5242 struct hlist_node *tmp;
5243 struct io_kiocb *req;
5246 spin_lock_irq(&ctx->completion_lock);
5247 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5248 struct hlist_head *list;
5250 list = &ctx->cancel_hash[i];
5251 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5252 if (io_match_task(req, tsk, cancel_all))
5253 posted += io_poll_remove_one(req);
5256 spin_unlock_irq(&ctx->completion_lock);
5259 io_cqring_ev_posted(ctx);
5264 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5266 __must_hold(&ctx->completion_lock)
5268 struct hlist_head *list;
5269 struct io_kiocb *req;
5271 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5272 hlist_for_each_entry(req, list, hash_node) {
5273 if (sqe_addr != req->user_data)
5275 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5282 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5284 __must_hold(&ctx->completion_lock)
5286 struct io_kiocb *req;
5288 req = io_poll_find(ctx, sqe_addr, poll_only);
5291 if (io_poll_remove_one(req))
5297 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5302 events = READ_ONCE(sqe->poll32_events);
5304 events = swahw32(events);
5306 if (!(flags & IORING_POLL_ADD_MULTI))
5307 events |= EPOLLONESHOT;
5308 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5311 static int io_poll_update_prep(struct io_kiocb *req,
5312 const struct io_uring_sqe *sqe)
5314 struct io_poll_update *upd = &req->poll_update;
5317 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5319 if (sqe->ioprio || sqe->buf_index)
5321 flags = READ_ONCE(sqe->len);
5322 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5323 IORING_POLL_ADD_MULTI))
5325 /* meaningless without update */
5326 if (flags == IORING_POLL_ADD_MULTI)
5329 upd->old_user_data = READ_ONCE(sqe->addr);
5330 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5331 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5333 upd->new_user_data = READ_ONCE(sqe->off);
5334 if (!upd->update_user_data && upd->new_user_data)
5336 if (upd->update_events)
5337 upd->events = io_poll_parse_events(sqe, flags);
5338 else if (sqe->poll32_events)
5344 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5347 struct io_kiocb *req = wait->private;
5348 struct io_poll_iocb *poll = &req->poll;
5350 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5353 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5354 struct poll_table_struct *p)
5356 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5358 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5361 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5363 struct io_poll_iocb *poll = &req->poll;
5366 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5368 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5370 flags = READ_ONCE(sqe->len);
5371 if (flags & ~IORING_POLL_ADD_MULTI)
5374 poll->events = io_poll_parse_events(sqe, flags);
5378 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5380 struct io_poll_iocb *poll = &req->poll;
5381 struct io_ring_ctx *ctx = req->ctx;
5382 struct io_poll_table ipt;
5385 ipt.pt._qproc = io_poll_queue_proc;
5387 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5390 if (mask) { /* no async, we'd stolen it */
5392 io_poll_complete(req, mask);
5394 spin_unlock_irq(&ctx->completion_lock);
5397 io_cqring_ev_posted(ctx);
5398 if (poll->events & EPOLLONESHOT)
5404 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5406 struct io_ring_ctx *ctx = req->ctx;
5407 struct io_kiocb *preq;
5411 spin_lock_irq(&ctx->completion_lock);
5412 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5418 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5420 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5425 * Don't allow racy completion with singleshot, as we cannot safely
5426 * update those. For multishot, if we're racing with completion, just
5427 * let completion re-add it.
5429 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5430 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5434 /* we now have a detached poll request. reissue. */
5438 spin_unlock_irq(&ctx->completion_lock);
5440 io_req_complete(req, ret);
5443 /* only mask one event flags, keep behavior flags */
5444 if (req->poll_update.update_events) {
5445 preq->poll.events &= ~0xffff;
5446 preq->poll.events |= req->poll_update.events & 0xffff;
5447 preq->poll.events |= IO_POLL_UNMASK;
5449 if (req->poll_update.update_user_data)
5450 preq->user_data = req->poll_update.new_user_data;
5451 spin_unlock_irq(&ctx->completion_lock);
5453 /* complete update request, we're done with it */
5454 io_req_complete(req, ret);
5457 ret = io_poll_add(preq, issue_flags);
5460 io_req_complete(preq, ret);
5466 static void io_req_task_timeout(struct io_kiocb *req)
5468 struct io_ring_ctx *ctx = req->ctx;
5470 spin_lock_irq(&ctx->completion_lock);
5471 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5472 io_commit_cqring(ctx);
5473 spin_unlock_irq(&ctx->completion_lock);
5475 io_cqring_ev_posted(ctx);
5480 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5482 struct io_timeout_data *data = container_of(timer,
5483 struct io_timeout_data, timer);
5484 struct io_kiocb *req = data->req;
5485 struct io_ring_ctx *ctx = req->ctx;
5486 unsigned long flags;
5488 spin_lock_irqsave(&ctx->timeout_lock, flags);
5489 list_del_init(&req->timeout.list);
5490 atomic_set(&req->ctx->cq_timeouts,
5491 atomic_read(&req->ctx->cq_timeouts) + 1);
5492 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5494 req->io_task_work.func = io_req_task_timeout;
5495 io_req_task_work_add(req);
5496 return HRTIMER_NORESTART;
5499 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5501 __must_hold(&ctx->timeout_lock)
5503 struct io_timeout_data *io;
5504 struct io_kiocb *req;
5507 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5508 found = user_data == req->user_data;
5513 return ERR_PTR(-ENOENT);
5515 io = req->async_data;
5516 if (hrtimer_try_to_cancel(&io->timer) == -1)
5517 return ERR_PTR(-EALREADY);
5518 list_del_init(&req->timeout.list);
5522 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5523 __must_hold(&ctx->timeout_lock)
5525 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5528 return PTR_ERR(req);
5531 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5532 io_put_req_deferred(req, 1);
5536 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5537 struct timespec64 *ts, enum hrtimer_mode mode)
5538 __must_hold(&ctx->timeout_lock)
5540 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5541 struct io_timeout_data *data;
5544 return PTR_ERR(req);
5546 req->timeout.off = 0; /* noseq */
5547 data = req->async_data;
5548 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5549 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5550 data->timer.function = io_timeout_fn;
5551 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5555 static int io_timeout_remove_prep(struct io_kiocb *req,
5556 const struct io_uring_sqe *sqe)
5558 struct io_timeout_rem *tr = &req->timeout_rem;
5560 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5562 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5564 if (sqe->ioprio || sqe->buf_index || sqe->len)
5567 tr->addr = READ_ONCE(sqe->addr);
5568 tr->flags = READ_ONCE(sqe->timeout_flags);
5569 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5570 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5572 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5574 } else if (tr->flags) {
5575 /* timeout removal doesn't support flags */
5582 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5584 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5589 * Remove or update an existing timeout command
5591 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5593 struct io_timeout_rem *tr = &req->timeout_rem;
5594 struct io_ring_ctx *ctx = req->ctx;
5597 spin_lock_irq(&ctx->timeout_lock);
5598 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5599 ret = io_timeout_cancel(ctx, tr->addr);
5601 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5602 io_translate_timeout_mode(tr->flags));
5603 spin_unlock_irq(&ctx->timeout_lock);
5605 spin_lock_irq(&ctx->completion_lock);
5606 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5607 io_commit_cqring(ctx);
5608 spin_unlock_irq(&ctx->completion_lock);
5609 io_cqring_ev_posted(ctx);
5616 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5617 bool is_timeout_link)
5619 struct io_timeout_data *data;
5621 u32 off = READ_ONCE(sqe->off);
5623 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5625 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5627 if (off && is_timeout_link)
5629 flags = READ_ONCE(sqe->timeout_flags);
5630 if (flags & ~IORING_TIMEOUT_ABS)
5633 req->timeout.off = off;
5634 if (unlikely(off && !req->ctx->off_timeout_used))
5635 req->ctx->off_timeout_used = true;
5637 if (!req->async_data && io_alloc_async_data(req))
5640 data = req->async_data;
5643 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5646 data->mode = io_translate_timeout_mode(flags);
5647 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5648 if (is_timeout_link)
5649 io_req_track_inflight(req);
5653 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5655 struct io_ring_ctx *ctx = req->ctx;
5656 struct io_timeout_data *data = req->async_data;
5657 struct list_head *entry;
5658 u32 tail, off = req->timeout.off;
5660 spin_lock_irq(&ctx->timeout_lock);
5663 * sqe->off holds how many events that need to occur for this
5664 * timeout event to be satisfied. If it isn't set, then this is
5665 * a pure timeout request, sequence isn't used.
5667 if (io_is_timeout_noseq(req)) {
5668 entry = ctx->timeout_list.prev;
5672 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5673 req->timeout.target_seq = tail + off;
5675 /* Update the last seq here in case io_flush_timeouts() hasn't.
5676 * This is safe because ->completion_lock is held, and submissions
5677 * and completions are never mixed in the same ->completion_lock section.
5679 ctx->cq_last_tm_flush = tail;
5682 * Insertion sort, ensuring the first entry in the list is always
5683 * the one we need first.
5685 list_for_each_prev(entry, &ctx->timeout_list) {
5686 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5689 if (io_is_timeout_noseq(nxt))
5691 /* nxt.seq is behind @tail, otherwise would've been completed */
5692 if (off >= nxt->timeout.target_seq - tail)
5696 list_add(&req->timeout.list, entry);
5697 data->timer.function = io_timeout_fn;
5698 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5699 spin_unlock_irq(&ctx->timeout_lock);
5703 struct io_cancel_data {
5704 struct io_ring_ctx *ctx;
5708 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5710 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5711 struct io_cancel_data *cd = data;
5713 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5716 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5717 struct io_ring_ctx *ctx)
5719 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5720 enum io_wq_cancel cancel_ret;
5723 if (!tctx || !tctx->io_wq)
5726 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5727 switch (cancel_ret) {
5728 case IO_WQ_CANCEL_OK:
5731 case IO_WQ_CANCEL_RUNNING:
5734 case IO_WQ_CANCEL_NOTFOUND:
5742 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5743 struct io_kiocb *req, __u64 sqe_addr,
5746 unsigned long flags;
5749 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5750 spin_lock_irqsave(&ctx->completion_lock, flags);
5753 spin_lock(&ctx->timeout_lock);
5754 ret = io_timeout_cancel(ctx, sqe_addr);
5755 spin_unlock(&ctx->timeout_lock);
5758 ret = io_poll_cancel(ctx, sqe_addr, false);
5762 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5763 io_commit_cqring(ctx);
5764 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5765 io_cqring_ev_posted(ctx);
5771 static int io_async_cancel_prep(struct io_kiocb *req,
5772 const struct io_uring_sqe *sqe)
5774 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5776 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5778 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5781 req->cancel.addr = READ_ONCE(sqe->addr);
5785 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5787 struct io_ring_ctx *ctx = req->ctx;
5788 u64 sqe_addr = req->cancel.addr;
5789 struct io_tctx_node *node;
5792 /* tasks should wait for their io-wq threads, so safe w/o sync */
5793 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5794 spin_lock_irq(&ctx->completion_lock);
5797 spin_lock(&ctx->timeout_lock);
5798 ret = io_timeout_cancel(ctx, sqe_addr);
5799 spin_unlock(&ctx->timeout_lock);
5802 ret = io_poll_cancel(ctx, sqe_addr, false);
5805 spin_unlock_irq(&ctx->completion_lock);
5807 /* slow path, try all io-wq's */
5808 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5810 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5811 struct io_uring_task *tctx = node->task->io_uring;
5813 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5817 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5819 spin_lock_irq(&ctx->completion_lock);
5821 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5822 io_commit_cqring(ctx);
5823 spin_unlock_irq(&ctx->completion_lock);
5824 io_cqring_ev_posted(ctx);
5832 static int io_rsrc_update_prep(struct io_kiocb *req,
5833 const struct io_uring_sqe *sqe)
5835 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5837 if (sqe->ioprio || sqe->rw_flags)
5840 req->rsrc_update.offset = READ_ONCE(sqe->off);
5841 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5842 if (!req->rsrc_update.nr_args)
5844 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5848 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5850 struct io_ring_ctx *ctx = req->ctx;
5851 struct io_uring_rsrc_update2 up;
5854 if (issue_flags & IO_URING_F_NONBLOCK)
5857 up.offset = req->rsrc_update.offset;
5858 up.data = req->rsrc_update.arg;
5863 mutex_lock(&ctx->uring_lock);
5864 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5865 &up, req->rsrc_update.nr_args);
5866 mutex_unlock(&ctx->uring_lock);
5870 __io_req_complete(req, issue_flags, ret, 0);
5874 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5876 switch (req->opcode) {
5879 case IORING_OP_READV:
5880 case IORING_OP_READ_FIXED:
5881 case IORING_OP_READ:
5882 return io_read_prep(req, sqe);
5883 case IORING_OP_WRITEV:
5884 case IORING_OP_WRITE_FIXED:
5885 case IORING_OP_WRITE:
5886 return io_write_prep(req, sqe);
5887 case IORING_OP_POLL_ADD:
5888 return io_poll_add_prep(req, sqe);
5889 case IORING_OP_POLL_REMOVE:
5890 return io_poll_update_prep(req, sqe);
5891 case IORING_OP_FSYNC:
5892 return io_fsync_prep(req, sqe);
5893 case IORING_OP_SYNC_FILE_RANGE:
5894 return io_sfr_prep(req, sqe);
5895 case IORING_OP_SENDMSG:
5896 case IORING_OP_SEND:
5897 return io_sendmsg_prep(req, sqe);
5898 case IORING_OP_RECVMSG:
5899 case IORING_OP_RECV:
5900 return io_recvmsg_prep(req, sqe);
5901 case IORING_OP_CONNECT:
5902 return io_connect_prep(req, sqe);
5903 case IORING_OP_TIMEOUT:
5904 return io_timeout_prep(req, sqe, false);
5905 case IORING_OP_TIMEOUT_REMOVE:
5906 return io_timeout_remove_prep(req, sqe);
5907 case IORING_OP_ASYNC_CANCEL:
5908 return io_async_cancel_prep(req, sqe);
5909 case IORING_OP_LINK_TIMEOUT:
5910 return io_timeout_prep(req, sqe, true);
5911 case IORING_OP_ACCEPT:
5912 return io_accept_prep(req, sqe);
5913 case IORING_OP_FALLOCATE:
5914 return io_fallocate_prep(req, sqe);
5915 case IORING_OP_OPENAT:
5916 return io_openat_prep(req, sqe);
5917 case IORING_OP_CLOSE:
5918 return io_close_prep(req, sqe);
5919 case IORING_OP_FILES_UPDATE:
5920 return io_rsrc_update_prep(req, sqe);
5921 case IORING_OP_STATX:
5922 return io_statx_prep(req, sqe);
5923 case IORING_OP_FADVISE:
5924 return io_fadvise_prep(req, sqe);
5925 case IORING_OP_MADVISE:
5926 return io_madvise_prep(req, sqe);
5927 case IORING_OP_OPENAT2:
5928 return io_openat2_prep(req, sqe);
5929 case IORING_OP_EPOLL_CTL:
5930 return io_epoll_ctl_prep(req, sqe);
5931 case IORING_OP_SPLICE:
5932 return io_splice_prep(req, sqe);
5933 case IORING_OP_PROVIDE_BUFFERS:
5934 return io_provide_buffers_prep(req, sqe);
5935 case IORING_OP_REMOVE_BUFFERS:
5936 return io_remove_buffers_prep(req, sqe);
5938 return io_tee_prep(req, sqe);
5939 case IORING_OP_SHUTDOWN:
5940 return io_shutdown_prep(req, sqe);
5941 case IORING_OP_RENAMEAT:
5942 return io_renameat_prep(req, sqe);
5943 case IORING_OP_UNLINKAT:
5944 return io_unlinkat_prep(req, sqe);
5947 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5952 static int io_req_prep_async(struct io_kiocb *req)
5954 if (!io_op_defs[req->opcode].needs_async_setup)
5956 if (WARN_ON_ONCE(req->async_data))
5958 if (io_alloc_async_data(req))
5961 switch (req->opcode) {
5962 case IORING_OP_READV:
5963 return io_rw_prep_async(req, READ);
5964 case IORING_OP_WRITEV:
5965 return io_rw_prep_async(req, WRITE);
5966 case IORING_OP_SENDMSG:
5967 return io_sendmsg_prep_async(req);
5968 case IORING_OP_RECVMSG:
5969 return io_recvmsg_prep_async(req);
5970 case IORING_OP_CONNECT:
5971 return io_connect_prep_async(req);
5973 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5978 static u32 io_get_sequence(struct io_kiocb *req)
5980 u32 seq = req->ctx->cached_sq_head;
5982 /* need original cached_sq_head, but it was increased for each req */
5983 io_for_each_link(req, req)
5988 static bool io_drain_req(struct io_kiocb *req)
5990 struct io_kiocb *pos;
5991 struct io_ring_ctx *ctx = req->ctx;
5992 struct io_defer_entry *de;
5997 * If we need to drain a request in the middle of a link, drain the
5998 * head request and the next request/link after the current link.
5999 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6000 * maintained for every request of our link.
6002 if (ctx->drain_next) {
6003 req->flags |= REQ_F_IO_DRAIN;
6004 ctx->drain_next = false;
6006 /* not interested in head, start from the first linked */
6007 io_for_each_link(pos, req->link) {
6008 if (pos->flags & REQ_F_IO_DRAIN) {
6009 ctx->drain_next = true;
6010 req->flags |= REQ_F_IO_DRAIN;
6015 /* Still need defer if there is pending req in defer list. */
6016 if (likely(list_empty_careful(&ctx->defer_list) &&
6017 !(req->flags & REQ_F_IO_DRAIN))) {
6018 ctx->drain_active = false;
6022 seq = io_get_sequence(req);
6023 /* Still a chance to pass the sequence check */
6024 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6027 ret = io_req_prep_async(req);
6030 io_prep_async_link(req);
6031 de = kmalloc(sizeof(*de), GFP_KERNEL);
6035 io_req_complete_failed(req, ret);
6039 spin_lock_irq(&ctx->completion_lock);
6040 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6041 spin_unlock_irq(&ctx->completion_lock);
6043 io_queue_async_work(req);
6047 trace_io_uring_defer(ctx, req, req->user_data);
6050 list_add_tail(&de->list, &ctx->defer_list);
6051 spin_unlock_irq(&ctx->completion_lock);
6055 static void io_clean_op(struct io_kiocb *req)
6057 if (req->flags & REQ_F_BUFFER_SELECTED) {
6058 switch (req->opcode) {
6059 case IORING_OP_READV:
6060 case IORING_OP_READ_FIXED:
6061 case IORING_OP_READ:
6062 kfree((void *)(unsigned long)req->rw.addr);
6064 case IORING_OP_RECVMSG:
6065 case IORING_OP_RECV:
6066 kfree(req->sr_msg.kbuf);
6071 if (req->flags & REQ_F_NEED_CLEANUP) {
6072 switch (req->opcode) {
6073 case IORING_OP_READV:
6074 case IORING_OP_READ_FIXED:
6075 case IORING_OP_READ:
6076 case IORING_OP_WRITEV:
6077 case IORING_OP_WRITE_FIXED:
6078 case IORING_OP_WRITE: {
6079 struct io_async_rw *io = req->async_data;
6081 kfree(io->free_iovec);
6084 case IORING_OP_RECVMSG:
6085 case IORING_OP_SENDMSG: {
6086 struct io_async_msghdr *io = req->async_data;
6088 kfree(io->free_iov);
6091 case IORING_OP_SPLICE:
6093 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6094 io_put_file(req->splice.file_in);
6096 case IORING_OP_OPENAT:
6097 case IORING_OP_OPENAT2:
6098 if (req->open.filename)
6099 putname(req->open.filename);
6101 case IORING_OP_RENAMEAT:
6102 putname(req->rename.oldpath);
6103 putname(req->rename.newpath);
6105 case IORING_OP_UNLINKAT:
6106 putname(req->unlink.filename);
6110 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6111 kfree(req->apoll->double_poll);
6115 if (req->flags & REQ_F_INFLIGHT) {
6116 struct io_uring_task *tctx = req->task->io_uring;
6118 atomic_dec(&tctx->inflight_tracked);
6120 if (req->flags & REQ_F_CREDS)
6121 put_cred(req->creds);
6123 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6126 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6128 struct io_ring_ctx *ctx = req->ctx;
6129 const struct cred *creds = NULL;
6132 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6133 creds = override_creds(req->creds);
6135 switch (req->opcode) {
6137 ret = io_nop(req, issue_flags);
6139 case IORING_OP_READV:
6140 case IORING_OP_READ_FIXED:
6141 case IORING_OP_READ:
6142 ret = io_read(req, issue_flags);
6144 case IORING_OP_WRITEV:
6145 case IORING_OP_WRITE_FIXED:
6146 case IORING_OP_WRITE:
6147 ret = io_write(req, issue_flags);
6149 case IORING_OP_FSYNC:
6150 ret = io_fsync(req, issue_flags);
6152 case IORING_OP_POLL_ADD:
6153 ret = io_poll_add(req, issue_flags);
6155 case IORING_OP_POLL_REMOVE:
6156 ret = io_poll_update(req, issue_flags);
6158 case IORING_OP_SYNC_FILE_RANGE:
6159 ret = io_sync_file_range(req, issue_flags);
6161 case IORING_OP_SENDMSG:
6162 ret = io_sendmsg(req, issue_flags);
6164 case IORING_OP_SEND:
6165 ret = io_send(req, issue_flags);
6167 case IORING_OP_RECVMSG:
6168 ret = io_recvmsg(req, issue_flags);
6170 case IORING_OP_RECV:
6171 ret = io_recv(req, issue_flags);
6173 case IORING_OP_TIMEOUT:
6174 ret = io_timeout(req, issue_flags);
6176 case IORING_OP_TIMEOUT_REMOVE:
6177 ret = io_timeout_remove(req, issue_flags);
6179 case IORING_OP_ACCEPT:
6180 ret = io_accept(req, issue_flags);
6182 case IORING_OP_CONNECT:
6183 ret = io_connect(req, issue_flags);
6185 case IORING_OP_ASYNC_CANCEL:
6186 ret = io_async_cancel(req, issue_flags);
6188 case IORING_OP_FALLOCATE:
6189 ret = io_fallocate(req, issue_flags);
6191 case IORING_OP_OPENAT:
6192 ret = io_openat(req, issue_flags);
6194 case IORING_OP_CLOSE:
6195 ret = io_close(req, issue_flags);
6197 case IORING_OP_FILES_UPDATE:
6198 ret = io_files_update(req, issue_flags);
6200 case IORING_OP_STATX:
6201 ret = io_statx(req, issue_flags);
6203 case IORING_OP_FADVISE:
6204 ret = io_fadvise(req, issue_flags);
6206 case IORING_OP_MADVISE:
6207 ret = io_madvise(req, issue_flags);
6209 case IORING_OP_OPENAT2:
6210 ret = io_openat2(req, issue_flags);
6212 case IORING_OP_EPOLL_CTL:
6213 ret = io_epoll_ctl(req, issue_flags);
6215 case IORING_OP_SPLICE:
6216 ret = io_splice(req, issue_flags);
6218 case IORING_OP_PROVIDE_BUFFERS:
6219 ret = io_provide_buffers(req, issue_flags);
6221 case IORING_OP_REMOVE_BUFFERS:
6222 ret = io_remove_buffers(req, issue_flags);
6225 ret = io_tee(req, issue_flags);
6227 case IORING_OP_SHUTDOWN:
6228 ret = io_shutdown(req, issue_flags);
6230 case IORING_OP_RENAMEAT:
6231 ret = io_renameat(req, issue_flags);
6233 case IORING_OP_UNLINKAT:
6234 ret = io_unlinkat(req, issue_flags);
6242 revert_creds(creds);
6245 /* If the op doesn't have a file, we're not polling for it */
6246 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6247 io_iopoll_req_issued(req);
6252 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6254 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6256 req = io_put_req_find_next(req);
6257 return req ? &req->work : NULL;
6260 static void io_wq_submit_work(struct io_wq_work *work)
6262 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6263 struct io_kiocb *timeout;
6266 timeout = io_prep_linked_timeout(req);
6268 io_queue_linked_timeout(timeout);
6270 if (work->flags & IO_WQ_WORK_CANCEL)
6275 ret = io_issue_sqe(req, 0);
6277 * We can get EAGAIN for polled IO even though we're
6278 * forcing a sync submission from here, since we can't
6279 * wait for request slots on the block side.
6287 /* avoid locking problems by failing it from a clean context */
6289 /* io-wq is going to take one down */
6291 io_req_task_queue_fail(req, ret);
6295 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6298 return &table->files[i];
6301 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6304 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6306 return (struct file *) (slot->file_ptr & FFS_MASK);
6309 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6311 unsigned long file_ptr = (unsigned long) file;
6313 if (__io_file_supports_nowait(file, READ))
6314 file_ptr |= FFS_ASYNC_READ;
6315 if (__io_file_supports_nowait(file, WRITE))
6316 file_ptr |= FFS_ASYNC_WRITE;
6317 if (S_ISREG(file_inode(file)->i_mode))
6318 file_ptr |= FFS_ISREG;
6319 file_slot->file_ptr = file_ptr;
6322 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6323 struct io_kiocb *req, int fd)
6326 unsigned long file_ptr;
6328 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6330 fd = array_index_nospec(fd, ctx->nr_user_files);
6331 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6332 file = (struct file *) (file_ptr & FFS_MASK);
6333 file_ptr &= ~FFS_MASK;
6334 /* mask in overlapping REQ_F and FFS bits */
6335 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6336 io_req_set_rsrc_node(req);
6340 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6341 struct io_kiocb *req, int fd)
6343 struct file *file = fget(fd);
6345 trace_io_uring_file_get(ctx, fd);
6347 /* we don't allow fixed io_uring files */
6348 if (file && unlikely(file->f_op == &io_uring_fops))
6349 io_req_track_inflight(req);
6353 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6354 struct io_kiocb *req, int fd, bool fixed)
6357 return io_file_get_fixed(ctx, req, fd);
6359 return io_file_get_normal(ctx, req, fd);
6362 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6364 struct io_timeout_data *data = container_of(timer,
6365 struct io_timeout_data, timer);
6366 struct io_kiocb *prev, *req = data->req;
6367 struct io_ring_ctx *ctx = req->ctx;
6368 unsigned long flags;
6370 spin_lock_irqsave(&ctx->completion_lock, flags);
6371 prev = req->timeout.head;
6372 req->timeout.head = NULL;
6375 * We don't expect the list to be empty, that will only happen if we
6376 * race with the completion of the linked work.
6379 io_remove_next_linked(prev);
6380 if (!req_ref_inc_not_zero(prev))
6383 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6386 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6387 io_put_req_deferred(prev, 1);
6388 io_put_req_deferred(req, 1);
6390 io_req_complete_post(req, -ETIME, 0);
6392 return HRTIMER_NORESTART;
6395 static void io_queue_linked_timeout(struct io_kiocb *req)
6397 struct io_ring_ctx *ctx = req->ctx;
6399 spin_lock_irq(&ctx->completion_lock);
6401 * If the back reference is NULL, then our linked request finished
6402 * before we got a chance to setup the timer
6404 if (req->timeout.head) {
6405 struct io_timeout_data *data = req->async_data;
6407 data->timer.function = io_link_timeout_fn;
6408 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6411 spin_unlock_irq(&ctx->completion_lock);
6412 /* drop submission reference */
6416 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6418 struct io_kiocb *nxt = req->link;
6420 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6421 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6424 nxt->timeout.head = req;
6425 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6426 req->flags |= REQ_F_LINK_TIMEOUT;
6430 static void __io_queue_sqe(struct io_kiocb *req)
6431 __must_hold(&req->ctx->uring_lock)
6433 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6437 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6440 * We async punt it if the file wasn't marked NOWAIT, or if the file
6441 * doesn't support non-blocking read/write attempts
6444 /* drop submission reference */
6445 if (req->flags & REQ_F_COMPLETE_INLINE) {
6446 struct io_ring_ctx *ctx = req->ctx;
6447 struct io_submit_state *state = &ctx->submit_state;
6449 state->compl_reqs[state->compl_nr++] = req;
6450 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6451 io_submit_flush_completions(ctx);
6455 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6456 switch (io_arm_poll_handler(req)) {
6457 case IO_APOLL_READY:
6459 case IO_APOLL_ABORTED:
6461 * Queued up for async execution, worker will release
6462 * submit reference when the iocb is actually submitted.
6464 io_queue_async_work(req);
6468 io_req_complete_failed(req, ret);
6471 io_queue_linked_timeout(linked_timeout);
6474 static inline void io_queue_sqe(struct io_kiocb *req)
6475 __must_hold(&req->ctx->uring_lock)
6477 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6480 if (likely(!(req->flags & REQ_F_FORCE_ASYNC))) {
6481 __io_queue_sqe(req);
6483 int ret = io_req_prep_async(req);
6486 io_req_complete_failed(req, ret);
6488 io_queue_async_work(req);
6493 * Check SQE restrictions (opcode and flags).
6495 * Returns 'true' if SQE is allowed, 'false' otherwise.
6497 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6498 struct io_kiocb *req,
6499 unsigned int sqe_flags)
6501 if (likely(!ctx->restricted))
6504 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6507 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6508 ctx->restrictions.sqe_flags_required)
6511 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6512 ctx->restrictions.sqe_flags_required))
6518 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6519 const struct io_uring_sqe *sqe)
6520 __must_hold(&ctx->uring_lock)
6522 struct io_submit_state *state;
6523 unsigned int sqe_flags;
6524 int personality, ret = 0;
6526 /* req is partially pre-initialised, see io_preinit_req() */
6527 req->opcode = READ_ONCE(sqe->opcode);
6528 /* same numerical values with corresponding REQ_F_*, safe to copy */
6529 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6530 req->user_data = READ_ONCE(sqe->user_data);
6532 req->fixed_rsrc_refs = NULL;
6533 /* one is dropped after submission, the other at completion */
6534 atomic_set(&req->refs, 2);
6535 req->task = current;
6537 /* enforce forwards compatibility on users */
6538 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6540 if (unlikely(req->opcode >= IORING_OP_LAST))
6542 if (!io_check_restriction(ctx, req, sqe_flags))
6545 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6546 !io_op_defs[req->opcode].buffer_select)
6548 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6549 ctx->drain_active = true;
6551 personality = READ_ONCE(sqe->personality);
6553 req->creds = xa_load(&ctx->personalities, personality);
6556 get_cred(req->creds);
6557 req->flags |= REQ_F_CREDS;
6559 state = &ctx->submit_state;
6562 * Plug now if we have more than 1 IO left after this, and the target
6563 * is potentially a read/write to block based storage.
6565 if (!state->plug_started && state->ios_left > 1 &&
6566 io_op_defs[req->opcode].plug) {
6567 blk_start_plug(&state->plug);
6568 state->plug_started = true;
6571 if (io_op_defs[req->opcode].needs_file) {
6572 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6573 (sqe_flags & IOSQE_FIXED_FILE));
6574 if (unlikely(!req->file))
6582 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6583 const struct io_uring_sqe *sqe)
6584 __must_hold(&ctx->uring_lock)
6586 struct io_submit_link *link = &ctx->submit_state.link;
6589 ret = io_init_req(ctx, req, sqe);
6590 if (unlikely(ret)) {
6593 /* fail even hard links since we don't submit */
6594 req_set_fail(link->head);
6595 io_req_complete_failed(link->head, -ECANCELED);
6598 io_req_complete_failed(req, ret);
6602 ret = io_req_prep(req, sqe);
6606 /* don't need @sqe from now on */
6607 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6609 ctx->flags & IORING_SETUP_SQPOLL);
6612 * If we already have a head request, queue this one for async
6613 * submittal once the head completes. If we don't have a head but
6614 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6615 * submitted sync once the chain is complete. If none of those
6616 * conditions are true (normal request), then just queue it.
6619 struct io_kiocb *head = link->head;
6621 ret = io_req_prep_async(req);
6624 trace_io_uring_link(ctx, req, head);
6625 link->last->link = req;
6628 /* last request of a link, enqueue the link */
6629 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6634 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6646 * Batched submission is done, ensure local IO is flushed out.
6648 static void io_submit_state_end(struct io_submit_state *state,
6649 struct io_ring_ctx *ctx)
6651 if (state->link.head)
6652 io_queue_sqe(state->link.head);
6653 if (state->compl_nr)
6654 io_submit_flush_completions(ctx);
6655 if (state->plug_started)
6656 blk_finish_plug(&state->plug);
6660 * Start submission side cache.
6662 static void io_submit_state_start(struct io_submit_state *state,
6663 unsigned int max_ios)
6665 state->plug_started = false;
6666 state->ios_left = max_ios;
6667 /* set only head, no need to init link_last in advance */
6668 state->link.head = NULL;
6671 static void io_commit_sqring(struct io_ring_ctx *ctx)
6673 struct io_rings *rings = ctx->rings;
6676 * Ensure any loads from the SQEs are done at this point,
6677 * since once we write the new head, the application could
6678 * write new data to them.
6680 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6684 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6685 * that is mapped by userspace. This means that care needs to be taken to
6686 * ensure that reads are stable, as we cannot rely on userspace always
6687 * being a good citizen. If members of the sqe are validated and then later
6688 * used, it's important that those reads are done through READ_ONCE() to
6689 * prevent a re-load down the line.
6691 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6693 unsigned head, mask = ctx->sq_entries - 1;
6694 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6697 * The cached sq head (or cq tail) serves two purposes:
6699 * 1) allows us to batch the cost of updating the user visible
6701 * 2) allows the kernel side to track the head on its own, even
6702 * though the application is the one updating it.
6704 head = READ_ONCE(ctx->sq_array[sq_idx]);
6705 if (likely(head < ctx->sq_entries))
6706 return &ctx->sq_sqes[head];
6708 /* drop invalid entries */
6710 WRITE_ONCE(ctx->rings->sq_dropped,
6711 READ_ONCE(ctx->rings->sq_dropped) + 1);
6715 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6716 __must_hold(&ctx->uring_lock)
6718 struct io_uring_task *tctx;
6721 /* make sure SQ entry isn't read before tail */
6722 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6723 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6726 tctx = current->io_uring;
6727 tctx->cached_refs -= nr;
6728 if (unlikely(tctx->cached_refs < 0)) {
6729 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
6731 percpu_counter_add(&tctx->inflight, refill);
6732 refcount_add(refill, ¤t->usage);
6733 tctx->cached_refs += refill;
6735 io_submit_state_start(&ctx->submit_state, nr);
6737 while (submitted < nr) {
6738 const struct io_uring_sqe *sqe;
6739 struct io_kiocb *req;
6741 req = io_alloc_req(ctx);
6742 if (unlikely(!req)) {
6744 submitted = -EAGAIN;
6747 sqe = io_get_sqe(ctx);
6748 if (unlikely(!sqe)) {
6749 kmem_cache_free(req_cachep, req);
6752 /* will complete beyond this point, count as submitted */
6754 if (io_submit_sqe(ctx, req, sqe))
6758 if (unlikely(submitted != nr)) {
6759 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6760 int unused = nr - ref_used;
6762 current->io_uring->cached_refs += unused;
6763 percpu_ref_put_many(&ctx->refs, unused);
6766 io_submit_state_end(&ctx->submit_state, ctx);
6767 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6768 io_commit_sqring(ctx);
6773 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6775 return READ_ONCE(sqd->state);
6778 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6780 /* Tell userspace we may need a wakeup call */
6781 spin_lock_irq(&ctx->completion_lock);
6782 WRITE_ONCE(ctx->rings->sq_flags,
6783 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
6784 spin_unlock_irq(&ctx->completion_lock);
6787 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6789 spin_lock_irq(&ctx->completion_lock);
6790 WRITE_ONCE(ctx->rings->sq_flags,
6791 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
6792 spin_unlock_irq(&ctx->completion_lock);
6795 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6797 unsigned int to_submit;
6800 to_submit = io_sqring_entries(ctx);
6801 /* if we're handling multiple rings, cap submit size for fairness */
6802 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6803 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6805 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6806 unsigned nr_events = 0;
6807 const struct cred *creds = NULL;
6809 if (ctx->sq_creds != current_cred())
6810 creds = override_creds(ctx->sq_creds);
6812 mutex_lock(&ctx->uring_lock);
6813 if (!list_empty(&ctx->iopoll_list))
6814 io_do_iopoll(ctx, &nr_events, 0, true);
6817 * Don't submit if refs are dying, good for io_uring_register(),
6818 * but also it is relied upon by io_ring_exit_work()
6820 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6821 !(ctx->flags & IORING_SETUP_R_DISABLED))
6822 ret = io_submit_sqes(ctx, to_submit);
6823 mutex_unlock(&ctx->uring_lock);
6825 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6826 wake_up(&ctx->sqo_sq_wait);
6828 revert_creds(creds);
6834 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6836 struct io_ring_ctx *ctx;
6837 unsigned sq_thread_idle = 0;
6839 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6840 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6841 sqd->sq_thread_idle = sq_thread_idle;
6844 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6846 bool did_sig = false;
6847 struct ksignal ksig;
6849 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6850 signal_pending(current)) {
6851 mutex_unlock(&sqd->lock);
6852 if (signal_pending(current))
6853 did_sig = get_signal(&ksig);
6855 mutex_lock(&sqd->lock);
6857 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6860 static int io_sq_thread(void *data)
6862 struct io_sq_data *sqd = data;
6863 struct io_ring_ctx *ctx;
6864 unsigned long timeout = 0;
6865 char buf[TASK_COMM_LEN];
6868 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6869 set_task_comm(current, buf);
6871 if (sqd->sq_cpu != -1)
6872 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6874 set_cpus_allowed_ptr(current, cpu_online_mask);
6875 current->flags |= PF_NO_SETAFFINITY;
6877 mutex_lock(&sqd->lock);
6879 bool cap_entries, sqt_spin = false;
6881 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
6882 if (io_sqd_handle_event(sqd))
6884 timeout = jiffies + sqd->sq_thread_idle;
6887 cap_entries = !list_is_singular(&sqd->ctx_list);
6888 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6889 int ret = __io_sq_thread(ctx, cap_entries);
6891 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6894 if (io_run_task_work())
6897 if (sqt_spin || !time_after(jiffies, timeout)) {
6900 timeout = jiffies + sqd->sq_thread_idle;
6904 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6905 if (!io_sqd_events_pending(sqd) && !current->task_works) {
6906 bool needs_sched = true;
6908 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6909 io_ring_set_wakeup_flag(ctx);
6911 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6912 !list_empty_careful(&ctx->iopoll_list)) {
6913 needs_sched = false;
6916 if (io_sqring_entries(ctx)) {
6917 needs_sched = false;
6923 mutex_unlock(&sqd->lock);
6925 mutex_lock(&sqd->lock);
6927 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6928 io_ring_clear_wakeup_flag(ctx);
6931 finish_wait(&sqd->wait, &wait);
6932 timeout = jiffies + sqd->sq_thread_idle;
6935 io_uring_cancel_generic(true, sqd);
6937 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6938 io_ring_set_wakeup_flag(ctx);
6940 mutex_unlock(&sqd->lock);
6942 complete(&sqd->exited);
6946 struct io_wait_queue {
6947 struct wait_queue_entry wq;
6948 struct io_ring_ctx *ctx;
6950 unsigned nr_timeouts;
6953 static inline bool io_should_wake(struct io_wait_queue *iowq)
6955 struct io_ring_ctx *ctx = iowq->ctx;
6956 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
6959 * Wake up if we have enough events, or if a timeout occurred since we
6960 * started waiting. For timeouts, we always want to return to userspace,
6961 * regardless of event count.
6963 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6966 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6967 int wake_flags, void *key)
6969 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6973 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6974 * the task, and the next invocation will do it.
6976 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
6977 return autoremove_wake_function(curr, mode, wake_flags, key);
6981 static int io_run_task_work_sig(void)
6983 if (io_run_task_work())
6985 if (!signal_pending(current))
6987 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6988 return -ERESTARTSYS;
6992 /* when returns >0, the caller should retry */
6993 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6994 struct io_wait_queue *iowq,
6995 signed long *timeout)
6999 /* make sure we run task_work before checking for signals */
7000 ret = io_run_task_work_sig();
7001 if (ret || io_should_wake(iowq))
7003 /* let the caller flush overflows, retry */
7004 if (test_bit(0, &ctx->check_cq_overflow))
7007 *timeout = schedule_timeout(*timeout);
7008 return !*timeout ? -ETIME : 1;
7012 * Wait until events become available, if we don't already have some. The
7013 * application must reap them itself, as they reside on the shared cq ring.
7015 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7016 const sigset_t __user *sig, size_t sigsz,
7017 struct __kernel_timespec __user *uts)
7019 struct io_wait_queue iowq;
7020 struct io_rings *rings = ctx->rings;
7021 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7025 io_cqring_overflow_flush(ctx);
7026 if (io_cqring_events(ctx) >= min_events)
7028 if (!io_run_task_work())
7033 #ifdef CONFIG_COMPAT
7034 if (in_compat_syscall())
7035 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7039 ret = set_user_sigmask(sig, sigsz);
7046 struct timespec64 ts;
7048 if (get_timespec64(&ts, uts))
7050 timeout = timespec64_to_jiffies(&ts);
7053 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7054 iowq.wq.private = current;
7055 INIT_LIST_HEAD(&iowq.wq.entry);
7057 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7058 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7060 trace_io_uring_cqring_wait(ctx, min_events);
7062 /* if we can't even flush overflow, don't wait for more */
7063 if (!io_cqring_overflow_flush(ctx)) {
7067 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7068 TASK_INTERRUPTIBLE);
7069 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7070 finish_wait(&ctx->cq_wait, &iowq.wq);
7074 restore_saved_sigmask_unless(ret == -EINTR);
7076 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7079 static void io_free_page_table(void **table, size_t size)
7081 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7083 for (i = 0; i < nr_tables; i++)
7088 static void **io_alloc_page_table(size_t size)
7090 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7091 size_t init_size = size;
7094 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL);
7098 for (i = 0; i < nr_tables; i++) {
7099 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7101 table[i] = kzalloc(this_size, GFP_KERNEL);
7103 io_free_page_table(table, init_size);
7111 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7113 percpu_ref_exit(&ref_node->refs);
7117 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7119 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7120 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7121 unsigned long flags;
7122 bool first_add = false;
7124 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7127 while (!list_empty(&ctx->rsrc_ref_list)) {
7128 node = list_first_entry(&ctx->rsrc_ref_list,
7129 struct io_rsrc_node, node);
7130 /* recycle ref nodes in order */
7133 list_del(&node->node);
7134 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7136 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7139 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7142 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7144 struct io_rsrc_node *ref_node;
7146 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7150 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7155 INIT_LIST_HEAD(&ref_node->node);
7156 INIT_LIST_HEAD(&ref_node->rsrc_list);
7157 ref_node->done = false;
7161 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7162 struct io_rsrc_data *data_to_kill)
7164 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7165 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7168 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7170 rsrc_node->rsrc_data = data_to_kill;
7171 spin_lock_irq(&ctx->rsrc_ref_lock);
7172 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7173 spin_unlock_irq(&ctx->rsrc_ref_lock);
7175 atomic_inc(&data_to_kill->refs);
7176 percpu_ref_kill(&rsrc_node->refs);
7177 ctx->rsrc_node = NULL;
7180 if (!ctx->rsrc_node) {
7181 ctx->rsrc_node = ctx->rsrc_backup_node;
7182 ctx->rsrc_backup_node = NULL;
7186 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7188 if (ctx->rsrc_backup_node)
7190 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7191 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7194 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7198 /* As we may drop ->uring_lock, other task may have started quiesce */
7202 data->quiesce = true;
7204 ret = io_rsrc_node_switch_start(ctx);
7207 io_rsrc_node_switch(ctx, data);
7209 /* kill initial ref, already quiesced if zero */
7210 if (atomic_dec_and_test(&data->refs))
7212 mutex_unlock(&ctx->uring_lock);
7213 flush_delayed_work(&ctx->rsrc_put_work);
7214 ret = wait_for_completion_interruptible(&data->done);
7216 mutex_lock(&ctx->uring_lock);
7220 atomic_inc(&data->refs);
7221 /* wait for all works potentially completing data->done */
7222 flush_delayed_work(&ctx->rsrc_put_work);
7223 reinit_completion(&data->done);
7225 ret = io_run_task_work_sig();
7226 mutex_lock(&ctx->uring_lock);
7228 data->quiesce = false;
7233 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7235 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7236 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7238 return &data->tags[table_idx][off];
7241 static void io_rsrc_data_free(struct io_rsrc_data *data)
7243 size_t size = data->nr * sizeof(data->tags[0][0]);
7246 io_free_page_table((void **)data->tags, size);
7250 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7251 u64 __user *utags, unsigned nr,
7252 struct io_rsrc_data **pdata)
7254 struct io_rsrc_data *data;
7258 data = kzalloc(sizeof(*data), GFP_KERNEL);
7261 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7269 data->do_put = do_put;
7272 for (i = 0; i < nr; i++) {
7273 u64 *tag_slot = io_get_tag_slot(data, i);
7275 if (copy_from_user(tag_slot, &utags[i],
7281 atomic_set(&data->refs, 1);
7282 init_completion(&data->done);
7286 io_rsrc_data_free(data);
7290 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7292 table->files = kvcalloc(nr_files, sizeof(table->files[0]), GFP_KERNEL);
7293 return !!table->files;
7296 static void io_free_file_tables(struct io_file_table *table)
7298 kvfree(table->files);
7299 table->files = NULL;
7302 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7304 #if defined(CONFIG_UNIX)
7305 if (ctx->ring_sock) {
7306 struct sock *sock = ctx->ring_sock->sk;
7307 struct sk_buff *skb;
7309 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7315 for (i = 0; i < ctx->nr_user_files; i++) {
7318 file = io_file_from_index(ctx, i);
7323 io_free_file_tables(&ctx->file_table);
7324 io_rsrc_data_free(ctx->file_data);
7325 ctx->file_data = NULL;
7326 ctx->nr_user_files = 0;
7329 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7333 if (!ctx->file_data)
7335 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7337 __io_sqe_files_unregister(ctx);
7341 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7342 __releases(&sqd->lock)
7344 WARN_ON_ONCE(sqd->thread == current);
7347 * Do the dance but not conditional clear_bit() because it'd race with
7348 * other threads incrementing park_pending and setting the bit.
7350 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7351 if (atomic_dec_return(&sqd->park_pending))
7352 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7353 mutex_unlock(&sqd->lock);
7356 static void io_sq_thread_park(struct io_sq_data *sqd)
7357 __acquires(&sqd->lock)
7359 WARN_ON_ONCE(sqd->thread == current);
7361 atomic_inc(&sqd->park_pending);
7362 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7363 mutex_lock(&sqd->lock);
7365 wake_up_process(sqd->thread);
7368 static void io_sq_thread_stop(struct io_sq_data *sqd)
7370 WARN_ON_ONCE(sqd->thread == current);
7371 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7373 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7374 mutex_lock(&sqd->lock);
7376 wake_up_process(sqd->thread);
7377 mutex_unlock(&sqd->lock);
7378 wait_for_completion(&sqd->exited);
7381 static void io_put_sq_data(struct io_sq_data *sqd)
7383 if (refcount_dec_and_test(&sqd->refs)) {
7384 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7386 io_sq_thread_stop(sqd);
7391 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7393 struct io_sq_data *sqd = ctx->sq_data;
7396 io_sq_thread_park(sqd);
7397 list_del_init(&ctx->sqd_list);
7398 io_sqd_update_thread_idle(sqd);
7399 io_sq_thread_unpark(sqd);
7401 io_put_sq_data(sqd);
7402 ctx->sq_data = NULL;
7406 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7408 struct io_ring_ctx *ctx_attach;
7409 struct io_sq_data *sqd;
7412 f = fdget(p->wq_fd);
7414 return ERR_PTR(-ENXIO);
7415 if (f.file->f_op != &io_uring_fops) {
7417 return ERR_PTR(-EINVAL);
7420 ctx_attach = f.file->private_data;
7421 sqd = ctx_attach->sq_data;
7424 return ERR_PTR(-EINVAL);
7426 if (sqd->task_tgid != current->tgid) {
7428 return ERR_PTR(-EPERM);
7431 refcount_inc(&sqd->refs);
7436 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7439 struct io_sq_data *sqd;
7442 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7443 sqd = io_attach_sq_data(p);
7448 /* fall through for EPERM case, setup new sqd/task */
7449 if (PTR_ERR(sqd) != -EPERM)
7453 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7455 return ERR_PTR(-ENOMEM);
7457 atomic_set(&sqd->park_pending, 0);
7458 refcount_set(&sqd->refs, 1);
7459 INIT_LIST_HEAD(&sqd->ctx_list);
7460 mutex_init(&sqd->lock);
7461 init_waitqueue_head(&sqd->wait);
7462 init_completion(&sqd->exited);
7466 #if defined(CONFIG_UNIX)
7468 * Ensure the UNIX gc is aware of our file set, so we are certain that
7469 * the io_uring can be safely unregistered on process exit, even if we have
7470 * loops in the file referencing.
7472 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7474 struct sock *sk = ctx->ring_sock->sk;
7475 struct scm_fp_list *fpl;
7476 struct sk_buff *skb;
7479 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7483 skb = alloc_skb(0, GFP_KERNEL);
7492 fpl->user = get_uid(current_user());
7493 for (i = 0; i < nr; i++) {
7494 struct file *file = io_file_from_index(ctx, i + offset);
7498 fpl->fp[nr_files] = get_file(file);
7499 unix_inflight(fpl->user, fpl->fp[nr_files]);
7504 fpl->max = SCM_MAX_FD;
7505 fpl->count = nr_files;
7506 UNIXCB(skb).fp = fpl;
7507 skb->destructor = unix_destruct_scm;
7508 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7509 skb_queue_head(&sk->sk_receive_queue, skb);
7511 for (i = 0; i < nr_files; i++)
7522 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7523 * causes regular reference counting to break down. We rely on the UNIX
7524 * garbage collection to take care of this problem for us.
7526 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7528 unsigned left, total;
7532 left = ctx->nr_user_files;
7534 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7536 ret = __io_sqe_files_scm(ctx, this_files, total);
7540 total += this_files;
7546 while (total < ctx->nr_user_files) {
7547 struct file *file = io_file_from_index(ctx, total);
7557 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7563 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7565 struct file *file = prsrc->file;
7566 #if defined(CONFIG_UNIX)
7567 struct sock *sock = ctx->ring_sock->sk;
7568 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7569 struct sk_buff *skb;
7572 __skb_queue_head_init(&list);
7575 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7576 * remove this entry and rearrange the file array.
7578 skb = skb_dequeue(head);
7580 struct scm_fp_list *fp;
7582 fp = UNIXCB(skb).fp;
7583 for (i = 0; i < fp->count; i++) {
7586 if (fp->fp[i] != file)
7589 unix_notinflight(fp->user, fp->fp[i]);
7590 left = fp->count - 1 - i;
7592 memmove(&fp->fp[i], &fp->fp[i + 1],
7593 left * sizeof(struct file *));
7600 __skb_queue_tail(&list, skb);
7610 __skb_queue_tail(&list, skb);
7612 skb = skb_dequeue(head);
7615 if (skb_peek(&list)) {
7616 spin_lock_irq(&head->lock);
7617 while ((skb = __skb_dequeue(&list)) != NULL)
7618 __skb_queue_tail(head, skb);
7619 spin_unlock_irq(&head->lock);
7626 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7628 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7629 struct io_ring_ctx *ctx = rsrc_data->ctx;
7630 struct io_rsrc_put *prsrc, *tmp;
7632 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7633 list_del(&prsrc->list);
7636 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7638 io_ring_submit_lock(ctx, lock_ring);
7639 spin_lock_irq(&ctx->completion_lock);
7640 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7642 io_commit_cqring(ctx);
7643 spin_unlock_irq(&ctx->completion_lock);
7644 io_cqring_ev_posted(ctx);
7645 io_ring_submit_unlock(ctx, lock_ring);
7648 rsrc_data->do_put(ctx, prsrc);
7652 io_rsrc_node_destroy(ref_node);
7653 if (atomic_dec_and_test(&rsrc_data->refs))
7654 complete(&rsrc_data->done);
7657 static void io_rsrc_put_work(struct work_struct *work)
7659 struct io_ring_ctx *ctx;
7660 struct llist_node *node;
7662 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7663 node = llist_del_all(&ctx->rsrc_put_llist);
7666 struct io_rsrc_node *ref_node;
7667 struct llist_node *next = node->next;
7669 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7670 __io_rsrc_put_work(ref_node);
7675 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7676 unsigned nr_args, u64 __user *tags)
7678 __s32 __user *fds = (__s32 __user *) arg;
7687 if (nr_args > IORING_MAX_FIXED_FILES)
7689 ret = io_rsrc_node_switch_start(ctx);
7692 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7698 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7701 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7702 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7706 /* allow sparse sets */
7709 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7716 if (unlikely(!file))
7720 * Don't allow io_uring instances to be registered. If UNIX
7721 * isn't enabled, then this causes a reference cycle and this
7722 * instance can never get freed. If UNIX is enabled we'll
7723 * handle it just fine, but there's still no point in allowing
7724 * a ring fd as it doesn't support regular read/write anyway.
7726 if (file->f_op == &io_uring_fops) {
7730 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7733 ret = io_sqe_files_scm(ctx);
7735 __io_sqe_files_unregister(ctx);
7739 io_rsrc_node_switch(ctx, NULL);
7742 for (i = 0; i < ctx->nr_user_files; i++) {
7743 file = io_file_from_index(ctx, i);
7747 io_free_file_tables(&ctx->file_table);
7748 ctx->nr_user_files = 0;
7750 io_rsrc_data_free(ctx->file_data);
7751 ctx->file_data = NULL;
7755 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7758 #if defined(CONFIG_UNIX)
7759 struct sock *sock = ctx->ring_sock->sk;
7760 struct sk_buff_head *head = &sock->sk_receive_queue;
7761 struct sk_buff *skb;
7764 * See if we can merge this file into an existing skb SCM_RIGHTS
7765 * file set. If there's no room, fall back to allocating a new skb
7766 * and filling it in.
7768 spin_lock_irq(&head->lock);
7769 skb = skb_peek(head);
7771 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7773 if (fpl->count < SCM_MAX_FD) {
7774 __skb_unlink(skb, head);
7775 spin_unlock_irq(&head->lock);
7776 fpl->fp[fpl->count] = get_file(file);
7777 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7779 spin_lock_irq(&head->lock);
7780 __skb_queue_head(head, skb);
7785 spin_unlock_irq(&head->lock);
7792 return __io_sqe_files_scm(ctx, 1, index);
7798 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7799 struct io_rsrc_node *node, void *rsrc)
7801 struct io_rsrc_put *prsrc;
7803 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7807 prsrc->tag = *io_get_tag_slot(data, idx);
7809 list_add(&prsrc->list, &node->rsrc_list);
7813 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7814 struct io_uring_rsrc_update2 *up,
7817 u64 __user *tags = u64_to_user_ptr(up->tags);
7818 __s32 __user *fds = u64_to_user_ptr(up->data);
7819 struct io_rsrc_data *data = ctx->file_data;
7820 struct io_fixed_file *file_slot;
7824 bool needs_switch = false;
7826 if (!ctx->file_data)
7828 if (up->offset + nr_args > ctx->nr_user_files)
7831 for (done = 0; done < nr_args; done++) {
7834 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7835 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7839 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7843 if (fd == IORING_REGISTER_FILES_SKIP)
7846 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7847 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7849 if (file_slot->file_ptr) {
7850 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7851 err = io_queue_rsrc_removal(data, up->offset + done,
7852 ctx->rsrc_node, file);
7855 file_slot->file_ptr = 0;
7856 needs_switch = true;
7865 * Don't allow io_uring instances to be registered. If
7866 * UNIX isn't enabled, then this causes a reference
7867 * cycle and this instance can never get freed. If UNIX
7868 * is enabled we'll handle it just fine, but there's
7869 * still no point in allowing a ring fd as it doesn't
7870 * support regular read/write anyway.
7872 if (file->f_op == &io_uring_fops) {
7877 *io_get_tag_slot(data, up->offset + done) = tag;
7878 io_fixed_file_set(file_slot, file);
7879 err = io_sqe_file_register(ctx, file, i);
7881 file_slot->file_ptr = 0;
7889 io_rsrc_node_switch(ctx, data);
7890 return done ? done : err;
7893 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7894 struct task_struct *task)
7896 struct io_wq_hash *hash;
7897 struct io_wq_data data;
7898 unsigned int concurrency;
7900 mutex_lock(&ctx->uring_lock);
7901 hash = ctx->hash_map;
7903 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7905 mutex_unlock(&ctx->uring_lock);
7906 return ERR_PTR(-ENOMEM);
7908 refcount_set(&hash->refs, 1);
7909 init_waitqueue_head(&hash->wait);
7910 ctx->hash_map = hash;
7912 mutex_unlock(&ctx->uring_lock);
7916 data.free_work = io_wq_free_work;
7917 data.do_work = io_wq_submit_work;
7919 /* Do QD, or 4 * CPUS, whatever is smallest */
7920 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7922 return io_wq_create(concurrency, &data);
7925 static int io_uring_alloc_task_context(struct task_struct *task,
7926 struct io_ring_ctx *ctx)
7928 struct io_uring_task *tctx;
7931 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
7932 if (unlikely(!tctx))
7935 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7936 if (unlikely(ret)) {
7941 tctx->io_wq = io_init_wq_offload(ctx, task);
7942 if (IS_ERR(tctx->io_wq)) {
7943 ret = PTR_ERR(tctx->io_wq);
7944 percpu_counter_destroy(&tctx->inflight);
7950 init_waitqueue_head(&tctx->wait);
7951 atomic_set(&tctx->in_idle, 0);
7952 atomic_set(&tctx->inflight_tracked, 0);
7953 task->io_uring = tctx;
7954 spin_lock_init(&tctx->task_lock);
7955 INIT_WQ_LIST(&tctx->task_list);
7956 init_task_work(&tctx->task_work, tctx_task_work);
7960 void __io_uring_free(struct task_struct *tsk)
7962 struct io_uring_task *tctx = tsk->io_uring;
7964 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7965 WARN_ON_ONCE(tctx->io_wq);
7966 WARN_ON_ONCE(tctx->cached_refs);
7968 percpu_counter_destroy(&tctx->inflight);
7970 tsk->io_uring = NULL;
7973 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7974 struct io_uring_params *p)
7978 /* Retain compatibility with failing for an invalid attach attempt */
7979 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7980 IORING_SETUP_ATTACH_WQ) {
7983 f = fdget(p->wq_fd);
7986 if (f.file->f_op != &io_uring_fops) {
7992 if (ctx->flags & IORING_SETUP_SQPOLL) {
7993 struct task_struct *tsk;
7994 struct io_sq_data *sqd;
7997 sqd = io_get_sq_data(p, &attached);
8003 ctx->sq_creds = get_current_cred();
8005 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8006 if (!ctx->sq_thread_idle)
8007 ctx->sq_thread_idle = HZ;
8009 io_sq_thread_park(sqd);
8010 list_add(&ctx->sqd_list, &sqd->ctx_list);
8011 io_sqd_update_thread_idle(sqd);
8012 /* don't attach to a dying SQPOLL thread, would be racy */
8013 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8014 io_sq_thread_unpark(sqd);
8021 if (p->flags & IORING_SETUP_SQ_AFF) {
8022 int cpu = p->sq_thread_cpu;
8025 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8032 sqd->task_pid = current->pid;
8033 sqd->task_tgid = current->tgid;
8034 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8041 ret = io_uring_alloc_task_context(tsk, ctx);
8042 wake_up_new_task(tsk);
8045 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8046 /* Can't have SQ_AFF without SQPOLL */
8053 complete(&ctx->sq_data->exited);
8055 io_sq_thread_finish(ctx);
8059 static inline void __io_unaccount_mem(struct user_struct *user,
8060 unsigned long nr_pages)
8062 atomic_long_sub(nr_pages, &user->locked_vm);
8065 static inline int __io_account_mem(struct user_struct *user,
8066 unsigned long nr_pages)
8068 unsigned long page_limit, cur_pages, new_pages;
8070 /* Don't allow more pages than we can safely lock */
8071 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8074 cur_pages = atomic_long_read(&user->locked_vm);
8075 new_pages = cur_pages + nr_pages;
8076 if (new_pages > page_limit)
8078 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8079 new_pages) != cur_pages);
8084 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8087 __io_unaccount_mem(ctx->user, nr_pages);
8089 if (ctx->mm_account)
8090 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8093 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8098 ret = __io_account_mem(ctx->user, nr_pages);
8103 if (ctx->mm_account)
8104 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8109 static void io_mem_free(void *ptr)
8116 page = virt_to_head_page(ptr);
8117 if (put_page_testzero(page))
8118 free_compound_page(page);
8121 static void *io_mem_alloc(size_t size)
8123 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8124 __GFP_NORETRY | __GFP_ACCOUNT;
8126 return (void *) __get_free_pages(gfp_flags, get_order(size));
8129 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8132 struct io_rings *rings;
8133 size_t off, sq_array_size;
8135 off = struct_size(rings, cqes, cq_entries);
8136 if (off == SIZE_MAX)
8140 off = ALIGN(off, SMP_CACHE_BYTES);
8148 sq_array_size = array_size(sizeof(u32), sq_entries);
8149 if (sq_array_size == SIZE_MAX)
8152 if (check_add_overflow(off, sq_array_size, &off))
8158 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8160 struct io_mapped_ubuf *imu = *slot;
8163 if (imu != ctx->dummy_ubuf) {
8164 for (i = 0; i < imu->nr_bvecs; i++)
8165 unpin_user_page(imu->bvec[i].bv_page);
8166 if (imu->acct_pages)
8167 io_unaccount_mem(ctx, imu->acct_pages);
8173 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8175 io_buffer_unmap(ctx, &prsrc->buf);
8179 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8183 for (i = 0; i < ctx->nr_user_bufs; i++)
8184 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8185 kfree(ctx->user_bufs);
8186 io_rsrc_data_free(ctx->buf_data);
8187 ctx->user_bufs = NULL;
8188 ctx->buf_data = NULL;
8189 ctx->nr_user_bufs = 0;
8192 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8199 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8201 __io_sqe_buffers_unregister(ctx);
8205 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8206 void __user *arg, unsigned index)
8208 struct iovec __user *src;
8210 #ifdef CONFIG_COMPAT
8212 struct compat_iovec __user *ciovs;
8213 struct compat_iovec ciov;
8215 ciovs = (struct compat_iovec __user *) arg;
8216 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8219 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8220 dst->iov_len = ciov.iov_len;
8224 src = (struct iovec __user *) arg;
8225 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8231 * Not super efficient, but this is just a registration time. And we do cache
8232 * the last compound head, so generally we'll only do a full search if we don't
8235 * We check if the given compound head page has already been accounted, to
8236 * avoid double accounting it. This allows us to account the full size of the
8237 * page, not just the constituent pages of a huge page.
8239 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8240 int nr_pages, struct page *hpage)
8244 /* check current page array */
8245 for (i = 0; i < nr_pages; i++) {
8246 if (!PageCompound(pages[i]))
8248 if (compound_head(pages[i]) == hpage)
8252 /* check previously registered pages */
8253 for (i = 0; i < ctx->nr_user_bufs; i++) {
8254 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8256 for (j = 0; j < imu->nr_bvecs; j++) {
8257 if (!PageCompound(imu->bvec[j].bv_page))
8259 if (compound_head(imu->bvec[j].bv_page) == hpage)
8267 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8268 int nr_pages, struct io_mapped_ubuf *imu,
8269 struct page **last_hpage)
8273 imu->acct_pages = 0;
8274 for (i = 0; i < nr_pages; i++) {
8275 if (!PageCompound(pages[i])) {
8280 hpage = compound_head(pages[i]);
8281 if (hpage == *last_hpage)
8283 *last_hpage = hpage;
8284 if (headpage_already_acct(ctx, pages, i, hpage))
8286 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8290 if (!imu->acct_pages)
8293 ret = io_account_mem(ctx, imu->acct_pages);
8295 imu->acct_pages = 0;
8299 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8300 struct io_mapped_ubuf **pimu,
8301 struct page **last_hpage)
8303 struct io_mapped_ubuf *imu = NULL;
8304 struct vm_area_struct **vmas = NULL;
8305 struct page **pages = NULL;
8306 unsigned long off, start, end, ubuf;
8308 int ret, pret, nr_pages, i;
8310 if (!iov->iov_base) {
8311 *pimu = ctx->dummy_ubuf;
8315 ubuf = (unsigned long) iov->iov_base;
8316 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8317 start = ubuf >> PAGE_SHIFT;
8318 nr_pages = end - start;
8323 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8327 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8332 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8337 mmap_read_lock(current->mm);
8338 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8340 if (pret == nr_pages) {
8341 /* don't support file backed memory */
8342 for (i = 0; i < nr_pages; i++) {
8343 struct vm_area_struct *vma = vmas[i];
8345 if (vma_is_shmem(vma))
8348 !is_file_hugepages(vma->vm_file)) {
8354 ret = pret < 0 ? pret : -EFAULT;
8356 mmap_read_unlock(current->mm);
8359 * if we did partial map, or found file backed vmas,
8360 * release any pages we did get
8363 unpin_user_pages(pages, pret);
8367 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8369 unpin_user_pages(pages, pret);
8373 off = ubuf & ~PAGE_MASK;
8374 size = iov->iov_len;
8375 for (i = 0; i < nr_pages; i++) {
8378 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8379 imu->bvec[i].bv_page = pages[i];
8380 imu->bvec[i].bv_len = vec_len;
8381 imu->bvec[i].bv_offset = off;
8385 /* store original address for later verification */
8387 imu->ubuf_end = ubuf + iov->iov_len;
8388 imu->nr_bvecs = nr_pages;
8399 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8401 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8402 return ctx->user_bufs ? 0 : -ENOMEM;
8405 static int io_buffer_validate(struct iovec *iov)
8407 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8410 * Don't impose further limits on the size and buffer
8411 * constraints here, we'll -EINVAL later when IO is
8412 * submitted if they are wrong.
8415 return iov->iov_len ? -EFAULT : 0;
8419 /* arbitrary limit, but we need something */
8420 if (iov->iov_len > SZ_1G)
8423 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8429 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8430 unsigned int nr_args, u64 __user *tags)
8432 struct page *last_hpage = NULL;
8433 struct io_rsrc_data *data;
8439 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8441 ret = io_rsrc_node_switch_start(ctx);
8444 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8447 ret = io_buffers_map_alloc(ctx, nr_args);
8449 io_rsrc_data_free(data);
8453 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8454 ret = io_copy_iov(ctx, &iov, arg, i);
8457 ret = io_buffer_validate(&iov);
8460 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8465 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8471 WARN_ON_ONCE(ctx->buf_data);
8473 ctx->buf_data = data;
8475 __io_sqe_buffers_unregister(ctx);
8477 io_rsrc_node_switch(ctx, NULL);
8481 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8482 struct io_uring_rsrc_update2 *up,
8483 unsigned int nr_args)
8485 u64 __user *tags = u64_to_user_ptr(up->tags);
8486 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8487 struct page *last_hpage = NULL;
8488 bool needs_switch = false;
8494 if (up->offset + nr_args > ctx->nr_user_bufs)
8497 for (done = 0; done < nr_args; done++) {
8498 struct io_mapped_ubuf *imu;
8499 int offset = up->offset + done;
8502 err = io_copy_iov(ctx, &iov, iovs, done);
8505 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8509 err = io_buffer_validate(&iov);
8512 if (!iov.iov_base && tag) {
8516 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8520 i = array_index_nospec(offset, ctx->nr_user_bufs);
8521 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8522 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8523 ctx->rsrc_node, ctx->user_bufs[i]);
8524 if (unlikely(err)) {
8525 io_buffer_unmap(ctx, &imu);
8528 ctx->user_bufs[i] = NULL;
8529 needs_switch = true;
8532 ctx->user_bufs[i] = imu;
8533 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8537 io_rsrc_node_switch(ctx, ctx->buf_data);
8538 return done ? done : err;
8541 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8543 __s32 __user *fds = arg;
8549 if (copy_from_user(&fd, fds, sizeof(*fds)))
8552 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8553 if (IS_ERR(ctx->cq_ev_fd)) {
8554 int ret = PTR_ERR(ctx->cq_ev_fd);
8556 ctx->cq_ev_fd = NULL;
8563 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8565 if (ctx->cq_ev_fd) {
8566 eventfd_ctx_put(ctx->cq_ev_fd);
8567 ctx->cq_ev_fd = NULL;
8574 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8576 struct io_buffer *buf;
8577 unsigned long index;
8579 xa_for_each(&ctx->io_buffers, index, buf)
8580 __io_remove_buffers(ctx, buf, index, -1U);
8583 static void io_req_cache_free(struct list_head *list)
8585 struct io_kiocb *req, *nxt;
8587 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8588 list_del(&req->inflight_entry);
8589 kmem_cache_free(req_cachep, req);
8593 static void io_req_caches_free(struct io_ring_ctx *ctx)
8595 struct io_submit_state *state = &ctx->submit_state;
8597 mutex_lock(&ctx->uring_lock);
8599 if (state->free_reqs) {
8600 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8601 state->free_reqs = 0;
8604 io_flush_cached_locked_reqs(ctx, state);
8605 io_req_cache_free(&state->free_list);
8606 mutex_unlock(&ctx->uring_lock);
8609 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8611 if (data && !atomic_dec_and_test(&data->refs))
8612 wait_for_completion(&data->done);
8615 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8617 io_sq_thread_finish(ctx);
8619 if (ctx->mm_account) {
8620 mmdrop(ctx->mm_account);
8621 ctx->mm_account = NULL;
8624 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8625 io_wait_rsrc_data(ctx->buf_data);
8626 io_wait_rsrc_data(ctx->file_data);
8628 mutex_lock(&ctx->uring_lock);
8630 __io_sqe_buffers_unregister(ctx);
8632 __io_sqe_files_unregister(ctx);
8634 __io_cqring_overflow_flush(ctx, true);
8635 mutex_unlock(&ctx->uring_lock);
8636 io_eventfd_unregister(ctx);
8637 io_destroy_buffers(ctx);
8639 put_cred(ctx->sq_creds);
8641 /* there are no registered resources left, nobody uses it */
8643 io_rsrc_node_destroy(ctx->rsrc_node);
8644 if (ctx->rsrc_backup_node)
8645 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8646 flush_delayed_work(&ctx->rsrc_put_work);
8648 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8649 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8651 #if defined(CONFIG_UNIX)
8652 if (ctx->ring_sock) {
8653 ctx->ring_sock->file = NULL; /* so that iput() is called */
8654 sock_release(ctx->ring_sock);
8658 io_mem_free(ctx->rings);
8659 io_mem_free(ctx->sq_sqes);
8661 percpu_ref_exit(&ctx->refs);
8662 free_uid(ctx->user);
8663 io_req_caches_free(ctx);
8665 io_wq_put_hash(ctx->hash_map);
8666 kfree(ctx->cancel_hash);
8667 kfree(ctx->dummy_ubuf);
8671 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8673 struct io_ring_ctx *ctx = file->private_data;
8676 poll_wait(file, &ctx->poll_wait, wait);
8678 * synchronizes with barrier from wq_has_sleeper call in
8682 if (!io_sqring_full(ctx))
8683 mask |= EPOLLOUT | EPOLLWRNORM;
8686 * Don't flush cqring overflow list here, just do a simple check.
8687 * Otherwise there could possible be ABBA deadlock:
8690 * lock(&ctx->uring_lock);
8692 * lock(&ctx->uring_lock);
8695 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8696 * pushs them to do the flush.
8698 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8699 mask |= EPOLLIN | EPOLLRDNORM;
8704 static int io_uring_fasync(int fd, struct file *file, int on)
8706 struct io_ring_ctx *ctx = file->private_data;
8708 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8711 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8713 const struct cred *creds;
8715 creds = xa_erase(&ctx->personalities, id);
8724 struct io_tctx_exit {
8725 struct callback_head task_work;
8726 struct completion completion;
8727 struct io_ring_ctx *ctx;
8730 static void io_tctx_exit_cb(struct callback_head *cb)
8732 struct io_uring_task *tctx = current->io_uring;
8733 struct io_tctx_exit *work;
8735 work = container_of(cb, struct io_tctx_exit, task_work);
8737 * When @in_idle, we're in cancellation and it's racy to remove the
8738 * node. It'll be removed by the end of cancellation, just ignore it.
8740 if (!atomic_read(&tctx->in_idle))
8741 io_uring_del_tctx_node((unsigned long)work->ctx);
8742 complete(&work->completion);
8745 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8747 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8749 return req->ctx == data;
8752 static void io_ring_exit_work(struct work_struct *work)
8754 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8755 unsigned long timeout = jiffies + HZ * 60 * 5;
8756 unsigned long interval = HZ / 20;
8757 struct io_tctx_exit exit;
8758 struct io_tctx_node *node;
8762 * If we're doing polled IO and end up having requests being
8763 * submitted async (out-of-line), then completions can come in while
8764 * we're waiting for refs to drop. We need to reap these manually,
8765 * as nobody else will be looking for them.
8768 io_uring_try_cancel_requests(ctx, NULL, true);
8770 struct io_sq_data *sqd = ctx->sq_data;
8771 struct task_struct *tsk;
8773 io_sq_thread_park(sqd);
8775 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8776 io_wq_cancel_cb(tsk->io_uring->io_wq,
8777 io_cancel_ctx_cb, ctx, true);
8778 io_sq_thread_unpark(sqd);
8781 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
8782 /* there is little hope left, don't run it too often */
8785 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
8787 init_completion(&exit.completion);
8788 init_task_work(&exit.task_work, io_tctx_exit_cb);
8791 * Some may use context even when all refs and requests have been put,
8792 * and they are free to do so while still holding uring_lock or
8793 * completion_lock, see io_req_task_submit(). Apart from other work,
8794 * this lock/unlock section also waits them to finish.
8796 mutex_lock(&ctx->uring_lock);
8797 while (!list_empty(&ctx->tctx_list)) {
8798 WARN_ON_ONCE(time_after(jiffies, timeout));
8800 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8802 /* don't spin on a single task if cancellation failed */
8803 list_rotate_left(&ctx->tctx_list);
8804 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8805 if (WARN_ON_ONCE(ret))
8807 wake_up_process(node->task);
8809 mutex_unlock(&ctx->uring_lock);
8810 wait_for_completion(&exit.completion);
8811 mutex_lock(&ctx->uring_lock);
8813 mutex_unlock(&ctx->uring_lock);
8814 spin_lock_irq(&ctx->completion_lock);
8815 spin_unlock_irq(&ctx->completion_lock);
8817 io_ring_ctx_free(ctx);
8820 /* Returns true if we found and killed one or more timeouts */
8821 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8824 struct io_kiocb *req, *tmp;
8827 spin_lock_irq(&ctx->completion_lock);
8828 spin_lock(&ctx->timeout_lock);
8829 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8830 if (io_match_task(req, tsk, cancel_all)) {
8831 io_kill_timeout(req, -ECANCELED);
8835 spin_unlock(&ctx->timeout_lock);
8837 io_commit_cqring(ctx);
8838 spin_unlock_irq(&ctx->completion_lock);
8840 io_cqring_ev_posted(ctx);
8841 return canceled != 0;
8844 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8846 unsigned long index;
8847 struct creds *creds;
8849 mutex_lock(&ctx->uring_lock);
8850 percpu_ref_kill(&ctx->refs);
8852 __io_cqring_overflow_flush(ctx, true);
8853 xa_for_each(&ctx->personalities, index, creds)
8854 io_unregister_personality(ctx, index);
8855 mutex_unlock(&ctx->uring_lock);
8857 io_kill_timeouts(ctx, NULL, true);
8858 io_poll_remove_all(ctx, NULL, true);
8860 /* if we failed setting up the ctx, we might not have any rings */
8861 io_iopoll_try_reap_events(ctx);
8863 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8865 * Use system_unbound_wq to avoid spawning tons of event kworkers
8866 * if we're exiting a ton of rings at the same time. It just adds
8867 * noise and overhead, there's no discernable change in runtime
8868 * over using system_wq.
8870 queue_work(system_unbound_wq, &ctx->exit_work);
8873 static int io_uring_release(struct inode *inode, struct file *file)
8875 struct io_ring_ctx *ctx = file->private_data;
8877 file->private_data = NULL;
8878 io_ring_ctx_wait_and_kill(ctx);
8882 struct io_task_cancel {
8883 struct task_struct *task;
8887 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8889 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8890 struct io_task_cancel *cancel = data;
8893 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
8894 unsigned long flags;
8895 struct io_ring_ctx *ctx = req->ctx;
8897 /* protect against races with linked timeouts */
8898 spin_lock_irqsave(&ctx->completion_lock, flags);
8899 ret = io_match_task(req, cancel->task, cancel->all);
8900 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8902 ret = io_match_task(req, cancel->task, cancel->all);
8907 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8908 struct task_struct *task, bool cancel_all)
8910 struct io_defer_entry *de;
8913 spin_lock_irq(&ctx->completion_lock);
8914 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8915 if (io_match_task(de->req, task, cancel_all)) {
8916 list_cut_position(&list, &ctx->defer_list, &de->list);
8920 spin_unlock_irq(&ctx->completion_lock);
8921 if (list_empty(&list))
8924 while (!list_empty(&list)) {
8925 de = list_first_entry(&list, struct io_defer_entry, list);
8926 list_del_init(&de->list);
8927 io_req_complete_failed(de->req, -ECANCELED);
8933 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8935 struct io_tctx_node *node;
8936 enum io_wq_cancel cret;
8939 mutex_lock(&ctx->uring_lock);
8940 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8941 struct io_uring_task *tctx = node->task->io_uring;
8944 * io_wq will stay alive while we hold uring_lock, because it's
8945 * killed after ctx nodes, which requires to take the lock.
8947 if (!tctx || !tctx->io_wq)
8949 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8950 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8952 mutex_unlock(&ctx->uring_lock);
8957 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8958 struct task_struct *task,
8961 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
8962 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8965 enum io_wq_cancel cret;
8969 ret |= io_uring_try_cancel_iowq(ctx);
8970 } else if (tctx && tctx->io_wq) {
8972 * Cancels requests of all rings, not only @ctx, but
8973 * it's fine as the task is in exit/exec.
8975 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8977 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8980 /* SQPOLL thread does its own polling */
8981 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
8982 (ctx->sq_data && ctx->sq_data->thread == current)) {
8983 while (!list_empty_careful(&ctx->iopoll_list)) {
8984 io_iopoll_try_reap_events(ctx);
8989 ret |= io_cancel_defer_files(ctx, task, cancel_all);
8990 ret |= io_poll_remove_all(ctx, task, cancel_all);
8991 ret |= io_kill_timeouts(ctx, task, cancel_all);
8993 ret |= io_run_task_work();
9000 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9002 struct io_uring_task *tctx = current->io_uring;
9003 struct io_tctx_node *node;
9006 if (unlikely(!tctx)) {
9007 ret = io_uring_alloc_task_context(current, ctx);
9010 tctx = current->io_uring;
9012 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9013 node = kmalloc(sizeof(*node), GFP_KERNEL);
9017 node->task = current;
9019 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9026 mutex_lock(&ctx->uring_lock);
9027 list_add(&node->ctx_node, &ctx->tctx_list);
9028 mutex_unlock(&ctx->uring_lock);
9035 * Note that this task has used io_uring. We use it for cancelation purposes.
9037 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9039 struct io_uring_task *tctx = current->io_uring;
9041 if (likely(tctx && tctx->last == ctx))
9043 return __io_uring_add_tctx_node(ctx);
9047 * Remove this io_uring_file -> task mapping.
9049 static void io_uring_del_tctx_node(unsigned long index)
9051 struct io_uring_task *tctx = current->io_uring;
9052 struct io_tctx_node *node;
9056 node = xa_erase(&tctx->xa, index);
9060 WARN_ON_ONCE(current != node->task);
9061 WARN_ON_ONCE(list_empty(&node->ctx_node));
9063 mutex_lock(&node->ctx->uring_lock);
9064 list_del(&node->ctx_node);
9065 mutex_unlock(&node->ctx->uring_lock);
9067 if (tctx->last == node->ctx)
9072 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9074 struct io_wq *wq = tctx->io_wq;
9075 struct io_tctx_node *node;
9076 unsigned long index;
9078 xa_for_each(&tctx->xa, index, node)
9079 io_uring_del_tctx_node(index);
9082 * Must be after io_uring_del_task_file() (removes nodes under
9083 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9086 io_wq_put_and_exit(wq);
9090 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9093 return atomic_read(&tctx->inflight_tracked);
9094 return percpu_counter_sum(&tctx->inflight);
9097 static void io_uring_drop_tctx_refs(struct task_struct *task)
9099 struct io_uring_task *tctx = task->io_uring;
9100 unsigned int refs = tctx->cached_refs;
9103 tctx->cached_refs = 0;
9104 percpu_counter_sub(&tctx->inflight, refs);
9105 put_task_struct_many(task, refs);
9110 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9111 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9113 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9115 struct io_uring_task *tctx = current->io_uring;
9116 struct io_ring_ctx *ctx;
9120 WARN_ON_ONCE(sqd && sqd->thread != current);
9122 if (!current->io_uring)
9125 io_wq_exit_start(tctx->io_wq);
9127 atomic_inc(&tctx->in_idle);
9129 io_uring_drop_tctx_refs(current);
9130 /* read completions before cancelations */
9131 inflight = tctx_inflight(tctx, !cancel_all);
9136 struct io_tctx_node *node;
9137 unsigned long index;
9139 xa_for_each(&tctx->xa, index, node) {
9140 /* sqpoll task will cancel all its requests */
9141 if (node->ctx->sq_data)
9143 io_uring_try_cancel_requests(node->ctx, current,
9147 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9148 io_uring_try_cancel_requests(ctx, current,
9152 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9153 io_uring_drop_tctx_refs(current);
9155 * If we've seen completions, retry without waiting. This
9156 * avoids a race where a completion comes in before we did
9157 * prepare_to_wait().
9159 if (inflight == tctx_inflight(tctx, !cancel_all))
9161 finish_wait(&tctx->wait, &wait);
9163 atomic_dec(&tctx->in_idle);
9165 io_uring_clean_tctx(tctx);
9167 /* for exec all current's requests should be gone, kill tctx */
9168 __io_uring_free(current);
9172 void __io_uring_cancel(struct files_struct *files)
9174 io_uring_cancel_generic(!files, NULL);
9177 static void *io_uring_validate_mmap_request(struct file *file,
9178 loff_t pgoff, size_t sz)
9180 struct io_ring_ctx *ctx = file->private_data;
9181 loff_t offset = pgoff << PAGE_SHIFT;
9186 case IORING_OFF_SQ_RING:
9187 case IORING_OFF_CQ_RING:
9190 case IORING_OFF_SQES:
9194 return ERR_PTR(-EINVAL);
9197 page = virt_to_head_page(ptr);
9198 if (sz > page_size(page))
9199 return ERR_PTR(-EINVAL);
9206 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9208 size_t sz = vma->vm_end - vma->vm_start;
9212 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9214 return PTR_ERR(ptr);
9216 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9217 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9220 #else /* !CONFIG_MMU */
9222 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9224 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9227 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9229 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9232 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9233 unsigned long addr, unsigned long len,
9234 unsigned long pgoff, unsigned long flags)
9238 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9240 return PTR_ERR(ptr);
9242 return (unsigned long) ptr;
9245 #endif /* !CONFIG_MMU */
9247 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9252 if (!io_sqring_full(ctx))
9254 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9256 if (!io_sqring_full(ctx))
9259 } while (!signal_pending(current));
9261 finish_wait(&ctx->sqo_sq_wait, &wait);
9265 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9266 struct __kernel_timespec __user **ts,
9267 const sigset_t __user **sig)
9269 struct io_uring_getevents_arg arg;
9272 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9273 * is just a pointer to the sigset_t.
9275 if (!(flags & IORING_ENTER_EXT_ARG)) {
9276 *sig = (const sigset_t __user *) argp;
9282 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9283 * timespec and sigset_t pointers if good.
9285 if (*argsz != sizeof(arg))
9287 if (copy_from_user(&arg, argp, sizeof(arg)))
9289 *sig = u64_to_user_ptr(arg.sigmask);
9290 *argsz = arg.sigmask_sz;
9291 *ts = u64_to_user_ptr(arg.ts);
9295 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9296 u32, min_complete, u32, flags, const void __user *, argp,
9299 struct io_ring_ctx *ctx;
9306 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9307 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9311 if (unlikely(!f.file))
9315 if (unlikely(f.file->f_op != &io_uring_fops))
9319 ctx = f.file->private_data;
9320 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9324 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9328 * For SQ polling, the thread will do all submissions and completions.
9329 * Just return the requested submit count, and wake the thread if
9333 if (ctx->flags & IORING_SETUP_SQPOLL) {
9334 io_cqring_overflow_flush(ctx);
9336 if (unlikely(ctx->sq_data->thread == NULL)) {
9340 if (flags & IORING_ENTER_SQ_WAKEUP)
9341 wake_up(&ctx->sq_data->wait);
9342 if (flags & IORING_ENTER_SQ_WAIT) {
9343 ret = io_sqpoll_wait_sq(ctx);
9347 submitted = to_submit;
9348 } else if (to_submit) {
9349 ret = io_uring_add_tctx_node(ctx);
9352 mutex_lock(&ctx->uring_lock);
9353 submitted = io_submit_sqes(ctx, to_submit);
9354 mutex_unlock(&ctx->uring_lock);
9356 if (submitted != to_submit)
9359 if (flags & IORING_ENTER_GETEVENTS) {
9360 const sigset_t __user *sig;
9361 struct __kernel_timespec __user *ts;
9363 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9367 min_complete = min(min_complete, ctx->cq_entries);
9370 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9371 * space applications don't need to do io completion events
9372 * polling again, they can rely on io_sq_thread to do polling
9373 * work, which can reduce cpu usage and uring_lock contention.
9375 if (ctx->flags & IORING_SETUP_IOPOLL &&
9376 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9377 ret = io_iopoll_check(ctx, min_complete);
9379 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9384 percpu_ref_put(&ctx->refs);
9387 return submitted ? submitted : ret;
9390 #ifdef CONFIG_PROC_FS
9391 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9392 const struct cred *cred)
9394 struct user_namespace *uns = seq_user_ns(m);
9395 struct group_info *gi;
9400 seq_printf(m, "%5d\n", id);
9401 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9402 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9403 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9404 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9405 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9406 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9407 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9408 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9409 seq_puts(m, "\n\tGroups:\t");
9410 gi = cred->group_info;
9411 for (g = 0; g < gi->ngroups; g++) {
9412 seq_put_decimal_ull(m, g ? " " : "",
9413 from_kgid_munged(uns, gi->gid[g]));
9415 seq_puts(m, "\n\tCapEff:\t");
9416 cap = cred->cap_effective;
9417 CAP_FOR_EACH_U32(__capi)
9418 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9423 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9425 struct io_sq_data *sq = NULL;
9430 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9431 * since fdinfo case grabs it in the opposite direction of normal use
9432 * cases. If we fail to get the lock, we just don't iterate any
9433 * structures that could be going away outside the io_uring mutex.
9435 has_lock = mutex_trylock(&ctx->uring_lock);
9437 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9443 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9444 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9445 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9446 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9447 struct file *f = io_file_from_index(ctx, i);
9450 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9452 seq_printf(m, "%5u: <none>\n", i);
9454 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9455 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9456 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9457 unsigned int len = buf->ubuf_end - buf->ubuf;
9459 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9461 if (has_lock && !xa_empty(&ctx->personalities)) {
9462 unsigned long index;
9463 const struct cred *cred;
9465 seq_printf(m, "Personalities:\n");
9466 xa_for_each(&ctx->personalities, index, cred)
9467 io_uring_show_cred(m, index, cred);
9469 seq_printf(m, "PollList:\n");
9470 spin_lock_irq(&ctx->completion_lock);
9471 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9472 struct hlist_head *list = &ctx->cancel_hash[i];
9473 struct io_kiocb *req;
9475 hlist_for_each_entry(req, list, hash_node)
9476 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9477 req->task->task_works != NULL);
9479 spin_unlock_irq(&ctx->completion_lock);
9481 mutex_unlock(&ctx->uring_lock);
9484 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9486 struct io_ring_ctx *ctx = f->private_data;
9488 if (percpu_ref_tryget(&ctx->refs)) {
9489 __io_uring_show_fdinfo(ctx, m);
9490 percpu_ref_put(&ctx->refs);
9495 static const struct file_operations io_uring_fops = {
9496 .release = io_uring_release,
9497 .mmap = io_uring_mmap,
9499 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9500 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9502 .poll = io_uring_poll,
9503 .fasync = io_uring_fasync,
9504 #ifdef CONFIG_PROC_FS
9505 .show_fdinfo = io_uring_show_fdinfo,
9509 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9510 struct io_uring_params *p)
9512 struct io_rings *rings;
9513 size_t size, sq_array_offset;
9515 /* make sure these are sane, as we already accounted them */
9516 ctx->sq_entries = p->sq_entries;
9517 ctx->cq_entries = p->cq_entries;
9519 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9520 if (size == SIZE_MAX)
9523 rings = io_mem_alloc(size);
9528 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9529 rings->sq_ring_mask = p->sq_entries - 1;
9530 rings->cq_ring_mask = p->cq_entries - 1;
9531 rings->sq_ring_entries = p->sq_entries;
9532 rings->cq_ring_entries = p->cq_entries;
9534 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9535 if (size == SIZE_MAX) {
9536 io_mem_free(ctx->rings);
9541 ctx->sq_sqes = io_mem_alloc(size);
9542 if (!ctx->sq_sqes) {
9543 io_mem_free(ctx->rings);
9551 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9555 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9559 ret = io_uring_add_tctx_node(ctx);
9564 fd_install(fd, file);
9569 * Allocate an anonymous fd, this is what constitutes the application
9570 * visible backing of an io_uring instance. The application mmaps this
9571 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9572 * we have to tie this fd to a socket for file garbage collection purposes.
9574 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9577 #if defined(CONFIG_UNIX)
9580 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9583 return ERR_PTR(ret);
9586 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9587 O_RDWR | O_CLOEXEC);
9588 #if defined(CONFIG_UNIX)
9590 sock_release(ctx->ring_sock);
9591 ctx->ring_sock = NULL;
9593 ctx->ring_sock->file = file;
9599 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9600 struct io_uring_params __user *params)
9602 struct io_ring_ctx *ctx;
9608 if (entries > IORING_MAX_ENTRIES) {
9609 if (!(p->flags & IORING_SETUP_CLAMP))
9611 entries = IORING_MAX_ENTRIES;
9615 * Use twice as many entries for the CQ ring. It's possible for the
9616 * application to drive a higher depth than the size of the SQ ring,
9617 * since the sqes are only used at submission time. This allows for
9618 * some flexibility in overcommitting a bit. If the application has
9619 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9620 * of CQ ring entries manually.
9622 p->sq_entries = roundup_pow_of_two(entries);
9623 if (p->flags & IORING_SETUP_CQSIZE) {
9625 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9626 * to a power-of-two, if it isn't already. We do NOT impose
9627 * any cq vs sq ring sizing.
9631 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9632 if (!(p->flags & IORING_SETUP_CLAMP))
9634 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9636 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9637 if (p->cq_entries < p->sq_entries)
9640 p->cq_entries = 2 * p->sq_entries;
9643 ctx = io_ring_ctx_alloc(p);
9646 ctx->compat = in_compat_syscall();
9647 if (!capable(CAP_IPC_LOCK))
9648 ctx->user = get_uid(current_user());
9651 * This is just grabbed for accounting purposes. When a process exits,
9652 * the mm is exited and dropped before the files, hence we need to hang
9653 * on to this mm purely for the purposes of being able to unaccount
9654 * memory (locked/pinned vm). It's not used for anything else.
9656 mmgrab(current->mm);
9657 ctx->mm_account = current->mm;
9659 ret = io_allocate_scq_urings(ctx, p);
9663 ret = io_sq_offload_create(ctx, p);
9666 /* always set a rsrc node */
9667 ret = io_rsrc_node_switch_start(ctx);
9670 io_rsrc_node_switch(ctx, NULL);
9672 memset(&p->sq_off, 0, sizeof(p->sq_off));
9673 p->sq_off.head = offsetof(struct io_rings, sq.head);
9674 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9675 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9676 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9677 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9678 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9679 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9681 memset(&p->cq_off, 0, sizeof(p->cq_off));
9682 p->cq_off.head = offsetof(struct io_rings, cq.head);
9683 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9684 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9685 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9686 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9687 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9688 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9690 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9691 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9692 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9693 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9694 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9695 IORING_FEAT_RSRC_TAGS;
9697 if (copy_to_user(params, p, sizeof(*p))) {
9702 file = io_uring_get_file(ctx);
9704 ret = PTR_ERR(file);
9709 * Install ring fd as the very last thing, so we don't risk someone
9710 * having closed it before we finish setup
9712 ret = io_uring_install_fd(ctx, file);
9714 /* fput will clean it up */
9719 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9722 io_ring_ctx_wait_and_kill(ctx);
9727 * Sets up an aio uring context, and returns the fd. Applications asks for a
9728 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9729 * params structure passed in.
9731 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9733 struct io_uring_params p;
9736 if (copy_from_user(&p, params, sizeof(p)))
9738 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9743 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9744 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9745 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9746 IORING_SETUP_R_DISABLED))
9749 return io_uring_create(entries, &p, params);
9752 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9753 struct io_uring_params __user *, params)
9755 return io_uring_setup(entries, params);
9758 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9760 struct io_uring_probe *p;
9764 size = struct_size(p, ops, nr_args);
9765 if (size == SIZE_MAX)
9767 p = kzalloc(size, GFP_KERNEL);
9772 if (copy_from_user(p, arg, size))
9775 if (memchr_inv(p, 0, size))
9778 p->last_op = IORING_OP_LAST - 1;
9779 if (nr_args > IORING_OP_LAST)
9780 nr_args = IORING_OP_LAST;
9782 for (i = 0; i < nr_args; i++) {
9784 if (!io_op_defs[i].not_supported)
9785 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9790 if (copy_to_user(arg, p, size))
9797 static int io_register_personality(struct io_ring_ctx *ctx)
9799 const struct cred *creds;
9803 creds = get_current_cred();
9805 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9806 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9814 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9815 unsigned int nr_args)
9817 struct io_uring_restriction *res;
9821 /* Restrictions allowed only if rings started disabled */
9822 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9825 /* We allow only a single restrictions registration */
9826 if (ctx->restrictions.registered)
9829 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9832 size = array_size(nr_args, sizeof(*res));
9833 if (size == SIZE_MAX)
9836 res = memdup_user(arg, size);
9838 return PTR_ERR(res);
9842 for (i = 0; i < nr_args; i++) {
9843 switch (res[i].opcode) {
9844 case IORING_RESTRICTION_REGISTER_OP:
9845 if (res[i].register_op >= IORING_REGISTER_LAST) {
9850 __set_bit(res[i].register_op,
9851 ctx->restrictions.register_op);
9853 case IORING_RESTRICTION_SQE_OP:
9854 if (res[i].sqe_op >= IORING_OP_LAST) {
9859 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9861 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9862 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9864 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9865 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9874 /* Reset all restrictions if an error happened */
9876 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9878 ctx->restrictions.registered = true;
9884 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9886 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9889 if (ctx->restrictions.registered)
9890 ctx->restricted = 1;
9892 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9893 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9894 wake_up(&ctx->sq_data->wait);
9898 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9899 struct io_uring_rsrc_update2 *up,
9907 if (check_add_overflow(up->offset, nr_args, &tmp))
9909 err = io_rsrc_node_switch_start(ctx);
9914 case IORING_RSRC_FILE:
9915 return __io_sqe_files_update(ctx, up, nr_args);
9916 case IORING_RSRC_BUFFER:
9917 return __io_sqe_buffers_update(ctx, up, nr_args);
9922 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9925 struct io_uring_rsrc_update2 up;
9929 memset(&up, 0, sizeof(up));
9930 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9932 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9935 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9936 unsigned size, unsigned type)
9938 struct io_uring_rsrc_update2 up;
9940 if (size != sizeof(up))
9942 if (copy_from_user(&up, arg, sizeof(up)))
9944 if (!up.nr || up.resv)
9946 return __io_register_rsrc_update(ctx, type, &up, up.nr);
9949 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9950 unsigned int size, unsigned int type)
9952 struct io_uring_rsrc_register rr;
9954 /* keep it extendible */
9955 if (size != sizeof(rr))
9958 memset(&rr, 0, sizeof(rr));
9959 if (copy_from_user(&rr, arg, size))
9961 if (!rr.nr || rr.resv || rr.resv2)
9965 case IORING_RSRC_FILE:
9966 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
9967 rr.nr, u64_to_user_ptr(rr.tags));
9968 case IORING_RSRC_BUFFER:
9969 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
9970 rr.nr, u64_to_user_ptr(rr.tags));
9975 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
9978 struct io_uring_task *tctx = current->io_uring;
9979 cpumask_var_t new_mask;
9982 if (!tctx || !tctx->io_wq)
9985 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
9988 cpumask_clear(new_mask);
9989 if (len > cpumask_size())
9990 len = cpumask_size();
9992 if (copy_from_user(new_mask, arg, len)) {
9993 free_cpumask_var(new_mask);
9997 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
9998 free_cpumask_var(new_mask);
10002 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10004 struct io_uring_task *tctx = current->io_uring;
10006 if (!tctx || !tctx->io_wq)
10009 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10012 static bool io_register_op_must_quiesce(int op)
10015 case IORING_REGISTER_BUFFERS:
10016 case IORING_UNREGISTER_BUFFERS:
10017 case IORING_REGISTER_FILES:
10018 case IORING_UNREGISTER_FILES:
10019 case IORING_REGISTER_FILES_UPDATE:
10020 case IORING_REGISTER_PROBE:
10021 case IORING_REGISTER_PERSONALITY:
10022 case IORING_UNREGISTER_PERSONALITY:
10023 case IORING_REGISTER_FILES2:
10024 case IORING_REGISTER_FILES_UPDATE2:
10025 case IORING_REGISTER_BUFFERS2:
10026 case IORING_REGISTER_BUFFERS_UPDATE:
10027 case IORING_REGISTER_IOWQ_AFF:
10028 case IORING_UNREGISTER_IOWQ_AFF:
10035 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10039 percpu_ref_kill(&ctx->refs);
10042 * Drop uring mutex before waiting for references to exit. If another
10043 * thread is currently inside io_uring_enter() it might need to grab the
10044 * uring_lock to make progress. If we hold it here across the drain
10045 * wait, then we can deadlock. It's safe to drop the mutex here, since
10046 * no new references will come in after we've killed the percpu ref.
10048 mutex_unlock(&ctx->uring_lock);
10050 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10053 ret = io_run_task_work_sig();
10054 } while (ret >= 0);
10055 mutex_lock(&ctx->uring_lock);
10058 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10062 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10063 void __user *arg, unsigned nr_args)
10064 __releases(ctx->uring_lock)
10065 __acquires(ctx->uring_lock)
10070 * We're inside the ring mutex, if the ref is already dying, then
10071 * someone else killed the ctx or is already going through
10072 * io_uring_register().
10074 if (percpu_ref_is_dying(&ctx->refs))
10077 if (ctx->restricted) {
10078 if (opcode >= IORING_REGISTER_LAST)
10080 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10081 if (!test_bit(opcode, ctx->restrictions.register_op))
10085 if (io_register_op_must_quiesce(opcode)) {
10086 ret = io_ctx_quiesce(ctx);
10092 case IORING_REGISTER_BUFFERS:
10093 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10095 case IORING_UNREGISTER_BUFFERS:
10097 if (arg || nr_args)
10099 ret = io_sqe_buffers_unregister(ctx);
10101 case IORING_REGISTER_FILES:
10102 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10104 case IORING_UNREGISTER_FILES:
10106 if (arg || nr_args)
10108 ret = io_sqe_files_unregister(ctx);
10110 case IORING_REGISTER_FILES_UPDATE:
10111 ret = io_register_files_update(ctx, arg, nr_args);
10113 case IORING_REGISTER_EVENTFD:
10114 case IORING_REGISTER_EVENTFD_ASYNC:
10118 ret = io_eventfd_register(ctx, arg);
10121 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10122 ctx->eventfd_async = 1;
10124 ctx->eventfd_async = 0;
10126 case IORING_UNREGISTER_EVENTFD:
10128 if (arg || nr_args)
10130 ret = io_eventfd_unregister(ctx);
10132 case IORING_REGISTER_PROBE:
10134 if (!arg || nr_args > 256)
10136 ret = io_probe(ctx, arg, nr_args);
10138 case IORING_REGISTER_PERSONALITY:
10140 if (arg || nr_args)
10142 ret = io_register_personality(ctx);
10144 case IORING_UNREGISTER_PERSONALITY:
10148 ret = io_unregister_personality(ctx, nr_args);
10150 case IORING_REGISTER_ENABLE_RINGS:
10152 if (arg || nr_args)
10154 ret = io_register_enable_rings(ctx);
10156 case IORING_REGISTER_RESTRICTIONS:
10157 ret = io_register_restrictions(ctx, arg, nr_args);
10159 case IORING_REGISTER_FILES2:
10160 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10162 case IORING_REGISTER_FILES_UPDATE2:
10163 ret = io_register_rsrc_update(ctx, arg, nr_args,
10166 case IORING_REGISTER_BUFFERS2:
10167 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10169 case IORING_REGISTER_BUFFERS_UPDATE:
10170 ret = io_register_rsrc_update(ctx, arg, nr_args,
10171 IORING_RSRC_BUFFER);
10173 case IORING_REGISTER_IOWQ_AFF:
10175 if (!arg || !nr_args)
10177 ret = io_register_iowq_aff(ctx, arg, nr_args);
10179 case IORING_UNREGISTER_IOWQ_AFF:
10181 if (arg || nr_args)
10183 ret = io_unregister_iowq_aff(ctx);
10190 if (io_register_op_must_quiesce(opcode)) {
10191 /* bring the ctx back to life */
10192 percpu_ref_reinit(&ctx->refs);
10193 reinit_completion(&ctx->ref_comp);
10198 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10199 void __user *, arg, unsigned int, nr_args)
10201 struct io_ring_ctx *ctx;
10210 if (f.file->f_op != &io_uring_fops)
10213 ctx = f.file->private_data;
10215 io_run_task_work();
10217 mutex_lock(&ctx->uring_lock);
10218 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10219 mutex_unlock(&ctx->uring_lock);
10220 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10221 ctx->cq_ev_fd != NULL, ret);
10227 static int __init io_uring_init(void)
10229 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10230 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10231 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10234 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10235 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10236 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10237 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10238 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10239 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10240 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10241 BUILD_BUG_SQE_ELEM(8, __u64, off);
10242 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10243 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10244 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10245 BUILD_BUG_SQE_ELEM(24, __u32, len);
10246 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10247 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10248 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10249 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10250 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10251 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10252 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10253 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10254 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10255 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10256 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10257 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10258 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10259 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10260 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10261 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10262 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10263 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10264 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10265 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10267 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10268 sizeof(struct io_uring_rsrc_update));
10269 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10270 sizeof(struct io_uring_rsrc_update2));
10271 /* should fit into one byte */
10272 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10274 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10275 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10277 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10281 __initcall(io_uring_init);