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_IOPOLL_BATCH 8
299 #define IO_COMPL_BATCH 32
300 #define IO_REQ_CACHE_SIZE 32
301 #define IO_REQ_ALLOC_BATCH 8
303 struct io_comp_state {
304 struct io_kiocb *reqs[IO_COMPL_BATCH];
306 /* inline/task_work completion list, under ->uring_lock */
307 struct list_head free_list;
310 struct io_submit_link {
311 struct io_kiocb *head;
312 struct io_kiocb *last;
315 struct io_submit_state {
316 struct blk_plug plug;
317 struct io_submit_link link;
320 * io_kiocb alloc cache
322 void *reqs[IO_REQ_CACHE_SIZE];
323 unsigned int free_reqs;
328 * Batch completion logic
330 struct io_comp_state comp;
333 * File reference cache
337 unsigned int file_refs;
338 unsigned int ios_left;
342 /* const or read-mostly hot data */
344 struct percpu_ref refs;
346 struct io_rings *rings;
348 unsigned int compat: 1;
349 unsigned int drain_next: 1;
350 unsigned int eventfd_async: 1;
351 unsigned int restricted: 1;
352 unsigned int off_timeout_used: 1;
353 unsigned int drain_active: 1;
354 } ____cacheline_aligned_in_smp;
356 /* submission data */
358 struct mutex uring_lock;
361 * Ring buffer of indices into array of io_uring_sqe, which is
362 * mmapped by the application using the IORING_OFF_SQES offset.
364 * This indirection could e.g. be used to assign fixed
365 * io_uring_sqe entries to operations and only submit them to
366 * the queue when needed.
368 * The kernel modifies neither the indices array nor the entries
372 struct io_uring_sqe *sq_sqes;
373 unsigned cached_sq_head;
375 struct list_head defer_list;
378 * Fixed resources fast path, should be accessed only under
379 * uring_lock, and updated through io_uring_register(2)
381 struct io_rsrc_node *rsrc_node;
382 struct io_file_table file_table;
383 unsigned nr_user_files;
384 unsigned nr_user_bufs;
385 struct io_mapped_ubuf **user_bufs;
387 struct io_submit_state submit_state;
388 struct list_head timeout_list;
389 struct list_head cq_overflow_list;
390 struct xarray io_buffers;
391 struct xarray personalities;
393 unsigned sq_thread_idle;
394 } ____cacheline_aligned_in_smp;
396 /* IRQ completion list, under ->completion_lock */
397 struct list_head locked_free_list;
398 unsigned int locked_free_nr;
400 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
401 struct io_sq_data *sq_data; /* if using sq thread polling */
403 struct wait_queue_head sqo_sq_wait;
404 struct list_head sqd_list;
406 unsigned long check_cq_overflow;
409 unsigned cached_cq_tail;
411 struct eventfd_ctx *cq_ev_fd;
412 struct wait_queue_head poll_wait;
413 struct wait_queue_head cq_wait;
415 atomic_t cq_timeouts;
416 struct fasync_struct *cq_fasync;
417 unsigned cq_last_tm_flush;
418 } ____cacheline_aligned_in_smp;
421 spinlock_t completion_lock;
424 * ->iopoll_list is protected by the ctx->uring_lock for
425 * io_uring instances that don't use IORING_SETUP_SQPOLL.
426 * For SQPOLL, only the single threaded io_sq_thread() will
427 * manipulate the list, hence no extra locking is needed there.
429 struct list_head iopoll_list;
430 struct hlist_head *cancel_hash;
431 unsigned cancel_hash_bits;
432 bool poll_multi_queue;
433 } ____cacheline_aligned_in_smp;
435 struct io_restriction restrictions;
437 /* slow path rsrc auxilary data, used by update/register */
439 struct io_rsrc_node *rsrc_backup_node;
440 struct io_mapped_ubuf *dummy_ubuf;
441 struct io_rsrc_data *file_data;
442 struct io_rsrc_data *buf_data;
444 struct delayed_work rsrc_put_work;
445 struct llist_head rsrc_put_llist;
446 struct list_head rsrc_ref_list;
447 spinlock_t rsrc_ref_lock;
450 /* Keep this last, we don't need it for the fast path */
452 #if defined(CONFIG_UNIX)
453 struct socket *ring_sock;
455 /* hashed buffered write serialization */
456 struct io_wq_hash *hash_map;
458 /* Only used for accounting purposes */
459 struct user_struct *user;
460 struct mm_struct *mm_account;
462 /* ctx exit and cancelation */
463 struct llist_head fallback_llist;
464 struct delayed_work fallback_work;
465 struct work_struct exit_work;
466 struct list_head tctx_list;
467 struct completion ref_comp;
471 struct io_uring_task {
472 /* submission side */
475 struct wait_queue_head wait;
476 const struct io_ring_ctx *last;
478 struct percpu_counter inflight;
479 atomic_t inflight_tracked;
482 spinlock_t task_lock;
483 struct io_wq_work_list task_list;
484 unsigned long task_state;
485 struct callback_head task_work;
489 * First field must be the file pointer in all the
490 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
492 struct io_poll_iocb {
494 struct wait_queue_head *head;
498 struct wait_queue_entry wait;
501 struct io_poll_update {
507 bool update_user_data;
515 struct io_timeout_data {
516 struct io_kiocb *req;
517 struct hrtimer timer;
518 struct timespec64 ts;
519 enum hrtimer_mode mode;
524 struct sockaddr __user *addr;
525 int __user *addr_len;
527 unsigned long nofile;
547 struct list_head list;
548 /* head of the link, used by linked timeouts only */
549 struct io_kiocb *head;
552 struct io_timeout_rem {
557 struct timespec64 ts;
562 /* NOTE: kiocb has the file as the first member, so don't do it here */
570 struct sockaddr __user *addr;
577 struct compat_msghdr __user *umsg_compat;
578 struct user_msghdr __user *umsg;
584 struct io_buffer *kbuf;
590 struct filename *filename;
592 unsigned long nofile;
595 struct io_rsrc_update {
621 struct epoll_event event;
625 struct file *file_out;
626 struct file *file_in;
633 struct io_provide_buf {
647 const char __user *filename;
648 struct statx __user *buffer;
660 struct filename *oldpath;
661 struct filename *newpath;
669 struct filename *filename;
672 struct io_completion {
674 struct list_head list;
678 struct io_async_connect {
679 struct sockaddr_storage address;
682 struct io_async_msghdr {
683 struct iovec fast_iov[UIO_FASTIOV];
684 /* points to an allocated iov, if NULL we use fast_iov instead */
685 struct iovec *free_iov;
686 struct sockaddr __user *uaddr;
688 struct sockaddr_storage addr;
692 struct iovec fast_iov[UIO_FASTIOV];
693 const struct iovec *free_iovec;
694 struct iov_iter iter;
696 struct wait_page_queue wpq;
700 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
701 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
702 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
703 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
704 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
705 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
707 /* first byte is taken by user flags, shift it to not overlap */
712 REQ_F_LINK_TIMEOUT_BIT,
713 REQ_F_NEED_CLEANUP_BIT,
715 REQ_F_BUFFER_SELECTED_BIT,
716 REQ_F_LTIMEOUT_ACTIVE_BIT,
717 REQ_F_COMPLETE_INLINE_BIT,
719 REQ_F_DONT_REISSUE_BIT,
721 /* keep async read/write and isreg together and in order */
722 REQ_F_NOWAIT_READ_BIT,
723 REQ_F_NOWAIT_WRITE_BIT,
726 /* not a real bit, just to check we're not overflowing the space */
732 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
733 /* drain existing IO first */
734 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
736 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
737 /* doesn't sever on completion < 0 */
738 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
740 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
741 /* IOSQE_BUFFER_SELECT */
742 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
744 /* fail rest of links */
745 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
746 /* on inflight list, should be cancelled and waited on exit reliably */
747 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
748 /* read/write uses file position */
749 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
750 /* must not punt to workers */
751 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
752 /* has or had linked timeout */
753 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
755 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
756 /* already went through poll handler */
757 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
758 /* buffer already selected */
759 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
760 /* linked timeout is active, i.e. prepared by link's head */
761 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
762 /* completion is deferred through io_comp_state */
763 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
764 /* caller should reissue async */
765 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
766 /* don't attempt request reissue, see io_rw_reissue() */
767 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
768 /* supports async reads */
769 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
770 /* supports async writes */
771 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
773 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
774 /* has creds assigned */
775 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
779 struct io_poll_iocb poll;
780 struct io_poll_iocb *double_poll;
783 typedef void (*io_req_tw_func_t)(struct io_kiocb *req);
785 struct io_task_work {
787 struct io_wq_work_node node;
788 struct llist_node fallback_node;
790 io_req_tw_func_t func;
794 IORING_RSRC_FILE = 0,
795 IORING_RSRC_BUFFER = 1,
799 * NOTE! Each of the iocb union members has the file pointer
800 * as the first entry in their struct definition. So you can
801 * access the file pointer through any of the sub-structs,
802 * or directly as just 'ki_filp' in this struct.
808 struct io_poll_iocb poll;
809 struct io_poll_update poll_update;
810 struct io_accept accept;
812 struct io_cancel cancel;
813 struct io_timeout timeout;
814 struct io_timeout_rem timeout_rem;
815 struct io_connect connect;
816 struct io_sr_msg sr_msg;
818 struct io_close close;
819 struct io_rsrc_update rsrc_update;
820 struct io_fadvise fadvise;
821 struct io_madvise madvise;
822 struct io_epoll epoll;
823 struct io_splice splice;
824 struct io_provide_buf pbuf;
825 struct io_statx statx;
826 struct io_shutdown shutdown;
827 struct io_rename rename;
828 struct io_unlink unlink;
829 /* use only after cleaning per-op data, see io_clean_op() */
830 struct io_completion compl;
833 /* opcode allocated if it needs to store data for async defer */
836 /* polled IO has completed */
842 struct io_ring_ctx *ctx;
845 struct task_struct *task;
848 struct io_kiocb *link;
849 struct percpu_ref *fixed_rsrc_refs;
851 /* used with ctx->iopoll_list with reads/writes */
852 struct list_head inflight_entry;
853 struct io_task_work io_task_work;
854 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
855 struct hlist_node hash_node;
856 struct async_poll *apoll;
857 struct io_wq_work work;
858 const struct cred *creds;
860 /* store used ubuf, so we can prevent reloading */
861 struct io_mapped_ubuf *imu;
864 struct io_tctx_node {
865 struct list_head ctx_node;
866 struct task_struct *task;
867 struct io_ring_ctx *ctx;
870 struct io_defer_entry {
871 struct list_head list;
872 struct io_kiocb *req;
877 /* needs req->file assigned */
878 unsigned needs_file : 1;
879 /* hash wq insertion if file is a regular file */
880 unsigned hash_reg_file : 1;
881 /* unbound wq insertion if file is a non-regular file */
882 unsigned unbound_nonreg_file : 1;
883 /* opcode is not supported by this kernel */
884 unsigned not_supported : 1;
885 /* set if opcode supports polled "wait" */
887 unsigned pollout : 1;
888 /* op supports buffer selection */
889 unsigned buffer_select : 1;
890 /* do prep async if is going to be punted */
891 unsigned needs_async_setup : 1;
892 /* should block plug */
894 /* size of async data needed, if any */
895 unsigned short async_size;
898 static const struct io_op_def io_op_defs[] = {
899 [IORING_OP_NOP] = {},
900 [IORING_OP_READV] = {
902 .unbound_nonreg_file = 1,
905 .needs_async_setup = 1,
907 .async_size = sizeof(struct io_async_rw),
909 [IORING_OP_WRITEV] = {
912 .unbound_nonreg_file = 1,
914 .needs_async_setup = 1,
916 .async_size = sizeof(struct io_async_rw),
918 [IORING_OP_FSYNC] = {
921 [IORING_OP_READ_FIXED] = {
923 .unbound_nonreg_file = 1,
926 .async_size = sizeof(struct io_async_rw),
928 [IORING_OP_WRITE_FIXED] = {
931 .unbound_nonreg_file = 1,
934 .async_size = sizeof(struct io_async_rw),
936 [IORING_OP_POLL_ADD] = {
938 .unbound_nonreg_file = 1,
940 [IORING_OP_POLL_REMOVE] = {},
941 [IORING_OP_SYNC_FILE_RANGE] = {
944 [IORING_OP_SENDMSG] = {
946 .unbound_nonreg_file = 1,
948 .needs_async_setup = 1,
949 .async_size = sizeof(struct io_async_msghdr),
951 [IORING_OP_RECVMSG] = {
953 .unbound_nonreg_file = 1,
956 .needs_async_setup = 1,
957 .async_size = sizeof(struct io_async_msghdr),
959 [IORING_OP_TIMEOUT] = {
960 .async_size = sizeof(struct io_timeout_data),
962 [IORING_OP_TIMEOUT_REMOVE] = {
963 /* used by timeout updates' prep() */
965 [IORING_OP_ACCEPT] = {
967 .unbound_nonreg_file = 1,
970 [IORING_OP_ASYNC_CANCEL] = {},
971 [IORING_OP_LINK_TIMEOUT] = {
972 .async_size = sizeof(struct io_timeout_data),
974 [IORING_OP_CONNECT] = {
976 .unbound_nonreg_file = 1,
978 .needs_async_setup = 1,
979 .async_size = sizeof(struct io_async_connect),
981 [IORING_OP_FALLOCATE] = {
984 [IORING_OP_OPENAT] = {},
985 [IORING_OP_CLOSE] = {},
986 [IORING_OP_FILES_UPDATE] = {},
987 [IORING_OP_STATX] = {},
990 .unbound_nonreg_file = 1,
994 .async_size = sizeof(struct io_async_rw),
996 [IORING_OP_WRITE] = {
998 .unbound_nonreg_file = 1,
1001 .async_size = sizeof(struct io_async_rw),
1003 [IORING_OP_FADVISE] = {
1006 [IORING_OP_MADVISE] = {},
1007 [IORING_OP_SEND] = {
1009 .unbound_nonreg_file = 1,
1012 [IORING_OP_RECV] = {
1014 .unbound_nonreg_file = 1,
1018 [IORING_OP_OPENAT2] = {
1020 [IORING_OP_EPOLL_CTL] = {
1021 .unbound_nonreg_file = 1,
1023 [IORING_OP_SPLICE] = {
1026 .unbound_nonreg_file = 1,
1028 [IORING_OP_PROVIDE_BUFFERS] = {},
1029 [IORING_OP_REMOVE_BUFFERS] = {},
1033 .unbound_nonreg_file = 1,
1035 [IORING_OP_SHUTDOWN] = {
1038 [IORING_OP_RENAMEAT] = {},
1039 [IORING_OP_UNLINKAT] = {},
1042 static bool io_disarm_next(struct io_kiocb *req);
1043 static void io_uring_del_tctx_node(unsigned long index);
1044 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1045 struct task_struct *task,
1047 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1048 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1050 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1051 long res, unsigned int cflags);
1052 static void io_put_req(struct io_kiocb *req);
1053 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1054 static void io_dismantle_req(struct io_kiocb *req);
1055 static void io_put_task(struct task_struct *task, int nr);
1056 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1057 static void io_queue_linked_timeout(struct io_kiocb *req);
1058 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1059 struct io_uring_rsrc_update2 *up,
1061 static void io_clean_op(struct io_kiocb *req);
1062 static struct file *io_file_get(struct io_ring_ctx *ctx,
1063 struct io_submit_state *state,
1064 struct io_kiocb *req, int fd, bool fixed);
1065 static void __io_queue_sqe(struct io_kiocb *req);
1066 static void io_rsrc_put_work(struct work_struct *work);
1068 static void io_req_task_queue(struct io_kiocb *req);
1069 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1070 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1071 static int io_req_prep_async(struct io_kiocb *req);
1073 static void io_fallback_req_func(struct work_struct *unused);
1075 static struct kmem_cache *req_cachep;
1077 static const struct file_operations io_uring_fops;
1079 struct sock *io_uring_get_socket(struct file *file)
1081 #if defined(CONFIG_UNIX)
1082 if (file->f_op == &io_uring_fops) {
1083 struct io_ring_ctx *ctx = file->private_data;
1085 return ctx->ring_sock->sk;
1090 EXPORT_SYMBOL(io_uring_get_socket);
1092 #define io_for_each_link(pos, head) \
1093 for (pos = (head); pos; pos = pos->link)
1095 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1097 struct io_ring_ctx *ctx = req->ctx;
1099 if (!req->fixed_rsrc_refs) {
1100 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1101 percpu_ref_get(req->fixed_rsrc_refs);
1105 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1107 bool got = percpu_ref_tryget(ref);
1109 /* already at zero, wait for ->release() */
1111 wait_for_completion(compl);
1112 percpu_ref_resurrect(ref);
1114 percpu_ref_put(ref);
1117 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1120 struct io_kiocb *req;
1122 if (task && head->task != task)
1127 io_for_each_link(req, head) {
1128 if (req->flags & REQ_F_INFLIGHT)
1134 static inline void req_set_fail(struct io_kiocb *req)
1136 req->flags |= REQ_F_FAIL;
1139 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1141 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1143 complete(&ctx->ref_comp);
1146 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1148 return !req->timeout.off;
1151 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1153 struct io_ring_ctx *ctx;
1156 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1161 * Use 5 bits less than the max cq entries, that should give us around
1162 * 32 entries per hash list if totally full and uniformly spread.
1164 hash_bits = ilog2(p->cq_entries);
1168 ctx->cancel_hash_bits = hash_bits;
1169 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1171 if (!ctx->cancel_hash)
1173 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1175 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1176 if (!ctx->dummy_ubuf)
1178 /* set invalid range, so io_import_fixed() fails meeting it */
1179 ctx->dummy_ubuf->ubuf = -1UL;
1181 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1182 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1185 ctx->flags = p->flags;
1186 init_waitqueue_head(&ctx->sqo_sq_wait);
1187 INIT_LIST_HEAD(&ctx->sqd_list);
1188 init_waitqueue_head(&ctx->poll_wait);
1189 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1190 init_completion(&ctx->ref_comp);
1191 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1192 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1193 mutex_init(&ctx->uring_lock);
1194 init_waitqueue_head(&ctx->cq_wait);
1195 spin_lock_init(&ctx->completion_lock);
1196 INIT_LIST_HEAD(&ctx->iopoll_list);
1197 INIT_LIST_HEAD(&ctx->defer_list);
1198 INIT_LIST_HEAD(&ctx->timeout_list);
1199 spin_lock_init(&ctx->rsrc_ref_lock);
1200 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1201 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1202 init_llist_head(&ctx->rsrc_put_llist);
1203 INIT_LIST_HEAD(&ctx->tctx_list);
1204 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1205 INIT_LIST_HEAD(&ctx->locked_free_list);
1206 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1209 kfree(ctx->dummy_ubuf);
1210 kfree(ctx->cancel_hash);
1215 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1217 struct io_rings *r = ctx->rings;
1219 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1223 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1225 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1226 struct io_ring_ctx *ctx = req->ctx;
1228 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1234 #define FFS_ASYNC_READ 0x1UL
1235 #define FFS_ASYNC_WRITE 0x2UL
1237 #define FFS_ISREG 0x4UL
1239 #define FFS_ISREG 0x0UL
1241 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1243 static inline bool io_req_ffs_set(struct io_kiocb *req)
1245 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1248 static void io_req_track_inflight(struct io_kiocb *req)
1250 if (!(req->flags & REQ_F_INFLIGHT)) {
1251 req->flags |= REQ_F_INFLIGHT;
1252 atomic_inc(¤t->io_uring->inflight_tracked);
1256 static void io_prep_async_work(struct io_kiocb *req)
1258 const struct io_op_def *def = &io_op_defs[req->opcode];
1259 struct io_ring_ctx *ctx = req->ctx;
1261 if (!(req->flags & REQ_F_CREDS)) {
1262 req->flags |= REQ_F_CREDS;
1263 req->creds = get_current_cred();
1266 req->work.list.next = NULL;
1267 req->work.flags = 0;
1268 if (req->flags & REQ_F_FORCE_ASYNC)
1269 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1271 if (req->flags & REQ_F_ISREG) {
1272 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1273 io_wq_hash_work(&req->work, file_inode(req->file));
1274 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1275 if (def->unbound_nonreg_file)
1276 req->work.flags |= IO_WQ_WORK_UNBOUND;
1279 switch (req->opcode) {
1280 case IORING_OP_SPLICE:
1282 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1283 req->work.flags |= IO_WQ_WORK_UNBOUND;
1288 static void io_prep_async_link(struct io_kiocb *req)
1290 struct io_kiocb *cur;
1292 if (req->flags & REQ_F_LINK_TIMEOUT) {
1293 struct io_ring_ctx *ctx = req->ctx;
1295 spin_lock_irq(&ctx->completion_lock);
1296 io_for_each_link(cur, req)
1297 io_prep_async_work(cur);
1298 spin_unlock_irq(&ctx->completion_lock);
1300 io_for_each_link(cur, req)
1301 io_prep_async_work(cur);
1305 static void io_queue_async_work(struct io_kiocb *req)
1307 struct io_ring_ctx *ctx = req->ctx;
1308 struct io_kiocb *link = io_prep_linked_timeout(req);
1309 struct io_uring_task *tctx = req->task->io_uring;
1312 BUG_ON(!tctx->io_wq);
1314 /* init ->work of the whole link before punting */
1315 io_prep_async_link(req);
1318 * Not expected to happen, but if we do have a bug where this _can_
1319 * happen, catch it here and ensure the request is marked as
1320 * canceled. That will make io-wq go through the usual work cancel
1321 * procedure rather than attempt to run this request (or create a new
1324 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1325 req->work.flags |= IO_WQ_WORK_CANCEL;
1327 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1328 &req->work, req->flags);
1329 io_wq_enqueue(tctx->io_wq, &req->work);
1331 io_queue_linked_timeout(link);
1334 static void io_kill_timeout(struct io_kiocb *req, int status)
1335 __must_hold(&req->ctx->completion_lock)
1337 struct io_timeout_data *io = req->async_data;
1339 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1340 atomic_set(&req->ctx->cq_timeouts,
1341 atomic_read(&req->ctx->cq_timeouts) + 1);
1342 list_del_init(&req->timeout.list);
1343 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1344 io_put_req_deferred(req, 1);
1348 static void io_queue_deferred(struct io_ring_ctx *ctx)
1350 while (!list_empty(&ctx->defer_list)) {
1351 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1352 struct io_defer_entry, list);
1354 if (req_need_defer(de->req, de->seq))
1356 list_del_init(&de->list);
1357 io_req_task_queue(de->req);
1362 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1364 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1366 while (!list_empty(&ctx->timeout_list)) {
1367 u32 events_needed, events_got;
1368 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1369 struct io_kiocb, timeout.list);
1371 if (io_is_timeout_noseq(req))
1375 * Since seq can easily wrap around over time, subtract
1376 * the last seq at which timeouts were flushed before comparing.
1377 * Assuming not more than 2^31-1 events have happened since,
1378 * these subtractions won't have wrapped, so we can check if
1379 * target is in [last_seq, current_seq] by comparing the two.
1381 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1382 events_got = seq - ctx->cq_last_tm_flush;
1383 if (events_got < events_needed)
1386 list_del_init(&req->timeout.list);
1387 io_kill_timeout(req, 0);
1389 ctx->cq_last_tm_flush = seq;
1392 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1394 if (ctx->off_timeout_used)
1395 io_flush_timeouts(ctx);
1396 if (ctx->drain_active)
1397 io_queue_deferred(ctx);
1400 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1402 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1403 __io_commit_cqring_flush(ctx);
1404 /* order cqe stores with ring update */
1405 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1408 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1410 struct io_rings *r = ctx->rings;
1412 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1415 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1417 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1420 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1422 struct io_rings *rings = ctx->rings;
1423 unsigned tail, mask = ctx->cq_entries - 1;
1426 * writes to the cq entry need to come after reading head; the
1427 * control dependency is enough as we're using WRITE_ONCE to
1430 if (__io_cqring_events(ctx) == ctx->cq_entries)
1433 tail = ctx->cached_cq_tail++;
1434 return &rings->cqes[tail & mask];
1437 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1439 if (likely(!ctx->cq_ev_fd))
1441 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1443 return !ctx->eventfd_async || io_wq_current_is_worker();
1446 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1449 * wake_up_all() may seem excessive, but io_wake_function() and
1450 * io_should_wake() handle the termination of the loop and only
1451 * wake as many waiters as we need to.
1453 if (wq_has_sleeper(&ctx->cq_wait))
1454 wake_up_all(&ctx->cq_wait);
1455 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1456 wake_up(&ctx->sq_data->wait);
1457 if (io_should_trigger_evfd(ctx))
1458 eventfd_signal(ctx->cq_ev_fd, 1);
1459 if (waitqueue_active(&ctx->poll_wait)) {
1460 wake_up_interruptible(&ctx->poll_wait);
1461 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1465 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1467 if (ctx->flags & IORING_SETUP_SQPOLL) {
1468 if (wq_has_sleeper(&ctx->cq_wait))
1469 wake_up_all(&ctx->cq_wait);
1471 if (io_should_trigger_evfd(ctx))
1472 eventfd_signal(ctx->cq_ev_fd, 1);
1473 if (waitqueue_active(&ctx->poll_wait)) {
1474 wake_up_interruptible(&ctx->poll_wait);
1475 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1479 /* Returns true if there are no backlogged entries after the flush */
1480 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1482 unsigned long flags;
1483 bool all_flushed, posted;
1485 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1489 spin_lock_irqsave(&ctx->completion_lock, flags);
1490 while (!list_empty(&ctx->cq_overflow_list)) {
1491 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1492 struct io_overflow_cqe *ocqe;
1496 ocqe = list_first_entry(&ctx->cq_overflow_list,
1497 struct io_overflow_cqe, list);
1499 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1501 io_account_cq_overflow(ctx);
1504 list_del(&ocqe->list);
1508 all_flushed = list_empty(&ctx->cq_overflow_list);
1510 clear_bit(0, &ctx->check_cq_overflow);
1511 WRITE_ONCE(ctx->rings->sq_flags,
1512 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1516 io_commit_cqring(ctx);
1517 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1519 io_cqring_ev_posted(ctx);
1523 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1527 if (test_bit(0, &ctx->check_cq_overflow)) {
1528 /* iopoll syncs against uring_lock, not completion_lock */
1529 if (ctx->flags & IORING_SETUP_IOPOLL)
1530 mutex_lock(&ctx->uring_lock);
1531 ret = __io_cqring_overflow_flush(ctx, force);
1532 if (ctx->flags & IORING_SETUP_IOPOLL)
1533 mutex_unlock(&ctx->uring_lock);
1540 * Shamelessly stolen from the mm implementation of page reference checking,
1541 * see commit f958d7b528b1 for details.
1543 #define req_ref_zero_or_close_to_overflow(req) \
1544 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1546 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1548 return atomic_inc_not_zero(&req->refs);
1551 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1553 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1554 return atomic_sub_and_test(refs, &req->refs);
1557 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1559 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1560 return atomic_dec_and_test(&req->refs);
1563 static inline void req_ref_put(struct io_kiocb *req)
1565 WARN_ON_ONCE(req_ref_put_and_test(req));
1568 static inline void req_ref_get(struct io_kiocb *req)
1570 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1571 atomic_inc(&req->refs);
1574 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1575 long res, unsigned int cflags)
1577 struct io_overflow_cqe *ocqe;
1579 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1582 * If we're in ring overflow flush mode, or in task cancel mode,
1583 * or cannot allocate an overflow entry, then we need to drop it
1586 io_account_cq_overflow(ctx);
1589 if (list_empty(&ctx->cq_overflow_list)) {
1590 set_bit(0, &ctx->check_cq_overflow);
1591 WRITE_ONCE(ctx->rings->sq_flags,
1592 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1595 ocqe->cqe.user_data = user_data;
1596 ocqe->cqe.res = res;
1597 ocqe->cqe.flags = cflags;
1598 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1602 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1603 long res, unsigned int cflags)
1605 struct io_uring_cqe *cqe;
1607 trace_io_uring_complete(ctx, user_data, res, cflags);
1610 * If we can't get a cq entry, userspace overflowed the
1611 * submission (by quite a lot). Increment the overflow count in
1614 cqe = io_get_cqe(ctx);
1616 WRITE_ONCE(cqe->user_data, user_data);
1617 WRITE_ONCE(cqe->res, res);
1618 WRITE_ONCE(cqe->flags, cflags);
1621 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1624 /* not as hot to bloat with inlining */
1625 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1626 long res, unsigned int cflags)
1628 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1631 static void io_req_complete_post(struct io_kiocb *req, long res,
1632 unsigned int cflags)
1634 struct io_ring_ctx *ctx = req->ctx;
1635 unsigned long flags;
1637 spin_lock_irqsave(&ctx->completion_lock, flags);
1638 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1640 * If we're the last reference to this request, add to our locked
1643 if (req_ref_put_and_test(req)) {
1644 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1645 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL))
1646 io_disarm_next(req);
1648 io_req_task_queue(req->link);
1652 io_dismantle_req(req);
1653 io_put_task(req->task, 1);
1654 list_add(&req->compl.list, &ctx->locked_free_list);
1655 ctx->locked_free_nr++;
1657 if (!percpu_ref_tryget(&ctx->refs))
1660 io_commit_cqring(ctx);
1661 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1664 io_cqring_ev_posted(ctx);
1665 percpu_ref_put(&ctx->refs);
1669 static inline bool io_req_needs_clean(struct io_kiocb *req)
1671 return req->flags & IO_REQ_CLEAN_FLAGS;
1674 static void io_req_complete_state(struct io_kiocb *req, long res,
1675 unsigned int cflags)
1677 if (io_req_needs_clean(req))
1680 req->compl.cflags = cflags;
1681 req->flags |= REQ_F_COMPLETE_INLINE;
1684 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1685 long res, unsigned cflags)
1687 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1688 io_req_complete_state(req, res, cflags);
1690 io_req_complete_post(req, res, cflags);
1693 static inline void io_req_complete(struct io_kiocb *req, long res)
1695 __io_req_complete(req, 0, res, 0);
1698 static void io_req_complete_failed(struct io_kiocb *req, long res)
1702 io_req_complete_post(req, res, 0);
1705 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1706 struct io_comp_state *cs)
1708 spin_lock_irq(&ctx->completion_lock);
1709 list_splice_init(&ctx->locked_free_list, &cs->free_list);
1710 ctx->locked_free_nr = 0;
1711 spin_unlock_irq(&ctx->completion_lock);
1714 /* Returns true IFF there are requests in the cache */
1715 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1717 struct io_submit_state *state = &ctx->submit_state;
1718 struct io_comp_state *cs = &state->comp;
1722 * If we have more than a batch's worth of requests in our IRQ side
1723 * locked cache, grab the lock and move them over to our submission
1726 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1727 io_flush_cached_locked_reqs(ctx, cs);
1729 nr = state->free_reqs;
1730 while (!list_empty(&cs->free_list)) {
1731 struct io_kiocb *req = list_first_entry(&cs->free_list,
1732 struct io_kiocb, compl.list);
1734 list_del(&req->compl.list);
1735 state->reqs[nr++] = req;
1736 if (nr == ARRAY_SIZE(state->reqs))
1740 state->free_reqs = nr;
1744 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1746 struct io_submit_state *state = &ctx->submit_state;
1748 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1750 if (!state->free_reqs) {
1751 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1754 if (io_flush_cached_reqs(ctx))
1757 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1761 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1762 * retry single alloc to be on the safe side.
1764 if (unlikely(ret <= 0)) {
1765 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1766 if (!state->reqs[0])
1772 * Don't initialise the fields below on every allocation, but
1773 * do that in advance and keep valid on free.
1775 for (i = 0; i < ret; i++) {
1776 struct io_kiocb *req = state->reqs[i];
1780 req->async_data = NULL;
1781 /* not necessary, but safer to zero */
1784 state->free_reqs = ret;
1788 return state->reqs[state->free_reqs];
1791 static inline void io_put_file(struct file *file)
1797 static void io_dismantle_req(struct io_kiocb *req)
1799 unsigned int flags = req->flags;
1801 if (io_req_needs_clean(req))
1803 if (!(flags & REQ_F_FIXED_FILE))
1804 io_put_file(req->file);
1805 if (req->fixed_rsrc_refs)
1806 percpu_ref_put(req->fixed_rsrc_refs);
1807 if (req->async_data) {
1808 kfree(req->async_data);
1809 req->async_data = NULL;
1813 /* must to be called somewhat shortly after putting a request */
1814 static inline void io_put_task(struct task_struct *task, int nr)
1816 struct io_uring_task *tctx = task->io_uring;
1818 percpu_counter_sub(&tctx->inflight, nr);
1819 if (unlikely(atomic_read(&tctx->in_idle)))
1820 wake_up(&tctx->wait);
1821 put_task_struct_many(task, nr);
1824 static void __io_free_req(struct io_kiocb *req)
1826 struct io_ring_ctx *ctx = req->ctx;
1828 io_dismantle_req(req);
1829 io_put_task(req->task, 1);
1831 kmem_cache_free(req_cachep, req);
1832 percpu_ref_put(&ctx->refs);
1835 static inline void io_remove_next_linked(struct io_kiocb *req)
1837 struct io_kiocb *nxt = req->link;
1839 req->link = nxt->link;
1843 static bool io_kill_linked_timeout(struct io_kiocb *req)
1844 __must_hold(&req->ctx->completion_lock)
1846 struct io_kiocb *link = req->link;
1849 * Can happen if a linked timeout fired and link had been like
1850 * req -> link t-out -> link t-out [-> ...]
1852 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1853 struct io_timeout_data *io = link->async_data;
1855 io_remove_next_linked(req);
1856 link->timeout.head = NULL;
1857 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1858 io_cqring_fill_event(link->ctx, link->user_data,
1860 io_put_req_deferred(link, 1);
1867 static void io_fail_links(struct io_kiocb *req)
1868 __must_hold(&req->ctx->completion_lock)
1870 struct io_kiocb *nxt, *link = req->link;
1877 trace_io_uring_fail_link(req, link);
1878 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1879 io_put_req_deferred(link, 2);
1884 static bool io_disarm_next(struct io_kiocb *req)
1885 __must_hold(&req->ctx->completion_lock)
1887 bool posted = false;
1889 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1890 posted = io_kill_linked_timeout(req);
1891 if (unlikely((req->flags & REQ_F_FAIL) &&
1892 !(req->flags & REQ_F_HARDLINK))) {
1893 posted |= (req->link != NULL);
1899 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1901 struct io_kiocb *nxt;
1904 * If LINK is set, we have dependent requests in this chain. If we
1905 * didn't fail this request, queue the first one up, moving any other
1906 * dependencies to the next request. In case of failure, fail the rest
1909 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL)) {
1910 struct io_ring_ctx *ctx = req->ctx;
1911 unsigned long flags;
1914 spin_lock_irqsave(&ctx->completion_lock, flags);
1915 posted = io_disarm_next(req);
1917 io_commit_cqring(req->ctx);
1918 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1920 io_cqring_ev_posted(ctx);
1927 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1929 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1931 return __io_req_find_next(req);
1934 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1938 if (ctx->submit_state.comp.nr) {
1939 mutex_lock(&ctx->uring_lock);
1940 io_submit_flush_completions(ctx);
1941 mutex_unlock(&ctx->uring_lock);
1943 percpu_ref_put(&ctx->refs);
1946 static void tctx_task_work(struct callback_head *cb)
1948 struct io_ring_ctx *ctx = NULL;
1949 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1953 struct io_wq_work_node *node;
1955 spin_lock_irq(&tctx->task_lock);
1956 node = tctx->task_list.first;
1957 INIT_WQ_LIST(&tctx->task_list);
1958 spin_unlock_irq(&tctx->task_lock);
1961 struct io_wq_work_node *next = node->next;
1962 struct io_kiocb *req = container_of(node, struct io_kiocb,
1965 if (req->ctx != ctx) {
1966 ctx_flush_and_put(ctx);
1968 percpu_ref_get(&ctx->refs);
1970 req->io_task_work.func(req);
1973 if (wq_list_empty(&tctx->task_list)) {
1974 spin_lock_irq(&tctx->task_lock);
1975 clear_bit(0, &tctx->task_state);
1976 if (wq_list_empty(&tctx->task_list)) {
1977 spin_unlock_irq(&tctx->task_lock);
1980 spin_unlock_irq(&tctx->task_lock);
1981 /* another tctx_task_work() is enqueued, yield */
1982 if (test_and_set_bit(0, &tctx->task_state))
1988 ctx_flush_and_put(ctx);
1991 static void io_req_task_work_add(struct io_kiocb *req)
1993 struct task_struct *tsk = req->task;
1994 struct io_uring_task *tctx = tsk->io_uring;
1995 enum task_work_notify_mode notify;
1996 struct io_wq_work_node *node;
1997 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 spin_unlock_irqrestore(&tctx->task_lock, flags);
2005 /* task_work already pending, we're done */
2006 if (test_bit(0, &tctx->task_state) ||
2007 test_and_set_bit(0, &tctx->task_state))
2009 if (unlikely(tsk->flags & PF_EXITING))
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 clear_bit(0, &tctx->task_state);
2025 spin_lock_irqsave(&tctx->task_lock, flags);
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 (!(req->task->flags & PF_EXITING) && !req->task->in_execve)
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 io_put_task(rb->task, rb->task_refs);
2114 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2117 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2118 struct io_submit_state *state)
2121 io_dismantle_req(req);
2123 if (req->task != rb->task) {
2125 io_put_task(rb->task, rb->task_refs);
2126 rb->task = req->task;
2132 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2133 state->reqs[state->free_reqs++] = req;
2135 list_add(&req->compl.list, &state->comp.free_list);
2138 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2140 struct io_comp_state *cs = &ctx->submit_state.comp;
2142 struct req_batch rb;
2144 spin_lock_irq(&ctx->completion_lock);
2145 for (i = 0; i < nr; i++) {
2146 struct io_kiocb *req = cs->reqs[i];
2148 __io_cqring_fill_event(ctx, req->user_data, req->result,
2151 io_commit_cqring(ctx);
2152 spin_unlock_irq(&ctx->completion_lock);
2153 io_cqring_ev_posted(ctx);
2155 io_init_req_batch(&rb);
2156 for (i = 0; i < nr; i++) {
2157 struct io_kiocb *req = cs->reqs[i];
2159 /* submission and completion refs */
2160 if (req_ref_sub_and_test(req, 2))
2161 io_req_free_batch(&rb, req, &ctx->submit_state);
2164 io_req_free_batch_finish(ctx, &rb);
2169 * Drop reference to request, return next in chain (if there is one) if this
2170 * was the last reference to this request.
2172 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2174 struct io_kiocb *nxt = NULL;
2176 if (req_ref_put_and_test(req)) {
2177 nxt = io_req_find_next(req);
2183 static inline void io_put_req(struct io_kiocb *req)
2185 if (req_ref_put_and_test(req))
2189 static void io_free_req_deferred(struct io_kiocb *req)
2191 req->io_task_work.func = io_free_req;
2192 io_req_task_work_add(req);
2195 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2197 if (req_ref_sub_and_test(req, refs))
2198 io_free_req_deferred(req);
2201 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2203 /* See comment at the top of this file */
2205 return __io_cqring_events(ctx);
2208 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2210 struct io_rings *rings = ctx->rings;
2212 /* make sure SQ entry isn't read before tail */
2213 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2216 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2218 unsigned int cflags;
2220 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2221 cflags |= IORING_CQE_F_BUFFER;
2222 req->flags &= ~REQ_F_BUFFER_SELECTED;
2227 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2229 struct io_buffer *kbuf;
2231 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2232 return io_put_kbuf(req, kbuf);
2235 static inline bool io_run_task_work(void)
2237 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2238 __set_current_state(TASK_RUNNING);
2239 tracehook_notify_signal();
2247 * Find and free completed poll iocbs
2249 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2250 struct list_head *done, bool resubmit)
2252 struct req_batch rb;
2253 struct io_kiocb *req;
2255 /* order with ->result store in io_complete_rw_iopoll() */
2258 io_init_req_batch(&rb);
2259 while (!list_empty(done)) {
2262 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2263 list_del(&req->inflight_entry);
2265 if (READ_ONCE(req->result) == -EAGAIN && resubmit &&
2266 !(req->flags & REQ_F_DONT_REISSUE)) {
2267 req->iopoll_completed = 0;
2269 io_req_task_queue_reissue(req);
2273 if (req->flags & REQ_F_BUFFER_SELECTED)
2274 cflags = io_put_rw_kbuf(req);
2276 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2279 if (req_ref_put_and_test(req))
2280 io_req_free_batch(&rb, req, &ctx->submit_state);
2283 io_commit_cqring(ctx);
2284 io_cqring_ev_posted_iopoll(ctx);
2285 io_req_free_batch_finish(ctx, &rb);
2288 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2289 long min, bool resubmit)
2291 struct io_kiocb *req, *tmp;
2297 * Only spin for completions if we don't have multiple devices hanging
2298 * off our complete list, and we're under the requested amount.
2300 spin = !ctx->poll_multi_queue && *nr_events < min;
2303 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2304 struct kiocb *kiocb = &req->rw.kiocb;
2307 * Move completed and retryable entries to our local lists.
2308 * If we find a request that requires polling, break out
2309 * and complete those lists first, if we have entries there.
2311 if (READ_ONCE(req->iopoll_completed)) {
2312 list_move_tail(&req->inflight_entry, &done);
2315 if (!list_empty(&done))
2318 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2322 /* iopoll may have completed current req */
2323 if (READ_ONCE(req->iopoll_completed))
2324 list_move_tail(&req->inflight_entry, &done);
2331 if (!list_empty(&done))
2332 io_iopoll_complete(ctx, nr_events, &done, resubmit);
2338 * We can't just wait for polled events to come to us, we have to actively
2339 * find and complete them.
2341 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2343 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2346 mutex_lock(&ctx->uring_lock);
2347 while (!list_empty(&ctx->iopoll_list)) {
2348 unsigned int nr_events = 0;
2350 io_do_iopoll(ctx, &nr_events, 0, false);
2352 /* let it sleep and repeat later if can't complete a request */
2356 * Ensure we allow local-to-the-cpu processing to take place,
2357 * in this case we need to ensure that we reap all events.
2358 * Also let task_work, etc. to progress by releasing the mutex
2360 if (need_resched()) {
2361 mutex_unlock(&ctx->uring_lock);
2363 mutex_lock(&ctx->uring_lock);
2366 mutex_unlock(&ctx->uring_lock);
2369 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2371 unsigned int nr_events = 0;
2375 * We disallow the app entering submit/complete with polling, but we
2376 * still need to lock the ring to prevent racing with polled issue
2377 * that got punted to a workqueue.
2379 mutex_lock(&ctx->uring_lock);
2381 * Don't enter poll loop if we already have events pending.
2382 * If we do, we can potentially be spinning for commands that
2383 * already triggered a CQE (eg in error).
2385 if (test_bit(0, &ctx->check_cq_overflow))
2386 __io_cqring_overflow_flush(ctx, false);
2387 if (io_cqring_events(ctx))
2391 * If a submit got punted to a workqueue, we can have the
2392 * application entering polling for a command before it gets
2393 * issued. That app will hold the uring_lock for the duration
2394 * of the poll right here, so we need to take a breather every
2395 * now and then to ensure that the issue has a chance to add
2396 * the poll to the issued list. Otherwise we can spin here
2397 * forever, while the workqueue is stuck trying to acquire the
2400 if (list_empty(&ctx->iopoll_list)) {
2401 u32 tail = ctx->cached_cq_tail;
2403 mutex_unlock(&ctx->uring_lock);
2405 mutex_lock(&ctx->uring_lock);
2407 /* some requests don't go through iopoll_list */
2408 if (tail != ctx->cached_cq_tail ||
2409 list_empty(&ctx->iopoll_list))
2412 ret = io_do_iopoll(ctx, &nr_events, min, true);
2413 } while (!ret && nr_events < min && !need_resched());
2415 mutex_unlock(&ctx->uring_lock);
2419 static void kiocb_end_write(struct io_kiocb *req)
2422 * Tell lockdep we inherited freeze protection from submission
2425 if (req->flags & REQ_F_ISREG) {
2426 struct super_block *sb = file_inode(req->file)->i_sb;
2428 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2434 static bool io_resubmit_prep(struct io_kiocb *req)
2436 struct io_async_rw *rw = req->async_data;
2439 return !io_req_prep_async(req);
2440 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2441 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2445 static bool io_rw_should_reissue(struct io_kiocb *req)
2447 umode_t mode = file_inode(req->file)->i_mode;
2448 struct io_ring_ctx *ctx = req->ctx;
2450 if (!S_ISBLK(mode) && !S_ISREG(mode))
2452 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2453 !(ctx->flags & IORING_SETUP_IOPOLL)))
2456 * If ref is dying, we might be running poll reap from the exit work.
2457 * Don't attempt to reissue from that path, just let it fail with
2460 if (percpu_ref_is_dying(&ctx->refs))
2463 * Play it safe and assume not safe to re-import and reissue if we're
2464 * not in the original thread group (or in task context).
2466 if (!same_thread_group(req->task, current) || !in_task())
2471 static bool io_resubmit_prep(struct io_kiocb *req)
2475 static bool io_rw_should_reissue(struct io_kiocb *req)
2481 static void io_fallback_req_func(struct work_struct *work)
2483 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
2484 fallback_work.work);
2485 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
2486 struct io_kiocb *req, *tmp;
2488 percpu_ref_get(&ctx->refs);
2489 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
2490 req->io_task_work.func(req);
2491 percpu_ref_put(&ctx->refs);
2494 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2495 unsigned int issue_flags)
2499 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2500 kiocb_end_write(req);
2501 if (res != req->result) {
2502 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2503 io_rw_should_reissue(req)) {
2504 req->flags |= REQ_F_REISSUE;
2509 if (req->flags & REQ_F_BUFFER_SELECTED)
2510 cflags = io_put_rw_kbuf(req);
2511 __io_req_complete(req, issue_flags, res, cflags);
2514 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2516 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2518 __io_complete_rw(req, res, res2, 0);
2521 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2523 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2525 if (kiocb->ki_flags & IOCB_WRITE)
2526 kiocb_end_write(req);
2527 if (unlikely(res != req->result)) {
2528 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2529 io_resubmit_prep(req))) {
2531 req->flags |= REQ_F_DONT_REISSUE;
2535 WRITE_ONCE(req->result, res);
2536 /* order with io_iopoll_complete() checking ->result */
2538 WRITE_ONCE(req->iopoll_completed, 1);
2542 * After the iocb has been issued, it's safe to be found on the poll list.
2543 * Adding the kiocb to the list AFTER submission ensures that we don't
2544 * find it from a io_do_iopoll() thread before the issuer is done
2545 * accessing the kiocb cookie.
2547 static void io_iopoll_req_issued(struct io_kiocb *req)
2549 struct io_ring_ctx *ctx = req->ctx;
2550 const bool in_async = io_wq_current_is_worker();
2552 /* workqueue context doesn't hold uring_lock, grab it now */
2553 if (unlikely(in_async))
2554 mutex_lock(&ctx->uring_lock);
2557 * Track whether we have multiple files in our lists. This will impact
2558 * how we do polling eventually, not spinning if we're on potentially
2559 * different devices.
2561 if (list_empty(&ctx->iopoll_list)) {
2562 ctx->poll_multi_queue = false;
2563 } else if (!ctx->poll_multi_queue) {
2564 struct io_kiocb *list_req;
2565 unsigned int queue_num0, queue_num1;
2567 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2570 if (list_req->file != req->file) {
2571 ctx->poll_multi_queue = true;
2573 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2574 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2575 if (queue_num0 != queue_num1)
2576 ctx->poll_multi_queue = true;
2581 * For fast devices, IO may have already completed. If it has, add
2582 * it to the front so we find it first.
2584 if (READ_ONCE(req->iopoll_completed))
2585 list_add(&req->inflight_entry, &ctx->iopoll_list);
2587 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2589 if (unlikely(in_async)) {
2591 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2592 * in sq thread task context or in io worker task context. If
2593 * current task context is sq thread, we don't need to check
2594 * whether should wake up sq thread.
2596 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2597 wq_has_sleeper(&ctx->sq_data->wait))
2598 wake_up(&ctx->sq_data->wait);
2600 mutex_unlock(&ctx->uring_lock);
2604 static inline void io_state_file_put(struct io_submit_state *state)
2606 if (state->file_refs) {
2607 fput_many(state->file, state->file_refs);
2608 state->file_refs = 0;
2613 * Get as many references to a file as we have IOs left in this submission,
2614 * assuming most submissions are for one file, or at least that each file
2615 * has more than one submission.
2617 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2622 if (state->file_refs) {
2623 if (state->fd == fd) {
2627 io_state_file_put(state);
2629 state->file = fget_many(fd, state->ios_left);
2630 if (unlikely(!state->file))
2634 state->file_refs = state->ios_left - 1;
2638 static bool io_bdev_nowait(struct block_device *bdev)
2640 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2644 * If we tracked the file through the SCM inflight mechanism, we could support
2645 * any file. For now, just ensure that anything potentially problematic is done
2648 static bool __io_file_supports_nowait(struct file *file, int rw)
2650 umode_t mode = file_inode(file)->i_mode;
2652 if (S_ISBLK(mode)) {
2653 if (IS_ENABLED(CONFIG_BLOCK) &&
2654 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2660 if (S_ISREG(mode)) {
2661 if (IS_ENABLED(CONFIG_BLOCK) &&
2662 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2663 file->f_op != &io_uring_fops)
2668 /* any ->read/write should understand O_NONBLOCK */
2669 if (file->f_flags & O_NONBLOCK)
2672 if (!(file->f_mode & FMODE_NOWAIT))
2676 return file->f_op->read_iter != NULL;
2678 return file->f_op->write_iter != NULL;
2681 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2683 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2685 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2688 return __io_file_supports_nowait(req->file, rw);
2691 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2693 struct io_ring_ctx *ctx = req->ctx;
2694 struct kiocb *kiocb = &req->rw.kiocb;
2695 struct file *file = req->file;
2699 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2700 req->flags |= REQ_F_ISREG;
2702 kiocb->ki_pos = READ_ONCE(sqe->off);
2703 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2704 req->flags |= REQ_F_CUR_POS;
2705 kiocb->ki_pos = file->f_pos;
2707 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2708 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2709 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2713 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2714 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2715 req->flags |= REQ_F_NOWAIT;
2717 ioprio = READ_ONCE(sqe->ioprio);
2719 ret = ioprio_check_cap(ioprio);
2723 kiocb->ki_ioprio = ioprio;
2725 kiocb->ki_ioprio = get_current_ioprio();
2727 if (ctx->flags & IORING_SETUP_IOPOLL) {
2728 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2729 !kiocb->ki_filp->f_op->iopoll)
2732 kiocb->ki_flags |= IOCB_HIPRI;
2733 kiocb->ki_complete = io_complete_rw_iopoll;
2734 req->iopoll_completed = 0;
2736 if (kiocb->ki_flags & IOCB_HIPRI)
2738 kiocb->ki_complete = io_complete_rw;
2741 if (req->opcode == IORING_OP_READ_FIXED ||
2742 req->opcode == IORING_OP_WRITE_FIXED) {
2744 io_req_set_rsrc_node(req);
2747 req->rw.addr = READ_ONCE(sqe->addr);
2748 req->rw.len = READ_ONCE(sqe->len);
2749 req->buf_index = READ_ONCE(sqe->buf_index);
2753 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2759 case -ERESTARTNOINTR:
2760 case -ERESTARTNOHAND:
2761 case -ERESTART_RESTARTBLOCK:
2763 * We can't just restart the syscall, since previously
2764 * submitted sqes may already be in progress. Just fail this
2770 kiocb->ki_complete(kiocb, ret, 0);
2774 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2775 unsigned int issue_flags)
2777 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2778 struct io_async_rw *io = req->async_data;
2779 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2781 /* add previously done IO, if any */
2782 if (io && io->bytes_done > 0) {
2784 ret = io->bytes_done;
2786 ret += io->bytes_done;
2789 if (req->flags & REQ_F_CUR_POS)
2790 req->file->f_pos = kiocb->ki_pos;
2791 if (ret >= 0 && check_reissue)
2792 __io_complete_rw(req, ret, 0, issue_flags);
2794 io_rw_done(kiocb, ret);
2796 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2797 req->flags &= ~REQ_F_REISSUE;
2798 if (io_resubmit_prep(req)) {
2800 io_req_task_queue_reissue(req);
2805 if (req->flags & REQ_F_BUFFER_SELECTED)
2806 cflags = io_put_rw_kbuf(req);
2807 __io_req_complete(req, issue_flags, ret, cflags);
2812 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2813 struct io_mapped_ubuf *imu)
2815 size_t len = req->rw.len;
2816 u64 buf_end, buf_addr = req->rw.addr;
2819 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2821 /* not inside the mapped region */
2822 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2826 * May not be a start of buffer, set size appropriately
2827 * and advance us to the beginning.
2829 offset = buf_addr - imu->ubuf;
2830 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2834 * Don't use iov_iter_advance() here, as it's really slow for
2835 * using the latter parts of a big fixed buffer - it iterates
2836 * over each segment manually. We can cheat a bit here, because
2839 * 1) it's a BVEC iter, we set it up
2840 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2841 * first and last bvec
2843 * So just find our index, and adjust the iterator afterwards.
2844 * If the offset is within the first bvec (or the whole first
2845 * bvec, just use iov_iter_advance(). This makes it easier
2846 * since we can just skip the first segment, which may not
2847 * be PAGE_SIZE aligned.
2849 const struct bio_vec *bvec = imu->bvec;
2851 if (offset <= bvec->bv_len) {
2852 iov_iter_advance(iter, offset);
2854 unsigned long seg_skip;
2856 /* skip first vec */
2857 offset -= bvec->bv_len;
2858 seg_skip = 1 + (offset >> PAGE_SHIFT);
2860 iter->bvec = bvec + seg_skip;
2861 iter->nr_segs -= seg_skip;
2862 iter->count -= bvec->bv_len + offset;
2863 iter->iov_offset = offset & ~PAGE_MASK;
2870 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2872 struct io_ring_ctx *ctx = req->ctx;
2873 struct io_mapped_ubuf *imu = req->imu;
2874 u16 index, buf_index = req->buf_index;
2877 if (unlikely(buf_index >= ctx->nr_user_bufs))
2879 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2880 imu = READ_ONCE(ctx->user_bufs[index]);
2883 return __io_import_fixed(req, rw, iter, imu);
2886 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2889 mutex_unlock(&ctx->uring_lock);
2892 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2895 * "Normal" inline submissions always hold the uring_lock, since we
2896 * grab it from the system call. Same is true for the SQPOLL offload.
2897 * The only exception is when we've detached the request and issue it
2898 * from an async worker thread, grab the lock for that case.
2901 mutex_lock(&ctx->uring_lock);
2904 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2905 int bgid, struct io_buffer *kbuf,
2908 struct io_buffer *head;
2910 if (req->flags & REQ_F_BUFFER_SELECTED)
2913 io_ring_submit_lock(req->ctx, needs_lock);
2915 lockdep_assert_held(&req->ctx->uring_lock);
2917 head = xa_load(&req->ctx->io_buffers, bgid);
2919 if (!list_empty(&head->list)) {
2920 kbuf = list_last_entry(&head->list, struct io_buffer,
2922 list_del(&kbuf->list);
2925 xa_erase(&req->ctx->io_buffers, bgid);
2927 if (*len > kbuf->len)
2930 kbuf = ERR_PTR(-ENOBUFS);
2933 io_ring_submit_unlock(req->ctx, needs_lock);
2938 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2941 struct io_buffer *kbuf;
2944 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2945 bgid = req->buf_index;
2946 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2949 req->rw.addr = (u64) (unsigned long) kbuf;
2950 req->flags |= REQ_F_BUFFER_SELECTED;
2951 return u64_to_user_ptr(kbuf->addr);
2954 #ifdef CONFIG_COMPAT
2955 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2958 struct compat_iovec __user *uiov;
2959 compat_ssize_t clen;
2963 uiov = u64_to_user_ptr(req->rw.addr);
2964 if (!access_ok(uiov, sizeof(*uiov)))
2966 if (__get_user(clen, &uiov->iov_len))
2972 buf = io_rw_buffer_select(req, &len, needs_lock);
2974 return PTR_ERR(buf);
2975 iov[0].iov_base = buf;
2976 iov[0].iov_len = (compat_size_t) len;
2981 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2984 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2988 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2991 len = iov[0].iov_len;
2994 buf = io_rw_buffer_select(req, &len, needs_lock);
2996 return PTR_ERR(buf);
2997 iov[0].iov_base = buf;
2998 iov[0].iov_len = len;
3002 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3005 if (req->flags & REQ_F_BUFFER_SELECTED) {
3006 struct io_buffer *kbuf;
3008 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3009 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3010 iov[0].iov_len = kbuf->len;
3013 if (req->rw.len != 1)
3016 #ifdef CONFIG_COMPAT
3017 if (req->ctx->compat)
3018 return io_compat_import(req, iov, needs_lock);
3021 return __io_iov_buffer_select(req, iov, needs_lock);
3024 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3025 struct iov_iter *iter, bool needs_lock)
3027 void __user *buf = u64_to_user_ptr(req->rw.addr);
3028 size_t sqe_len = req->rw.len;
3029 u8 opcode = req->opcode;
3032 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3034 return io_import_fixed(req, rw, iter);
3037 /* buffer index only valid with fixed read/write, or buffer select */
3038 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3041 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3042 if (req->flags & REQ_F_BUFFER_SELECT) {
3043 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3045 return PTR_ERR(buf);
3046 req->rw.len = sqe_len;
3049 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3054 if (req->flags & REQ_F_BUFFER_SELECT) {
3055 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3057 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3062 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3066 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3068 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3072 * For files that don't have ->read_iter() and ->write_iter(), handle them
3073 * by looping over ->read() or ->write() manually.
3075 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3077 struct kiocb *kiocb = &req->rw.kiocb;
3078 struct file *file = req->file;
3082 * Don't support polled IO through this interface, and we can't
3083 * support non-blocking either. For the latter, this just causes
3084 * the kiocb to be handled from an async context.
3086 if (kiocb->ki_flags & IOCB_HIPRI)
3088 if (kiocb->ki_flags & IOCB_NOWAIT)
3091 while (iov_iter_count(iter)) {
3095 if (!iov_iter_is_bvec(iter)) {
3096 iovec = iov_iter_iovec(iter);
3098 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3099 iovec.iov_len = req->rw.len;
3103 nr = file->f_op->read(file, iovec.iov_base,
3104 iovec.iov_len, io_kiocb_ppos(kiocb));
3106 nr = file->f_op->write(file, iovec.iov_base,
3107 iovec.iov_len, io_kiocb_ppos(kiocb));
3116 if (nr != iovec.iov_len)
3120 iov_iter_advance(iter, nr);
3126 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3127 const struct iovec *fast_iov, struct iov_iter *iter)
3129 struct io_async_rw *rw = req->async_data;
3131 memcpy(&rw->iter, iter, sizeof(*iter));
3132 rw->free_iovec = iovec;
3134 /* can only be fixed buffers, no need to do anything */
3135 if (iov_iter_is_bvec(iter))
3138 unsigned iov_off = 0;
3140 rw->iter.iov = rw->fast_iov;
3141 if (iter->iov != fast_iov) {
3142 iov_off = iter->iov - fast_iov;
3143 rw->iter.iov += iov_off;
3145 if (rw->fast_iov != fast_iov)
3146 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3147 sizeof(struct iovec) * iter->nr_segs);
3149 req->flags |= REQ_F_NEED_CLEANUP;
3153 static inline int io_alloc_async_data(struct io_kiocb *req)
3155 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3156 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3157 return req->async_data == NULL;
3160 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3161 const struct iovec *fast_iov,
3162 struct iov_iter *iter, bool force)
3164 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3166 if (!req->async_data) {
3167 if (io_alloc_async_data(req)) {
3172 io_req_map_rw(req, iovec, fast_iov, iter);
3177 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3179 struct io_async_rw *iorw = req->async_data;
3180 struct iovec *iov = iorw->fast_iov;
3183 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3184 if (unlikely(ret < 0))
3187 iorw->bytes_done = 0;
3188 iorw->free_iovec = iov;
3190 req->flags |= REQ_F_NEED_CLEANUP;
3194 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3196 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3198 return io_prep_rw(req, sqe);
3202 * This is our waitqueue callback handler, registered through lock_page_async()
3203 * when we initially tried to do the IO with the iocb armed our waitqueue.
3204 * This gets called when the page is unlocked, and we generally expect that to
3205 * happen when the page IO is completed and the page is now uptodate. This will
3206 * queue a task_work based retry of the operation, attempting to copy the data
3207 * again. If the latter fails because the page was NOT uptodate, then we will
3208 * do a thread based blocking retry of the operation. That's the unexpected
3211 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3212 int sync, void *arg)
3214 struct wait_page_queue *wpq;
3215 struct io_kiocb *req = wait->private;
3216 struct wait_page_key *key = arg;
3218 wpq = container_of(wait, struct wait_page_queue, wait);
3220 if (!wake_page_match(wpq, key))
3223 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3224 list_del_init(&wait->entry);
3226 /* submit ref gets dropped, acquire a new one */
3228 io_req_task_queue(req);
3233 * This controls whether a given IO request should be armed for async page
3234 * based retry. If we return false here, the request is handed to the async
3235 * worker threads for retry. If we're doing buffered reads on a regular file,
3236 * we prepare a private wait_page_queue entry and retry the operation. This
3237 * will either succeed because the page is now uptodate and unlocked, or it
3238 * will register a callback when the page is unlocked at IO completion. Through
3239 * that callback, io_uring uses task_work to setup a retry of the operation.
3240 * That retry will attempt the buffered read again. The retry will generally
3241 * succeed, or in rare cases where it fails, we then fall back to using the
3242 * async worker threads for a blocking retry.
3244 static bool io_rw_should_retry(struct io_kiocb *req)
3246 struct io_async_rw *rw = req->async_data;
3247 struct wait_page_queue *wait = &rw->wpq;
3248 struct kiocb *kiocb = &req->rw.kiocb;
3250 /* never retry for NOWAIT, we just complete with -EAGAIN */
3251 if (req->flags & REQ_F_NOWAIT)
3254 /* Only for buffered IO */
3255 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3259 * just use poll if we can, and don't attempt if the fs doesn't
3260 * support callback based unlocks
3262 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3265 wait->wait.func = io_async_buf_func;
3266 wait->wait.private = req;
3267 wait->wait.flags = 0;
3268 INIT_LIST_HEAD(&wait->wait.entry);
3269 kiocb->ki_flags |= IOCB_WAITQ;
3270 kiocb->ki_flags &= ~IOCB_NOWAIT;
3271 kiocb->ki_waitq = wait;
3275 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3277 if (req->file->f_op->read_iter)
3278 return call_read_iter(req->file, &req->rw.kiocb, iter);
3279 else if (req->file->f_op->read)
3280 return loop_rw_iter(READ, req, iter);
3285 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3287 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3288 struct kiocb *kiocb = &req->rw.kiocb;
3289 struct iov_iter __iter, *iter = &__iter;
3290 struct io_async_rw *rw = req->async_data;
3291 ssize_t io_size, ret, ret2;
3292 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3298 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3302 io_size = iov_iter_count(iter);
3303 req->result = io_size;
3305 /* Ensure we clear previously set non-block flag */
3306 if (!force_nonblock)
3307 kiocb->ki_flags &= ~IOCB_NOWAIT;
3309 kiocb->ki_flags |= IOCB_NOWAIT;
3311 /* If the file doesn't support async, just async punt */
3312 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3313 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3314 return ret ?: -EAGAIN;
3317 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3318 if (unlikely(ret)) {
3323 ret = io_iter_do_read(req, iter);
3325 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3326 req->flags &= ~REQ_F_REISSUE;
3327 /* IOPOLL retry should happen for io-wq threads */
3328 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3330 /* no retry on NONBLOCK nor RWF_NOWAIT */
3331 if (req->flags & REQ_F_NOWAIT)
3333 /* some cases will consume bytes even on error returns */
3334 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3336 } else if (ret == -EIOCBQUEUED) {
3338 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3339 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3340 /* read all, failed, already did sync or don't want to retry */
3344 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3349 rw = req->async_data;
3350 /* now use our persistent iterator, if we aren't already */
3355 rw->bytes_done += ret;
3356 /* if we can retry, do so with the callbacks armed */
3357 if (!io_rw_should_retry(req)) {
3358 kiocb->ki_flags &= ~IOCB_WAITQ;
3363 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3364 * we get -EIOCBQUEUED, then we'll get a notification when the
3365 * desired page gets unlocked. We can also get a partial read
3366 * here, and if we do, then just retry at the new offset.
3368 ret = io_iter_do_read(req, iter);
3369 if (ret == -EIOCBQUEUED)
3371 /* we got some bytes, but not all. retry. */
3372 kiocb->ki_flags &= ~IOCB_WAITQ;
3373 } while (ret > 0 && ret < io_size);
3375 kiocb_done(kiocb, ret, issue_flags);
3377 /* it's faster to check here then delegate to kfree */
3383 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3385 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3387 return io_prep_rw(req, sqe);
3390 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3392 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3393 struct kiocb *kiocb = &req->rw.kiocb;
3394 struct iov_iter __iter, *iter = &__iter;
3395 struct io_async_rw *rw = req->async_data;
3396 ssize_t ret, ret2, io_size;
3397 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3403 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3407 io_size = iov_iter_count(iter);
3408 req->result = io_size;
3410 /* Ensure we clear previously set non-block flag */
3411 if (!force_nonblock)
3412 kiocb->ki_flags &= ~IOCB_NOWAIT;
3414 kiocb->ki_flags |= IOCB_NOWAIT;
3416 /* If the file doesn't support async, just async punt */
3417 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3420 /* file path doesn't support NOWAIT for non-direct_IO */
3421 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3422 (req->flags & REQ_F_ISREG))
3425 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3430 * Open-code file_start_write here to grab freeze protection,
3431 * which will be released by another thread in
3432 * io_complete_rw(). Fool lockdep by telling it the lock got
3433 * released so that it doesn't complain about the held lock when
3434 * we return to userspace.
3436 if (req->flags & REQ_F_ISREG) {
3437 sb_start_write(file_inode(req->file)->i_sb);
3438 __sb_writers_release(file_inode(req->file)->i_sb,
3441 kiocb->ki_flags |= IOCB_WRITE;
3443 if (req->file->f_op->write_iter)
3444 ret2 = call_write_iter(req->file, kiocb, iter);
3445 else if (req->file->f_op->write)
3446 ret2 = loop_rw_iter(WRITE, req, iter);
3450 if (req->flags & REQ_F_REISSUE) {
3451 req->flags &= ~REQ_F_REISSUE;
3456 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3457 * retry them without IOCB_NOWAIT.
3459 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3461 /* no retry on NONBLOCK nor RWF_NOWAIT */
3462 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3464 if (!force_nonblock || ret2 != -EAGAIN) {
3465 /* IOPOLL retry should happen for io-wq threads */
3466 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3469 kiocb_done(kiocb, ret2, issue_flags);
3472 /* some cases will consume bytes even on error returns */
3473 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3474 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3475 return ret ?: -EAGAIN;
3478 /* it's reportedly faster than delegating the null check to kfree() */
3484 static int io_renameat_prep(struct io_kiocb *req,
3485 const struct io_uring_sqe *sqe)
3487 struct io_rename *ren = &req->rename;
3488 const char __user *oldf, *newf;
3490 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3492 if (sqe->ioprio || sqe->buf_index)
3494 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3497 ren->old_dfd = READ_ONCE(sqe->fd);
3498 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3499 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3500 ren->new_dfd = READ_ONCE(sqe->len);
3501 ren->flags = READ_ONCE(sqe->rename_flags);
3503 ren->oldpath = getname(oldf);
3504 if (IS_ERR(ren->oldpath))
3505 return PTR_ERR(ren->oldpath);
3507 ren->newpath = getname(newf);
3508 if (IS_ERR(ren->newpath)) {
3509 putname(ren->oldpath);
3510 return PTR_ERR(ren->newpath);
3513 req->flags |= REQ_F_NEED_CLEANUP;
3517 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3519 struct io_rename *ren = &req->rename;
3522 if (issue_flags & IO_URING_F_NONBLOCK)
3525 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3526 ren->newpath, ren->flags);
3528 req->flags &= ~REQ_F_NEED_CLEANUP;
3531 io_req_complete(req, ret);
3535 static int io_unlinkat_prep(struct io_kiocb *req,
3536 const struct io_uring_sqe *sqe)
3538 struct io_unlink *un = &req->unlink;
3539 const char __user *fname;
3541 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3543 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3545 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3548 un->dfd = READ_ONCE(sqe->fd);
3550 un->flags = READ_ONCE(sqe->unlink_flags);
3551 if (un->flags & ~AT_REMOVEDIR)
3554 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3555 un->filename = getname(fname);
3556 if (IS_ERR(un->filename))
3557 return PTR_ERR(un->filename);
3559 req->flags |= REQ_F_NEED_CLEANUP;
3563 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3565 struct io_unlink *un = &req->unlink;
3568 if (issue_flags & IO_URING_F_NONBLOCK)
3571 if (un->flags & AT_REMOVEDIR)
3572 ret = do_rmdir(un->dfd, un->filename);
3574 ret = do_unlinkat(un->dfd, un->filename);
3576 req->flags &= ~REQ_F_NEED_CLEANUP;
3579 io_req_complete(req, ret);
3583 static int io_shutdown_prep(struct io_kiocb *req,
3584 const struct io_uring_sqe *sqe)
3586 #if defined(CONFIG_NET)
3587 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3589 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3593 req->shutdown.how = READ_ONCE(sqe->len);
3600 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3602 #if defined(CONFIG_NET)
3603 struct socket *sock;
3606 if (issue_flags & IO_URING_F_NONBLOCK)
3609 sock = sock_from_file(req->file);
3610 if (unlikely(!sock))
3613 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3616 io_req_complete(req, ret);
3623 static int __io_splice_prep(struct io_kiocb *req,
3624 const struct io_uring_sqe *sqe)
3626 struct io_splice *sp = &req->splice;
3627 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3629 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3633 sp->len = READ_ONCE(sqe->len);
3634 sp->flags = READ_ONCE(sqe->splice_flags);
3636 if (unlikely(sp->flags & ~valid_flags))
3639 sp->file_in = io_file_get(req->ctx, NULL, req,
3640 READ_ONCE(sqe->splice_fd_in),
3641 (sp->flags & SPLICE_F_FD_IN_FIXED));
3644 req->flags |= REQ_F_NEED_CLEANUP;
3648 static int io_tee_prep(struct io_kiocb *req,
3649 const struct io_uring_sqe *sqe)
3651 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3653 return __io_splice_prep(req, sqe);
3656 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3658 struct io_splice *sp = &req->splice;
3659 struct file *in = sp->file_in;
3660 struct file *out = sp->file_out;
3661 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3664 if (issue_flags & IO_URING_F_NONBLOCK)
3667 ret = do_tee(in, out, sp->len, flags);
3669 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3671 req->flags &= ~REQ_F_NEED_CLEANUP;
3675 io_req_complete(req, ret);
3679 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3681 struct io_splice *sp = &req->splice;
3683 sp->off_in = READ_ONCE(sqe->splice_off_in);
3684 sp->off_out = READ_ONCE(sqe->off);
3685 return __io_splice_prep(req, sqe);
3688 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3690 struct io_splice *sp = &req->splice;
3691 struct file *in = sp->file_in;
3692 struct file *out = sp->file_out;
3693 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3694 loff_t *poff_in, *poff_out;
3697 if (issue_flags & IO_URING_F_NONBLOCK)
3700 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3701 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3704 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3706 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3708 req->flags &= ~REQ_F_NEED_CLEANUP;
3712 io_req_complete(req, ret);
3717 * IORING_OP_NOP just posts a completion event, nothing else.
3719 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3721 struct io_ring_ctx *ctx = req->ctx;
3723 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3726 __io_req_complete(req, issue_flags, 0, 0);
3730 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3732 struct io_ring_ctx *ctx = req->ctx;
3737 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3739 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3742 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3743 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3746 req->sync.off = READ_ONCE(sqe->off);
3747 req->sync.len = READ_ONCE(sqe->len);
3751 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3753 loff_t end = req->sync.off + req->sync.len;
3756 /* fsync always requires a blocking context */
3757 if (issue_flags & IO_URING_F_NONBLOCK)
3760 ret = vfs_fsync_range(req->file, req->sync.off,
3761 end > 0 ? end : LLONG_MAX,
3762 req->sync.flags & IORING_FSYNC_DATASYNC);
3765 io_req_complete(req, ret);
3769 static int io_fallocate_prep(struct io_kiocb *req,
3770 const struct io_uring_sqe *sqe)
3772 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3774 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3777 req->sync.off = READ_ONCE(sqe->off);
3778 req->sync.len = READ_ONCE(sqe->addr);
3779 req->sync.mode = READ_ONCE(sqe->len);
3783 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3787 /* fallocate always requiring blocking context */
3788 if (issue_flags & IO_URING_F_NONBLOCK)
3790 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3794 io_req_complete(req, ret);
3798 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3800 const char __user *fname;
3803 if (unlikely(sqe->ioprio || sqe->buf_index))
3805 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3808 /* open.how should be already initialised */
3809 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3810 req->open.how.flags |= O_LARGEFILE;
3812 req->open.dfd = READ_ONCE(sqe->fd);
3813 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3814 req->open.filename = getname(fname);
3815 if (IS_ERR(req->open.filename)) {
3816 ret = PTR_ERR(req->open.filename);
3817 req->open.filename = NULL;
3820 req->open.nofile = rlimit(RLIMIT_NOFILE);
3821 req->flags |= REQ_F_NEED_CLEANUP;
3825 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3829 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3831 mode = READ_ONCE(sqe->len);
3832 flags = READ_ONCE(sqe->open_flags);
3833 req->open.how = build_open_how(flags, mode);
3834 return __io_openat_prep(req, sqe);
3837 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3839 struct open_how __user *how;
3843 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3845 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3846 len = READ_ONCE(sqe->len);
3847 if (len < OPEN_HOW_SIZE_VER0)
3850 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3855 return __io_openat_prep(req, sqe);
3858 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3860 struct open_flags op;
3863 bool resolve_nonblock;
3866 ret = build_open_flags(&req->open.how, &op);
3869 nonblock_set = op.open_flag & O_NONBLOCK;
3870 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3871 if (issue_flags & IO_URING_F_NONBLOCK) {
3873 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3874 * it'll always -EAGAIN
3876 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3878 op.lookup_flags |= LOOKUP_CACHED;
3879 op.open_flag |= O_NONBLOCK;
3882 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3886 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3889 * We could hang on to this 'fd' on retrying, but seems like
3890 * marginal gain for something that is now known to be a slower
3891 * path. So just put it, and we'll get a new one when we retry.
3895 ret = PTR_ERR(file);
3896 /* only retry if RESOLVE_CACHED wasn't already set by application */
3897 if (ret == -EAGAIN &&
3898 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3903 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3904 file->f_flags &= ~O_NONBLOCK;
3905 fsnotify_open(file);
3906 fd_install(ret, file);
3908 putname(req->open.filename);
3909 req->flags &= ~REQ_F_NEED_CLEANUP;
3912 __io_req_complete(req, issue_flags, ret, 0);
3916 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3918 return io_openat2(req, issue_flags);
3921 static int io_remove_buffers_prep(struct io_kiocb *req,
3922 const struct io_uring_sqe *sqe)
3924 struct io_provide_buf *p = &req->pbuf;
3927 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3930 tmp = READ_ONCE(sqe->fd);
3931 if (!tmp || tmp > USHRT_MAX)
3934 memset(p, 0, sizeof(*p));
3936 p->bgid = READ_ONCE(sqe->buf_group);
3940 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3941 int bgid, unsigned nbufs)
3945 /* shouldn't happen */
3949 /* the head kbuf is the list itself */
3950 while (!list_empty(&buf->list)) {
3951 struct io_buffer *nxt;
3953 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3954 list_del(&nxt->list);
3961 xa_erase(&ctx->io_buffers, bgid);
3966 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3968 struct io_provide_buf *p = &req->pbuf;
3969 struct io_ring_ctx *ctx = req->ctx;
3970 struct io_buffer *head;
3972 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3974 io_ring_submit_lock(ctx, !force_nonblock);
3976 lockdep_assert_held(&ctx->uring_lock);
3979 head = xa_load(&ctx->io_buffers, p->bgid);
3981 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3985 /* complete before unlock, IOPOLL may need the lock */
3986 __io_req_complete(req, issue_flags, ret, 0);
3987 io_ring_submit_unlock(ctx, !force_nonblock);
3991 static int io_provide_buffers_prep(struct io_kiocb *req,
3992 const struct io_uring_sqe *sqe)
3994 unsigned long size, tmp_check;
3995 struct io_provide_buf *p = &req->pbuf;
3998 if (sqe->ioprio || sqe->rw_flags)
4001 tmp = READ_ONCE(sqe->fd);
4002 if (!tmp || tmp > USHRT_MAX)
4005 p->addr = READ_ONCE(sqe->addr);
4006 p->len = READ_ONCE(sqe->len);
4008 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4011 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4014 size = (unsigned long)p->len * p->nbufs;
4015 if (!access_ok(u64_to_user_ptr(p->addr), size))
4018 p->bgid = READ_ONCE(sqe->buf_group);
4019 tmp = READ_ONCE(sqe->off);
4020 if (tmp > USHRT_MAX)
4026 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4028 struct io_buffer *buf;
4029 u64 addr = pbuf->addr;
4030 int i, bid = pbuf->bid;
4032 for (i = 0; i < pbuf->nbufs; i++) {
4033 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4038 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4043 INIT_LIST_HEAD(&buf->list);
4046 list_add_tail(&buf->list, &(*head)->list);
4050 return i ? i : -ENOMEM;
4053 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4055 struct io_provide_buf *p = &req->pbuf;
4056 struct io_ring_ctx *ctx = req->ctx;
4057 struct io_buffer *head, *list;
4059 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4061 io_ring_submit_lock(ctx, !force_nonblock);
4063 lockdep_assert_held(&ctx->uring_lock);
4065 list = head = xa_load(&ctx->io_buffers, p->bgid);
4067 ret = io_add_buffers(p, &head);
4068 if (ret >= 0 && !list) {
4069 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4071 __io_remove_buffers(ctx, head, p->bgid, -1U);
4075 /* complete before unlock, IOPOLL may need the lock */
4076 __io_req_complete(req, issue_flags, ret, 0);
4077 io_ring_submit_unlock(ctx, !force_nonblock);
4081 static int io_epoll_ctl_prep(struct io_kiocb *req,
4082 const struct io_uring_sqe *sqe)
4084 #if defined(CONFIG_EPOLL)
4085 if (sqe->ioprio || sqe->buf_index)
4087 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4090 req->epoll.epfd = READ_ONCE(sqe->fd);
4091 req->epoll.op = READ_ONCE(sqe->len);
4092 req->epoll.fd = READ_ONCE(sqe->off);
4094 if (ep_op_has_event(req->epoll.op)) {
4095 struct epoll_event __user *ev;
4097 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4098 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4108 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4110 #if defined(CONFIG_EPOLL)
4111 struct io_epoll *ie = &req->epoll;
4113 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4115 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4116 if (force_nonblock && ret == -EAGAIN)
4121 __io_req_complete(req, issue_flags, ret, 0);
4128 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4130 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4131 if (sqe->ioprio || sqe->buf_index || sqe->off)
4133 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4136 req->madvise.addr = READ_ONCE(sqe->addr);
4137 req->madvise.len = READ_ONCE(sqe->len);
4138 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4145 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4147 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4148 struct io_madvise *ma = &req->madvise;
4151 if (issue_flags & IO_URING_F_NONBLOCK)
4154 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4157 io_req_complete(req, ret);
4164 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4166 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4168 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4171 req->fadvise.offset = READ_ONCE(sqe->off);
4172 req->fadvise.len = READ_ONCE(sqe->len);
4173 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4177 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4179 struct io_fadvise *fa = &req->fadvise;
4182 if (issue_flags & IO_URING_F_NONBLOCK) {
4183 switch (fa->advice) {
4184 case POSIX_FADV_NORMAL:
4185 case POSIX_FADV_RANDOM:
4186 case POSIX_FADV_SEQUENTIAL:
4193 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4196 __io_req_complete(req, issue_flags, ret, 0);
4200 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4202 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4204 if (sqe->ioprio || sqe->buf_index)
4206 if (req->flags & REQ_F_FIXED_FILE)
4209 req->statx.dfd = READ_ONCE(sqe->fd);
4210 req->statx.mask = READ_ONCE(sqe->len);
4211 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4212 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4213 req->statx.flags = READ_ONCE(sqe->statx_flags);
4218 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4220 struct io_statx *ctx = &req->statx;
4223 if (issue_flags & IO_URING_F_NONBLOCK)
4226 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4231 io_req_complete(req, ret);
4235 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4237 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4239 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4240 sqe->rw_flags || sqe->buf_index)
4242 if (req->flags & REQ_F_FIXED_FILE)
4245 req->close.fd = READ_ONCE(sqe->fd);
4249 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4251 struct files_struct *files = current->files;
4252 struct io_close *close = &req->close;
4253 struct fdtable *fdt;
4254 struct file *file = NULL;
4257 spin_lock(&files->file_lock);
4258 fdt = files_fdtable(files);
4259 if (close->fd >= fdt->max_fds) {
4260 spin_unlock(&files->file_lock);
4263 file = fdt->fd[close->fd];
4264 if (!file || file->f_op == &io_uring_fops) {
4265 spin_unlock(&files->file_lock);
4270 /* if the file has a flush method, be safe and punt to async */
4271 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4272 spin_unlock(&files->file_lock);
4276 ret = __close_fd_get_file(close->fd, &file);
4277 spin_unlock(&files->file_lock);
4284 /* No ->flush() or already async, safely close from here */
4285 ret = filp_close(file, current->files);
4291 __io_req_complete(req, issue_flags, ret, 0);
4295 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4297 struct io_ring_ctx *ctx = req->ctx;
4299 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4301 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4304 req->sync.off = READ_ONCE(sqe->off);
4305 req->sync.len = READ_ONCE(sqe->len);
4306 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4310 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4314 /* sync_file_range always requires a blocking context */
4315 if (issue_flags & IO_URING_F_NONBLOCK)
4318 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4322 io_req_complete(req, ret);
4326 #if defined(CONFIG_NET)
4327 static int io_setup_async_msg(struct io_kiocb *req,
4328 struct io_async_msghdr *kmsg)
4330 struct io_async_msghdr *async_msg = req->async_data;
4334 if (io_alloc_async_data(req)) {
4335 kfree(kmsg->free_iov);
4338 async_msg = req->async_data;
4339 req->flags |= REQ_F_NEED_CLEANUP;
4340 memcpy(async_msg, kmsg, sizeof(*kmsg));
4341 async_msg->msg.msg_name = &async_msg->addr;
4342 /* if were using fast_iov, set it to the new one */
4343 if (!async_msg->free_iov)
4344 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4349 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4350 struct io_async_msghdr *iomsg)
4352 iomsg->msg.msg_name = &iomsg->addr;
4353 iomsg->free_iov = iomsg->fast_iov;
4354 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4355 req->sr_msg.msg_flags, &iomsg->free_iov);
4358 static int io_sendmsg_prep_async(struct io_kiocb *req)
4362 ret = io_sendmsg_copy_hdr(req, req->async_data);
4364 req->flags |= REQ_F_NEED_CLEANUP;
4368 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4370 struct io_sr_msg *sr = &req->sr_msg;
4372 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4375 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4376 sr->len = READ_ONCE(sqe->len);
4377 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4378 if (sr->msg_flags & MSG_DONTWAIT)
4379 req->flags |= REQ_F_NOWAIT;
4381 #ifdef CONFIG_COMPAT
4382 if (req->ctx->compat)
4383 sr->msg_flags |= MSG_CMSG_COMPAT;
4388 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4390 struct io_async_msghdr iomsg, *kmsg;
4391 struct socket *sock;
4396 sock = sock_from_file(req->file);
4397 if (unlikely(!sock))
4400 kmsg = req->async_data;
4402 ret = io_sendmsg_copy_hdr(req, &iomsg);
4408 flags = req->sr_msg.msg_flags;
4409 if (issue_flags & IO_URING_F_NONBLOCK)
4410 flags |= MSG_DONTWAIT;
4411 if (flags & MSG_WAITALL)
4412 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4414 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4415 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4416 return io_setup_async_msg(req, kmsg);
4417 if (ret == -ERESTARTSYS)
4420 /* fast path, check for non-NULL to avoid function call */
4422 kfree(kmsg->free_iov);
4423 req->flags &= ~REQ_F_NEED_CLEANUP;
4426 __io_req_complete(req, issue_flags, ret, 0);
4430 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4432 struct io_sr_msg *sr = &req->sr_msg;
4435 struct socket *sock;
4440 sock = sock_from_file(req->file);
4441 if (unlikely(!sock))
4444 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4448 msg.msg_name = NULL;
4449 msg.msg_control = NULL;
4450 msg.msg_controllen = 0;
4451 msg.msg_namelen = 0;
4453 flags = req->sr_msg.msg_flags;
4454 if (issue_flags & IO_URING_F_NONBLOCK)
4455 flags |= MSG_DONTWAIT;
4456 if (flags & MSG_WAITALL)
4457 min_ret = iov_iter_count(&msg.msg_iter);
4459 msg.msg_flags = flags;
4460 ret = sock_sendmsg(sock, &msg);
4461 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4463 if (ret == -ERESTARTSYS)
4468 __io_req_complete(req, issue_flags, ret, 0);
4472 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4473 struct io_async_msghdr *iomsg)
4475 struct io_sr_msg *sr = &req->sr_msg;
4476 struct iovec __user *uiov;
4480 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4481 &iomsg->uaddr, &uiov, &iov_len);
4485 if (req->flags & REQ_F_BUFFER_SELECT) {
4488 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4490 sr->len = iomsg->fast_iov[0].iov_len;
4491 iomsg->free_iov = NULL;
4493 iomsg->free_iov = iomsg->fast_iov;
4494 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4495 &iomsg->free_iov, &iomsg->msg.msg_iter,
4504 #ifdef CONFIG_COMPAT
4505 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4506 struct io_async_msghdr *iomsg)
4508 struct io_sr_msg *sr = &req->sr_msg;
4509 struct compat_iovec __user *uiov;
4514 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4519 uiov = compat_ptr(ptr);
4520 if (req->flags & REQ_F_BUFFER_SELECT) {
4521 compat_ssize_t clen;
4525 if (!access_ok(uiov, sizeof(*uiov)))
4527 if (__get_user(clen, &uiov->iov_len))
4532 iomsg->free_iov = NULL;
4534 iomsg->free_iov = iomsg->fast_iov;
4535 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4536 UIO_FASTIOV, &iomsg->free_iov,
4537 &iomsg->msg.msg_iter, true);
4546 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4547 struct io_async_msghdr *iomsg)
4549 iomsg->msg.msg_name = &iomsg->addr;
4551 #ifdef CONFIG_COMPAT
4552 if (req->ctx->compat)
4553 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4556 return __io_recvmsg_copy_hdr(req, iomsg);
4559 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4562 struct io_sr_msg *sr = &req->sr_msg;
4563 struct io_buffer *kbuf;
4565 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4570 req->flags |= REQ_F_BUFFER_SELECTED;
4574 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4576 return io_put_kbuf(req, req->sr_msg.kbuf);
4579 static int io_recvmsg_prep_async(struct io_kiocb *req)
4583 ret = io_recvmsg_copy_hdr(req, req->async_data);
4585 req->flags |= REQ_F_NEED_CLEANUP;
4589 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4591 struct io_sr_msg *sr = &req->sr_msg;
4593 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4596 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4597 sr->len = READ_ONCE(sqe->len);
4598 sr->bgid = READ_ONCE(sqe->buf_group);
4599 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4600 if (sr->msg_flags & MSG_DONTWAIT)
4601 req->flags |= REQ_F_NOWAIT;
4603 #ifdef CONFIG_COMPAT
4604 if (req->ctx->compat)
4605 sr->msg_flags |= MSG_CMSG_COMPAT;
4610 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4612 struct io_async_msghdr iomsg, *kmsg;
4613 struct socket *sock;
4614 struct io_buffer *kbuf;
4617 int ret, cflags = 0;
4618 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4620 sock = sock_from_file(req->file);
4621 if (unlikely(!sock))
4624 kmsg = req->async_data;
4626 ret = io_recvmsg_copy_hdr(req, &iomsg);
4632 if (req->flags & REQ_F_BUFFER_SELECT) {
4633 kbuf = io_recv_buffer_select(req, !force_nonblock);
4635 return PTR_ERR(kbuf);
4636 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4637 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4638 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4639 1, req->sr_msg.len);
4642 flags = req->sr_msg.msg_flags;
4644 flags |= MSG_DONTWAIT;
4645 if (flags & MSG_WAITALL)
4646 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4648 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4649 kmsg->uaddr, flags);
4650 if (force_nonblock && ret == -EAGAIN)
4651 return io_setup_async_msg(req, kmsg);
4652 if (ret == -ERESTARTSYS)
4655 if (req->flags & REQ_F_BUFFER_SELECTED)
4656 cflags = io_put_recv_kbuf(req);
4657 /* fast path, check for non-NULL to avoid function call */
4659 kfree(kmsg->free_iov);
4660 req->flags &= ~REQ_F_NEED_CLEANUP;
4661 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4663 __io_req_complete(req, issue_flags, ret, cflags);
4667 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4669 struct io_buffer *kbuf;
4670 struct io_sr_msg *sr = &req->sr_msg;
4672 void __user *buf = sr->buf;
4673 struct socket *sock;
4677 int ret, cflags = 0;
4678 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4680 sock = sock_from_file(req->file);
4681 if (unlikely(!sock))
4684 if (req->flags & REQ_F_BUFFER_SELECT) {
4685 kbuf = io_recv_buffer_select(req, !force_nonblock);
4687 return PTR_ERR(kbuf);
4688 buf = u64_to_user_ptr(kbuf->addr);
4691 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4695 msg.msg_name = NULL;
4696 msg.msg_control = NULL;
4697 msg.msg_controllen = 0;
4698 msg.msg_namelen = 0;
4699 msg.msg_iocb = NULL;
4702 flags = req->sr_msg.msg_flags;
4704 flags |= MSG_DONTWAIT;
4705 if (flags & MSG_WAITALL)
4706 min_ret = iov_iter_count(&msg.msg_iter);
4708 ret = sock_recvmsg(sock, &msg, flags);
4709 if (force_nonblock && ret == -EAGAIN)
4711 if (ret == -ERESTARTSYS)
4714 if (req->flags & REQ_F_BUFFER_SELECTED)
4715 cflags = io_put_recv_kbuf(req);
4716 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4718 __io_req_complete(req, issue_flags, ret, cflags);
4722 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4724 struct io_accept *accept = &req->accept;
4726 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4728 if (sqe->ioprio || sqe->len || sqe->buf_index)
4731 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4732 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4733 accept->flags = READ_ONCE(sqe->accept_flags);
4734 accept->nofile = rlimit(RLIMIT_NOFILE);
4738 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4740 struct io_accept *accept = &req->accept;
4741 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4742 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4745 if (req->file->f_flags & O_NONBLOCK)
4746 req->flags |= REQ_F_NOWAIT;
4748 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4749 accept->addr_len, accept->flags,
4751 if (ret == -EAGAIN && force_nonblock)
4754 if (ret == -ERESTARTSYS)
4758 __io_req_complete(req, issue_flags, ret, 0);
4762 static int io_connect_prep_async(struct io_kiocb *req)
4764 struct io_async_connect *io = req->async_data;
4765 struct io_connect *conn = &req->connect;
4767 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4770 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4772 struct io_connect *conn = &req->connect;
4774 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4776 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4779 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4780 conn->addr_len = READ_ONCE(sqe->addr2);
4784 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4786 struct io_async_connect __io, *io;
4787 unsigned file_flags;
4789 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4791 if (req->async_data) {
4792 io = req->async_data;
4794 ret = move_addr_to_kernel(req->connect.addr,
4795 req->connect.addr_len,
4802 file_flags = force_nonblock ? O_NONBLOCK : 0;
4804 ret = __sys_connect_file(req->file, &io->address,
4805 req->connect.addr_len, file_flags);
4806 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4807 if (req->async_data)
4809 if (io_alloc_async_data(req)) {
4813 memcpy(req->async_data, &__io, sizeof(__io));
4816 if (ret == -ERESTARTSYS)
4821 __io_req_complete(req, issue_flags, ret, 0);
4824 #else /* !CONFIG_NET */
4825 #define IO_NETOP_FN(op) \
4826 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4828 return -EOPNOTSUPP; \
4831 #define IO_NETOP_PREP(op) \
4833 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4835 return -EOPNOTSUPP; \
4838 #define IO_NETOP_PREP_ASYNC(op) \
4840 static int io_##op##_prep_async(struct io_kiocb *req) \
4842 return -EOPNOTSUPP; \
4845 IO_NETOP_PREP_ASYNC(sendmsg);
4846 IO_NETOP_PREP_ASYNC(recvmsg);
4847 IO_NETOP_PREP_ASYNC(connect);
4848 IO_NETOP_PREP(accept);
4851 #endif /* CONFIG_NET */
4853 struct io_poll_table {
4854 struct poll_table_struct pt;
4855 struct io_kiocb *req;
4860 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4861 __poll_t mask, io_req_tw_func_t func)
4863 /* for instances that support it check for an event match first: */
4864 if (mask && !(mask & poll->events))
4867 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4869 list_del_init(&poll->wait.entry);
4872 req->io_task_work.func = func;
4875 * If this fails, then the task is exiting. When a task exits, the
4876 * work gets canceled, so just cancel this request as well instead
4877 * of executing it. We can't safely execute it anyway, as we may not
4878 * have the needed state needed for it anyway.
4880 io_req_task_work_add(req);
4884 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4885 __acquires(&req->ctx->completion_lock)
4887 struct io_ring_ctx *ctx = req->ctx;
4889 if (unlikely(req->task->flags & PF_EXITING))
4890 WRITE_ONCE(poll->canceled, true);
4892 if (!req->result && !READ_ONCE(poll->canceled)) {
4893 struct poll_table_struct pt = { ._key = poll->events };
4895 req->result = vfs_poll(req->file, &pt) & poll->events;
4898 spin_lock_irq(&ctx->completion_lock);
4899 if (!req->result && !READ_ONCE(poll->canceled)) {
4900 add_wait_queue(poll->head, &poll->wait);
4907 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4909 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4910 if (req->opcode == IORING_OP_POLL_ADD)
4911 return req->async_data;
4912 return req->apoll->double_poll;
4915 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4917 if (req->opcode == IORING_OP_POLL_ADD)
4919 return &req->apoll->poll;
4922 static void io_poll_remove_double(struct io_kiocb *req)
4923 __must_hold(&req->ctx->completion_lock)
4925 struct io_poll_iocb *poll = io_poll_get_double(req);
4927 lockdep_assert_held(&req->ctx->completion_lock);
4929 if (poll && poll->head) {
4930 struct wait_queue_head *head = poll->head;
4932 spin_lock(&head->lock);
4933 list_del_init(&poll->wait.entry);
4934 if (poll->wait.private)
4937 spin_unlock(&head->lock);
4941 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4942 __must_hold(&req->ctx->completion_lock)
4944 struct io_ring_ctx *ctx = req->ctx;
4945 unsigned flags = IORING_CQE_F_MORE;
4948 if (READ_ONCE(req->poll.canceled)) {
4950 req->poll.events |= EPOLLONESHOT;
4952 error = mangle_poll(mask);
4954 if (req->poll.events & EPOLLONESHOT)
4956 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4957 req->poll.done = true;
4960 if (flags & IORING_CQE_F_MORE)
4963 io_commit_cqring(ctx);
4964 return !(flags & IORING_CQE_F_MORE);
4967 static void io_poll_task_func(struct io_kiocb *req)
4969 struct io_ring_ctx *ctx = req->ctx;
4970 struct io_kiocb *nxt;
4972 if (io_poll_rewait(req, &req->poll)) {
4973 spin_unlock_irq(&ctx->completion_lock);
4977 done = io_poll_complete(req, req->result);
4979 io_poll_remove_double(req);
4980 hash_del(&req->hash_node);
4983 add_wait_queue(req->poll.head, &req->poll.wait);
4985 spin_unlock_irq(&ctx->completion_lock);
4986 io_cqring_ev_posted(ctx);
4989 nxt = io_put_req_find_next(req);
4991 io_req_task_submit(nxt);
4996 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4997 int sync, void *key)
4999 struct io_kiocb *req = wait->private;
5000 struct io_poll_iocb *poll = io_poll_get_single(req);
5001 __poll_t mask = key_to_poll(key);
5003 /* for instances that support it check for an event match first: */
5004 if (mask && !(mask & poll->events))
5006 if (!(poll->events & EPOLLONESHOT))
5007 return poll->wait.func(&poll->wait, mode, sync, key);
5009 list_del_init(&wait->entry);
5014 spin_lock(&poll->head->lock);
5015 done = list_empty(&poll->wait.entry);
5017 list_del_init(&poll->wait.entry);
5018 /* make sure double remove sees this as being gone */
5019 wait->private = NULL;
5020 spin_unlock(&poll->head->lock);
5022 /* use wait func handler, so it matches the rq type */
5023 poll->wait.func(&poll->wait, mode, sync, key);
5030 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5031 wait_queue_func_t wake_func)
5035 poll->canceled = false;
5036 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5037 /* mask in events that we always want/need */
5038 poll->events = events | IO_POLL_UNMASK;
5039 INIT_LIST_HEAD(&poll->wait.entry);
5040 init_waitqueue_func_entry(&poll->wait, wake_func);
5043 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5044 struct wait_queue_head *head,
5045 struct io_poll_iocb **poll_ptr)
5047 struct io_kiocb *req = pt->req;
5050 * The file being polled uses multiple waitqueues for poll handling
5051 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5054 if (unlikely(pt->nr_entries)) {
5055 struct io_poll_iocb *poll_one = poll;
5057 /* already have a 2nd entry, fail a third attempt */
5059 pt->error = -EINVAL;
5063 * Can't handle multishot for double wait for now, turn it
5064 * into one-shot mode.
5066 if (!(poll_one->events & EPOLLONESHOT))
5067 poll_one->events |= EPOLLONESHOT;
5068 /* double add on the same waitqueue head, ignore */
5069 if (poll_one->head == head)
5071 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5073 pt->error = -ENOMEM;
5076 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5078 poll->wait.private = req;
5085 if (poll->events & EPOLLEXCLUSIVE)
5086 add_wait_queue_exclusive(head, &poll->wait);
5088 add_wait_queue(head, &poll->wait);
5091 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5092 struct poll_table_struct *p)
5094 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5095 struct async_poll *apoll = pt->req->apoll;
5097 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5100 static void io_async_task_func(struct io_kiocb *req)
5102 struct async_poll *apoll = req->apoll;
5103 struct io_ring_ctx *ctx = req->ctx;
5105 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5107 if (io_poll_rewait(req, &apoll->poll)) {
5108 spin_unlock_irq(&ctx->completion_lock);
5112 hash_del(&req->hash_node);
5113 io_poll_remove_double(req);
5114 spin_unlock_irq(&ctx->completion_lock);
5116 if (!READ_ONCE(apoll->poll.canceled))
5117 io_req_task_submit(req);
5119 io_req_complete_failed(req, -ECANCELED);
5122 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5125 struct io_kiocb *req = wait->private;
5126 struct io_poll_iocb *poll = &req->apoll->poll;
5128 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5131 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5134 static void io_poll_req_insert(struct io_kiocb *req)
5136 struct io_ring_ctx *ctx = req->ctx;
5137 struct hlist_head *list;
5139 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5140 hlist_add_head(&req->hash_node, list);
5143 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5144 struct io_poll_iocb *poll,
5145 struct io_poll_table *ipt, __poll_t mask,
5146 wait_queue_func_t wake_func)
5147 __acquires(&ctx->completion_lock)
5149 struct io_ring_ctx *ctx = req->ctx;
5150 bool cancel = false;
5152 INIT_HLIST_NODE(&req->hash_node);
5153 io_init_poll_iocb(poll, mask, wake_func);
5154 poll->file = req->file;
5155 poll->wait.private = req;
5157 ipt->pt._key = mask;
5160 ipt->nr_entries = 0;
5162 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5163 if (unlikely(!ipt->nr_entries) && !ipt->error)
5164 ipt->error = -EINVAL;
5166 spin_lock_irq(&ctx->completion_lock);
5167 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5168 io_poll_remove_double(req);
5169 if (likely(poll->head)) {
5170 spin_lock(&poll->head->lock);
5171 if (unlikely(list_empty(&poll->wait.entry))) {
5177 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5178 list_del_init(&poll->wait.entry);
5180 WRITE_ONCE(poll->canceled, true);
5181 else if (!poll->done) /* actually waiting for an event */
5182 io_poll_req_insert(req);
5183 spin_unlock(&poll->head->lock);
5195 static int io_arm_poll_handler(struct io_kiocb *req)
5197 const struct io_op_def *def = &io_op_defs[req->opcode];
5198 struct io_ring_ctx *ctx = req->ctx;
5199 struct async_poll *apoll;
5200 struct io_poll_table ipt;
5201 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5204 if (!req->file || !file_can_poll(req->file))
5205 return IO_APOLL_ABORTED;
5206 if (req->flags & REQ_F_POLLED)
5207 return IO_APOLL_ABORTED;
5208 if (!def->pollin && !def->pollout)
5209 return IO_APOLL_ABORTED;
5213 mask |= POLLIN | POLLRDNORM;
5215 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5216 if ((req->opcode == IORING_OP_RECVMSG) &&
5217 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5221 mask |= POLLOUT | POLLWRNORM;
5224 /* if we can't nonblock try, then no point in arming a poll handler */
5225 if (!io_file_supports_nowait(req, rw))
5226 return IO_APOLL_ABORTED;
5228 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5229 if (unlikely(!apoll))
5230 return IO_APOLL_ABORTED;
5231 apoll->double_poll = NULL;
5233 req->flags |= REQ_F_POLLED;
5234 ipt.pt._qproc = io_async_queue_proc;
5236 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5238 if (ret || ipt.error) {
5239 spin_unlock_irq(&ctx->completion_lock);
5241 return IO_APOLL_READY;
5242 return IO_APOLL_ABORTED;
5244 spin_unlock_irq(&ctx->completion_lock);
5245 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5246 mask, apoll->poll.events);
5250 static bool __io_poll_remove_one(struct io_kiocb *req,
5251 struct io_poll_iocb *poll, bool do_cancel)
5252 __must_hold(&req->ctx->completion_lock)
5254 bool do_complete = false;
5258 spin_lock(&poll->head->lock);
5260 WRITE_ONCE(poll->canceled, true);
5261 if (!list_empty(&poll->wait.entry)) {
5262 list_del_init(&poll->wait.entry);
5265 spin_unlock(&poll->head->lock);
5266 hash_del(&req->hash_node);
5270 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5271 __must_hold(&req->ctx->completion_lock)
5275 io_poll_remove_double(req);
5276 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5278 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5279 /* non-poll requests have submit ref still */
5285 static bool io_poll_remove_one(struct io_kiocb *req)
5286 __must_hold(&req->ctx->completion_lock)
5290 do_complete = io_poll_remove_waitqs(req);
5292 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5293 io_commit_cqring(req->ctx);
5295 io_put_req_deferred(req, 1);
5302 * Returns true if we found and killed one or more poll requests
5304 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5307 struct hlist_node *tmp;
5308 struct io_kiocb *req;
5311 spin_lock_irq(&ctx->completion_lock);
5312 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5313 struct hlist_head *list;
5315 list = &ctx->cancel_hash[i];
5316 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5317 if (io_match_task(req, tsk, cancel_all))
5318 posted += io_poll_remove_one(req);
5321 spin_unlock_irq(&ctx->completion_lock);
5324 io_cqring_ev_posted(ctx);
5329 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5331 __must_hold(&ctx->completion_lock)
5333 struct hlist_head *list;
5334 struct io_kiocb *req;
5336 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5337 hlist_for_each_entry(req, list, hash_node) {
5338 if (sqe_addr != req->user_data)
5340 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5347 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5349 __must_hold(&ctx->completion_lock)
5351 struct io_kiocb *req;
5353 req = io_poll_find(ctx, sqe_addr, poll_only);
5356 if (io_poll_remove_one(req))
5362 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5367 events = READ_ONCE(sqe->poll32_events);
5369 events = swahw32(events);
5371 if (!(flags & IORING_POLL_ADD_MULTI))
5372 events |= EPOLLONESHOT;
5373 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5376 static int io_poll_update_prep(struct io_kiocb *req,
5377 const struct io_uring_sqe *sqe)
5379 struct io_poll_update *upd = &req->poll_update;
5382 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5384 if (sqe->ioprio || sqe->buf_index)
5386 flags = READ_ONCE(sqe->len);
5387 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5388 IORING_POLL_ADD_MULTI))
5390 /* meaningless without update */
5391 if (flags == IORING_POLL_ADD_MULTI)
5394 upd->old_user_data = READ_ONCE(sqe->addr);
5395 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5396 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5398 upd->new_user_data = READ_ONCE(sqe->off);
5399 if (!upd->update_user_data && upd->new_user_data)
5401 if (upd->update_events)
5402 upd->events = io_poll_parse_events(sqe, flags);
5403 else if (sqe->poll32_events)
5409 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5412 struct io_kiocb *req = wait->private;
5413 struct io_poll_iocb *poll = &req->poll;
5415 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5418 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5419 struct poll_table_struct *p)
5421 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5423 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5426 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5428 struct io_poll_iocb *poll = &req->poll;
5431 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5433 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5435 flags = READ_ONCE(sqe->len);
5436 if (flags & ~IORING_POLL_ADD_MULTI)
5439 poll->events = io_poll_parse_events(sqe, flags);
5443 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5445 struct io_poll_iocb *poll = &req->poll;
5446 struct io_ring_ctx *ctx = req->ctx;
5447 struct io_poll_table ipt;
5450 ipt.pt._qproc = io_poll_queue_proc;
5452 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5455 if (mask) { /* no async, we'd stolen it */
5457 io_poll_complete(req, mask);
5459 spin_unlock_irq(&ctx->completion_lock);
5462 io_cqring_ev_posted(ctx);
5463 if (poll->events & EPOLLONESHOT)
5469 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5471 struct io_ring_ctx *ctx = req->ctx;
5472 struct io_kiocb *preq;
5476 spin_lock_irq(&ctx->completion_lock);
5477 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5483 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5485 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5490 * Don't allow racy completion with singleshot, as we cannot safely
5491 * update those. For multishot, if we're racing with completion, just
5492 * let completion re-add it.
5494 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5495 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5499 /* we now have a detached poll request. reissue. */
5503 spin_unlock_irq(&ctx->completion_lock);
5505 io_req_complete(req, ret);
5508 /* only mask one event flags, keep behavior flags */
5509 if (req->poll_update.update_events) {
5510 preq->poll.events &= ~0xffff;
5511 preq->poll.events |= req->poll_update.events & 0xffff;
5512 preq->poll.events |= IO_POLL_UNMASK;
5514 if (req->poll_update.update_user_data)
5515 preq->user_data = req->poll_update.new_user_data;
5516 spin_unlock_irq(&ctx->completion_lock);
5518 /* complete update request, we're done with it */
5519 io_req_complete(req, ret);
5522 ret = io_poll_add(preq, issue_flags);
5525 io_req_complete(preq, ret);
5531 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5533 struct io_timeout_data *data = container_of(timer,
5534 struct io_timeout_data, timer);
5535 struct io_kiocb *req = data->req;
5536 struct io_ring_ctx *ctx = req->ctx;
5537 unsigned long flags;
5539 spin_lock_irqsave(&ctx->completion_lock, flags);
5540 list_del_init(&req->timeout.list);
5541 atomic_set(&req->ctx->cq_timeouts,
5542 atomic_read(&req->ctx->cq_timeouts) + 1);
5544 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5545 io_commit_cqring(ctx);
5546 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5548 io_cqring_ev_posted(ctx);
5551 return HRTIMER_NORESTART;
5554 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5556 __must_hold(&ctx->completion_lock)
5558 struct io_timeout_data *io;
5559 struct io_kiocb *req;
5562 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5563 found = user_data == req->user_data;
5568 return ERR_PTR(-ENOENT);
5570 io = req->async_data;
5571 if (hrtimer_try_to_cancel(&io->timer) == -1)
5572 return ERR_PTR(-EALREADY);
5573 list_del_init(&req->timeout.list);
5577 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5578 __must_hold(&ctx->completion_lock)
5580 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5583 return PTR_ERR(req);
5586 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5587 io_put_req_deferred(req, 1);
5591 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5592 struct timespec64 *ts, enum hrtimer_mode mode)
5593 __must_hold(&ctx->completion_lock)
5595 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5596 struct io_timeout_data *data;
5599 return PTR_ERR(req);
5601 req->timeout.off = 0; /* noseq */
5602 data = req->async_data;
5603 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5604 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5605 data->timer.function = io_timeout_fn;
5606 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5610 static int io_timeout_remove_prep(struct io_kiocb *req,
5611 const struct io_uring_sqe *sqe)
5613 struct io_timeout_rem *tr = &req->timeout_rem;
5615 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5617 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5619 if (sqe->ioprio || sqe->buf_index || sqe->len)
5622 tr->addr = READ_ONCE(sqe->addr);
5623 tr->flags = READ_ONCE(sqe->timeout_flags);
5624 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5625 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5627 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5629 } else if (tr->flags) {
5630 /* timeout removal doesn't support flags */
5637 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5639 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5644 * Remove or update an existing timeout command
5646 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5648 struct io_timeout_rem *tr = &req->timeout_rem;
5649 struct io_ring_ctx *ctx = req->ctx;
5652 spin_lock_irq(&ctx->completion_lock);
5653 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5654 ret = io_timeout_cancel(ctx, tr->addr);
5656 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5657 io_translate_timeout_mode(tr->flags));
5659 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5660 io_commit_cqring(ctx);
5661 spin_unlock_irq(&ctx->completion_lock);
5662 io_cqring_ev_posted(ctx);
5669 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5670 bool is_timeout_link)
5672 struct io_timeout_data *data;
5674 u32 off = READ_ONCE(sqe->off);
5676 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5678 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5680 if (off && is_timeout_link)
5682 flags = READ_ONCE(sqe->timeout_flags);
5683 if (flags & ~IORING_TIMEOUT_ABS)
5686 req->timeout.off = off;
5687 if (unlikely(off && !req->ctx->off_timeout_used))
5688 req->ctx->off_timeout_used = true;
5690 if (!req->async_data && io_alloc_async_data(req))
5693 data = req->async_data;
5696 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5699 data->mode = io_translate_timeout_mode(flags);
5700 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5701 if (is_timeout_link)
5702 io_req_track_inflight(req);
5706 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5708 struct io_ring_ctx *ctx = req->ctx;
5709 struct io_timeout_data *data = req->async_data;
5710 struct list_head *entry;
5711 u32 tail, off = req->timeout.off;
5713 spin_lock_irq(&ctx->completion_lock);
5716 * sqe->off holds how many events that need to occur for this
5717 * timeout event to be satisfied. If it isn't set, then this is
5718 * a pure timeout request, sequence isn't used.
5720 if (io_is_timeout_noseq(req)) {
5721 entry = ctx->timeout_list.prev;
5725 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5726 req->timeout.target_seq = tail + off;
5728 /* Update the last seq here in case io_flush_timeouts() hasn't.
5729 * This is safe because ->completion_lock is held, and submissions
5730 * and completions are never mixed in the same ->completion_lock section.
5732 ctx->cq_last_tm_flush = tail;
5735 * Insertion sort, ensuring the first entry in the list is always
5736 * the one we need first.
5738 list_for_each_prev(entry, &ctx->timeout_list) {
5739 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5742 if (io_is_timeout_noseq(nxt))
5744 /* nxt.seq is behind @tail, otherwise would've been completed */
5745 if (off >= nxt->timeout.target_seq - tail)
5749 list_add(&req->timeout.list, entry);
5750 data->timer.function = io_timeout_fn;
5751 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5752 spin_unlock_irq(&ctx->completion_lock);
5756 struct io_cancel_data {
5757 struct io_ring_ctx *ctx;
5761 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5763 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5764 struct io_cancel_data *cd = data;
5766 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5769 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5770 struct io_ring_ctx *ctx)
5772 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5773 enum io_wq_cancel cancel_ret;
5776 if (!tctx || !tctx->io_wq)
5779 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5780 switch (cancel_ret) {
5781 case IO_WQ_CANCEL_OK:
5784 case IO_WQ_CANCEL_RUNNING:
5787 case IO_WQ_CANCEL_NOTFOUND:
5795 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5796 struct io_kiocb *req, __u64 sqe_addr,
5799 unsigned long flags;
5802 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5803 spin_lock_irqsave(&ctx->completion_lock, flags);
5806 ret = io_timeout_cancel(ctx, sqe_addr);
5809 ret = io_poll_cancel(ctx, sqe_addr, false);
5813 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5814 io_commit_cqring(ctx);
5815 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5816 io_cqring_ev_posted(ctx);
5822 static int io_async_cancel_prep(struct io_kiocb *req,
5823 const struct io_uring_sqe *sqe)
5825 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5827 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5829 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5832 req->cancel.addr = READ_ONCE(sqe->addr);
5836 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5838 struct io_ring_ctx *ctx = req->ctx;
5839 u64 sqe_addr = req->cancel.addr;
5840 struct io_tctx_node *node;
5843 /* tasks should wait for their io-wq threads, so safe w/o sync */
5844 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5845 spin_lock_irq(&ctx->completion_lock);
5848 ret = io_timeout_cancel(ctx, sqe_addr);
5851 ret = io_poll_cancel(ctx, sqe_addr, false);
5854 spin_unlock_irq(&ctx->completion_lock);
5856 /* slow path, try all io-wq's */
5857 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5859 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5860 struct io_uring_task *tctx = node->task->io_uring;
5862 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5866 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5868 spin_lock_irq(&ctx->completion_lock);
5870 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5871 io_commit_cqring(ctx);
5872 spin_unlock_irq(&ctx->completion_lock);
5873 io_cqring_ev_posted(ctx);
5881 static int io_rsrc_update_prep(struct io_kiocb *req,
5882 const struct io_uring_sqe *sqe)
5884 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5886 if (sqe->ioprio || sqe->rw_flags)
5889 req->rsrc_update.offset = READ_ONCE(sqe->off);
5890 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5891 if (!req->rsrc_update.nr_args)
5893 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5897 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5899 struct io_ring_ctx *ctx = req->ctx;
5900 struct io_uring_rsrc_update2 up;
5903 if (issue_flags & IO_URING_F_NONBLOCK)
5906 up.offset = req->rsrc_update.offset;
5907 up.data = req->rsrc_update.arg;
5912 mutex_lock(&ctx->uring_lock);
5913 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5914 &up, req->rsrc_update.nr_args);
5915 mutex_unlock(&ctx->uring_lock);
5919 __io_req_complete(req, issue_flags, ret, 0);
5923 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5925 switch (req->opcode) {
5928 case IORING_OP_READV:
5929 case IORING_OP_READ_FIXED:
5930 case IORING_OP_READ:
5931 return io_read_prep(req, sqe);
5932 case IORING_OP_WRITEV:
5933 case IORING_OP_WRITE_FIXED:
5934 case IORING_OP_WRITE:
5935 return io_write_prep(req, sqe);
5936 case IORING_OP_POLL_ADD:
5937 return io_poll_add_prep(req, sqe);
5938 case IORING_OP_POLL_REMOVE:
5939 return io_poll_update_prep(req, sqe);
5940 case IORING_OP_FSYNC:
5941 return io_fsync_prep(req, sqe);
5942 case IORING_OP_SYNC_FILE_RANGE:
5943 return io_sfr_prep(req, sqe);
5944 case IORING_OP_SENDMSG:
5945 case IORING_OP_SEND:
5946 return io_sendmsg_prep(req, sqe);
5947 case IORING_OP_RECVMSG:
5948 case IORING_OP_RECV:
5949 return io_recvmsg_prep(req, sqe);
5950 case IORING_OP_CONNECT:
5951 return io_connect_prep(req, sqe);
5952 case IORING_OP_TIMEOUT:
5953 return io_timeout_prep(req, sqe, false);
5954 case IORING_OP_TIMEOUT_REMOVE:
5955 return io_timeout_remove_prep(req, sqe);
5956 case IORING_OP_ASYNC_CANCEL:
5957 return io_async_cancel_prep(req, sqe);
5958 case IORING_OP_LINK_TIMEOUT:
5959 return io_timeout_prep(req, sqe, true);
5960 case IORING_OP_ACCEPT:
5961 return io_accept_prep(req, sqe);
5962 case IORING_OP_FALLOCATE:
5963 return io_fallocate_prep(req, sqe);
5964 case IORING_OP_OPENAT:
5965 return io_openat_prep(req, sqe);
5966 case IORING_OP_CLOSE:
5967 return io_close_prep(req, sqe);
5968 case IORING_OP_FILES_UPDATE:
5969 return io_rsrc_update_prep(req, sqe);
5970 case IORING_OP_STATX:
5971 return io_statx_prep(req, sqe);
5972 case IORING_OP_FADVISE:
5973 return io_fadvise_prep(req, sqe);
5974 case IORING_OP_MADVISE:
5975 return io_madvise_prep(req, sqe);
5976 case IORING_OP_OPENAT2:
5977 return io_openat2_prep(req, sqe);
5978 case IORING_OP_EPOLL_CTL:
5979 return io_epoll_ctl_prep(req, sqe);
5980 case IORING_OP_SPLICE:
5981 return io_splice_prep(req, sqe);
5982 case IORING_OP_PROVIDE_BUFFERS:
5983 return io_provide_buffers_prep(req, sqe);
5984 case IORING_OP_REMOVE_BUFFERS:
5985 return io_remove_buffers_prep(req, sqe);
5987 return io_tee_prep(req, sqe);
5988 case IORING_OP_SHUTDOWN:
5989 return io_shutdown_prep(req, sqe);
5990 case IORING_OP_RENAMEAT:
5991 return io_renameat_prep(req, sqe);
5992 case IORING_OP_UNLINKAT:
5993 return io_unlinkat_prep(req, sqe);
5996 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6001 static int io_req_prep_async(struct io_kiocb *req)
6003 if (!io_op_defs[req->opcode].needs_async_setup)
6005 if (WARN_ON_ONCE(req->async_data))
6007 if (io_alloc_async_data(req))
6010 switch (req->opcode) {
6011 case IORING_OP_READV:
6012 return io_rw_prep_async(req, READ);
6013 case IORING_OP_WRITEV:
6014 return io_rw_prep_async(req, WRITE);
6015 case IORING_OP_SENDMSG:
6016 return io_sendmsg_prep_async(req);
6017 case IORING_OP_RECVMSG:
6018 return io_recvmsg_prep_async(req);
6019 case IORING_OP_CONNECT:
6020 return io_connect_prep_async(req);
6022 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6027 static u32 io_get_sequence(struct io_kiocb *req)
6029 u32 seq = req->ctx->cached_sq_head;
6031 /* need original cached_sq_head, but it was increased for each req */
6032 io_for_each_link(req, req)
6037 static bool io_drain_req(struct io_kiocb *req)
6039 struct io_kiocb *pos;
6040 struct io_ring_ctx *ctx = req->ctx;
6041 struct io_defer_entry *de;
6046 * If we need to drain a request in the middle of a link, drain the
6047 * head request and the next request/link after the current link.
6048 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6049 * maintained for every request of our link.
6051 if (ctx->drain_next) {
6052 req->flags |= REQ_F_IO_DRAIN;
6053 ctx->drain_next = false;
6055 /* not interested in head, start from the first linked */
6056 io_for_each_link(pos, req->link) {
6057 if (pos->flags & REQ_F_IO_DRAIN) {
6058 ctx->drain_next = true;
6059 req->flags |= REQ_F_IO_DRAIN;
6064 /* Still need defer if there is pending req in defer list. */
6065 if (likely(list_empty_careful(&ctx->defer_list) &&
6066 !(req->flags & REQ_F_IO_DRAIN))) {
6067 ctx->drain_active = false;
6071 seq = io_get_sequence(req);
6072 /* Still a chance to pass the sequence check */
6073 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6076 ret = io_req_prep_async(req);
6079 io_prep_async_link(req);
6080 de = kmalloc(sizeof(*de), GFP_KERNEL);
6084 io_req_complete_failed(req, ret);
6088 spin_lock_irq(&ctx->completion_lock);
6089 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6090 spin_unlock_irq(&ctx->completion_lock);
6092 io_queue_async_work(req);
6096 trace_io_uring_defer(ctx, req, req->user_data);
6099 list_add_tail(&de->list, &ctx->defer_list);
6100 spin_unlock_irq(&ctx->completion_lock);
6104 static void io_clean_op(struct io_kiocb *req)
6106 if (req->flags & REQ_F_BUFFER_SELECTED) {
6107 switch (req->opcode) {
6108 case IORING_OP_READV:
6109 case IORING_OP_READ_FIXED:
6110 case IORING_OP_READ:
6111 kfree((void *)(unsigned long)req->rw.addr);
6113 case IORING_OP_RECVMSG:
6114 case IORING_OP_RECV:
6115 kfree(req->sr_msg.kbuf);
6120 if (req->flags & REQ_F_NEED_CLEANUP) {
6121 switch (req->opcode) {
6122 case IORING_OP_READV:
6123 case IORING_OP_READ_FIXED:
6124 case IORING_OP_READ:
6125 case IORING_OP_WRITEV:
6126 case IORING_OP_WRITE_FIXED:
6127 case IORING_OP_WRITE: {
6128 struct io_async_rw *io = req->async_data;
6130 kfree(io->free_iovec);
6133 case IORING_OP_RECVMSG:
6134 case IORING_OP_SENDMSG: {
6135 struct io_async_msghdr *io = req->async_data;
6137 kfree(io->free_iov);
6140 case IORING_OP_SPLICE:
6142 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6143 io_put_file(req->splice.file_in);
6145 case IORING_OP_OPENAT:
6146 case IORING_OP_OPENAT2:
6147 if (req->open.filename)
6148 putname(req->open.filename);
6150 case IORING_OP_RENAMEAT:
6151 putname(req->rename.oldpath);
6152 putname(req->rename.newpath);
6154 case IORING_OP_UNLINKAT:
6155 putname(req->unlink.filename);
6159 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6160 kfree(req->apoll->double_poll);
6164 if (req->flags & REQ_F_INFLIGHT) {
6165 struct io_uring_task *tctx = req->task->io_uring;
6167 atomic_dec(&tctx->inflight_tracked);
6169 if (req->flags & REQ_F_CREDS)
6170 put_cred(req->creds);
6172 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6175 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6177 struct io_ring_ctx *ctx = req->ctx;
6178 const struct cred *creds = NULL;
6181 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6182 creds = override_creds(req->creds);
6184 switch (req->opcode) {
6186 ret = io_nop(req, issue_flags);
6188 case IORING_OP_READV:
6189 case IORING_OP_READ_FIXED:
6190 case IORING_OP_READ:
6191 ret = io_read(req, issue_flags);
6193 case IORING_OP_WRITEV:
6194 case IORING_OP_WRITE_FIXED:
6195 case IORING_OP_WRITE:
6196 ret = io_write(req, issue_flags);
6198 case IORING_OP_FSYNC:
6199 ret = io_fsync(req, issue_flags);
6201 case IORING_OP_POLL_ADD:
6202 ret = io_poll_add(req, issue_flags);
6204 case IORING_OP_POLL_REMOVE:
6205 ret = io_poll_update(req, issue_flags);
6207 case IORING_OP_SYNC_FILE_RANGE:
6208 ret = io_sync_file_range(req, issue_flags);
6210 case IORING_OP_SENDMSG:
6211 ret = io_sendmsg(req, issue_flags);
6213 case IORING_OP_SEND:
6214 ret = io_send(req, issue_flags);
6216 case IORING_OP_RECVMSG:
6217 ret = io_recvmsg(req, issue_flags);
6219 case IORING_OP_RECV:
6220 ret = io_recv(req, issue_flags);
6222 case IORING_OP_TIMEOUT:
6223 ret = io_timeout(req, issue_flags);
6225 case IORING_OP_TIMEOUT_REMOVE:
6226 ret = io_timeout_remove(req, issue_flags);
6228 case IORING_OP_ACCEPT:
6229 ret = io_accept(req, issue_flags);
6231 case IORING_OP_CONNECT:
6232 ret = io_connect(req, issue_flags);
6234 case IORING_OP_ASYNC_CANCEL:
6235 ret = io_async_cancel(req, issue_flags);
6237 case IORING_OP_FALLOCATE:
6238 ret = io_fallocate(req, issue_flags);
6240 case IORING_OP_OPENAT:
6241 ret = io_openat(req, issue_flags);
6243 case IORING_OP_CLOSE:
6244 ret = io_close(req, issue_flags);
6246 case IORING_OP_FILES_UPDATE:
6247 ret = io_files_update(req, issue_flags);
6249 case IORING_OP_STATX:
6250 ret = io_statx(req, issue_flags);
6252 case IORING_OP_FADVISE:
6253 ret = io_fadvise(req, issue_flags);
6255 case IORING_OP_MADVISE:
6256 ret = io_madvise(req, issue_flags);
6258 case IORING_OP_OPENAT2:
6259 ret = io_openat2(req, issue_flags);
6261 case IORING_OP_EPOLL_CTL:
6262 ret = io_epoll_ctl(req, issue_flags);
6264 case IORING_OP_SPLICE:
6265 ret = io_splice(req, issue_flags);
6267 case IORING_OP_PROVIDE_BUFFERS:
6268 ret = io_provide_buffers(req, issue_flags);
6270 case IORING_OP_REMOVE_BUFFERS:
6271 ret = io_remove_buffers(req, issue_flags);
6274 ret = io_tee(req, issue_flags);
6276 case IORING_OP_SHUTDOWN:
6277 ret = io_shutdown(req, issue_flags);
6279 case IORING_OP_RENAMEAT:
6280 ret = io_renameat(req, issue_flags);
6282 case IORING_OP_UNLINKAT:
6283 ret = io_unlinkat(req, issue_flags);
6291 revert_creds(creds);
6294 /* If the op doesn't have a file, we're not polling for it */
6295 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6296 io_iopoll_req_issued(req);
6301 static void io_wq_submit_work(struct io_wq_work *work)
6303 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6304 struct io_kiocb *timeout;
6307 timeout = io_prep_linked_timeout(req);
6309 io_queue_linked_timeout(timeout);
6311 if (work->flags & IO_WQ_WORK_CANCEL)
6316 ret = io_issue_sqe(req, 0);
6318 * We can get EAGAIN for polled IO even though we're
6319 * forcing a sync submission from here, since we can't
6320 * wait for request slots on the block side.
6328 /* avoid locking problems by failing it from a clean context */
6330 /* io-wq is going to take one down */
6332 io_req_task_queue_fail(req, ret);
6336 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6339 return &table->files[i];
6342 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6345 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6347 return (struct file *) (slot->file_ptr & FFS_MASK);
6350 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6352 unsigned long file_ptr = (unsigned long) file;
6354 if (__io_file_supports_nowait(file, READ))
6355 file_ptr |= FFS_ASYNC_READ;
6356 if (__io_file_supports_nowait(file, WRITE))
6357 file_ptr |= FFS_ASYNC_WRITE;
6358 if (S_ISREG(file_inode(file)->i_mode))
6359 file_ptr |= FFS_ISREG;
6360 file_slot->file_ptr = file_ptr;
6363 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6364 struct io_kiocb *req, int fd)
6367 unsigned long file_ptr;
6369 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6371 fd = array_index_nospec(fd, ctx->nr_user_files);
6372 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6373 file = (struct file *) (file_ptr & FFS_MASK);
6374 file_ptr &= ~FFS_MASK;
6375 /* mask in overlapping REQ_F and FFS bits */
6376 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6377 io_req_set_rsrc_node(req);
6381 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6382 struct io_submit_state *state,
6383 struct io_kiocb *req, int fd)
6385 struct file *file = __io_file_get(state, fd);
6387 trace_io_uring_file_get(ctx, fd);
6389 /* we don't allow fixed io_uring files */
6390 if (file && unlikely(file->f_op == &io_uring_fops))
6391 io_req_track_inflight(req);
6395 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6396 struct io_submit_state *state,
6397 struct io_kiocb *req, int fd, bool fixed)
6400 return io_file_get_fixed(ctx, req, fd);
6402 return io_file_get_normal(ctx, state, req, fd);
6405 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6407 struct io_timeout_data *data = container_of(timer,
6408 struct io_timeout_data, timer);
6409 struct io_kiocb *prev, *req = data->req;
6410 struct io_ring_ctx *ctx = req->ctx;
6411 unsigned long flags;
6413 spin_lock_irqsave(&ctx->completion_lock, flags);
6414 prev = req->timeout.head;
6415 req->timeout.head = NULL;
6418 * We don't expect the list to be empty, that will only happen if we
6419 * race with the completion of the linked work.
6422 io_remove_next_linked(prev);
6423 if (!req_ref_inc_not_zero(prev))
6426 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6429 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6430 io_put_req_deferred(prev, 1);
6431 io_put_req_deferred(req, 1);
6433 io_req_complete_post(req, -ETIME, 0);
6435 return HRTIMER_NORESTART;
6438 static void io_queue_linked_timeout(struct io_kiocb *req)
6440 struct io_ring_ctx *ctx = req->ctx;
6442 spin_lock_irq(&ctx->completion_lock);
6444 * If the back reference is NULL, then our linked request finished
6445 * before we got a chance to setup the timer
6447 if (req->timeout.head) {
6448 struct io_timeout_data *data = req->async_data;
6450 data->timer.function = io_link_timeout_fn;
6451 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6454 spin_unlock_irq(&ctx->completion_lock);
6455 /* drop submission reference */
6459 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6461 struct io_kiocb *nxt = req->link;
6463 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6464 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6467 nxt->timeout.head = req;
6468 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6469 req->flags |= REQ_F_LINK_TIMEOUT;
6473 static void __io_queue_sqe(struct io_kiocb *req)
6475 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6479 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6482 * We async punt it if the file wasn't marked NOWAIT, or if the file
6483 * doesn't support non-blocking read/write attempts
6486 /* drop submission reference */
6487 if (req->flags & REQ_F_COMPLETE_INLINE) {
6488 struct io_ring_ctx *ctx = req->ctx;
6489 struct io_comp_state *cs = &ctx->submit_state.comp;
6491 cs->reqs[cs->nr++] = req;
6492 if (cs->nr == ARRAY_SIZE(cs->reqs))
6493 io_submit_flush_completions(ctx);
6497 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6498 switch (io_arm_poll_handler(req)) {
6499 case IO_APOLL_READY:
6501 case IO_APOLL_ABORTED:
6503 * Queued up for async execution, worker will release
6504 * submit reference when the iocb is actually submitted.
6506 io_queue_async_work(req);
6510 io_req_complete_failed(req, ret);
6513 io_queue_linked_timeout(linked_timeout);
6516 static inline void io_queue_sqe(struct io_kiocb *req)
6518 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6521 if (likely(!(req->flags & REQ_F_FORCE_ASYNC))) {
6522 __io_queue_sqe(req);
6524 int ret = io_req_prep_async(req);
6527 io_req_complete_failed(req, ret);
6529 io_queue_async_work(req);
6534 * Check SQE restrictions (opcode and flags).
6536 * Returns 'true' if SQE is allowed, 'false' otherwise.
6538 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6539 struct io_kiocb *req,
6540 unsigned int sqe_flags)
6542 if (likely(!ctx->restricted))
6545 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6548 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6549 ctx->restrictions.sqe_flags_required)
6552 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6553 ctx->restrictions.sqe_flags_required))
6559 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6560 const struct io_uring_sqe *sqe)
6562 struct io_submit_state *state;
6563 unsigned int sqe_flags;
6564 int personality, ret = 0;
6566 req->opcode = READ_ONCE(sqe->opcode);
6567 /* same numerical values with corresponding REQ_F_*, safe to copy */
6568 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6569 req->user_data = READ_ONCE(sqe->user_data);
6571 req->fixed_rsrc_refs = NULL;
6572 /* one is dropped after submission, the other at completion */
6573 atomic_set(&req->refs, 2);
6574 req->task = current;
6576 /* enforce forwards compatibility on users */
6577 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6579 if (unlikely(req->opcode >= IORING_OP_LAST))
6581 if (!io_check_restriction(ctx, req, sqe_flags))
6584 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6585 !io_op_defs[req->opcode].buffer_select)
6587 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6588 ctx->drain_active = true;
6590 personality = READ_ONCE(sqe->personality);
6592 req->creds = xa_load(&ctx->personalities, personality);
6595 get_cred(req->creds);
6596 req->flags |= REQ_F_CREDS;
6598 state = &ctx->submit_state;
6601 * Plug now if we have more than 1 IO left after this, and the target
6602 * is potentially a read/write to block based storage.
6604 if (!state->plug_started && state->ios_left > 1 &&
6605 io_op_defs[req->opcode].plug) {
6606 blk_start_plug(&state->plug);
6607 state->plug_started = true;
6610 if (io_op_defs[req->opcode].needs_file) {
6611 req->file = io_file_get(ctx, state, req, READ_ONCE(sqe->fd),
6612 (sqe_flags & IOSQE_FIXED_FILE));
6613 if (unlikely(!req->file))
6621 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6622 const struct io_uring_sqe *sqe)
6624 struct io_submit_link *link = &ctx->submit_state.link;
6627 ret = io_init_req(ctx, req, sqe);
6628 if (unlikely(ret)) {
6631 /* fail even hard links since we don't submit */
6632 req_set_fail(link->head);
6633 io_req_complete_failed(link->head, -ECANCELED);
6636 io_req_complete_failed(req, ret);
6640 ret = io_req_prep(req, sqe);
6644 /* don't need @sqe from now on */
6645 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6647 ctx->flags & IORING_SETUP_SQPOLL);
6650 * If we already have a head request, queue this one for async
6651 * submittal once the head completes. If we don't have a head but
6652 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6653 * submitted sync once the chain is complete. If none of those
6654 * conditions are true (normal request), then just queue it.
6657 struct io_kiocb *head = link->head;
6659 ret = io_req_prep_async(req);
6662 trace_io_uring_link(ctx, req, head);
6663 link->last->link = req;
6666 /* last request of a link, enqueue the link */
6667 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6672 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6684 * Batched submission is done, ensure local IO is flushed out.
6686 static void io_submit_state_end(struct io_submit_state *state,
6687 struct io_ring_ctx *ctx)
6689 if (state->link.head)
6690 io_queue_sqe(state->link.head);
6692 io_submit_flush_completions(ctx);
6693 if (state->plug_started)
6694 blk_finish_plug(&state->plug);
6695 io_state_file_put(state);
6699 * Start submission side cache.
6701 static void io_submit_state_start(struct io_submit_state *state,
6702 unsigned int max_ios)
6704 state->plug_started = false;
6705 state->ios_left = max_ios;
6706 /* set only head, no need to init link_last in advance */
6707 state->link.head = NULL;
6710 static void io_commit_sqring(struct io_ring_ctx *ctx)
6712 struct io_rings *rings = ctx->rings;
6715 * Ensure any loads from the SQEs are done at this point,
6716 * since once we write the new head, the application could
6717 * write new data to them.
6719 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6723 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6724 * that is mapped by userspace. This means that care needs to be taken to
6725 * ensure that reads are stable, as we cannot rely on userspace always
6726 * being a good citizen. If members of the sqe are validated and then later
6727 * used, it's important that those reads are done through READ_ONCE() to
6728 * prevent a re-load down the line.
6730 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6732 unsigned head, mask = ctx->sq_entries - 1;
6733 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6736 * The cached sq head (or cq tail) serves two purposes:
6738 * 1) allows us to batch the cost of updating the user visible
6740 * 2) allows the kernel side to track the head on its own, even
6741 * though the application is the one updating it.
6743 head = READ_ONCE(ctx->sq_array[sq_idx]);
6744 if (likely(head < ctx->sq_entries))
6745 return &ctx->sq_sqes[head];
6747 /* drop invalid entries */
6749 WRITE_ONCE(ctx->rings->sq_dropped,
6750 READ_ONCE(ctx->rings->sq_dropped) + 1);
6754 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6756 struct io_uring_task *tctx;
6759 /* make sure SQ entry isn't read before tail */
6760 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6761 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6764 tctx = current->io_uring;
6765 tctx->cached_refs -= nr;
6766 if (unlikely(tctx->cached_refs < 0)) {
6767 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
6769 percpu_counter_add(&tctx->inflight, refill);
6770 refcount_add(refill, ¤t->usage);
6771 tctx->cached_refs += refill;
6773 io_submit_state_start(&ctx->submit_state, nr);
6775 while (submitted < nr) {
6776 const struct io_uring_sqe *sqe;
6777 struct io_kiocb *req;
6779 req = io_alloc_req(ctx);
6780 if (unlikely(!req)) {
6782 submitted = -EAGAIN;
6785 sqe = io_get_sqe(ctx);
6786 if (unlikely(!sqe)) {
6787 kmem_cache_free(req_cachep, req);
6790 /* will complete beyond this point, count as submitted */
6792 if (io_submit_sqe(ctx, req, sqe))
6796 if (unlikely(submitted != nr)) {
6797 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6798 int unused = nr - ref_used;
6800 current->io_uring->cached_refs += unused;
6801 percpu_ref_put_many(&ctx->refs, unused);
6804 io_submit_state_end(&ctx->submit_state, ctx);
6805 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6806 io_commit_sqring(ctx);
6811 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6813 return READ_ONCE(sqd->state);
6816 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6818 /* Tell userspace we may need a wakeup call */
6819 spin_lock_irq(&ctx->completion_lock);
6820 WRITE_ONCE(ctx->rings->sq_flags,
6821 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
6822 spin_unlock_irq(&ctx->completion_lock);
6825 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6827 spin_lock_irq(&ctx->completion_lock);
6828 WRITE_ONCE(ctx->rings->sq_flags,
6829 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
6830 spin_unlock_irq(&ctx->completion_lock);
6833 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6835 unsigned int to_submit;
6838 to_submit = io_sqring_entries(ctx);
6839 /* if we're handling multiple rings, cap submit size for fairness */
6840 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6841 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6843 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6844 unsigned nr_events = 0;
6845 const struct cred *creds = NULL;
6847 if (ctx->sq_creds != current_cred())
6848 creds = override_creds(ctx->sq_creds);
6850 mutex_lock(&ctx->uring_lock);
6851 if (!list_empty(&ctx->iopoll_list))
6852 io_do_iopoll(ctx, &nr_events, 0, true);
6855 * Don't submit if refs are dying, good for io_uring_register(),
6856 * but also it is relied upon by io_ring_exit_work()
6858 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6859 !(ctx->flags & IORING_SETUP_R_DISABLED))
6860 ret = io_submit_sqes(ctx, to_submit);
6861 mutex_unlock(&ctx->uring_lock);
6863 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6864 wake_up(&ctx->sqo_sq_wait);
6866 revert_creds(creds);
6872 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6874 struct io_ring_ctx *ctx;
6875 unsigned sq_thread_idle = 0;
6877 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6878 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6879 sqd->sq_thread_idle = sq_thread_idle;
6882 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6884 bool did_sig = false;
6885 struct ksignal ksig;
6887 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6888 signal_pending(current)) {
6889 mutex_unlock(&sqd->lock);
6890 if (signal_pending(current))
6891 did_sig = get_signal(&ksig);
6893 mutex_lock(&sqd->lock);
6895 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6898 static int io_sq_thread(void *data)
6900 struct io_sq_data *sqd = data;
6901 struct io_ring_ctx *ctx;
6902 unsigned long timeout = 0;
6903 char buf[TASK_COMM_LEN];
6906 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6907 set_task_comm(current, buf);
6909 if (sqd->sq_cpu != -1)
6910 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6912 set_cpus_allowed_ptr(current, cpu_online_mask);
6913 current->flags |= PF_NO_SETAFFINITY;
6915 mutex_lock(&sqd->lock);
6917 bool cap_entries, sqt_spin = false;
6919 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
6920 if (io_sqd_handle_event(sqd))
6922 timeout = jiffies + sqd->sq_thread_idle;
6925 cap_entries = !list_is_singular(&sqd->ctx_list);
6926 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6927 int ret = __io_sq_thread(ctx, cap_entries);
6929 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6932 if (io_run_task_work())
6935 if (sqt_spin || !time_after(jiffies, timeout)) {
6938 timeout = jiffies + sqd->sq_thread_idle;
6942 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6943 if (!io_sqd_events_pending(sqd) && !current->task_works) {
6944 bool needs_sched = true;
6946 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6947 io_ring_set_wakeup_flag(ctx);
6949 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6950 !list_empty_careful(&ctx->iopoll_list)) {
6951 needs_sched = false;
6954 if (io_sqring_entries(ctx)) {
6955 needs_sched = false;
6961 mutex_unlock(&sqd->lock);
6963 mutex_lock(&sqd->lock);
6965 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6966 io_ring_clear_wakeup_flag(ctx);
6969 finish_wait(&sqd->wait, &wait);
6970 timeout = jiffies + sqd->sq_thread_idle;
6973 io_uring_cancel_generic(true, sqd);
6975 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6976 io_ring_set_wakeup_flag(ctx);
6978 mutex_unlock(&sqd->lock);
6980 complete(&sqd->exited);
6984 struct io_wait_queue {
6985 struct wait_queue_entry wq;
6986 struct io_ring_ctx *ctx;
6988 unsigned nr_timeouts;
6991 static inline bool io_should_wake(struct io_wait_queue *iowq)
6993 struct io_ring_ctx *ctx = iowq->ctx;
6994 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
6997 * Wake up if we have enough events, or if a timeout occurred since we
6998 * started waiting. For timeouts, we always want to return to userspace,
6999 * regardless of event count.
7001 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7004 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7005 int wake_flags, void *key)
7007 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7011 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7012 * the task, and the next invocation will do it.
7014 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7015 return autoremove_wake_function(curr, mode, wake_flags, key);
7019 static int io_run_task_work_sig(void)
7021 if (io_run_task_work())
7023 if (!signal_pending(current))
7025 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7026 return -ERESTARTSYS;
7030 /* when returns >0, the caller should retry */
7031 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7032 struct io_wait_queue *iowq,
7033 signed long *timeout)
7037 /* make sure we run task_work before checking for signals */
7038 ret = io_run_task_work_sig();
7039 if (ret || io_should_wake(iowq))
7041 /* let the caller flush overflows, retry */
7042 if (test_bit(0, &ctx->check_cq_overflow))
7045 *timeout = schedule_timeout(*timeout);
7046 return !*timeout ? -ETIME : 1;
7050 * Wait until events become available, if we don't already have some. The
7051 * application must reap them itself, as they reside on the shared cq ring.
7053 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7054 const sigset_t __user *sig, size_t sigsz,
7055 struct __kernel_timespec __user *uts)
7057 struct io_wait_queue iowq = {
7060 .func = io_wake_function,
7061 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7065 struct io_rings *rings = ctx->rings;
7066 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7070 io_cqring_overflow_flush(ctx, false);
7071 if (io_cqring_events(ctx) >= min_events)
7073 if (!io_run_task_work())
7078 #ifdef CONFIG_COMPAT
7079 if (in_compat_syscall())
7080 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7084 ret = set_user_sigmask(sig, sigsz);
7091 struct timespec64 ts;
7093 if (get_timespec64(&ts, uts))
7095 timeout = timespec64_to_jiffies(&ts);
7098 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7099 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7100 trace_io_uring_cqring_wait(ctx, min_events);
7102 /* if we can't even flush overflow, don't wait for more */
7103 if (!io_cqring_overflow_flush(ctx, false)) {
7107 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7108 TASK_INTERRUPTIBLE);
7109 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7110 finish_wait(&ctx->cq_wait, &iowq.wq);
7114 restore_saved_sigmask_unless(ret == -EINTR);
7116 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7119 static void io_free_page_table(void **table, size_t size)
7121 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7123 for (i = 0; i < nr_tables; i++)
7128 static void **io_alloc_page_table(size_t size)
7130 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7131 size_t init_size = size;
7134 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL);
7138 for (i = 0; i < nr_tables; i++) {
7139 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7141 table[i] = kzalloc(this_size, GFP_KERNEL);
7143 io_free_page_table(table, init_size);
7151 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7153 percpu_ref_exit(&ref_node->refs);
7157 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7158 struct io_rsrc_data *data_to_kill)
7160 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7161 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7164 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7166 rsrc_node->rsrc_data = data_to_kill;
7167 spin_lock_irq(&ctx->rsrc_ref_lock);
7168 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7169 spin_unlock_irq(&ctx->rsrc_ref_lock);
7171 atomic_inc(&data_to_kill->refs);
7172 percpu_ref_kill(&rsrc_node->refs);
7173 ctx->rsrc_node = NULL;
7176 if (!ctx->rsrc_node) {
7177 ctx->rsrc_node = ctx->rsrc_backup_node;
7178 ctx->rsrc_backup_node = NULL;
7182 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7184 if (ctx->rsrc_backup_node)
7186 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7187 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7190 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7194 /* As we may drop ->uring_lock, other task may have started quiesce */
7198 data->quiesce = true;
7200 ret = io_rsrc_node_switch_start(ctx);
7203 io_rsrc_node_switch(ctx, data);
7205 /* kill initial ref, already quiesced if zero */
7206 if (atomic_dec_and_test(&data->refs))
7208 mutex_unlock(&ctx->uring_lock);
7209 flush_delayed_work(&ctx->rsrc_put_work);
7210 ret = wait_for_completion_interruptible(&data->done);
7212 mutex_lock(&ctx->uring_lock);
7216 atomic_inc(&data->refs);
7217 /* wait for all works potentially completing data->done */
7218 flush_delayed_work(&ctx->rsrc_put_work);
7219 reinit_completion(&data->done);
7221 ret = io_run_task_work_sig();
7222 mutex_lock(&ctx->uring_lock);
7224 data->quiesce = false;
7229 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7231 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7232 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7234 return &data->tags[table_idx][off];
7237 static void io_rsrc_data_free(struct io_rsrc_data *data)
7239 size_t size = data->nr * sizeof(data->tags[0][0]);
7242 io_free_page_table((void **)data->tags, size);
7246 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7247 u64 __user *utags, unsigned nr,
7248 struct io_rsrc_data **pdata)
7250 struct io_rsrc_data *data;
7254 data = kzalloc(sizeof(*data), GFP_KERNEL);
7257 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7265 data->do_put = do_put;
7268 for (i = 0; i < nr; i++) {
7269 u64 *tag_slot = io_get_tag_slot(data, i);
7271 if (copy_from_user(tag_slot, &utags[i],
7277 atomic_set(&data->refs, 1);
7278 init_completion(&data->done);
7282 io_rsrc_data_free(data);
7286 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7288 table->files = kvcalloc(nr_files, sizeof(table->files[0]), GFP_KERNEL);
7289 return !!table->files;
7292 static void io_free_file_tables(struct io_file_table *table)
7294 kvfree(table->files);
7295 table->files = NULL;
7298 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7300 #if defined(CONFIG_UNIX)
7301 if (ctx->ring_sock) {
7302 struct sock *sock = ctx->ring_sock->sk;
7303 struct sk_buff *skb;
7305 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7311 for (i = 0; i < ctx->nr_user_files; i++) {
7314 file = io_file_from_index(ctx, i);
7319 io_free_file_tables(&ctx->file_table);
7320 io_rsrc_data_free(ctx->file_data);
7321 ctx->file_data = NULL;
7322 ctx->nr_user_files = 0;
7325 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7329 if (!ctx->file_data)
7331 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7333 __io_sqe_files_unregister(ctx);
7337 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7338 __releases(&sqd->lock)
7340 WARN_ON_ONCE(sqd->thread == current);
7343 * Do the dance but not conditional clear_bit() because it'd race with
7344 * other threads incrementing park_pending and setting the bit.
7346 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7347 if (atomic_dec_return(&sqd->park_pending))
7348 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7349 mutex_unlock(&sqd->lock);
7352 static void io_sq_thread_park(struct io_sq_data *sqd)
7353 __acquires(&sqd->lock)
7355 WARN_ON_ONCE(sqd->thread == current);
7357 atomic_inc(&sqd->park_pending);
7358 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7359 mutex_lock(&sqd->lock);
7361 wake_up_process(sqd->thread);
7364 static void io_sq_thread_stop(struct io_sq_data *sqd)
7366 WARN_ON_ONCE(sqd->thread == current);
7367 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7369 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7370 mutex_lock(&sqd->lock);
7372 wake_up_process(sqd->thread);
7373 mutex_unlock(&sqd->lock);
7374 wait_for_completion(&sqd->exited);
7377 static void io_put_sq_data(struct io_sq_data *sqd)
7379 if (refcount_dec_and_test(&sqd->refs)) {
7380 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7382 io_sq_thread_stop(sqd);
7387 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7389 struct io_sq_data *sqd = ctx->sq_data;
7392 io_sq_thread_park(sqd);
7393 list_del_init(&ctx->sqd_list);
7394 io_sqd_update_thread_idle(sqd);
7395 io_sq_thread_unpark(sqd);
7397 io_put_sq_data(sqd);
7398 ctx->sq_data = NULL;
7402 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7404 struct io_ring_ctx *ctx_attach;
7405 struct io_sq_data *sqd;
7408 f = fdget(p->wq_fd);
7410 return ERR_PTR(-ENXIO);
7411 if (f.file->f_op != &io_uring_fops) {
7413 return ERR_PTR(-EINVAL);
7416 ctx_attach = f.file->private_data;
7417 sqd = ctx_attach->sq_data;
7420 return ERR_PTR(-EINVAL);
7422 if (sqd->task_tgid != current->tgid) {
7424 return ERR_PTR(-EPERM);
7427 refcount_inc(&sqd->refs);
7432 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7435 struct io_sq_data *sqd;
7438 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7439 sqd = io_attach_sq_data(p);
7444 /* fall through for EPERM case, setup new sqd/task */
7445 if (PTR_ERR(sqd) != -EPERM)
7449 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7451 return ERR_PTR(-ENOMEM);
7453 atomic_set(&sqd->park_pending, 0);
7454 refcount_set(&sqd->refs, 1);
7455 INIT_LIST_HEAD(&sqd->ctx_list);
7456 mutex_init(&sqd->lock);
7457 init_waitqueue_head(&sqd->wait);
7458 init_completion(&sqd->exited);
7462 #if defined(CONFIG_UNIX)
7464 * Ensure the UNIX gc is aware of our file set, so we are certain that
7465 * the io_uring can be safely unregistered on process exit, even if we have
7466 * loops in the file referencing.
7468 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7470 struct sock *sk = ctx->ring_sock->sk;
7471 struct scm_fp_list *fpl;
7472 struct sk_buff *skb;
7475 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7479 skb = alloc_skb(0, GFP_KERNEL);
7488 fpl->user = get_uid(current_user());
7489 for (i = 0; i < nr; i++) {
7490 struct file *file = io_file_from_index(ctx, i + offset);
7494 fpl->fp[nr_files] = get_file(file);
7495 unix_inflight(fpl->user, fpl->fp[nr_files]);
7500 fpl->max = SCM_MAX_FD;
7501 fpl->count = nr_files;
7502 UNIXCB(skb).fp = fpl;
7503 skb->destructor = unix_destruct_scm;
7504 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7505 skb_queue_head(&sk->sk_receive_queue, skb);
7507 for (i = 0; i < nr_files; i++)
7518 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7519 * causes regular reference counting to break down. We rely on the UNIX
7520 * garbage collection to take care of this problem for us.
7522 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7524 unsigned left, total;
7528 left = ctx->nr_user_files;
7530 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7532 ret = __io_sqe_files_scm(ctx, this_files, total);
7536 total += this_files;
7542 while (total < ctx->nr_user_files) {
7543 struct file *file = io_file_from_index(ctx, total);
7553 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7559 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7561 struct file *file = prsrc->file;
7562 #if defined(CONFIG_UNIX)
7563 struct sock *sock = ctx->ring_sock->sk;
7564 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7565 struct sk_buff *skb;
7568 __skb_queue_head_init(&list);
7571 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7572 * remove this entry and rearrange the file array.
7574 skb = skb_dequeue(head);
7576 struct scm_fp_list *fp;
7578 fp = UNIXCB(skb).fp;
7579 for (i = 0; i < fp->count; i++) {
7582 if (fp->fp[i] != file)
7585 unix_notinflight(fp->user, fp->fp[i]);
7586 left = fp->count - 1 - i;
7588 memmove(&fp->fp[i], &fp->fp[i + 1],
7589 left * sizeof(struct file *));
7596 __skb_queue_tail(&list, skb);
7606 __skb_queue_tail(&list, skb);
7608 skb = skb_dequeue(head);
7611 if (skb_peek(&list)) {
7612 spin_lock_irq(&head->lock);
7613 while ((skb = __skb_dequeue(&list)) != NULL)
7614 __skb_queue_tail(head, skb);
7615 spin_unlock_irq(&head->lock);
7622 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7624 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7625 struct io_ring_ctx *ctx = rsrc_data->ctx;
7626 struct io_rsrc_put *prsrc, *tmp;
7628 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7629 list_del(&prsrc->list);
7632 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7634 io_ring_submit_lock(ctx, lock_ring);
7635 spin_lock_irq(&ctx->completion_lock);
7636 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7638 io_commit_cqring(ctx);
7639 spin_unlock_irq(&ctx->completion_lock);
7640 io_cqring_ev_posted(ctx);
7641 io_ring_submit_unlock(ctx, lock_ring);
7644 rsrc_data->do_put(ctx, prsrc);
7648 io_rsrc_node_destroy(ref_node);
7649 if (atomic_dec_and_test(&rsrc_data->refs))
7650 complete(&rsrc_data->done);
7653 static void io_rsrc_put_work(struct work_struct *work)
7655 struct io_ring_ctx *ctx;
7656 struct llist_node *node;
7658 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7659 node = llist_del_all(&ctx->rsrc_put_llist);
7662 struct io_rsrc_node *ref_node;
7663 struct llist_node *next = node->next;
7665 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7666 __io_rsrc_put_work(ref_node);
7671 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7673 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7674 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7675 unsigned long flags;
7676 bool first_add = false;
7678 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7681 while (!list_empty(&ctx->rsrc_ref_list)) {
7682 node = list_first_entry(&ctx->rsrc_ref_list,
7683 struct io_rsrc_node, node);
7684 /* recycle ref nodes in order */
7687 list_del(&node->node);
7688 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7690 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7693 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7696 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7698 struct io_rsrc_node *ref_node;
7700 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7704 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7709 INIT_LIST_HEAD(&ref_node->node);
7710 INIT_LIST_HEAD(&ref_node->rsrc_list);
7711 ref_node->done = false;
7715 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7716 unsigned nr_args, u64 __user *tags)
7718 __s32 __user *fds = (__s32 __user *) arg;
7727 if (nr_args > IORING_MAX_FIXED_FILES)
7729 ret = io_rsrc_node_switch_start(ctx);
7732 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7738 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7741 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7742 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7746 /* allow sparse sets */
7749 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7756 if (unlikely(!file))
7760 * Don't allow io_uring instances to be registered. If UNIX
7761 * isn't enabled, then this causes a reference cycle and this
7762 * instance can never get freed. If UNIX is enabled we'll
7763 * handle it just fine, but there's still no point in allowing
7764 * a ring fd as it doesn't support regular read/write anyway.
7766 if (file->f_op == &io_uring_fops) {
7770 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7773 ret = io_sqe_files_scm(ctx);
7775 __io_sqe_files_unregister(ctx);
7779 io_rsrc_node_switch(ctx, NULL);
7782 for (i = 0; i < ctx->nr_user_files; i++) {
7783 file = io_file_from_index(ctx, i);
7787 io_free_file_tables(&ctx->file_table);
7788 ctx->nr_user_files = 0;
7790 io_rsrc_data_free(ctx->file_data);
7791 ctx->file_data = NULL;
7795 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7798 #if defined(CONFIG_UNIX)
7799 struct sock *sock = ctx->ring_sock->sk;
7800 struct sk_buff_head *head = &sock->sk_receive_queue;
7801 struct sk_buff *skb;
7804 * See if we can merge this file into an existing skb SCM_RIGHTS
7805 * file set. If there's no room, fall back to allocating a new skb
7806 * and filling it in.
7808 spin_lock_irq(&head->lock);
7809 skb = skb_peek(head);
7811 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7813 if (fpl->count < SCM_MAX_FD) {
7814 __skb_unlink(skb, head);
7815 spin_unlock_irq(&head->lock);
7816 fpl->fp[fpl->count] = get_file(file);
7817 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7819 spin_lock_irq(&head->lock);
7820 __skb_queue_head(head, skb);
7825 spin_unlock_irq(&head->lock);
7832 return __io_sqe_files_scm(ctx, 1, index);
7838 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7839 struct io_rsrc_node *node, void *rsrc)
7841 struct io_rsrc_put *prsrc;
7843 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7847 prsrc->tag = *io_get_tag_slot(data, idx);
7849 list_add(&prsrc->list, &node->rsrc_list);
7853 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7854 struct io_uring_rsrc_update2 *up,
7857 u64 __user *tags = u64_to_user_ptr(up->tags);
7858 __s32 __user *fds = u64_to_user_ptr(up->data);
7859 struct io_rsrc_data *data = ctx->file_data;
7860 struct io_fixed_file *file_slot;
7864 bool needs_switch = false;
7866 if (!ctx->file_data)
7868 if (up->offset + nr_args > ctx->nr_user_files)
7871 for (done = 0; done < nr_args; done++) {
7874 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7875 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7879 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7883 if (fd == IORING_REGISTER_FILES_SKIP)
7886 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7887 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7889 if (file_slot->file_ptr) {
7890 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7891 err = io_queue_rsrc_removal(data, up->offset + done,
7892 ctx->rsrc_node, file);
7895 file_slot->file_ptr = 0;
7896 needs_switch = true;
7905 * Don't allow io_uring instances to be registered. If
7906 * UNIX isn't enabled, then this causes a reference
7907 * cycle and this instance can never get freed. If UNIX
7908 * is enabled we'll handle it just fine, but there's
7909 * still no point in allowing a ring fd as it doesn't
7910 * support regular read/write anyway.
7912 if (file->f_op == &io_uring_fops) {
7917 *io_get_tag_slot(data, up->offset + done) = tag;
7918 io_fixed_file_set(file_slot, file);
7919 err = io_sqe_file_register(ctx, file, i);
7921 file_slot->file_ptr = 0;
7929 io_rsrc_node_switch(ctx, data);
7930 return done ? done : err;
7933 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7935 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7937 req = io_put_req_find_next(req);
7938 return req ? &req->work : NULL;
7941 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7942 struct task_struct *task)
7944 struct io_wq_hash *hash;
7945 struct io_wq_data data;
7946 unsigned int concurrency;
7948 mutex_lock(&ctx->uring_lock);
7949 hash = ctx->hash_map;
7951 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7953 mutex_unlock(&ctx->uring_lock);
7954 return ERR_PTR(-ENOMEM);
7956 refcount_set(&hash->refs, 1);
7957 init_waitqueue_head(&hash->wait);
7958 ctx->hash_map = hash;
7960 mutex_unlock(&ctx->uring_lock);
7964 data.free_work = io_free_work;
7965 data.do_work = io_wq_submit_work;
7967 /* Do QD, or 4 * CPUS, whatever is smallest */
7968 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7970 return io_wq_create(concurrency, &data);
7973 static int io_uring_alloc_task_context(struct task_struct *task,
7974 struct io_ring_ctx *ctx)
7976 struct io_uring_task *tctx;
7979 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
7980 if (unlikely(!tctx))
7983 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7984 if (unlikely(ret)) {
7989 tctx->io_wq = io_init_wq_offload(ctx, task);
7990 if (IS_ERR(tctx->io_wq)) {
7991 ret = PTR_ERR(tctx->io_wq);
7992 percpu_counter_destroy(&tctx->inflight);
7998 init_waitqueue_head(&tctx->wait);
7999 atomic_set(&tctx->in_idle, 0);
8000 atomic_set(&tctx->inflight_tracked, 0);
8001 task->io_uring = tctx;
8002 spin_lock_init(&tctx->task_lock);
8003 INIT_WQ_LIST(&tctx->task_list);
8004 init_task_work(&tctx->task_work, tctx_task_work);
8008 void __io_uring_free(struct task_struct *tsk)
8010 struct io_uring_task *tctx = tsk->io_uring;
8012 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8013 WARN_ON_ONCE(tctx->io_wq);
8014 WARN_ON_ONCE(tctx->cached_refs);
8016 percpu_counter_destroy(&tctx->inflight);
8018 tsk->io_uring = NULL;
8021 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8022 struct io_uring_params *p)
8026 /* Retain compatibility with failing for an invalid attach attempt */
8027 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8028 IORING_SETUP_ATTACH_WQ) {
8031 f = fdget(p->wq_fd);
8034 if (f.file->f_op != &io_uring_fops) {
8040 if (ctx->flags & IORING_SETUP_SQPOLL) {
8041 struct task_struct *tsk;
8042 struct io_sq_data *sqd;
8045 sqd = io_get_sq_data(p, &attached);
8051 ctx->sq_creds = get_current_cred();
8053 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8054 if (!ctx->sq_thread_idle)
8055 ctx->sq_thread_idle = HZ;
8057 io_sq_thread_park(sqd);
8058 list_add(&ctx->sqd_list, &sqd->ctx_list);
8059 io_sqd_update_thread_idle(sqd);
8060 /* don't attach to a dying SQPOLL thread, would be racy */
8061 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8062 io_sq_thread_unpark(sqd);
8069 if (p->flags & IORING_SETUP_SQ_AFF) {
8070 int cpu = p->sq_thread_cpu;
8073 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8080 sqd->task_pid = current->pid;
8081 sqd->task_tgid = current->tgid;
8082 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8089 ret = io_uring_alloc_task_context(tsk, ctx);
8090 wake_up_new_task(tsk);
8093 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8094 /* Can't have SQ_AFF without SQPOLL */
8101 complete(&ctx->sq_data->exited);
8103 io_sq_thread_finish(ctx);
8107 static inline void __io_unaccount_mem(struct user_struct *user,
8108 unsigned long nr_pages)
8110 atomic_long_sub(nr_pages, &user->locked_vm);
8113 static inline int __io_account_mem(struct user_struct *user,
8114 unsigned long nr_pages)
8116 unsigned long page_limit, cur_pages, new_pages;
8118 /* Don't allow more pages than we can safely lock */
8119 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8122 cur_pages = atomic_long_read(&user->locked_vm);
8123 new_pages = cur_pages + nr_pages;
8124 if (new_pages > page_limit)
8126 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8127 new_pages) != cur_pages);
8132 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8135 __io_unaccount_mem(ctx->user, nr_pages);
8137 if (ctx->mm_account)
8138 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8141 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8146 ret = __io_account_mem(ctx->user, nr_pages);
8151 if (ctx->mm_account)
8152 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8157 static void io_mem_free(void *ptr)
8164 page = virt_to_head_page(ptr);
8165 if (put_page_testzero(page))
8166 free_compound_page(page);
8169 static void *io_mem_alloc(size_t size)
8171 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8172 __GFP_NORETRY | __GFP_ACCOUNT;
8174 return (void *) __get_free_pages(gfp_flags, get_order(size));
8177 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8180 struct io_rings *rings;
8181 size_t off, sq_array_size;
8183 off = struct_size(rings, cqes, cq_entries);
8184 if (off == SIZE_MAX)
8188 off = ALIGN(off, SMP_CACHE_BYTES);
8196 sq_array_size = array_size(sizeof(u32), sq_entries);
8197 if (sq_array_size == SIZE_MAX)
8200 if (check_add_overflow(off, sq_array_size, &off))
8206 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8208 struct io_mapped_ubuf *imu = *slot;
8211 if (imu != ctx->dummy_ubuf) {
8212 for (i = 0; i < imu->nr_bvecs; i++)
8213 unpin_user_page(imu->bvec[i].bv_page);
8214 if (imu->acct_pages)
8215 io_unaccount_mem(ctx, imu->acct_pages);
8221 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8223 io_buffer_unmap(ctx, &prsrc->buf);
8227 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8231 for (i = 0; i < ctx->nr_user_bufs; i++)
8232 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8233 kfree(ctx->user_bufs);
8234 io_rsrc_data_free(ctx->buf_data);
8235 ctx->user_bufs = NULL;
8236 ctx->buf_data = NULL;
8237 ctx->nr_user_bufs = 0;
8240 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8247 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8249 __io_sqe_buffers_unregister(ctx);
8253 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8254 void __user *arg, unsigned index)
8256 struct iovec __user *src;
8258 #ifdef CONFIG_COMPAT
8260 struct compat_iovec __user *ciovs;
8261 struct compat_iovec ciov;
8263 ciovs = (struct compat_iovec __user *) arg;
8264 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8267 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8268 dst->iov_len = ciov.iov_len;
8272 src = (struct iovec __user *) arg;
8273 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8279 * Not super efficient, but this is just a registration time. And we do cache
8280 * the last compound head, so generally we'll only do a full search if we don't
8283 * We check if the given compound head page has already been accounted, to
8284 * avoid double accounting it. This allows us to account the full size of the
8285 * page, not just the constituent pages of a huge page.
8287 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8288 int nr_pages, struct page *hpage)
8292 /* check current page array */
8293 for (i = 0; i < nr_pages; i++) {
8294 if (!PageCompound(pages[i]))
8296 if (compound_head(pages[i]) == hpage)
8300 /* check previously registered pages */
8301 for (i = 0; i < ctx->nr_user_bufs; i++) {
8302 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8304 for (j = 0; j < imu->nr_bvecs; j++) {
8305 if (!PageCompound(imu->bvec[j].bv_page))
8307 if (compound_head(imu->bvec[j].bv_page) == hpage)
8315 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8316 int nr_pages, struct io_mapped_ubuf *imu,
8317 struct page **last_hpage)
8321 imu->acct_pages = 0;
8322 for (i = 0; i < nr_pages; i++) {
8323 if (!PageCompound(pages[i])) {
8328 hpage = compound_head(pages[i]);
8329 if (hpage == *last_hpage)
8331 *last_hpage = hpage;
8332 if (headpage_already_acct(ctx, pages, i, hpage))
8334 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8338 if (!imu->acct_pages)
8341 ret = io_account_mem(ctx, imu->acct_pages);
8343 imu->acct_pages = 0;
8347 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8348 struct io_mapped_ubuf **pimu,
8349 struct page **last_hpage)
8351 struct io_mapped_ubuf *imu = NULL;
8352 struct vm_area_struct **vmas = NULL;
8353 struct page **pages = NULL;
8354 unsigned long off, start, end, ubuf;
8356 int ret, pret, nr_pages, i;
8358 if (!iov->iov_base) {
8359 *pimu = ctx->dummy_ubuf;
8363 ubuf = (unsigned long) iov->iov_base;
8364 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8365 start = ubuf >> PAGE_SHIFT;
8366 nr_pages = end - start;
8371 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8375 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8380 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8385 mmap_read_lock(current->mm);
8386 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8388 if (pret == nr_pages) {
8389 /* don't support file backed memory */
8390 for (i = 0; i < nr_pages; i++) {
8391 struct vm_area_struct *vma = vmas[i];
8393 if (vma_is_shmem(vma))
8396 !is_file_hugepages(vma->vm_file)) {
8402 ret = pret < 0 ? pret : -EFAULT;
8404 mmap_read_unlock(current->mm);
8407 * if we did partial map, or found file backed vmas,
8408 * release any pages we did get
8411 unpin_user_pages(pages, pret);
8415 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8417 unpin_user_pages(pages, pret);
8421 off = ubuf & ~PAGE_MASK;
8422 size = iov->iov_len;
8423 for (i = 0; i < nr_pages; i++) {
8426 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8427 imu->bvec[i].bv_page = pages[i];
8428 imu->bvec[i].bv_len = vec_len;
8429 imu->bvec[i].bv_offset = off;
8433 /* store original address for later verification */
8435 imu->ubuf_end = ubuf + iov->iov_len;
8436 imu->nr_bvecs = nr_pages;
8447 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8449 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8450 return ctx->user_bufs ? 0 : -ENOMEM;
8453 static int io_buffer_validate(struct iovec *iov)
8455 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8458 * Don't impose further limits on the size and buffer
8459 * constraints here, we'll -EINVAL later when IO is
8460 * submitted if they are wrong.
8463 return iov->iov_len ? -EFAULT : 0;
8467 /* arbitrary limit, but we need something */
8468 if (iov->iov_len > SZ_1G)
8471 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8477 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8478 unsigned int nr_args, u64 __user *tags)
8480 struct page *last_hpage = NULL;
8481 struct io_rsrc_data *data;
8487 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8489 ret = io_rsrc_node_switch_start(ctx);
8492 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8495 ret = io_buffers_map_alloc(ctx, nr_args);
8497 io_rsrc_data_free(data);
8501 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8502 ret = io_copy_iov(ctx, &iov, arg, i);
8505 ret = io_buffer_validate(&iov);
8508 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8513 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8519 WARN_ON_ONCE(ctx->buf_data);
8521 ctx->buf_data = data;
8523 __io_sqe_buffers_unregister(ctx);
8525 io_rsrc_node_switch(ctx, NULL);
8529 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8530 struct io_uring_rsrc_update2 *up,
8531 unsigned int nr_args)
8533 u64 __user *tags = u64_to_user_ptr(up->tags);
8534 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8535 struct page *last_hpage = NULL;
8536 bool needs_switch = false;
8542 if (up->offset + nr_args > ctx->nr_user_bufs)
8545 for (done = 0; done < nr_args; done++) {
8546 struct io_mapped_ubuf *imu;
8547 int offset = up->offset + done;
8550 err = io_copy_iov(ctx, &iov, iovs, done);
8553 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8557 err = io_buffer_validate(&iov);
8560 if (!iov.iov_base && tag) {
8564 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8568 i = array_index_nospec(offset, ctx->nr_user_bufs);
8569 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8570 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8571 ctx->rsrc_node, ctx->user_bufs[i]);
8572 if (unlikely(err)) {
8573 io_buffer_unmap(ctx, &imu);
8576 ctx->user_bufs[i] = NULL;
8577 needs_switch = true;
8580 ctx->user_bufs[i] = imu;
8581 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8585 io_rsrc_node_switch(ctx, ctx->buf_data);
8586 return done ? done : err;
8589 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8591 __s32 __user *fds = arg;
8597 if (copy_from_user(&fd, fds, sizeof(*fds)))
8600 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8601 if (IS_ERR(ctx->cq_ev_fd)) {
8602 int ret = PTR_ERR(ctx->cq_ev_fd);
8604 ctx->cq_ev_fd = NULL;
8611 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8613 if (ctx->cq_ev_fd) {
8614 eventfd_ctx_put(ctx->cq_ev_fd);
8615 ctx->cq_ev_fd = NULL;
8622 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8624 struct io_buffer *buf;
8625 unsigned long index;
8627 xa_for_each(&ctx->io_buffers, index, buf)
8628 __io_remove_buffers(ctx, buf, index, -1U);
8631 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8633 struct io_kiocb *req, *nxt;
8635 list_for_each_entry_safe(req, nxt, list, compl.list) {
8636 if (tsk && req->task != tsk)
8638 list_del(&req->compl.list);
8639 kmem_cache_free(req_cachep, req);
8643 static void io_req_caches_free(struct io_ring_ctx *ctx)
8645 struct io_submit_state *submit_state = &ctx->submit_state;
8646 struct io_comp_state *cs = &ctx->submit_state.comp;
8648 mutex_lock(&ctx->uring_lock);
8650 if (submit_state->free_reqs) {
8651 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8652 submit_state->reqs);
8653 submit_state->free_reqs = 0;
8656 io_flush_cached_locked_reqs(ctx, cs);
8657 io_req_cache_free(&cs->free_list, NULL);
8658 mutex_unlock(&ctx->uring_lock);
8661 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8663 if (data && !atomic_dec_and_test(&data->refs))
8664 wait_for_completion(&data->done);
8667 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8669 io_sq_thread_finish(ctx);
8671 if (ctx->mm_account) {
8672 mmdrop(ctx->mm_account);
8673 ctx->mm_account = NULL;
8676 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8677 io_wait_rsrc_data(ctx->buf_data);
8678 io_wait_rsrc_data(ctx->file_data);
8680 mutex_lock(&ctx->uring_lock);
8682 __io_sqe_buffers_unregister(ctx);
8684 __io_sqe_files_unregister(ctx);
8686 __io_cqring_overflow_flush(ctx, true);
8687 mutex_unlock(&ctx->uring_lock);
8688 io_eventfd_unregister(ctx);
8689 io_destroy_buffers(ctx);
8691 put_cred(ctx->sq_creds);
8693 /* there are no registered resources left, nobody uses it */
8695 io_rsrc_node_destroy(ctx->rsrc_node);
8696 if (ctx->rsrc_backup_node)
8697 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8698 flush_delayed_work(&ctx->rsrc_put_work);
8700 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8701 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8703 #if defined(CONFIG_UNIX)
8704 if (ctx->ring_sock) {
8705 ctx->ring_sock->file = NULL; /* so that iput() is called */
8706 sock_release(ctx->ring_sock);
8710 io_mem_free(ctx->rings);
8711 io_mem_free(ctx->sq_sqes);
8713 percpu_ref_exit(&ctx->refs);
8714 free_uid(ctx->user);
8715 io_req_caches_free(ctx);
8717 io_wq_put_hash(ctx->hash_map);
8718 kfree(ctx->cancel_hash);
8719 kfree(ctx->dummy_ubuf);
8723 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8725 struct io_ring_ctx *ctx = file->private_data;
8728 poll_wait(file, &ctx->poll_wait, wait);
8730 * synchronizes with barrier from wq_has_sleeper call in
8734 if (!io_sqring_full(ctx))
8735 mask |= EPOLLOUT | EPOLLWRNORM;
8738 * Don't flush cqring overflow list here, just do a simple check.
8739 * Otherwise there could possible be ABBA deadlock:
8742 * lock(&ctx->uring_lock);
8744 * lock(&ctx->uring_lock);
8747 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8748 * pushs them to do the flush.
8750 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8751 mask |= EPOLLIN | EPOLLRDNORM;
8756 static int io_uring_fasync(int fd, struct file *file, int on)
8758 struct io_ring_ctx *ctx = file->private_data;
8760 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8763 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8765 const struct cred *creds;
8767 creds = xa_erase(&ctx->personalities, id);
8776 struct io_tctx_exit {
8777 struct callback_head task_work;
8778 struct completion completion;
8779 struct io_ring_ctx *ctx;
8782 static void io_tctx_exit_cb(struct callback_head *cb)
8784 struct io_uring_task *tctx = current->io_uring;
8785 struct io_tctx_exit *work;
8787 work = container_of(cb, struct io_tctx_exit, task_work);
8789 * When @in_idle, we're in cancellation and it's racy to remove the
8790 * node. It'll be removed by the end of cancellation, just ignore it.
8792 if (!atomic_read(&tctx->in_idle))
8793 io_uring_del_tctx_node((unsigned long)work->ctx);
8794 complete(&work->completion);
8797 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8799 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8801 return req->ctx == data;
8804 static void io_ring_exit_work(struct work_struct *work)
8806 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8807 unsigned long timeout = jiffies + HZ * 60 * 5;
8808 struct io_tctx_exit exit;
8809 struct io_tctx_node *node;
8813 * If we're doing polled IO and end up having requests being
8814 * submitted async (out-of-line), then completions can come in while
8815 * we're waiting for refs to drop. We need to reap these manually,
8816 * as nobody else will be looking for them.
8819 io_uring_try_cancel_requests(ctx, NULL, true);
8821 struct io_sq_data *sqd = ctx->sq_data;
8822 struct task_struct *tsk;
8824 io_sq_thread_park(sqd);
8826 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8827 io_wq_cancel_cb(tsk->io_uring->io_wq,
8828 io_cancel_ctx_cb, ctx, true);
8829 io_sq_thread_unpark(sqd);
8832 WARN_ON_ONCE(time_after(jiffies, timeout));
8833 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8835 init_completion(&exit.completion);
8836 init_task_work(&exit.task_work, io_tctx_exit_cb);
8839 * Some may use context even when all refs and requests have been put,
8840 * and they are free to do so while still holding uring_lock or
8841 * completion_lock, see io_req_task_submit(). Apart from other work,
8842 * this lock/unlock section also waits them to finish.
8844 mutex_lock(&ctx->uring_lock);
8845 while (!list_empty(&ctx->tctx_list)) {
8846 WARN_ON_ONCE(time_after(jiffies, timeout));
8848 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8850 /* don't spin on a single task if cancellation failed */
8851 list_rotate_left(&ctx->tctx_list);
8852 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8853 if (WARN_ON_ONCE(ret))
8855 wake_up_process(node->task);
8857 mutex_unlock(&ctx->uring_lock);
8858 wait_for_completion(&exit.completion);
8859 mutex_lock(&ctx->uring_lock);
8861 mutex_unlock(&ctx->uring_lock);
8862 spin_lock_irq(&ctx->completion_lock);
8863 spin_unlock_irq(&ctx->completion_lock);
8865 io_ring_ctx_free(ctx);
8868 /* Returns true if we found and killed one or more timeouts */
8869 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8872 struct io_kiocb *req, *tmp;
8875 spin_lock_irq(&ctx->completion_lock);
8876 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8877 if (io_match_task(req, tsk, cancel_all)) {
8878 io_kill_timeout(req, -ECANCELED);
8883 io_commit_cqring(ctx);
8884 spin_unlock_irq(&ctx->completion_lock);
8886 io_cqring_ev_posted(ctx);
8887 return canceled != 0;
8890 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8892 unsigned long index;
8893 struct creds *creds;
8895 mutex_lock(&ctx->uring_lock);
8896 percpu_ref_kill(&ctx->refs);
8898 __io_cqring_overflow_flush(ctx, true);
8899 xa_for_each(&ctx->personalities, index, creds)
8900 io_unregister_personality(ctx, index);
8901 mutex_unlock(&ctx->uring_lock);
8903 io_kill_timeouts(ctx, NULL, true);
8904 io_poll_remove_all(ctx, NULL, true);
8906 /* if we failed setting up the ctx, we might not have any rings */
8907 io_iopoll_try_reap_events(ctx);
8909 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8911 * Use system_unbound_wq to avoid spawning tons of event kworkers
8912 * if we're exiting a ton of rings at the same time. It just adds
8913 * noise and overhead, there's no discernable change in runtime
8914 * over using system_wq.
8916 queue_work(system_unbound_wq, &ctx->exit_work);
8919 static int io_uring_release(struct inode *inode, struct file *file)
8921 struct io_ring_ctx *ctx = file->private_data;
8923 file->private_data = NULL;
8924 io_ring_ctx_wait_and_kill(ctx);
8928 struct io_task_cancel {
8929 struct task_struct *task;
8933 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8935 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8936 struct io_task_cancel *cancel = data;
8939 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
8940 unsigned long flags;
8941 struct io_ring_ctx *ctx = req->ctx;
8943 /* protect against races with linked timeouts */
8944 spin_lock_irqsave(&ctx->completion_lock, flags);
8945 ret = io_match_task(req, cancel->task, cancel->all);
8946 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8948 ret = io_match_task(req, cancel->task, cancel->all);
8953 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8954 struct task_struct *task, bool cancel_all)
8956 struct io_defer_entry *de;
8959 spin_lock_irq(&ctx->completion_lock);
8960 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8961 if (io_match_task(de->req, task, cancel_all)) {
8962 list_cut_position(&list, &ctx->defer_list, &de->list);
8966 spin_unlock_irq(&ctx->completion_lock);
8967 if (list_empty(&list))
8970 while (!list_empty(&list)) {
8971 de = list_first_entry(&list, struct io_defer_entry, list);
8972 list_del_init(&de->list);
8973 io_req_complete_failed(de->req, -ECANCELED);
8979 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8981 struct io_tctx_node *node;
8982 enum io_wq_cancel cret;
8985 mutex_lock(&ctx->uring_lock);
8986 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8987 struct io_uring_task *tctx = node->task->io_uring;
8990 * io_wq will stay alive while we hold uring_lock, because it's
8991 * killed after ctx nodes, which requires to take the lock.
8993 if (!tctx || !tctx->io_wq)
8995 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8996 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8998 mutex_unlock(&ctx->uring_lock);
9003 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9004 struct task_struct *task,
9007 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9008 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9011 enum io_wq_cancel cret;
9015 ret |= io_uring_try_cancel_iowq(ctx);
9016 } else if (tctx && tctx->io_wq) {
9018 * Cancels requests of all rings, not only @ctx, but
9019 * it's fine as the task is in exit/exec.
9021 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9023 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9026 /* SQPOLL thread does its own polling */
9027 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9028 (ctx->sq_data && ctx->sq_data->thread == current)) {
9029 while (!list_empty_careful(&ctx->iopoll_list)) {
9030 io_iopoll_try_reap_events(ctx);
9035 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9036 ret |= io_poll_remove_all(ctx, task, cancel_all);
9037 ret |= io_kill_timeouts(ctx, task, cancel_all);
9039 ret |= io_run_task_work();
9046 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9048 struct io_uring_task *tctx = current->io_uring;
9049 struct io_tctx_node *node;
9052 if (unlikely(!tctx)) {
9053 ret = io_uring_alloc_task_context(current, ctx);
9056 tctx = current->io_uring;
9058 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9059 node = kmalloc(sizeof(*node), GFP_KERNEL);
9063 node->task = current;
9065 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9072 mutex_lock(&ctx->uring_lock);
9073 list_add(&node->ctx_node, &ctx->tctx_list);
9074 mutex_unlock(&ctx->uring_lock);
9081 * Note that this task has used io_uring. We use it for cancelation purposes.
9083 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9085 struct io_uring_task *tctx = current->io_uring;
9087 if (likely(tctx && tctx->last == ctx))
9089 return __io_uring_add_tctx_node(ctx);
9093 * Remove this io_uring_file -> task mapping.
9095 static void io_uring_del_tctx_node(unsigned long index)
9097 struct io_uring_task *tctx = current->io_uring;
9098 struct io_tctx_node *node;
9102 node = xa_erase(&tctx->xa, index);
9106 WARN_ON_ONCE(current != node->task);
9107 WARN_ON_ONCE(list_empty(&node->ctx_node));
9109 mutex_lock(&node->ctx->uring_lock);
9110 list_del(&node->ctx_node);
9111 mutex_unlock(&node->ctx->uring_lock);
9113 if (tctx->last == node->ctx)
9118 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9120 struct io_wq *wq = tctx->io_wq;
9121 struct io_tctx_node *node;
9122 unsigned long index;
9124 xa_for_each(&tctx->xa, index, node)
9125 io_uring_del_tctx_node(index);
9128 * Must be after io_uring_del_task_file() (removes nodes under
9129 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9132 io_wq_put_and_exit(wq);
9136 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9139 return atomic_read(&tctx->inflight_tracked);
9140 return percpu_counter_sum(&tctx->inflight);
9143 static void io_uring_drop_tctx_refs(struct task_struct *task)
9145 struct io_uring_task *tctx = task->io_uring;
9146 unsigned int refs = tctx->cached_refs;
9148 tctx->cached_refs = 0;
9149 percpu_counter_sub(&tctx->inflight, refs);
9150 put_task_struct_many(task, refs);
9154 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9155 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9157 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9159 struct io_uring_task *tctx = current->io_uring;
9160 struct io_ring_ctx *ctx;
9164 WARN_ON_ONCE(sqd && sqd->thread != current);
9166 if (!current->io_uring)
9169 io_wq_exit_start(tctx->io_wq);
9171 io_uring_drop_tctx_refs(current);
9172 atomic_inc(&tctx->in_idle);
9174 /* read completions before cancelations */
9175 inflight = tctx_inflight(tctx, !cancel_all);
9180 struct io_tctx_node *node;
9181 unsigned long index;
9183 xa_for_each(&tctx->xa, index, node) {
9184 /* sqpoll task will cancel all its requests */
9185 if (node->ctx->sq_data)
9187 io_uring_try_cancel_requests(node->ctx, current,
9191 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9192 io_uring_try_cancel_requests(ctx, current,
9196 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9198 * If we've seen completions, retry without waiting. This
9199 * avoids a race where a completion comes in before we did
9200 * prepare_to_wait().
9202 if (inflight == tctx_inflight(tctx, !cancel_all))
9204 finish_wait(&tctx->wait, &wait);
9206 atomic_dec(&tctx->in_idle);
9208 io_uring_clean_tctx(tctx);
9210 /* for exec all current's requests should be gone, kill tctx */
9211 __io_uring_free(current);
9215 void __io_uring_cancel(struct files_struct *files)
9217 io_uring_cancel_generic(!files, NULL);
9220 static void *io_uring_validate_mmap_request(struct file *file,
9221 loff_t pgoff, size_t sz)
9223 struct io_ring_ctx *ctx = file->private_data;
9224 loff_t offset = pgoff << PAGE_SHIFT;
9229 case IORING_OFF_SQ_RING:
9230 case IORING_OFF_CQ_RING:
9233 case IORING_OFF_SQES:
9237 return ERR_PTR(-EINVAL);
9240 page = virt_to_head_page(ptr);
9241 if (sz > page_size(page))
9242 return ERR_PTR(-EINVAL);
9249 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9251 size_t sz = vma->vm_end - vma->vm_start;
9255 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9257 return PTR_ERR(ptr);
9259 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9260 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9263 #else /* !CONFIG_MMU */
9265 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9267 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9270 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9272 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9275 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9276 unsigned long addr, unsigned long len,
9277 unsigned long pgoff, unsigned long flags)
9281 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9283 return PTR_ERR(ptr);
9285 return (unsigned long) ptr;
9288 #endif /* !CONFIG_MMU */
9290 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9295 if (!io_sqring_full(ctx))
9297 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9299 if (!io_sqring_full(ctx))
9302 } while (!signal_pending(current));
9304 finish_wait(&ctx->sqo_sq_wait, &wait);
9308 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9309 struct __kernel_timespec __user **ts,
9310 const sigset_t __user **sig)
9312 struct io_uring_getevents_arg arg;
9315 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9316 * is just a pointer to the sigset_t.
9318 if (!(flags & IORING_ENTER_EXT_ARG)) {
9319 *sig = (const sigset_t __user *) argp;
9325 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9326 * timespec and sigset_t pointers if good.
9328 if (*argsz != sizeof(arg))
9330 if (copy_from_user(&arg, argp, sizeof(arg)))
9332 *sig = u64_to_user_ptr(arg.sigmask);
9333 *argsz = arg.sigmask_sz;
9334 *ts = u64_to_user_ptr(arg.ts);
9338 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9339 u32, min_complete, u32, flags, const void __user *, argp,
9342 struct io_ring_ctx *ctx;
9349 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9350 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9354 if (unlikely(!f.file))
9358 if (unlikely(f.file->f_op != &io_uring_fops))
9362 ctx = f.file->private_data;
9363 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9367 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9371 * For SQ polling, the thread will do all submissions and completions.
9372 * Just return the requested submit count, and wake the thread if
9376 if (ctx->flags & IORING_SETUP_SQPOLL) {
9377 io_cqring_overflow_flush(ctx, false);
9379 if (unlikely(ctx->sq_data->thread == NULL)) {
9383 if (flags & IORING_ENTER_SQ_WAKEUP)
9384 wake_up(&ctx->sq_data->wait);
9385 if (flags & IORING_ENTER_SQ_WAIT) {
9386 ret = io_sqpoll_wait_sq(ctx);
9390 submitted = to_submit;
9391 } else if (to_submit) {
9392 ret = io_uring_add_tctx_node(ctx);
9395 mutex_lock(&ctx->uring_lock);
9396 submitted = io_submit_sqes(ctx, to_submit);
9397 mutex_unlock(&ctx->uring_lock);
9399 if (submitted != to_submit)
9402 if (flags & IORING_ENTER_GETEVENTS) {
9403 const sigset_t __user *sig;
9404 struct __kernel_timespec __user *ts;
9406 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9410 min_complete = min(min_complete, ctx->cq_entries);
9413 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9414 * space applications don't need to do io completion events
9415 * polling again, they can rely on io_sq_thread to do polling
9416 * work, which can reduce cpu usage and uring_lock contention.
9418 if (ctx->flags & IORING_SETUP_IOPOLL &&
9419 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9420 ret = io_iopoll_check(ctx, min_complete);
9422 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9427 percpu_ref_put(&ctx->refs);
9430 return submitted ? submitted : ret;
9433 #ifdef CONFIG_PROC_FS
9434 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9435 const struct cred *cred)
9437 struct user_namespace *uns = seq_user_ns(m);
9438 struct group_info *gi;
9443 seq_printf(m, "%5d\n", id);
9444 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9445 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9446 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9447 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9448 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9449 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9450 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9451 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9452 seq_puts(m, "\n\tGroups:\t");
9453 gi = cred->group_info;
9454 for (g = 0; g < gi->ngroups; g++) {
9455 seq_put_decimal_ull(m, g ? " " : "",
9456 from_kgid_munged(uns, gi->gid[g]));
9458 seq_puts(m, "\n\tCapEff:\t");
9459 cap = cred->cap_effective;
9460 CAP_FOR_EACH_U32(__capi)
9461 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9466 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9468 struct io_sq_data *sq = NULL;
9473 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9474 * since fdinfo case grabs it in the opposite direction of normal use
9475 * cases. If we fail to get the lock, we just don't iterate any
9476 * structures that could be going away outside the io_uring mutex.
9478 has_lock = mutex_trylock(&ctx->uring_lock);
9480 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9486 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9487 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9488 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9489 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9490 struct file *f = io_file_from_index(ctx, i);
9493 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9495 seq_printf(m, "%5u: <none>\n", i);
9497 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9498 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9499 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9500 unsigned int len = buf->ubuf_end - buf->ubuf;
9502 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9504 if (has_lock && !xa_empty(&ctx->personalities)) {
9505 unsigned long index;
9506 const struct cred *cred;
9508 seq_printf(m, "Personalities:\n");
9509 xa_for_each(&ctx->personalities, index, cred)
9510 io_uring_show_cred(m, index, cred);
9512 seq_printf(m, "PollList:\n");
9513 spin_lock_irq(&ctx->completion_lock);
9514 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9515 struct hlist_head *list = &ctx->cancel_hash[i];
9516 struct io_kiocb *req;
9518 hlist_for_each_entry(req, list, hash_node)
9519 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9520 req->task->task_works != NULL);
9522 spin_unlock_irq(&ctx->completion_lock);
9524 mutex_unlock(&ctx->uring_lock);
9527 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9529 struct io_ring_ctx *ctx = f->private_data;
9531 if (percpu_ref_tryget(&ctx->refs)) {
9532 __io_uring_show_fdinfo(ctx, m);
9533 percpu_ref_put(&ctx->refs);
9538 static const struct file_operations io_uring_fops = {
9539 .release = io_uring_release,
9540 .mmap = io_uring_mmap,
9542 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9543 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9545 .poll = io_uring_poll,
9546 .fasync = io_uring_fasync,
9547 #ifdef CONFIG_PROC_FS
9548 .show_fdinfo = io_uring_show_fdinfo,
9552 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9553 struct io_uring_params *p)
9555 struct io_rings *rings;
9556 size_t size, sq_array_offset;
9558 /* make sure these are sane, as we already accounted them */
9559 ctx->sq_entries = p->sq_entries;
9560 ctx->cq_entries = p->cq_entries;
9562 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9563 if (size == SIZE_MAX)
9566 rings = io_mem_alloc(size);
9571 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9572 rings->sq_ring_mask = p->sq_entries - 1;
9573 rings->cq_ring_mask = p->cq_entries - 1;
9574 rings->sq_ring_entries = p->sq_entries;
9575 rings->cq_ring_entries = p->cq_entries;
9577 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9578 if (size == SIZE_MAX) {
9579 io_mem_free(ctx->rings);
9584 ctx->sq_sqes = io_mem_alloc(size);
9585 if (!ctx->sq_sqes) {
9586 io_mem_free(ctx->rings);
9594 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9598 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9602 ret = io_uring_add_tctx_node(ctx);
9607 fd_install(fd, file);
9612 * Allocate an anonymous fd, this is what constitutes the application
9613 * visible backing of an io_uring instance. The application mmaps this
9614 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9615 * we have to tie this fd to a socket for file garbage collection purposes.
9617 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9620 #if defined(CONFIG_UNIX)
9623 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9626 return ERR_PTR(ret);
9629 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9630 O_RDWR | O_CLOEXEC);
9631 #if defined(CONFIG_UNIX)
9633 sock_release(ctx->ring_sock);
9634 ctx->ring_sock = NULL;
9636 ctx->ring_sock->file = file;
9642 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9643 struct io_uring_params __user *params)
9645 struct io_ring_ctx *ctx;
9651 if (entries > IORING_MAX_ENTRIES) {
9652 if (!(p->flags & IORING_SETUP_CLAMP))
9654 entries = IORING_MAX_ENTRIES;
9658 * Use twice as many entries for the CQ ring. It's possible for the
9659 * application to drive a higher depth than the size of the SQ ring,
9660 * since the sqes are only used at submission time. This allows for
9661 * some flexibility in overcommitting a bit. If the application has
9662 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9663 * of CQ ring entries manually.
9665 p->sq_entries = roundup_pow_of_two(entries);
9666 if (p->flags & IORING_SETUP_CQSIZE) {
9668 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9669 * to a power-of-two, if it isn't already. We do NOT impose
9670 * any cq vs sq ring sizing.
9674 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9675 if (!(p->flags & IORING_SETUP_CLAMP))
9677 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9679 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9680 if (p->cq_entries < p->sq_entries)
9683 p->cq_entries = 2 * p->sq_entries;
9686 ctx = io_ring_ctx_alloc(p);
9689 ctx->compat = in_compat_syscall();
9690 if (!capable(CAP_IPC_LOCK))
9691 ctx->user = get_uid(current_user());
9694 * This is just grabbed for accounting purposes. When a process exits,
9695 * the mm is exited and dropped before the files, hence we need to hang
9696 * on to this mm purely for the purposes of being able to unaccount
9697 * memory (locked/pinned vm). It's not used for anything else.
9699 mmgrab(current->mm);
9700 ctx->mm_account = current->mm;
9702 ret = io_allocate_scq_urings(ctx, p);
9706 ret = io_sq_offload_create(ctx, p);
9709 /* always set a rsrc node */
9710 ret = io_rsrc_node_switch_start(ctx);
9713 io_rsrc_node_switch(ctx, NULL);
9715 memset(&p->sq_off, 0, sizeof(p->sq_off));
9716 p->sq_off.head = offsetof(struct io_rings, sq.head);
9717 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9718 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9719 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9720 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9721 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9722 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9724 memset(&p->cq_off, 0, sizeof(p->cq_off));
9725 p->cq_off.head = offsetof(struct io_rings, cq.head);
9726 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9727 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9728 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9729 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9730 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9731 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9733 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9734 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9735 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9736 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9737 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9738 IORING_FEAT_RSRC_TAGS;
9740 if (copy_to_user(params, p, sizeof(*p))) {
9745 file = io_uring_get_file(ctx);
9747 ret = PTR_ERR(file);
9752 * Install ring fd as the very last thing, so we don't risk someone
9753 * having closed it before we finish setup
9755 ret = io_uring_install_fd(ctx, file);
9757 /* fput will clean it up */
9762 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9765 io_ring_ctx_wait_and_kill(ctx);
9770 * Sets up an aio uring context, and returns the fd. Applications asks for a
9771 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9772 * params structure passed in.
9774 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9776 struct io_uring_params p;
9779 if (copy_from_user(&p, params, sizeof(p)))
9781 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9786 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9787 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9788 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9789 IORING_SETUP_R_DISABLED))
9792 return io_uring_create(entries, &p, params);
9795 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9796 struct io_uring_params __user *, params)
9798 return io_uring_setup(entries, params);
9801 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9803 struct io_uring_probe *p;
9807 size = struct_size(p, ops, nr_args);
9808 if (size == SIZE_MAX)
9810 p = kzalloc(size, GFP_KERNEL);
9815 if (copy_from_user(p, arg, size))
9818 if (memchr_inv(p, 0, size))
9821 p->last_op = IORING_OP_LAST - 1;
9822 if (nr_args > IORING_OP_LAST)
9823 nr_args = IORING_OP_LAST;
9825 for (i = 0; i < nr_args; i++) {
9827 if (!io_op_defs[i].not_supported)
9828 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9833 if (copy_to_user(arg, p, size))
9840 static int io_register_personality(struct io_ring_ctx *ctx)
9842 const struct cred *creds;
9846 creds = get_current_cred();
9848 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9849 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9857 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9858 unsigned int nr_args)
9860 struct io_uring_restriction *res;
9864 /* Restrictions allowed only if rings started disabled */
9865 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9868 /* We allow only a single restrictions registration */
9869 if (ctx->restrictions.registered)
9872 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9875 size = array_size(nr_args, sizeof(*res));
9876 if (size == SIZE_MAX)
9879 res = memdup_user(arg, size);
9881 return PTR_ERR(res);
9885 for (i = 0; i < nr_args; i++) {
9886 switch (res[i].opcode) {
9887 case IORING_RESTRICTION_REGISTER_OP:
9888 if (res[i].register_op >= IORING_REGISTER_LAST) {
9893 __set_bit(res[i].register_op,
9894 ctx->restrictions.register_op);
9896 case IORING_RESTRICTION_SQE_OP:
9897 if (res[i].sqe_op >= IORING_OP_LAST) {
9902 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9904 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9905 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9907 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9908 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9917 /* Reset all restrictions if an error happened */
9919 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9921 ctx->restrictions.registered = true;
9927 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9929 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9932 if (ctx->restrictions.registered)
9933 ctx->restricted = 1;
9935 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9936 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9937 wake_up(&ctx->sq_data->wait);
9941 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9942 struct io_uring_rsrc_update2 *up,
9950 if (check_add_overflow(up->offset, nr_args, &tmp))
9952 err = io_rsrc_node_switch_start(ctx);
9957 case IORING_RSRC_FILE:
9958 return __io_sqe_files_update(ctx, up, nr_args);
9959 case IORING_RSRC_BUFFER:
9960 return __io_sqe_buffers_update(ctx, up, nr_args);
9965 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9968 struct io_uring_rsrc_update2 up;
9972 memset(&up, 0, sizeof(up));
9973 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9975 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9978 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9979 unsigned size, unsigned type)
9981 struct io_uring_rsrc_update2 up;
9983 if (size != sizeof(up))
9985 if (copy_from_user(&up, arg, sizeof(up)))
9987 if (!up.nr || up.resv)
9989 return __io_register_rsrc_update(ctx, type, &up, up.nr);
9992 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9993 unsigned int size, unsigned int type)
9995 struct io_uring_rsrc_register rr;
9997 /* keep it extendible */
9998 if (size != sizeof(rr))
10001 memset(&rr, 0, sizeof(rr));
10002 if (copy_from_user(&rr, arg, size))
10004 if (!rr.nr || rr.resv || rr.resv2)
10008 case IORING_RSRC_FILE:
10009 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10010 rr.nr, u64_to_user_ptr(rr.tags));
10011 case IORING_RSRC_BUFFER:
10012 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10013 rr.nr, u64_to_user_ptr(rr.tags));
10018 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10021 struct io_uring_task *tctx = current->io_uring;
10022 cpumask_var_t new_mask;
10025 if (!tctx || !tctx->io_wq)
10028 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10031 cpumask_clear(new_mask);
10032 if (len > cpumask_size())
10033 len = cpumask_size();
10035 if (copy_from_user(new_mask, arg, len)) {
10036 free_cpumask_var(new_mask);
10040 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10041 free_cpumask_var(new_mask);
10045 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10047 struct io_uring_task *tctx = current->io_uring;
10049 if (!tctx || !tctx->io_wq)
10052 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10055 static bool io_register_op_must_quiesce(int op)
10058 case IORING_REGISTER_BUFFERS:
10059 case IORING_UNREGISTER_BUFFERS:
10060 case IORING_REGISTER_FILES:
10061 case IORING_UNREGISTER_FILES:
10062 case IORING_REGISTER_FILES_UPDATE:
10063 case IORING_REGISTER_PROBE:
10064 case IORING_REGISTER_PERSONALITY:
10065 case IORING_UNREGISTER_PERSONALITY:
10066 case IORING_REGISTER_FILES2:
10067 case IORING_REGISTER_FILES_UPDATE2:
10068 case IORING_REGISTER_BUFFERS2:
10069 case IORING_REGISTER_BUFFERS_UPDATE:
10070 case IORING_REGISTER_IOWQ_AFF:
10071 case IORING_UNREGISTER_IOWQ_AFF:
10078 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10079 void __user *arg, unsigned nr_args)
10080 __releases(ctx->uring_lock)
10081 __acquires(ctx->uring_lock)
10086 * We're inside the ring mutex, if the ref is already dying, then
10087 * someone else killed the ctx or is already going through
10088 * io_uring_register().
10090 if (percpu_ref_is_dying(&ctx->refs))
10093 if (ctx->restricted) {
10094 if (opcode >= IORING_REGISTER_LAST)
10096 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10097 if (!test_bit(opcode, ctx->restrictions.register_op))
10101 if (io_register_op_must_quiesce(opcode)) {
10102 percpu_ref_kill(&ctx->refs);
10105 * Drop uring mutex before waiting for references to exit. If
10106 * another thread is currently inside io_uring_enter() it might
10107 * need to grab the uring_lock to make progress. If we hold it
10108 * here across the drain wait, then we can deadlock. It's safe
10109 * to drop the mutex here, since no new references will come in
10110 * after we've killed the percpu ref.
10112 mutex_unlock(&ctx->uring_lock);
10114 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10117 ret = io_run_task_work_sig();
10121 mutex_lock(&ctx->uring_lock);
10124 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10130 case IORING_REGISTER_BUFFERS:
10131 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10133 case IORING_UNREGISTER_BUFFERS:
10135 if (arg || nr_args)
10137 ret = io_sqe_buffers_unregister(ctx);
10139 case IORING_REGISTER_FILES:
10140 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10142 case IORING_UNREGISTER_FILES:
10144 if (arg || nr_args)
10146 ret = io_sqe_files_unregister(ctx);
10148 case IORING_REGISTER_FILES_UPDATE:
10149 ret = io_register_files_update(ctx, arg, nr_args);
10151 case IORING_REGISTER_EVENTFD:
10152 case IORING_REGISTER_EVENTFD_ASYNC:
10156 ret = io_eventfd_register(ctx, arg);
10159 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10160 ctx->eventfd_async = 1;
10162 ctx->eventfd_async = 0;
10164 case IORING_UNREGISTER_EVENTFD:
10166 if (arg || nr_args)
10168 ret = io_eventfd_unregister(ctx);
10170 case IORING_REGISTER_PROBE:
10172 if (!arg || nr_args > 256)
10174 ret = io_probe(ctx, arg, nr_args);
10176 case IORING_REGISTER_PERSONALITY:
10178 if (arg || nr_args)
10180 ret = io_register_personality(ctx);
10182 case IORING_UNREGISTER_PERSONALITY:
10186 ret = io_unregister_personality(ctx, nr_args);
10188 case IORING_REGISTER_ENABLE_RINGS:
10190 if (arg || nr_args)
10192 ret = io_register_enable_rings(ctx);
10194 case IORING_REGISTER_RESTRICTIONS:
10195 ret = io_register_restrictions(ctx, arg, nr_args);
10197 case IORING_REGISTER_FILES2:
10198 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10200 case IORING_REGISTER_FILES_UPDATE2:
10201 ret = io_register_rsrc_update(ctx, arg, nr_args,
10204 case IORING_REGISTER_BUFFERS2:
10205 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10207 case IORING_REGISTER_BUFFERS_UPDATE:
10208 ret = io_register_rsrc_update(ctx, arg, nr_args,
10209 IORING_RSRC_BUFFER);
10211 case IORING_REGISTER_IOWQ_AFF:
10213 if (!arg || !nr_args)
10215 ret = io_register_iowq_aff(ctx, arg, nr_args);
10217 case IORING_UNREGISTER_IOWQ_AFF:
10219 if (arg || nr_args)
10221 ret = io_unregister_iowq_aff(ctx);
10228 if (io_register_op_must_quiesce(opcode)) {
10229 /* bring the ctx back to life */
10230 percpu_ref_reinit(&ctx->refs);
10231 reinit_completion(&ctx->ref_comp);
10236 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10237 void __user *, arg, unsigned int, nr_args)
10239 struct io_ring_ctx *ctx;
10248 if (f.file->f_op != &io_uring_fops)
10251 ctx = f.file->private_data;
10253 io_run_task_work();
10255 mutex_lock(&ctx->uring_lock);
10256 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10257 mutex_unlock(&ctx->uring_lock);
10258 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10259 ctx->cq_ev_fd != NULL, ret);
10265 static int __init io_uring_init(void)
10267 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10268 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10269 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10272 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10273 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10274 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10275 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10276 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10277 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10278 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10279 BUILD_BUG_SQE_ELEM(8, __u64, off);
10280 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10281 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10282 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10283 BUILD_BUG_SQE_ELEM(24, __u32, len);
10284 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10285 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10286 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10287 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10288 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10289 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10290 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10291 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10292 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10293 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10294 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10295 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10296 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10297 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10298 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10299 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10300 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10301 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10302 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10303 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10305 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10306 sizeof(struct io_uring_rsrc_update));
10307 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10308 sizeof(struct io_uring_rsrc_update2));
10309 /* should fit into one byte */
10310 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10312 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10313 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10315 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10319 __initcall(io_uring_init);