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);
1049 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1050 long res, unsigned int cflags);
1051 static void io_put_req(struct io_kiocb *req);
1052 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1053 static void io_dismantle_req(struct io_kiocb *req);
1054 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1055 static void io_queue_linked_timeout(struct io_kiocb *req);
1056 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1057 struct io_uring_rsrc_update2 *up,
1059 static void io_clean_op(struct io_kiocb *req);
1060 static struct file *io_file_get(struct io_ring_ctx *ctx,
1061 struct io_submit_state *state,
1062 struct io_kiocb *req, int fd, bool fixed);
1063 static void __io_queue_sqe(struct io_kiocb *req);
1064 static void io_rsrc_put_work(struct work_struct *work);
1066 static void io_req_task_queue(struct io_kiocb *req);
1067 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1068 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1069 static int io_req_prep_async(struct io_kiocb *req);
1071 static void io_fallback_req_func(struct work_struct *unused);
1073 static struct kmem_cache *req_cachep;
1075 static const struct file_operations io_uring_fops;
1077 struct sock *io_uring_get_socket(struct file *file)
1079 #if defined(CONFIG_UNIX)
1080 if (file->f_op == &io_uring_fops) {
1081 struct io_ring_ctx *ctx = file->private_data;
1083 return ctx->ring_sock->sk;
1088 EXPORT_SYMBOL(io_uring_get_socket);
1090 #define io_for_each_link(pos, head) \
1091 for (pos = (head); pos; pos = pos->link)
1093 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1095 struct io_ring_ctx *ctx = req->ctx;
1097 if (!req->fixed_rsrc_refs) {
1098 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1099 percpu_ref_get(req->fixed_rsrc_refs);
1103 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1105 bool got = percpu_ref_tryget(ref);
1107 /* already at zero, wait for ->release() */
1109 wait_for_completion(compl);
1110 percpu_ref_resurrect(ref);
1112 percpu_ref_put(ref);
1115 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1118 struct io_kiocb *req;
1120 if (task && head->task != task)
1125 io_for_each_link(req, head) {
1126 if (req->flags & REQ_F_INFLIGHT)
1132 static inline void req_set_fail(struct io_kiocb *req)
1134 req->flags |= REQ_F_FAIL;
1137 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1139 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1141 complete(&ctx->ref_comp);
1144 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1146 return !req->timeout.off;
1149 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1151 struct io_ring_ctx *ctx;
1154 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1159 * Use 5 bits less than the max cq entries, that should give us around
1160 * 32 entries per hash list if totally full and uniformly spread.
1162 hash_bits = ilog2(p->cq_entries);
1166 ctx->cancel_hash_bits = hash_bits;
1167 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1169 if (!ctx->cancel_hash)
1171 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1173 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1174 if (!ctx->dummy_ubuf)
1176 /* set invalid range, so io_import_fixed() fails meeting it */
1177 ctx->dummy_ubuf->ubuf = -1UL;
1179 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1180 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1183 ctx->flags = p->flags;
1184 init_waitqueue_head(&ctx->sqo_sq_wait);
1185 INIT_LIST_HEAD(&ctx->sqd_list);
1186 init_waitqueue_head(&ctx->poll_wait);
1187 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1188 init_completion(&ctx->ref_comp);
1189 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1190 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1191 mutex_init(&ctx->uring_lock);
1192 init_waitqueue_head(&ctx->cq_wait);
1193 spin_lock_init(&ctx->completion_lock);
1194 INIT_LIST_HEAD(&ctx->iopoll_list);
1195 INIT_LIST_HEAD(&ctx->defer_list);
1196 INIT_LIST_HEAD(&ctx->timeout_list);
1197 spin_lock_init(&ctx->rsrc_ref_lock);
1198 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1199 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1200 init_llist_head(&ctx->rsrc_put_llist);
1201 INIT_LIST_HEAD(&ctx->tctx_list);
1202 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1203 INIT_LIST_HEAD(&ctx->locked_free_list);
1204 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1207 kfree(ctx->dummy_ubuf);
1208 kfree(ctx->cancel_hash);
1213 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1215 struct io_rings *r = ctx->rings;
1217 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1221 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1223 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1224 struct io_ring_ctx *ctx = req->ctx;
1226 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1232 #define FFS_ASYNC_READ 0x1UL
1233 #define FFS_ASYNC_WRITE 0x2UL
1235 #define FFS_ISREG 0x4UL
1237 #define FFS_ISREG 0x0UL
1239 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1241 static inline bool io_req_ffs_set(struct io_kiocb *req)
1243 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1246 static void io_req_track_inflight(struct io_kiocb *req)
1248 if (!(req->flags & REQ_F_INFLIGHT)) {
1249 req->flags |= REQ_F_INFLIGHT;
1250 atomic_inc(¤t->io_uring->inflight_tracked);
1254 static void io_prep_async_work(struct io_kiocb *req)
1256 const struct io_op_def *def = &io_op_defs[req->opcode];
1257 struct io_ring_ctx *ctx = req->ctx;
1259 if (!(req->flags & REQ_F_CREDS)) {
1260 req->flags |= REQ_F_CREDS;
1261 req->creds = get_current_cred();
1264 req->work.list.next = NULL;
1265 req->work.flags = 0;
1266 if (req->flags & REQ_F_FORCE_ASYNC)
1267 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1269 if (req->flags & REQ_F_ISREG) {
1270 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1271 io_wq_hash_work(&req->work, file_inode(req->file));
1272 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1273 if (def->unbound_nonreg_file)
1274 req->work.flags |= IO_WQ_WORK_UNBOUND;
1277 switch (req->opcode) {
1278 case IORING_OP_SPLICE:
1280 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1281 req->work.flags |= IO_WQ_WORK_UNBOUND;
1286 static void io_prep_async_link(struct io_kiocb *req)
1288 struct io_kiocb *cur;
1290 if (req->flags & REQ_F_LINK_TIMEOUT) {
1291 struct io_ring_ctx *ctx = req->ctx;
1293 spin_lock_irq(&ctx->completion_lock);
1294 io_for_each_link(cur, req)
1295 io_prep_async_work(cur);
1296 spin_unlock_irq(&ctx->completion_lock);
1298 io_for_each_link(cur, req)
1299 io_prep_async_work(cur);
1303 static void io_queue_async_work(struct io_kiocb *req)
1305 struct io_ring_ctx *ctx = req->ctx;
1306 struct io_kiocb *link = io_prep_linked_timeout(req);
1307 struct io_uring_task *tctx = req->task->io_uring;
1310 BUG_ON(!tctx->io_wq);
1312 /* init ->work of the whole link before punting */
1313 io_prep_async_link(req);
1316 * Not expected to happen, but if we do have a bug where this _can_
1317 * happen, catch it here and ensure the request is marked as
1318 * canceled. That will make io-wq go through the usual work cancel
1319 * procedure rather than attempt to run this request (or create a new
1322 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1323 req->work.flags |= IO_WQ_WORK_CANCEL;
1325 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1326 &req->work, req->flags);
1327 io_wq_enqueue(tctx->io_wq, &req->work);
1329 io_queue_linked_timeout(link);
1332 static void io_kill_timeout(struct io_kiocb *req, int status)
1333 __must_hold(&req->ctx->completion_lock)
1335 struct io_timeout_data *io = req->async_data;
1337 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1338 atomic_set(&req->ctx->cq_timeouts,
1339 atomic_read(&req->ctx->cq_timeouts) + 1);
1340 list_del_init(&req->timeout.list);
1341 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1342 io_put_req_deferred(req, 1);
1346 static void io_queue_deferred(struct io_ring_ctx *ctx)
1348 while (!list_empty(&ctx->defer_list)) {
1349 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1350 struct io_defer_entry, list);
1352 if (req_need_defer(de->req, de->seq))
1354 list_del_init(&de->list);
1355 io_req_task_queue(de->req);
1360 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1362 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1364 while (!list_empty(&ctx->timeout_list)) {
1365 u32 events_needed, events_got;
1366 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1367 struct io_kiocb, timeout.list);
1369 if (io_is_timeout_noseq(req))
1373 * Since seq can easily wrap around over time, subtract
1374 * the last seq at which timeouts were flushed before comparing.
1375 * Assuming not more than 2^31-1 events have happened since,
1376 * these subtractions won't have wrapped, so we can check if
1377 * target is in [last_seq, current_seq] by comparing the two.
1379 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1380 events_got = seq - ctx->cq_last_tm_flush;
1381 if (events_got < events_needed)
1384 list_del_init(&req->timeout.list);
1385 io_kill_timeout(req, 0);
1387 ctx->cq_last_tm_flush = seq;
1390 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1392 if (ctx->off_timeout_used)
1393 io_flush_timeouts(ctx);
1394 if (ctx->drain_active)
1395 io_queue_deferred(ctx);
1398 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1400 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1401 __io_commit_cqring_flush(ctx);
1402 /* order cqe stores with ring update */
1403 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1406 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1408 struct io_rings *r = ctx->rings;
1410 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1413 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1415 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1418 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1420 struct io_rings *rings = ctx->rings;
1421 unsigned tail, mask = ctx->cq_entries - 1;
1424 * writes to the cq entry need to come after reading head; the
1425 * control dependency is enough as we're using WRITE_ONCE to
1428 if (__io_cqring_events(ctx) == ctx->cq_entries)
1431 tail = ctx->cached_cq_tail++;
1432 return &rings->cqes[tail & mask];
1435 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1437 if (likely(!ctx->cq_ev_fd))
1439 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1441 return !ctx->eventfd_async || io_wq_current_is_worker();
1444 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1447 * wake_up_all() may seem excessive, but io_wake_function() and
1448 * io_should_wake() handle the termination of the loop and only
1449 * wake as many waiters as we need to.
1451 if (wq_has_sleeper(&ctx->cq_wait))
1452 wake_up_all(&ctx->cq_wait);
1453 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1454 wake_up(&ctx->sq_data->wait);
1455 if (io_should_trigger_evfd(ctx))
1456 eventfd_signal(ctx->cq_ev_fd, 1);
1457 if (waitqueue_active(&ctx->poll_wait)) {
1458 wake_up_interruptible(&ctx->poll_wait);
1459 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1463 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1465 if (ctx->flags & IORING_SETUP_SQPOLL) {
1466 if (wq_has_sleeper(&ctx->cq_wait))
1467 wake_up_all(&ctx->cq_wait);
1469 if (io_should_trigger_evfd(ctx))
1470 eventfd_signal(ctx->cq_ev_fd, 1);
1471 if (waitqueue_active(&ctx->poll_wait)) {
1472 wake_up_interruptible(&ctx->poll_wait);
1473 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1477 /* Returns true if there are no backlogged entries after the flush */
1478 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1480 unsigned long flags;
1481 bool all_flushed, posted;
1483 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1487 spin_lock_irqsave(&ctx->completion_lock, flags);
1488 while (!list_empty(&ctx->cq_overflow_list)) {
1489 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1490 struct io_overflow_cqe *ocqe;
1494 ocqe = list_first_entry(&ctx->cq_overflow_list,
1495 struct io_overflow_cqe, list);
1497 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1499 io_account_cq_overflow(ctx);
1502 list_del(&ocqe->list);
1506 all_flushed = list_empty(&ctx->cq_overflow_list);
1508 clear_bit(0, &ctx->check_cq_overflow);
1509 WRITE_ONCE(ctx->rings->sq_flags,
1510 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1514 io_commit_cqring(ctx);
1515 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1517 io_cqring_ev_posted(ctx);
1521 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1525 if (test_bit(0, &ctx->check_cq_overflow)) {
1526 /* iopoll syncs against uring_lock, not completion_lock */
1527 if (ctx->flags & IORING_SETUP_IOPOLL)
1528 mutex_lock(&ctx->uring_lock);
1529 ret = __io_cqring_overflow_flush(ctx, force);
1530 if (ctx->flags & IORING_SETUP_IOPOLL)
1531 mutex_unlock(&ctx->uring_lock);
1538 * Shamelessly stolen from the mm implementation of page reference checking,
1539 * see commit f958d7b528b1 for details.
1541 #define req_ref_zero_or_close_to_overflow(req) \
1542 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1544 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1546 return atomic_inc_not_zero(&req->refs);
1549 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1551 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1552 return atomic_sub_and_test(refs, &req->refs);
1555 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1557 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1558 return atomic_dec_and_test(&req->refs);
1561 static inline void req_ref_put(struct io_kiocb *req)
1563 WARN_ON_ONCE(req_ref_put_and_test(req));
1566 static inline void req_ref_get(struct io_kiocb *req)
1568 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1569 atomic_inc(&req->refs);
1572 /* must to be called somewhat shortly after putting a request */
1573 static inline void io_put_task(struct task_struct *task, int nr)
1575 struct io_uring_task *tctx = task->io_uring;
1577 percpu_counter_sub(&tctx->inflight, nr);
1578 if (unlikely(atomic_read(&tctx->in_idle)))
1579 wake_up(&tctx->wait);
1580 put_task_struct_many(task, nr);
1583 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1584 long res, unsigned int cflags)
1586 struct io_overflow_cqe *ocqe;
1588 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1591 * If we're in ring overflow flush mode, or in task cancel mode,
1592 * or cannot allocate an overflow entry, then we need to drop it
1595 io_account_cq_overflow(ctx);
1598 if (list_empty(&ctx->cq_overflow_list)) {
1599 set_bit(0, &ctx->check_cq_overflow);
1600 WRITE_ONCE(ctx->rings->sq_flags,
1601 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1604 ocqe->cqe.user_data = user_data;
1605 ocqe->cqe.res = res;
1606 ocqe->cqe.flags = cflags;
1607 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1611 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1612 long res, unsigned int cflags)
1614 struct io_uring_cqe *cqe;
1616 trace_io_uring_complete(ctx, user_data, res, cflags);
1619 * If we can't get a cq entry, userspace overflowed the
1620 * submission (by quite a lot). Increment the overflow count in
1623 cqe = io_get_cqe(ctx);
1625 WRITE_ONCE(cqe->user_data, user_data);
1626 WRITE_ONCE(cqe->res, res);
1627 WRITE_ONCE(cqe->flags, cflags);
1630 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1633 /* not as hot to bloat with inlining */
1634 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1635 long res, unsigned int cflags)
1637 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1640 static void io_req_complete_post(struct io_kiocb *req, long res,
1641 unsigned int cflags)
1643 struct io_ring_ctx *ctx = req->ctx;
1644 unsigned long flags;
1646 spin_lock_irqsave(&ctx->completion_lock, flags);
1647 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1649 * If we're the last reference to this request, add to our locked
1652 if (req_ref_put_and_test(req)) {
1653 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1654 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL))
1655 io_disarm_next(req);
1657 io_req_task_queue(req->link);
1661 io_dismantle_req(req);
1662 io_put_task(req->task, 1);
1663 list_add(&req->compl.list, &ctx->locked_free_list);
1664 ctx->locked_free_nr++;
1666 if (!percpu_ref_tryget(&ctx->refs))
1669 io_commit_cqring(ctx);
1670 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1673 io_cqring_ev_posted(ctx);
1674 percpu_ref_put(&ctx->refs);
1678 static inline bool io_req_needs_clean(struct io_kiocb *req)
1680 return req->flags & IO_REQ_CLEAN_FLAGS;
1683 static void io_req_complete_state(struct io_kiocb *req, long res,
1684 unsigned int cflags)
1686 if (io_req_needs_clean(req))
1689 req->compl.cflags = cflags;
1690 req->flags |= REQ_F_COMPLETE_INLINE;
1693 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1694 long res, unsigned cflags)
1696 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1697 io_req_complete_state(req, res, cflags);
1699 io_req_complete_post(req, res, cflags);
1702 static inline void io_req_complete(struct io_kiocb *req, long res)
1704 __io_req_complete(req, 0, res, 0);
1707 static void io_req_complete_failed(struct io_kiocb *req, long res)
1711 io_req_complete_post(req, res, 0);
1715 * Don't initialise the fields below on every allocation, but do that in
1716 * advance and keep them valid across allocations.
1718 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1722 req->async_data = NULL;
1723 /* not necessary, but safer to zero */
1727 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1728 struct io_comp_state *cs)
1730 spin_lock_irq(&ctx->completion_lock);
1731 list_splice_init(&ctx->locked_free_list, &cs->free_list);
1732 ctx->locked_free_nr = 0;
1733 spin_unlock_irq(&ctx->completion_lock);
1736 /* Returns true IFF there are requests in the cache */
1737 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1739 struct io_submit_state *state = &ctx->submit_state;
1740 struct io_comp_state *cs = &state->comp;
1744 * If we have more than a batch's worth of requests in our IRQ side
1745 * locked cache, grab the lock and move them over to our submission
1748 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1749 io_flush_cached_locked_reqs(ctx, cs);
1751 nr = state->free_reqs;
1752 while (!list_empty(&cs->free_list)) {
1753 struct io_kiocb *req = list_first_entry(&cs->free_list,
1754 struct io_kiocb, compl.list);
1756 list_del(&req->compl.list);
1757 state->reqs[nr++] = req;
1758 if (nr == ARRAY_SIZE(state->reqs))
1762 state->free_reqs = nr;
1766 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1768 struct io_submit_state *state = &ctx->submit_state;
1769 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1772 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1774 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1777 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1781 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1782 * retry single alloc to be on the safe side.
1784 if (unlikely(ret <= 0)) {
1785 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1786 if (!state->reqs[0])
1791 for (i = 0; i < ret; i++)
1792 io_preinit_req(state->reqs[i], ctx);
1793 state->free_reqs = ret;
1796 return state->reqs[state->free_reqs];
1799 static inline void io_put_file(struct file *file)
1805 static void io_dismantle_req(struct io_kiocb *req)
1807 unsigned int flags = req->flags;
1809 if (io_req_needs_clean(req))
1811 if (!(flags & REQ_F_FIXED_FILE))
1812 io_put_file(req->file);
1813 if (req->fixed_rsrc_refs)
1814 percpu_ref_put(req->fixed_rsrc_refs);
1815 if (req->async_data) {
1816 kfree(req->async_data);
1817 req->async_data = NULL;
1821 static void __io_free_req(struct io_kiocb *req)
1823 struct io_ring_ctx *ctx = req->ctx;
1825 io_dismantle_req(req);
1826 io_put_task(req->task, 1);
1828 kmem_cache_free(req_cachep, req);
1829 percpu_ref_put(&ctx->refs);
1832 static inline void io_remove_next_linked(struct io_kiocb *req)
1834 struct io_kiocb *nxt = req->link;
1836 req->link = nxt->link;
1840 static bool io_kill_linked_timeout(struct io_kiocb *req)
1841 __must_hold(&req->ctx->completion_lock)
1843 struct io_kiocb *link = req->link;
1846 * Can happen if a linked timeout fired and link had been like
1847 * req -> link t-out -> link t-out [-> ...]
1849 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1850 struct io_timeout_data *io = link->async_data;
1852 io_remove_next_linked(req);
1853 link->timeout.head = NULL;
1854 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1855 io_cqring_fill_event(link->ctx, link->user_data,
1857 io_put_req_deferred(link, 1);
1864 static void io_fail_links(struct io_kiocb *req)
1865 __must_hold(&req->ctx->completion_lock)
1867 struct io_kiocb *nxt, *link = req->link;
1874 trace_io_uring_fail_link(req, link);
1875 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1876 io_put_req_deferred(link, 2);
1881 static bool io_disarm_next(struct io_kiocb *req)
1882 __must_hold(&req->ctx->completion_lock)
1884 bool posted = false;
1886 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1887 posted = io_kill_linked_timeout(req);
1888 if (unlikely((req->flags & REQ_F_FAIL) &&
1889 !(req->flags & REQ_F_HARDLINK))) {
1890 posted |= (req->link != NULL);
1896 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1898 struct io_kiocb *nxt;
1901 * If LINK is set, we have dependent requests in this chain. If we
1902 * didn't fail this request, queue the first one up, moving any other
1903 * dependencies to the next request. In case of failure, fail the rest
1906 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL)) {
1907 struct io_ring_ctx *ctx = req->ctx;
1908 unsigned long flags;
1911 spin_lock_irqsave(&ctx->completion_lock, flags);
1912 posted = io_disarm_next(req);
1914 io_commit_cqring(req->ctx);
1915 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1917 io_cqring_ev_posted(ctx);
1924 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1926 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1928 return __io_req_find_next(req);
1931 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1935 if (ctx->submit_state.comp.nr) {
1936 mutex_lock(&ctx->uring_lock);
1937 io_submit_flush_completions(ctx);
1938 mutex_unlock(&ctx->uring_lock);
1940 percpu_ref_put(&ctx->refs);
1943 static void tctx_task_work(struct callback_head *cb)
1945 struct io_ring_ctx *ctx = NULL;
1946 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1950 struct io_wq_work_node *node;
1952 spin_lock_irq(&tctx->task_lock);
1953 node = tctx->task_list.first;
1954 INIT_WQ_LIST(&tctx->task_list);
1955 spin_unlock_irq(&tctx->task_lock);
1958 struct io_wq_work_node *next = node->next;
1959 struct io_kiocb *req = container_of(node, struct io_kiocb,
1962 if (req->ctx != ctx) {
1963 ctx_flush_and_put(ctx);
1965 percpu_ref_get(&ctx->refs);
1967 req->io_task_work.func(req);
1970 if (wq_list_empty(&tctx->task_list)) {
1971 spin_lock_irq(&tctx->task_lock);
1972 clear_bit(0, &tctx->task_state);
1973 if (wq_list_empty(&tctx->task_list)) {
1974 spin_unlock_irq(&tctx->task_lock);
1977 spin_unlock_irq(&tctx->task_lock);
1978 /* another tctx_task_work() is enqueued, yield */
1979 if (test_and_set_bit(0, &tctx->task_state))
1985 ctx_flush_and_put(ctx);
1988 static void io_req_task_work_add(struct io_kiocb *req)
1990 struct task_struct *tsk = req->task;
1991 struct io_uring_task *tctx = tsk->io_uring;
1992 enum task_work_notify_mode notify;
1993 struct io_wq_work_node *node;
1994 unsigned long flags;
1996 WARN_ON_ONCE(!tctx);
1998 spin_lock_irqsave(&tctx->task_lock, flags);
1999 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2000 spin_unlock_irqrestore(&tctx->task_lock, flags);
2002 /* task_work already pending, we're done */
2003 if (test_bit(0, &tctx->task_state) ||
2004 test_and_set_bit(0, &tctx->task_state))
2008 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2009 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2010 * processing task_work. There's no reliable way to tell if TWA_RESUME
2013 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2014 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2015 wake_up_process(tsk);
2019 clear_bit(0, &tctx->task_state);
2020 spin_lock_irqsave(&tctx->task_lock, flags);
2021 node = tctx->task_list.first;
2022 INIT_WQ_LIST(&tctx->task_list);
2023 spin_unlock_irqrestore(&tctx->task_lock, flags);
2026 req = container_of(node, struct io_kiocb, io_task_work.node);
2028 if (llist_add(&req->io_task_work.fallback_node,
2029 &req->ctx->fallback_llist))
2030 schedule_delayed_work(&req->ctx->fallback_work, 1);
2034 static void io_req_task_cancel(struct io_kiocb *req)
2036 struct io_ring_ctx *ctx = req->ctx;
2038 /* ctx is guaranteed to stay alive while we hold uring_lock */
2039 mutex_lock(&ctx->uring_lock);
2040 io_req_complete_failed(req, req->result);
2041 mutex_unlock(&ctx->uring_lock);
2044 static void io_req_task_submit(struct io_kiocb *req)
2046 struct io_ring_ctx *ctx = req->ctx;
2048 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2049 mutex_lock(&ctx->uring_lock);
2050 if (!(req->task->flags & PF_EXITING) && !req->task->in_execve)
2051 __io_queue_sqe(req);
2053 io_req_complete_failed(req, -EFAULT);
2054 mutex_unlock(&ctx->uring_lock);
2057 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2060 req->io_task_work.func = io_req_task_cancel;
2061 io_req_task_work_add(req);
2064 static void io_req_task_queue(struct io_kiocb *req)
2066 req->io_task_work.func = io_req_task_submit;
2067 io_req_task_work_add(req);
2070 static void io_req_task_queue_reissue(struct io_kiocb *req)
2072 req->io_task_work.func = io_queue_async_work;
2073 io_req_task_work_add(req);
2076 static inline void io_queue_next(struct io_kiocb *req)
2078 struct io_kiocb *nxt = io_req_find_next(req);
2081 io_req_task_queue(nxt);
2084 static void io_free_req(struct io_kiocb *req)
2091 struct task_struct *task;
2096 static inline void io_init_req_batch(struct req_batch *rb)
2103 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2104 struct req_batch *rb)
2107 io_put_task(rb->task, rb->task_refs);
2109 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2112 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2113 struct io_submit_state *state)
2116 io_dismantle_req(req);
2118 if (req->task != rb->task) {
2120 io_put_task(rb->task, rb->task_refs);
2121 rb->task = req->task;
2127 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2128 state->reqs[state->free_reqs++] = req;
2130 list_add(&req->compl.list, &state->comp.free_list);
2133 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2134 __must_hold(&req->ctx->uring_lock)
2136 struct io_comp_state *cs = &ctx->submit_state.comp;
2138 struct req_batch rb;
2140 spin_lock_irq(&ctx->completion_lock);
2141 for (i = 0; i < nr; i++) {
2142 struct io_kiocb *req = cs->reqs[i];
2144 __io_cqring_fill_event(ctx, req->user_data, req->result,
2147 io_commit_cqring(ctx);
2148 spin_unlock_irq(&ctx->completion_lock);
2149 io_cqring_ev_posted(ctx);
2151 io_init_req_batch(&rb);
2152 for (i = 0; i < nr; i++) {
2153 struct io_kiocb *req = cs->reqs[i];
2155 /* submission and completion refs */
2156 if (req_ref_sub_and_test(req, 2))
2157 io_req_free_batch(&rb, req, &ctx->submit_state);
2160 io_req_free_batch_finish(ctx, &rb);
2165 * Drop reference to request, return next in chain (if there is one) if this
2166 * was the last reference to this request.
2168 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2170 struct io_kiocb *nxt = NULL;
2172 if (req_ref_put_and_test(req)) {
2173 nxt = io_req_find_next(req);
2179 static inline void io_put_req(struct io_kiocb *req)
2181 if (req_ref_put_and_test(req))
2185 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2187 if (req_ref_sub_and_test(req, refs)) {
2188 req->io_task_work.func = io_free_req;
2189 io_req_task_work_add(req);
2193 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2195 /* See comment at the top of this file */
2197 return __io_cqring_events(ctx);
2200 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2202 struct io_rings *rings = ctx->rings;
2204 /* make sure SQ entry isn't read before tail */
2205 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2208 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2210 unsigned int cflags;
2212 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2213 cflags |= IORING_CQE_F_BUFFER;
2214 req->flags &= ~REQ_F_BUFFER_SELECTED;
2219 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2221 struct io_buffer *kbuf;
2223 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2224 return io_put_kbuf(req, kbuf);
2227 static inline bool io_run_task_work(void)
2229 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2230 __set_current_state(TASK_RUNNING);
2231 tracehook_notify_signal();
2239 * Find and free completed poll iocbs
2241 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2242 struct list_head *done, bool resubmit)
2244 struct req_batch rb;
2245 struct io_kiocb *req;
2247 /* order with ->result store in io_complete_rw_iopoll() */
2250 io_init_req_batch(&rb);
2251 while (!list_empty(done)) {
2254 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2255 list_del(&req->inflight_entry);
2257 if (READ_ONCE(req->result) == -EAGAIN && resubmit &&
2258 !(req->flags & REQ_F_DONT_REISSUE)) {
2259 req->iopoll_completed = 0;
2261 io_req_task_queue_reissue(req);
2265 if (req->flags & REQ_F_BUFFER_SELECTED)
2266 cflags = io_put_rw_kbuf(req);
2268 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2271 if (req_ref_put_and_test(req))
2272 io_req_free_batch(&rb, req, &ctx->submit_state);
2275 io_commit_cqring(ctx);
2276 io_cqring_ev_posted_iopoll(ctx);
2277 io_req_free_batch_finish(ctx, &rb);
2280 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2281 long min, bool resubmit)
2283 struct io_kiocb *req, *tmp;
2288 * Only spin for completions if we don't have multiple devices hanging
2289 * off our complete list, and we're under the requested amount.
2291 spin = !ctx->poll_multi_queue && *nr_events < min;
2293 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2294 struct kiocb *kiocb = &req->rw.kiocb;
2298 * Move completed and retryable entries to our local lists.
2299 * If we find a request that requires polling, break out
2300 * and complete those lists first, if we have entries there.
2302 if (READ_ONCE(req->iopoll_completed)) {
2303 list_move_tail(&req->inflight_entry, &done);
2306 if (!list_empty(&done))
2309 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2310 if (unlikely(ret < 0))
2315 /* iopoll may have completed current req */
2316 if (READ_ONCE(req->iopoll_completed))
2317 list_move_tail(&req->inflight_entry, &done);
2320 if (!list_empty(&done))
2321 io_iopoll_complete(ctx, nr_events, &done, resubmit);
2327 * We can't just wait for polled events to come to us, we have to actively
2328 * find and complete them.
2330 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2332 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2335 mutex_lock(&ctx->uring_lock);
2336 while (!list_empty(&ctx->iopoll_list)) {
2337 unsigned int nr_events = 0;
2339 io_do_iopoll(ctx, &nr_events, 0, false);
2341 /* let it sleep and repeat later if can't complete a request */
2345 * Ensure we allow local-to-the-cpu processing to take place,
2346 * in this case we need to ensure that we reap all events.
2347 * Also let task_work, etc. to progress by releasing the mutex
2349 if (need_resched()) {
2350 mutex_unlock(&ctx->uring_lock);
2352 mutex_lock(&ctx->uring_lock);
2355 mutex_unlock(&ctx->uring_lock);
2358 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2360 unsigned int nr_events = 0;
2364 * We disallow the app entering submit/complete with polling, but we
2365 * still need to lock the ring to prevent racing with polled issue
2366 * that got punted to a workqueue.
2368 mutex_lock(&ctx->uring_lock);
2370 * Don't enter poll loop if we already have events pending.
2371 * If we do, we can potentially be spinning for commands that
2372 * already triggered a CQE (eg in error).
2374 if (test_bit(0, &ctx->check_cq_overflow))
2375 __io_cqring_overflow_flush(ctx, false);
2376 if (io_cqring_events(ctx))
2380 * If a submit got punted to a workqueue, we can have the
2381 * application entering polling for a command before it gets
2382 * issued. That app will hold the uring_lock for the duration
2383 * of the poll right here, so we need to take a breather every
2384 * now and then to ensure that the issue has a chance to add
2385 * the poll to the issued list. Otherwise we can spin here
2386 * forever, while the workqueue is stuck trying to acquire the
2389 if (list_empty(&ctx->iopoll_list)) {
2390 u32 tail = ctx->cached_cq_tail;
2392 mutex_unlock(&ctx->uring_lock);
2394 mutex_lock(&ctx->uring_lock);
2396 /* some requests don't go through iopoll_list */
2397 if (tail != ctx->cached_cq_tail ||
2398 list_empty(&ctx->iopoll_list))
2401 ret = io_do_iopoll(ctx, &nr_events, min, true);
2402 } while (!ret && nr_events < min && !need_resched());
2404 mutex_unlock(&ctx->uring_lock);
2408 static void kiocb_end_write(struct io_kiocb *req)
2411 * Tell lockdep we inherited freeze protection from submission
2414 if (req->flags & REQ_F_ISREG) {
2415 struct super_block *sb = file_inode(req->file)->i_sb;
2417 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2423 static bool io_resubmit_prep(struct io_kiocb *req)
2425 struct io_async_rw *rw = req->async_data;
2428 return !io_req_prep_async(req);
2429 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2430 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2434 static bool io_rw_should_reissue(struct io_kiocb *req)
2436 umode_t mode = file_inode(req->file)->i_mode;
2437 struct io_ring_ctx *ctx = req->ctx;
2439 if (!S_ISBLK(mode) && !S_ISREG(mode))
2441 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2442 !(ctx->flags & IORING_SETUP_IOPOLL)))
2445 * If ref is dying, we might be running poll reap from the exit work.
2446 * Don't attempt to reissue from that path, just let it fail with
2449 if (percpu_ref_is_dying(&ctx->refs))
2452 * Play it safe and assume not safe to re-import and reissue if we're
2453 * not in the original thread group (or in task context).
2455 if (!same_thread_group(req->task, current) || !in_task())
2460 static bool io_resubmit_prep(struct io_kiocb *req)
2464 static bool io_rw_should_reissue(struct io_kiocb *req)
2470 static void io_fallback_req_func(struct work_struct *work)
2472 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
2473 fallback_work.work);
2474 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
2475 struct io_kiocb *req, *tmp;
2477 percpu_ref_get(&ctx->refs);
2478 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
2479 req->io_task_work.func(req);
2480 percpu_ref_put(&ctx->refs);
2483 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2484 unsigned int issue_flags)
2488 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2489 kiocb_end_write(req);
2490 if (res != req->result) {
2491 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2492 io_rw_should_reissue(req)) {
2493 req->flags |= REQ_F_REISSUE;
2498 if (req->flags & REQ_F_BUFFER_SELECTED)
2499 cflags = io_put_rw_kbuf(req);
2500 __io_req_complete(req, issue_flags, res, cflags);
2503 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2505 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2507 __io_complete_rw(req, res, res2, 0);
2510 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2512 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2514 if (kiocb->ki_flags & IOCB_WRITE)
2515 kiocb_end_write(req);
2516 if (unlikely(res != req->result)) {
2517 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2518 io_resubmit_prep(req))) {
2520 req->flags |= REQ_F_DONT_REISSUE;
2524 WRITE_ONCE(req->result, res);
2525 /* order with io_iopoll_complete() checking ->result */
2527 WRITE_ONCE(req->iopoll_completed, 1);
2531 * After the iocb has been issued, it's safe to be found on the poll list.
2532 * Adding the kiocb to the list AFTER submission ensures that we don't
2533 * find it from a io_do_iopoll() thread before the issuer is done
2534 * accessing the kiocb cookie.
2536 static void io_iopoll_req_issued(struct io_kiocb *req)
2538 struct io_ring_ctx *ctx = req->ctx;
2539 const bool in_async = io_wq_current_is_worker();
2541 /* workqueue context doesn't hold uring_lock, grab it now */
2542 if (unlikely(in_async))
2543 mutex_lock(&ctx->uring_lock);
2546 * Track whether we have multiple files in our lists. This will impact
2547 * how we do polling eventually, not spinning if we're on potentially
2548 * different devices.
2550 if (list_empty(&ctx->iopoll_list)) {
2551 ctx->poll_multi_queue = false;
2552 } else if (!ctx->poll_multi_queue) {
2553 struct io_kiocb *list_req;
2554 unsigned int queue_num0, queue_num1;
2556 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2559 if (list_req->file != req->file) {
2560 ctx->poll_multi_queue = true;
2562 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2563 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2564 if (queue_num0 != queue_num1)
2565 ctx->poll_multi_queue = true;
2570 * For fast devices, IO may have already completed. If it has, add
2571 * it to the front so we find it first.
2573 if (READ_ONCE(req->iopoll_completed))
2574 list_add(&req->inflight_entry, &ctx->iopoll_list);
2576 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2578 if (unlikely(in_async)) {
2580 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2581 * in sq thread task context or in io worker task context. If
2582 * current task context is sq thread, we don't need to check
2583 * whether should wake up sq thread.
2585 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2586 wq_has_sleeper(&ctx->sq_data->wait))
2587 wake_up(&ctx->sq_data->wait);
2589 mutex_unlock(&ctx->uring_lock);
2593 static inline void io_state_file_put(struct io_submit_state *state)
2595 if (state->file_refs) {
2596 fput_many(state->file, state->file_refs);
2597 state->file_refs = 0;
2602 * Get as many references to a file as we have IOs left in this submission,
2603 * assuming most submissions are for one file, or at least that each file
2604 * has more than one submission.
2606 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2611 if (state->file_refs) {
2612 if (state->fd == fd) {
2616 io_state_file_put(state);
2618 state->file = fget_many(fd, state->ios_left);
2619 if (unlikely(!state->file))
2623 state->file_refs = state->ios_left - 1;
2627 static bool io_bdev_nowait(struct block_device *bdev)
2629 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2633 * If we tracked the file through the SCM inflight mechanism, we could support
2634 * any file. For now, just ensure that anything potentially problematic is done
2637 static bool __io_file_supports_nowait(struct file *file, int rw)
2639 umode_t mode = file_inode(file)->i_mode;
2641 if (S_ISBLK(mode)) {
2642 if (IS_ENABLED(CONFIG_BLOCK) &&
2643 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2649 if (S_ISREG(mode)) {
2650 if (IS_ENABLED(CONFIG_BLOCK) &&
2651 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2652 file->f_op != &io_uring_fops)
2657 /* any ->read/write should understand O_NONBLOCK */
2658 if (file->f_flags & O_NONBLOCK)
2661 if (!(file->f_mode & FMODE_NOWAIT))
2665 return file->f_op->read_iter != NULL;
2667 return file->f_op->write_iter != NULL;
2670 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2672 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2674 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2677 return __io_file_supports_nowait(req->file, rw);
2680 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2682 struct io_ring_ctx *ctx = req->ctx;
2683 struct kiocb *kiocb = &req->rw.kiocb;
2684 struct file *file = req->file;
2688 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2689 req->flags |= REQ_F_ISREG;
2691 kiocb->ki_pos = READ_ONCE(sqe->off);
2692 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2693 req->flags |= REQ_F_CUR_POS;
2694 kiocb->ki_pos = file->f_pos;
2696 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2697 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2698 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2702 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2703 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2704 req->flags |= REQ_F_NOWAIT;
2706 ioprio = READ_ONCE(sqe->ioprio);
2708 ret = ioprio_check_cap(ioprio);
2712 kiocb->ki_ioprio = ioprio;
2714 kiocb->ki_ioprio = get_current_ioprio();
2716 if (ctx->flags & IORING_SETUP_IOPOLL) {
2717 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2718 !kiocb->ki_filp->f_op->iopoll)
2721 kiocb->ki_flags |= IOCB_HIPRI;
2722 kiocb->ki_complete = io_complete_rw_iopoll;
2723 req->iopoll_completed = 0;
2725 if (kiocb->ki_flags & IOCB_HIPRI)
2727 kiocb->ki_complete = io_complete_rw;
2730 if (req->opcode == IORING_OP_READ_FIXED ||
2731 req->opcode == IORING_OP_WRITE_FIXED) {
2733 io_req_set_rsrc_node(req);
2736 req->rw.addr = READ_ONCE(sqe->addr);
2737 req->rw.len = READ_ONCE(sqe->len);
2738 req->buf_index = READ_ONCE(sqe->buf_index);
2742 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2748 case -ERESTARTNOINTR:
2749 case -ERESTARTNOHAND:
2750 case -ERESTART_RESTARTBLOCK:
2752 * We can't just restart the syscall, since previously
2753 * submitted sqes may already be in progress. Just fail this
2759 kiocb->ki_complete(kiocb, ret, 0);
2763 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2764 unsigned int issue_flags)
2766 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2767 struct io_async_rw *io = req->async_data;
2768 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2770 /* add previously done IO, if any */
2771 if (io && io->bytes_done > 0) {
2773 ret = io->bytes_done;
2775 ret += io->bytes_done;
2778 if (req->flags & REQ_F_CUR_POS)
2779 req->file->f_pos = kiocb->ki_pos;
2780 if (ret >= 0 && check_reissue)
2781 __io_complete_rw(req, ret, 0, issue_flags);
2783 io_rw_done(kiocb, ret);
2785 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2786 req->flags &= ~REQ_F_REISSUE;
2787 if (io_resubmit_prep(req)) {
2789 io_req_task_queue_reissue(req);
2794 if (req->flags & REQ_F_BUFFER_SELECTED)
2795 cflags = io_put_rw_kbuf(req);
2796 __io_req_complete(req, issue_flags, ret, cflags);
2801 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2802 struct io_mapped_ubuf *imu)
2804 size_t len = req->rw.len;
2805 u64 buf_end, buf_addr = req->rw.addr;
2808 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2810 /* not inside the mapped region */
2811 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2815 * May not be a start of buffer, set size appropriately
2816 * and advance us to the beginning.
2818 offset = buf_addr - imu->ubuf;
2819 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2823 * Don't use iov_iter_advance() here, as it's really slow for
2824 * using the latter parts of a big fixed buffer - it iterates
2825 * over each segment manually. We can cheat a bit here, because
2828 * 1) it's a BVEC iter, we set it up
2829 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2830 * first and last bvec
2832 * So just find our index, and adjust the iterator afterwards.
2833 * If the offset is within the first bvec (or the whole first
2834 * bvec, just use iov_iter_advance(). This makes it easier
2835 * since we can just skip the first segment, which may not
2836 * be PAGE_SIZE aligned.
2838 const struct bio_vec *bvec = imu->bvec;
2840 if (offset <= bvec->bv_len) {
2841 iov_iter_advance(iter, offset);
2843 unsigned long seg_skip;
2845 /* skip first vec */
2846 offset -= bvec->bv_len;
2847 seg_skip = 1 + (offset >> PAGE_SHIFT);
2849 iter->bvec = bvec + seg_skip;
2850 iter->nr_segs -= seg_skip;
2851 iter->count -= bvec->bv_len + offset;
2852 iter->iov_offset = offset & ~PAGE_MASK;
2859 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2861 struct io_ring_ctx *ctx = req->ctx;
2862 struct io_mapped_ubuf *imu = req->imu;
2863 u16 index, buf_index = req->buf_index;
2866 if (unlikely(buf_index >= ctx->nr_user_bufs))
2868 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2869 imu = READ_ONCE(ctx->user_bufs[index]);
2872 return __io_import_fixed(req, rw, iter, imu);
2875 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2878 mutex_unlock(&ctx->uring_lock);
2881 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2884 * "Normal" inline submissions always hold the uring_lock, since we
2885 * grab it from the system call. Same is true for the SQPOLL offload.
2886 * The only exception is when we've detached the request and issue it
2887 * from an async worker thread, grab the lock for that case.
2890 mutex_lock(&ctx->uring_lock);
2893 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2894 int bgid, struct io_buffer *kbuf,
2897 struct io_buffer *head;
2899 if (req->flags & REQ_F_BUFFER_SELECTED)
2902 io_ring_submit_lock(req->ctx, needs_lock);
2904 lockdep_assert_held(&req->ctx->uring_lock);
2906 head = xa_load(&req->ctx->io_buffers, bgid);
2908 if (!list_empty(&head->list)) {
2909 kbuf = list_last_entry(&head->list, struct io_buffer,
2911 list_del(&kbuf->list);
2914 xa_erase(&req->ctx->io_buffers, bgid);
2916 if (*len > kbuf->len)
2919 kbuf = ERR_PTR(-ENOBUFS);
2922 io_ring_submit_unlock(req->ctx, needs_lock);
2927 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2930 struct io_buffer *kbuf;
2933 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2934 bgid = req->buf_index;
2935 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2938 req->rw.addr = (u64) (unsigned long) kbuf;
2939 req->flags |= REQ_F_BUFFER_SELECTED;
2940 return u64_to_user_ptr(kbuf->addr);
2943 #ifdef CONFIG_COMPAT
2944 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2947 struct compat_iovec __user *uiov;
2948 compat_ssize_t clen;
2952 uiov = u64_to_user_ptr(req->rw.addr);
2953 if (!access_ok(uiov, sizeof(*uiov)))
2955 if (__get_user(clen, &uiov->iov_len))
2961 buf = io_rw_buffer_select(req, &len, needs_lock);
2963 return PTR_ERR(buf);
2964 iov[0].iov_base = buf;
2965 iov[0].iov_len = (compat_size_t) len;
2970 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2973 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2977 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2980 len = iov[0].iov_len;
2983 buf = io_rw_buffer_select(req, &len, needs_lock);
2985 return PTR_ERR(buf);
2986 iov[0].iov_base = buf;
2987 iov[0].iov_len = len;
2991 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2994 if (req->flags & REQ_F_BUFFER_SELECTED) {
2995 struct io_buffer *kbuf;
2997 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2998 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2999 iov[0].iov_len = kbuf->len;
3002 if (req->rw.len != 1)
3005 #ifdef CONFIG_COMPAT
3006 if (req->ctx->compat)
3007 return io_compat_import(req, iov, needs_lock);
3010 return __io_iov_buffer_select(req, iov, needs_lock);
3013 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3014 struct iov_iter *iter, bool needs_lock)
3016 void __user *buf = u64_to_user_ptr(req->rw.addr);
3017 size_t sqe_len = req->rw.len;
3018 u8 opcode = req->opcode;
3021 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3023 return io_import_fixed(req, rw, iter);
3026 /* buffer index only valid with fixed read/write, or buffer select */
3027 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3030 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3031 if (req->flags & REQ_F_BUFFER_SELECT) {
3032 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3034 return PTR_ERR(buf);
3035 req->rw.len = sqe_len;
3038 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3043 if (req->flags & REQ_F_BUFFER_SELECT) {
3044 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3046 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3051 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3055 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3057 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3061 * For files that don't have ->read_iter() and ->write_iter(), handle them
3062 * by looping over ->read() or ->write() manually.
3064 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3066 struct kiocb *kiocb = &req->rw.kiocb;
3067 struct file *file = req->file;
3071 * Don't support polled IO through this interface, and we can't
3072 * support non-blocking either. For the latter, this just causes
3073 * the kiocb to be handled from an async context.
3075 if (kiocb->ki_flags & IOCB_HIPRI)
3077 if (kiocb->ki_flags & IOCB_NOWAIT)
3080 while (iov_iter_count(iter)) {
3084 if (!iov_iter_is_bvec(iter)) {
3085 iovec = iov_iter_iovec(iter);
3087 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3088 iovec.iov_len = req->rw.len;
3092 nr = file->f_op->read(file, iovec.iov_base,
3093 iovec.iov_len, io_kiocb_ppos(kiocb));
3095 nr = file->f_op->write(file, iovec.iov_base,
3096 iovec.iov_len, io_kiocb_ppos(kiocb));
3105 if (nr != iovec.iov_len)
3109 iov_iter_advance(iter, nr);
3115 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3116 const struct iovec *fast_iov, struct iov_iter *iter)
3118 struct io_async_rw *rw = req->async_data;
3120 memcpy(&rw->iter, iter, sizeof(*iter));
3121 rw->free_iovec = iovec;
3123 /* can only be fixed buffers, no need to do anything */
3124 if (iov_iter_is_bvec(iter))
3127 unsigned iov_off = 0;
3129 rw->iter.iov = rw->fast_iov;
3130 if (iter->iov != fast_iov) {
3131 iov_off = iter->iov - fast_iov;
3132 rw->iter.iov += iov_off;
3134 if (rw->fast_iov != fast_iov)
3135 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3136 sizeof(struct iovec) * iter->nr_segs);
3138 req->flags |= REQ_F_NEED_CLEANUP;
3142 static inline int io_alloc_async_data(struct io_kiocb *req)
3144 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3145 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3146 return req->async_data == NULL;
3149 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3150 const struct iovec *fast_iov,
3151 struct iov_iter *iter, bool force)
3153 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3155 if (!req->async_data) {
3156 if (io_alloc_async_data(req)) {
3161 io_req_map_rw(req, iovec, fast_iov, iter);
3166 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3168 struct io_async_rw *iorw = req->async_data;
3169 struct iovec *iov = iorw->fast_iov;
3172 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3173 if (unlikely(ret < 0))
3176 iorw->bytes_done = 0;
3177 iorw->free_iovec = iov;
3179 req->flags |= REQ_F_NEED_CLEANUP;
3183 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3185 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3187 return io_prep_rw(req, sqe);
3191 * This is our waitqueue callback handler, registered through lock_page_async()
3192 * when we initially tried to do the IO with the iocb armed our waitqueue.
3193 * This gets called when the page is unlocked, and we generally expect that to
3194 * happen when the page IO is completed and the page is now uptodate. This will
3195 * queue a task_work based retry of the operation, attempting to copy the data
3196 * again. If the latter fails because the page was NOT uptodate, then we will
3197 * do a thread based blocking retry of the operation. That's the unexpected
3200 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3201 int sync, void *arg)
3203 struct wait_page_queue *wpq;
3204 struct io_kiocb *req = wait->private;
3205 struct wait_page_key *key = arg;
3207 wpq = container_of(wait, struct wait_page_queue, wait);
3209 if (!wake_page_match(wpq, key))
3212 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3213 list_del_init(&wait->entry);
3215 /* submit ref gets dropped, acquire a new one */
3217 io_req_task_queue(req);
3222 * This controls whether a given IO request should be armed for async page
3223 * based retry. If we return false here, the request is handed to the async
3224 * worker threads for retry. If we're doing buffered reads on a regular file,
3225 * we prepare a private wait_page_queue entry and retry the operation. This
3226 * will either succeed because the page is now uptodate and unlocked, or it
3227 * will register a callback when the page is unlocked at IO completion. Through
3228 * that callback, io_uring uses task_work to setup a retry of the operation.
3229 * That retry will attempt the buffered read again. The retry will generally
3230 * succeed, or in rare cases where it fails, we then fall back to using the
3231 * async worker threads for a blocking retry.
3233 static bool io_rw_should_retry(struct io_kiocb *req)
3235 struct io_async_rw *rw = req->async_data;
3236 struct wait_page_queue *wait = &rw->wpq;
3237 struct kiocb *kiocb = &req->rw.kiocb;
3239 /* never retry for NOWAIT, we just complete with -EAGAIN */
3240 if (req->flags & REQ_F_NOWAIT)
3243 /* Only for buffered IO */
3244 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3248 * just use poll if we can, and don't attempt if the fs doesn't
3249 * support callback based unlocks
3251 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3254 wait->wait.func = io_async_buf_func;
3255 wait->wait.private = req;
3256 wait->wait.flags = 0;
3257 INIT_LIST_HEAD(&wait->wait.entry);
3258 kiocb->ki_flags |= IOCB_WAITQ;
3259 kiocb->ki_flags &= ~IOCB_NOWAIT;
3260 kiocb->ki_waitq = wait;
3264 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3266 if (req->file->f_op->read_iter)
3267 return call_read_iter(req->file, &req->rw.kiocb, iter);
3268 else if (req->file->f_op->read)
3269 return loop_rw_iter(READ, req, iter);
3274 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3276 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3277 struct kiocb *kiocb = &req->rw.kiocb;
3278 struct iov_iter __iter, *iter = &__iter;
3279 struct io_async_rw *rw = req->async_data;
3280 ssize_t io_size, ret, ret2;
3281 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3287 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3291 io_size = iov_iter_count(iter);
3292 req->result = io_size;
3294 /* Ensure we clear previously set non-block flag */
3295 if (!force_nonblock)
3296 kiocb->ki_flags &= ~IOCB_NOWAIT;
3298 kiocb->ki_flags |= IOCB_NOWAIT;
3300 /* If the file doesn't support async, just async punt */
3301 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3302 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3303 return ret ?: -EAGAIN;
3306 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3307 if (unlikely(ret)) {
3312 ret = io_iter_do_read(req, iter);
3314 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3315 req->flags &= ~REQ_F_REISSUE;
3316 /* IOPOLL retry should happen for io-wq threads */
3317 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3319 /* no retry on NONBLOCK nor RWF_NOWAIT */
3320 if (req->flags & REQ_F_NOWAIT)
3322 /* some cases will consume bytes even on error returns */
3323 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3325 } else if (ret == -EIOCBQUEUED) {
3327 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3328 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3329 /* read all, failed, already did sync or don't want to retry */
3333 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3338 rw = req->async_data;
3339 /* now use our persistent iterator, if we aren't already */
3344 rw->bytes_done += ret;
3345 /* if we can retry, do so with the callbacks armed */
3346 if (!io_rw_should_retry(req)) {
3347 kiocb->ki_flags &= ~IOCB_WAITQ;
3352 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3353 * we get -EIOCBQUEUED, then we'll get a notification when the
3354 * desired page gets unlocked. We can also get a partial read
3355 * here, and if we do, then just retry at the new offset.
3357 ret = io_iter_do_read(req, iter);
3358 if (ret == -EIOCBQUEUED)
3360 /* we got some bytes, but not all. retry. */
3361 kiocb->ki_flags &= ~IOCB_WAITQ;
3362 } while (ret > 0 && ret < io_size);
3364 kiocb_done(kiocb, ret, issue_flags);
3366 /* it's faster to check here then delegate to kfree */
3372 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3374 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3376 return io_prep_rw(req, sqe);
3379 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3381 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3382 struct kiocb *kiocb = &req->rw.kiocb;
3383 struct iov_iter __iter, *iter = &__iter;
3384 struct io_async_rw *rw = req->async_data;
3385 ssize_t ret, ret2, io_size;
3386 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3392 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3396 io_size = iov_iter_count(iter);
3397 req->result = io_size;
3399 /* Ensure we clear previously set non-block flag */
3400 if (!force_nonblock)
3401 kiocb->ki_flags &= ~IOCB_NOWAIT;
3403 kiocb->ki_flags |= IOCB_NOWAIT;
3405 /* If the file doesn't support async, just async punt */
3406 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3409 /* file path doesn't support NOWAIT for non-direct_IO */
3410 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3411 (req->flags & REQ_F_ISREG))
3414 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3419 * Open-code file_start_write here to grab freeze protection,
3420 * which will be released by another thread in
3421 * io_complete_rw(). Fool lockdep by telling it the lock got
3422 * released so that it doesn't complain about the held lock when
3423 * we return to userspace.
3425 if (req->flags & REQ_F_ISREG) {
3426 sb_start_write(file_inode(req->file)->i_sb);
3427 __sb_writers_release(file_inode(req->file)->i_sb,
3430 kiocb->ki_flags |= IOCB_WRITE;
3432 if (req->file->f_op->write_iter)
3433 ret2 = call_write_iter(req->file, kiocb, iter);
3434 else if (req->file->f_op->write)
3435 ret2 = loop_rw_iter(WRITE, req, iter);
3439 if (req->flags & REQ_F_REISSUE) {
3440 req->flags &= ~REQ_F_REISSUE;
3445 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3446 * retry them without IOCB_NOWAIT.
3448 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3450 /* no retry on NONBLOCK nor RWF_NOWAIT */
3451 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3453 if (!force_nonblock || ret2 != -EAGAIN) {
3454 /* IOPOLL retry should happen for io-wq threads */
3455 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3458 kiocb_done(kiocb, ret2, issue_flags);
3461 /* some cases will consume bytes even on error returns */
3462 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3463 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3464 return ret ?: -EAGAIN;
3467 /* it's reportedly faster than delegating the null check to kfree() */
3473 static int io_renameat_prep(struct io_kiocb *req,
3474 const struct io_uring_sqe *sqe)
3476 struct io_rename *ren = &req->rename;
3477 const char __user *oldf, *newf;
3479 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3481 if (sqe->ioprio || sqe->buf_index)
3483 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3486 ren->old_dfd = READ_ONCE(sqe->fd);
3487 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3488 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3489 ren->new_dfd = READ_ONCE(sqe->len);
3490 ren->flags = READ_ONCE(sqe->rename_flags);
3492 ren->oldpath = getname(oldf);
3493 if (IS_ERR(ren->oldpath))
3494 return PTR_ERR(ren->oldpath);
3496 ren->newpath = getname(newf);
3497 if (IS_ERR(ren->newpath)) {
3498 putname(ren->oldpath);
3499 return PTR_ERR(ren->newpath);
3502 req->flags |= REQ_F_NEED_CLEANUP;
3506 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3508 struct io_rename *ren = &req->rename;
3511 if (issue_flags & IO_URING_F_NONBLOCK)
3514 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3515 ren->newpath, ren->flags);
3517 req->flags &= ~REQ_F_NEED_CLEANUP;
3520 io_req_complete(req, ret);
3524 static int io_unlinkat_prep(struct io_kiocb *req,
3525 const struct io_uring_sqe *sqe)
3527 struct io_unlink *un = &req->unlink;
3528 const char __user *fname;
3530 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3532 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3534 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3537 un->dfd = READ_ONCE(sqe->fd);
3539 un->flags = READ_ONCE(sqe->unlink_flags);
3540 if (un->flags & ~AT_REMOVEDIR)
3543 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3544 un->filename = getname(fname);
3545 if (IS_ERR(un->filename))
3546 return PTR_ERR(un->filename);
3548 req->flags |= REQ_F_NEED_CLEANUP;
3552 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3554 struct io_unlink *un = &req->unlink;
3557 if (issue_flags & IO_URING_F_NONBLOCK)
3560 if (un->flags & AT_REMOVEDIR)
3561 ret = do_rmdir(un->dfd, un->filename);
3563 ret = do_unlinkat(un->dfd, un->filename);
3565 req->flags &= ~REQ_F_NEED_CLEANUP;
3568 io_req_complete(req, ret);
3572 static int io_shutdown_prep(struct io_kiocb *req,
3573 const struct io_uring_sqe *sqe)
3575 #if defined(CONFIG_NET)
3576 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3578 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3582 req->shutdown.how = READ_ONCE(sqe->len);
3589 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3591 #if defined(CONFIG_NET)
3592 struct socket *sock;
3595 if (issue_flags & IO_URING_F_NONBLOCK)
3598 sock = sock_from_file(req->file);
3599 if (unlikely(!sock))
3602 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3605 io_req_complete(req, ret);
3612 static int __io_splice_prep(struct io_kiocb *req,
3613 const struct io_uring_sqe *sqe)
3615 struct io_splice *sp = &req->splice;
3616 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3618 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3622 sp->len = READ_ONCE(sqe->len);
3623 sp->flags = READ_ONCE(sqe->splice_flags);
3625 if (unlikely(sp->flags & ~valid_flags))
3628 sp->file_in = io_file_get(req->ctx, NULL, req,
3629 READ_ONCE(sqe->splice_fd_in),
3630 (sp->flags & SPLICE_F_FD_IN_FIXED));
3633 req->flags |= REQ_F_NEED_CLEANUP;
3637 static int io_tee_prep(struct io_kiocb *req,
3638 const struct io_uring_sqe *sqe)
3640 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3642 return __io_splice_prep(req, sqe);
3645 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3647 struct io_splice *sp = &req->splice;
3648 struct file *in = sp->file_in;
3649 struct file *out = sp->file_out;
3650 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3653 if (issue_flags & IO_URING_F_NONBLOCK)
3656 ret = do_tee(in, out, sp->len, flags);
3658 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3660 req->flags &= ~REQ_F_NEED_CLEANUP;
3664 io_req_complete(req, ret);
3668 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3670 struct io_splice *sp = &req->splice;
3672 sp->off_in = READ_ONCE(sqe->splice_off_in);
3673 sp->off_out = READ_ONCE(sqe->off);
3674 return __io_splice_prep(req, sqe);
3677 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3679 struct io_splice *sp = &req->splice;
3680 struct file *in = sp->file_in;
3681 struct file *out = sp->file_out;
3682 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3683 loff_t *poff_in, *poff_out;
3686 if (issue_flags & IO_URING_F_NONBLOCK)
3689 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3690 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3693 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3695 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3697 req->flags &= ~REQ_F_NEED_CLEANUP;
3701 io_req_complete(req, ret);
3706 * IORING_OP_NOP just posts a completion event, nothing else.
3708 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3710 struct io_ring_ctx *ctx = req->ctx;
3712 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3715 __io_req_complete(req, issue_flags, 0, 0);
3719 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3721 struct io_ring_ctx *ctx = req->ctx;
3726 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3728 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3731 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3732 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3735 req->sync.off = READ_ONCE(sqe->off);
3736 req->sync.len = READ_ONCE(sqe->len);
3740 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3742 loff_t end = req->sync.off + req->sync.len;
3745 /* fsync always requires a blocking context */
3746 if (issue_flags & IO_URING_F_NONBLOCK)
3749 ret = vfs_fsync_range(req->file, req->sync.off,
3750 end > 0 ? end : LLONG_MAX,
3751 req->sync.flags & IORING_FSYNC_DATASYNC);
3754 io_req_complete(req, ret);
3758 static int io_fallocate_prep(struct io_kiocb *req,
3759 const struct io_uring_sqe *sqe)
3761 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3763 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3766 req->sync.off = READ_ONCE(sqe->off);
3767 req->sync.len = READ_ONCE(sqe->addr);
3768 req->sync.mode = READ_ONCE(sqe->len);
3772 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3776 /* fallocate always requiring blocking context */
3777 if (issue_flags & IO_URING_F_NONBLOCK)
3779 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3783 io_req_complete(req, ret);
3787 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3789 const char __user *fname;
3792 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3794 if (unlikely(sqe->ioprio || sqe->buf_index))
3796 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3799 /* open.how should be already initialised */
3800 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3801 req->open.how.flags |= O_LARGEFILE;
3803 req->open.dfd = READ_ONCE(sqe->fd);
3804 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3805 req->open.filename = getname(fname);
3806 if (IS_ERR(req->open.filename)) {
3807 ret = PTR_ERR(req->open.filename);
3808 req->open.filename = NULL;
3811 req->open.nofile = rlimit(RLIMIT_NOFILE);
3812 req->flags |= REQ_F_NEED_CLEANUP;
3816 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3818 u64 mode = READ_ONCE(sqe->len);
3819 u64 flags = READ_ONCE(sqe->open_flags);
3821 req->open.how = build_open_how(flags, mode);
3822 return __io_openat_prep(req, sqe);
3825 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3827 struct open_how __user *how;
3831 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3832 len = READ_ONCE(sqe->len);
3833 if (len < OPEN_HOW_SIZE_VER0)
3836 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3841 return __io_openat_prep(req, sqe);
3844 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3846 struct open_flags op;
3849 bool resolve_nonblock;
3852 ret = build_open_flags(&req->open.how, &op);
3855 nonblock_set = op.open_flag & O_NONBLOCK;
3856 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3857 if (issue_flags & IO_URING_F_NONBLOCK) {
3859 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3860 * it'll always -EAGAIN
3862 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3864 op.lookup_flags |= LOOKUP_CACHED;
3865 op.open_flag |= O_NONBLOCK;
3868 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3872 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3875 * We could hang on to this 'fd' on retrying, but seems like
3876 * marginal gain for something that is now known to be a slower
3877 * path. So just put it, and we'll get a new one when we retry.
3881 ret = PTR_ERR(file);
3882 /* only retry if RESOLVE_CACHED wasn't already set by application */
3883 if (ret == -EAGAIN &&
3884 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3889 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3890 file->f_flags &= ~O_NONBLOCK;
3891 fsnotify_open(file);
3892 fd_install(ret, file);
3894 putname(req->open.filename);
3895 req->flags &= ~REQ_F_NEED_CLEANUP;
3898 __io_req_complete(req, issue_flags, ret, 0);
3902 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3904 return io_openat2(req, issue_flags);
3907 static int io_remove_buffers_prep(struct io_kiocb *req,
3908 const struct io_uring_sqe *sqe)
3910 struct io_provide_buf *p = &req->pbuf;
3913 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3916 tmp = READ_ONCE(sqe->fd);
3917 if (!tmp || tmp > USHRT_MAX)
3920 memset(p, 0, sizeof(*p));
3922 p->bgid = READ_ONCE(sqe->buf_group);
3926 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3927 int bgid, unsigned nbufs)
3931 /* shouldn't happen */
3935 /* the head kbuf is the list itself */
3936 while (!list_empty(&buf->list)) {
3937 struct io_buffer *nxt;
3939 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3940 list_del(&nxt->list);
3947 xa_erase(&ctx->io_buffers, bgid);
3952 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3954 struct io_provide_buf *p = &req->pbuf;
3955 struct io_ring_ctx *ctx = req->ctx;
3956 struct io_buffer *head;
3958 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3960 io_ring_submit_lock(ctx, !force_nonblock);
3962 lockdep_assert_held(&ctx->uring_lock);
3965 head = xa_load(&ctx->io_buffers, p->bgid);
3967 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3971 /* complete before unlock, IOPOLL may need the lock */
3972 __io_req_complete(req, issue_flags, ret, 0);
3973 io_ring_submit_unlock(ctx, !force_nonblock);
3977 static int io_provide_buffers_prep(struct io_kiocb *req,
3978 const struct io_uring_sqe *sqe)
3980 unsigned long size, tmp_check;
3981 struct io_provide_buf *p = &req->pbuf;
3984 if (sqe->ioprio || sqe->rw_flags)
3987 tmp = READ_ONCE(sqe->fd);
3988 if (!tmp || tmp > USHRT_MAX)
3991 p->addr = READ_ONCE(sqe->addr);
3992 p->len = READ_ONCE(sqe->len);
3994 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3997 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4000 size = (unsigned long)p->len * p->nbufs;
4001 if (!access_ok(u64_to_user_ptr(p->addr), size))
4004 p->bgid = READ_ONCE(sqe->buf_group);
4005 tmp = READ_ONCE(sqe->off);
4006 if (tmp > USHRT_MAX)
4012 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4014 struct io_buffer *buf;
4015 u64 addr = pbuf->addr;
4016 int i, bid = pbuf->bid;
4018 for (i = 0; i < pbuf->nbufs; i++) {
4019 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4024 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4029 INIT_LIST_HEAD(&buf->list);
4032 list_add_tail(&buf->list, &(*head)->list);
4036 return i ? i : -ENOMEM;
4039 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4041 struct io_provide_buf *p = &req->pbuf;
4042 struct io_ring_ctx *ctx = req->ctx;
4043 struct io_buffer *head, *list;
4045 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4047 io_ring_submit_lock(ctx, !force_nonblock);
4049 lockdep_assert_held(&ctx->uring_lock);
4051 list = head = xa_load(&ctx->io_buffers, p->bgid);
4053 ret = io_add_buffers(p, &head);
4054 if (ret >= 0 && !list) {
4055 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4057 __io_remove_buffers(ctx, head, p->bgid, -1U);
4061 /* complete before unlock, IOPOLL may need the lock */
4062 __io_req_complete(req, issue_flags, ret, 0);
4063 io_ring_submit_unlock(ctx, !force_nonblock);
4067 static int io_epoll_ctl_prep(struct io_kiocb *req,
4068 const struct io_uring_sqe *sqe)
4070 #if defined(CONFIG_EPOLL)
4071 if (sqe->ioprio || sqe->buf_index)
4073 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4076 req->epoll.epfd = READ_ONCE(sqe->fd);
4077 req->epoll.op = READ_ONCE(sqe->len);
4078 req->epoll.fd = READ_ONCE(sqe->off);
4080 if (ep_op_has_event(req->epoll.op)) {
4081 struct epoll_event __user *ev;
4083 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4084 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4094 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4096 #if defined(CONFIG_EPOLL)
4097 struct io_epoll *ie = &req->epoll;
4099 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4101 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4102 if (force_nonblock && ret == -EAGAIN)
4107 __io_req_complete(req, issue_flags, ret, 0);
4114 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4116 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4117 if (sqe->ioprio || sqe->buf_index || sqe->off)
4119 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4122 req->madvise.addr = READ_ONCE(sqe->addr);
4123 req->madvise.len = READ_ONCE(sqe->len);
4124 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4131 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4133 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4134 struct io_madvise *ma = &req->madvise;
4137 if (issue_flags & IO_URING_F_NONBLOCK)
4140 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4143 io_req_complete(req, ret);
4150 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4152 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4154 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4157 req->fadvise.offset = READ_ONCE(sqe->off);
4158 req->fadvise.len = READ_ONCE(sqe->len);
4159 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4163 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4165 struct io_fadvise *fa = &req->fadvise;
4168 if (issue_flags & IO_URING_F_NONBLOCK) {
4169 switch (fa->advice) {
4170 case POSIX_FADV_NORMAL:
4171 case POSIX_FADV_RANDOM:
4172 case POSIX_FADV_SEQUENTIAL:
4179 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4182 __io_req_complete(req, issue_flags, ret, 0);
4186 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4188 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4190 if (sqe->ioprio || sqe->buf_index)
4192 if (req->flags & REQ_F_FIXED_FILE)
4195 req->statx.dfd = READ_ONCE(sqe->fd);
4196 req->statx.mask = READ_ONCE(sqe->len);
4197 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4198 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4199 req->statx.flags = READ_ONCE(sqe->statx_flags);
4204 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4206 struct io_statx *ctx = &req->statx;
4209 if (issue_flags & IO_URING_F_NONBLOCK)
4212 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4217 io_req_complete(req, ret);
4221 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4223 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4225 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4226 sqe->rw_flags || sqe->buf_index)
4228 if (req->flags & REQ_F_FIXED_FILE)
4231 req->close.fd = READ_ONCE(sqe->fd);
4235 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4237 struct files_struct *files = current->files;
4238 struct io_close *close = &req->close;
4239 struct fdtable *fdt;
4240 struct file *file = NULL;
4243 spin_lock(&files->file_lock);
4244 fdt = files_fdtable(files);
4245 if (close->fd >= fdt->max_fds) {
4246 spin_unlock(&files->file_lock);
4249 file = fdt->fd[close->fd];
4250 if (!file || file->f_op == &io_uring_fops) {
4251 spin_unlock(&files->file_lock);
4256 /* if the file has a flush method, be safe and punt to async */
4257 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4258 spin_unlock(&files->file_lock);
4262 ret = __close_fd_get_file(close->fd, &file);
4263 spin_unlock(&files->file_lock);
4270 /* No ->flush() or already async, safely close from here */
4271 ret = filp_close(file, current->files);
4277 __io_req_complete(req, issue_flags, ret, 0);
4281 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4283 struct io_ring_ctx *ctx = req->ctx;
4285 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4287 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4290 req->sync.off = READ_ONCE(sqe->off);
4291 req->sync.len = READ_ONCE(sqe->len);
4292 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4296 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4300 /* sync_file_range always requires a blocking context */
4301 if (issue_flags & IO_URING_F_NONBLOCK)
4304 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4308 io_req_complete(req, ret);
4312 #if defined(CONFIG_NET)
4313 static int io_setup_async_msg(struct io_kiocb *req,
4314 struct io_async_msghdr *kmsg)
4316 struct io_async_msghdr *async_msg = req->async_data;
4320 if (io_alloc_async_data(req)) {
4321 kfree(kmsg->free_iov);
4324 async_msg = req->async_data;
4325 req->flags |= REQ_F_NEED_CLEANUP;
4326 memcpy(async_msg, kmsg, sizeof(*kmsg));
4327 async_msg->msg.msg_name = &async_msg->addr;
4328 /* if were using fast_iov, set it to the new one */
4329 if (!async_msg->free_iov)
4330 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4335 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4336 struct io_async_msghdr *iomsg)
4338 iomsg->msg.msg_name = &iomsg->addr;
4339 iomsg->free_iov = iomsg->fast_iov;
4340 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4341 req->sr_msg.msg_flags, &iomsg->free_iov);
4344 static int io_sendmsg_prep_async(struct io_kiocb *req)
4348 ret = io_sendmsg_copy_hdr(req, req->async_data);
4350 req->flags |= REQ_F_NEED_CLEANUP;
4354 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4356 struct io_sr_msg *sr = &req->sr_msg;
4358 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4361 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4362 sr->len = READ_ONCE(sqe->len);
4363 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4364 if (sr->msg_flags & MSG_DONTWAIT)
4365 req->flags |= REQ_F_NOWAIT;
4367 #ifdef CONFIG_COMPAT
4368 if (req->ctx->compat)
4369 sr->msg_flags |= MSG_CMSG_COMPAT;
4374 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4376 struct io_async_msghdr iomsg, *kmsg;
4377 struct socket *sock;
4382 sock = sock_from_file(req->file);
4383 if (unlikely(!sock))
4386 kmsg = req->async_data;
4388 ret = io_sendmsg_copy_hdr(req, &iomsg);
4394 flags = req->sr_msg.msg_flags;
4395 if (issue_flags & IO_URING_F_NONBLOCK)
4396 flags |= MSG_DONTWAIT;
4397 if (flags & MSG_WAITALL)
4398 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4400 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4401 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4402 return io_setup_async_msg(req, kmsg);
4403 if (ret == -ERESTARTSYS)
4406 /* fast path, check for non-NULL to avoid function call */
4408 kfree(kmsg->free_iov);
4409 req->flags &= ~REQ_F_NEED_CLEANUP;
4412 __io_req_complete(req, issue_flags, ret, 0);
4416 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4418 struct io_sr_msg *sr = &req->sr_msg;
4421 struct socket *sock;
4426 sock = sock_from_file(req->file);
4427 if (unlikely(!sock))
4430 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4434 msg.msg_name = NULL;
4435 msg.msg_control = NULL;
4436 msg.msg_controllen = 0;
4437 msg.msg_namelen = 0;
4439 flags = req->sr_msg.msg_flags;
4440 if (issue_flags & IO_URING_F_NONBLOCK)
4441 flags |= MSG_DONTWAIT;
4442 if (flags & MSG_WAITALL)
4443 min_ret = iov_iter_count(&msg.msg_iter);
4445 msg.msg_flags = flags;
4446 ret = sock_sendmsg(sock, &msg);
4447 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4449 if (ret == -ERESTARTSYS)
4454 __io_req_complete(req, issue_flags, ret, 0);
4458 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4459 struct io_async_msghdr *iomsg)
4461 struct io_sr_msg *sr = &req->sr_msg;
4462 struct iovec __user *uiov;
4466 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4467 &iomsg->uaddr, &uiov, &iov_len);
4471 if (req->flags & REQ_F_BUFFER_SELECT) {
4474 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4476 sr->len = iomsg->fast_iov[0].iov_len;
4477 iomsg->free_iov = NULL;
4479 iomsg->free_iov = iomsg->fast_iov;
4480 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4481 &iomsg->free_iov, &iomsg->msg.msg_iter,
4490 #ifdef CONFIG_COMPAT
4491 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4492 struct io_async_msghdr *iomsg)
4494 struct io_sr_msg *sr = &req->sr_msg;
4495 struct compat_iovec __user *uiov;
4500 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4505 uiov = compat_ptr(ptr);
4506 if (req->flags & REQ_F_BUFFER_SELECT) {
4507 compat_ssize_t clen;
4511 if (!access_ok(uiov, sizeof(*uiov)))
4513 if (__get_user(clen, &uiov->iov_len))
4518 iomsg->free_iov = NULL;
4520 iomsg->free_iov = iomsg->fast_iov;
4521 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4522 UIO_FASTIOV, &iomsg->free_iov,
4523 &iomsg->msg.msg_iter, true);
4532 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4533 struct io_async_msghdr *iomsg)
4535 iomsg->msg.msg_name = &iomsg->addr;
4537 #ifdef CONFIG_COMPAT
4538 if (req->ctx->compat)
4539 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4542 return __io_recvmsg_copy_hdr(req, iomsg);
4545 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4548 struct io_sr_msg *sr = &req->sr_msg;
4549 struct io_buffer *kbuf;
4551 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4556 req->flags |= REQ_F_BUFFER_SELECTED;
4560 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4562 return io_put_kbuf(req, req->sr_msg.kbuf);
4565 static int io_recvmsg_prep_async(struct io_kiocb *req)
4569 ret = io_recvmsg_copy_hdr(req, req->async_data);
4571 req->flags |= REQ_F_NEED_CLEANUP;
4575 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4577 struct io_sr_msg *sr = &req->sr_msg;
4579 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4582 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4583 sr->len = READ_ONCE(sqe->len);
4584 sr->bgid = READ_ONCE(sqe->buf_group);
4585 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4586 if (sr->msg_flags & MSG_DONTWAIT)
4587 req->flags |= REQ_F_NOWAIT;
4589 #ifdef CONFIG_COMPAT
4590 if (req->ctx->compat)
4591 sr->msg_flags |= MSG_CMSG_COMPAT;
4596 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4598 struct io_async_msghdr iomsg, *kmsg;
4599 struct socket *sock;
4600 struct io_buffer *kbuf;
4603 int ret, cflags = 0;
4604 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4606 sock = sock_from_file(req->file);
4607 if (unlikely(!sock))
4610 kmsg = req->async_data;
4612 ret = io_recvmsg_copy_hdr(req, &iomsg);
4618 if (req->flags & REQ_F_BUFFER_SELECT) {
4619 kbuf = io_recv_buffer_select(req, !force_nonblock);
4621 return PTR_ERR(kbuf);
4622 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4623 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4624 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4625 1, req->sr_msg.len);
4628 flags = req->sr_msg.msg_flags;
4630 flags |= MSG_DONTWAIT;
4631 if (flags & MSG_WAITALL)
4632 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4634 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4635 kmsg->uaddr, flags);
4636 if (force_nonblock && ret == -EAGAIN)
4637 return io_setup_async_msg(req, kmsg);
4638 if (ret == -ERESTARTSYS)
4641 if (req->flags & REQ_F_BUFFER_SELECTED)
4642 cflags = io_put_recv_kbuf(req);
4643 /* fast path, check for non-NULL to avoid function call */
4645 kfree(kmsg->free_iov);
4646 req->flags &= ~REQ_F_NEED_CLEANUP;
4647 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4649 __io_req_complete(req, issue_flags, ret, cflags);
4653 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4655 struct io_buffer *kbuf;
4656 struct io_sr_msg *sr = &req->sr_msg;
4658 void __user *buf = sr->buf;
4659 struct socket *sock;
4663 int ret, cflags = 0;
4664 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4666 sock = sock_from_file(req->file);
4667 if (unlikely(!sock))
4670 if (req->flags & REQ_F_BUFFER_SELECT) {
4671 kbuf = io_recv_buffer_select(req, !force_nonblock);
4673 return PTR_ERR(kbuf);
4674 buf = u64_to_user_ptr(kbuf->addr);
4677 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4681 msg.msg_name = NULL;
4682 msg.msg_control = NULL;
4683 msg.msg_controllen = 0;
4684 msg.msg_namelen = 0;
4685 msg.msg_iocb = NULL;
4688 flags = req->sr_msg.msg_flags;
4690 flags |= MSG_DONTWAIT;
4691 if (flags & MSG_WAITALL)
4692 min_ret = iov_iter_count(&msg.msg_iter);
4694 ret = sock_recvmsg(sock, &msg, flags);
4695 if (force_nonblock && ret == -EAGAIN)
4697 if (ret == -ERESTARTSYS)
4700 if (req->flags & REQ_F_BUFFER_SELECTED)
4701 cflags = io_put_recv_kbuf(req);
4702 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4704 __io_req_complete(req, issue_flags, ret, cflags);
4708 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4710 struct io_accept *accept = &req->accept;
4712 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4714 if (sqe->ioprio || sqe->len || sqe->buf_index)
4717 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4718 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4719 accept->flags = READ_ONCE(sqe->accept_flags);
4720 accept->nofile = rlimit(RLIMIT_NOFILE);
4724 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4726 struct io_accept *accept = &req->accept;
4727 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4728 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4731 if (req->file->f_flags & O_NONBLOCK)
4732 req->flags |= REQ_F_NOWAIT;
4734 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4735 accept->addr_len, accept->flags,
4737 if (ret == -EAGAIN && force_nonblock)
4740 if (ret == -ERESTARTSYS)
4744 __io_req_complete(req, issue_flags, ret, 0);
4748 static int io_connect_prep_async(struct io_kiocb *req)
4750 struct io_async_connect *io = req->async_data;
4751 struct io_connect *conn = &req->connect;
4753 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4756 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4758 struct io_connect *conn = &req->connect;
4760 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4762 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4765 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4766 conn->addr_len = READ_ONCE(sqe->addr2);
4770 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4772 struct io_async_connect __io, *io;
4773 unsigned file_flags;
4775 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4777 if (req->async_data) {
4778 io = req->async_data;
4780 ret = move_addr_to_kernel(req->connect.addr,
4781 req->connect.addr_len,
4788 file_flags = force_nonblock ? O_NONBLOCK : 0;
4790 ret = __sys_connect_file(req->file, &io->address,
4791 req->connect.addr_len, file_flags);
4792 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4793 if (req->async_data)
4795 if (io_alloc_async_data(req)) {
4799 memcpy(req->async_data, &__io, sizeof(__io));
4802 if (ret == -ERESTARTSYS)
4807 __io_req_complete(req, issue_flags, ret, 0);
4810 #else /* !CONFIG_NET */
4811 #define IO_NETOP_FN(op) \
4812 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4814 return -EOPNOTSUPP; \
4817 #define IO_NETOP_PREP(op) \
4819 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4821 return -EOPNOTSUPP; \
4824 #define IO_NETOP_PREP_ASYNC(op) \
4826 static int io_##op##_prep_async(struct io_kiocb *req) \
4828 return -EOPNOTSUPP; \
4831 IO_NETOP_PREP_ASYNC(sendmsg);
4832 IO_NETOP_PREP_ASYNC(recvmsg);
4833 IO_NETOP_PREP_ASYNC(connect);
4834 IO_NETOP_PREP(accept);
4837 #endif /* CONFIG_NET */
4839 struct io_poll_table {
4840 struct poll_table_struct pt;
4841 struct io_kiocb *req;
4846 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4847 __poll_t mask, io_req_tw_func_t func)
4849 /* for instances that support it check for an event match first: */
4850 if (mask && !(mask & poll->events))
4853 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4855 list_del_init(&poll->wait.entry);
4858 req->io_task_work.func = func;
4861 * If this fails, then the task is exiting. When a task exits, the
4862 * work gets canceled, so just cancel this request as well instead
4863 * of executing it. We can't safely execute it anyway, as we may not
4864 * have the needed state needed for it anyway.
4866 io_req_task_work_add(req);
4870 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4871 __acquires(&req->ctx->completion_lock)
4873 struct io_ring_ctx *ctx = req->ctx;
4875 if (unlikely(req->task->flags & PF_EXITING))
4876 WRITE_ONCE(poll->canceled, true);
4878 if (!req->result && !READ_ONCE(poll->canceled)) {
4879 struct poll_table_struct pt = { ._key = poll->events };
4881 req->result = vfs_poll(req->file, &pt) & poll->events;
4884 spin_lock_irq(&ctx->completion_lock);
4885 if (!req->result && !READ_ONCE(poll->canceled)) {
4886 add_wait_queue(poll->head, &poll->wait);
4893 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4895 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4896 if (req->opcode == IORING_OP_POLL_ADD)
4897 return req->async_data;
4898 return req->apoll->double_poll;
4901 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4903 if (req->opcode == IORING_OP_POLL_ADD)
4905 return &req->apoll->poll;
4908 static void io_poll_remove_double(struct io_kiocb *req)
4909 __must_hold(&req->ctx->completion_lock)
4911 struct io_poll_iocb *poll = io_poll_get_double(req);
4913 lockdep_assert_held(&req->ctx->completion_lock);
4915 if (poll && poll->head) {
4916 struct wait_queue_head *head = poll->head;
4918 spin_lock(&head->lock);
4919 list_del_init(&poll->wait.entry);
4920 if (poll->wait.private)
4923 spin_unlock(&head->lock);
4927 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4928 __must_hold(&req->ctx->completion_lock)
4930 struct io_ring_ctx *ctx = req->ctx;
4931 unsigned flags = IORING_CQE_F_MORE;
4934 if (READ_ONCE(req->poll.canceled)) {
4936 req->poll.events |= EPOLLONESHOT;
4938 error = mangle_poll(mask);
4940 if (req->poll.events & EPOLLONESHOT)
4942 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4943 req->poll.done = true;
4946 if (flags & IORING_CQE_F_MORE)
4949 io_commit_cqring(ctx);
4950 return !(flags & IORING_CQE_F_MORE);
4953 static void io_poll_task_func(struct io_kiocb *req)
4955 struct io_ring_ctx *ctx = req->ctx;
4956 struct io_kiocb *nxt;
4958 if (io_poll_rewait(req, &req->poll)) {
4959 spin_unlock_irq(&ctx->completion_lock);
4963 done = io_poll_complete(req, req->result);
4965 io_poll_remove_double(req);
4966 hash_del(&req->hash_node);
4969 add_wait_queue(req->poll.head, &req->poll.wait);
4971 spin_unlock_irq(&ctx->completion_lock);
4972 io_cqring_ev_posted(ctx);
4975 nxt = io_put_req_find_next(req);
4977 io_req_task_submit(nxt);
4982 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4983 int sync, void *key)
4985 struct io_kiocb *req = wait->private;
4986 struct io_poll_iocb *poll = io_poll_get_single(req);
4987 __poll_t mask = key_to_poll(key);
4989 /* for instances that support it check for an event match first: */
4990 if (mask && !(mask & poll->events))
4992 if (!(poll->events & EPOLLONESHOT))
4993 return poll->wait.func(&poll->wait, mode, sync, key);
4995 list_del_init(&wait->entry);
5000 spin_lock(&poll->head->lock);
5001 done = list_empty(&poll->wait.entry);
5003 list_del_init(&poll->wait.entry);
5004 /* make sure double remove sees this as being gone */
5005 wait->private = NULL;
5006 spin_unlock(&poll->head->lock);
5008 /* use wait func handler, so it matches the rq type */
5009 poll->wait.func(&poll->wait, mode, sync, key);
5016 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5017 wait_queue_func_t wake_func)
5021 poll->canceled = false;
5022 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5023 /* mask in events that we always want/need */
5024 poll->events = events | IO_POLL_UNMASK;
5025 INIT_LIST_HEAD(&poll->wait.entry);
5026 init_waitqueue_func_entry(&poll->wait, wake_func);
5029 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5030 struct wait_queue_head *head,
5031 struct io_poll_iocb **poll_ptr)
5033 struct io_kiocb *req = pt->req;
5036 * The file being polled uses multiple waitqueues for poll handling
5037 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5040 if (unlikely(pt->nr_entries)) {
5041 struct io_poll_iocb *poll_one = poll;
5043 /* already have a 2nd entry, fail a third attempt */
5045 pt->error = -EINVAL;
5049 * Can't handle multishot for double wait for now, turn it
5050 * into one-shot mode.
5052 if (!(poll_one->events & EPOLLONESHOT))
5053 poll_one->events |= EPOLLONESHOT;
5054 /* double add on the same waitqueue head, ignore */
5055 if (poll_one->head == head)
5057 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5059 pt->error = -ENOMEM;
5062 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5064 poll->wait.private = req;
5071 if (poll->events & EPOLLEXCLUSIVE)
5072 add_wait_queue_exclusive(head, &poll->wait);
5074 add_wait_queue(head, &poll->wait);
5077 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5078 struct poll_table_struct *p)
5080 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5081 struct async_poll *apoll = pt->req->apoll;
5083 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5086 static void io_async_task_func(struct io_kiocb *req)
5088 struct async_poll *apoll = req->apoll;
5089 struct io_ring_ctx *ctx = req->ctx;
5091 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5093 if (io_poll_rewait(req, &apoll->poll)) {
5094 spin_unlock_irq(&ctx->completion_lock);
5098 hash_del(&req->hash_node);
5099 io_poll_remove_double(req);
5100 spin_unlock_irq(&ctx->completion_lock);
5102 if (!READ_ONCE(apoll->poll.canceled))
5103 io_req_task_submit(req);
5105 io_req_complete_failed(req, -ECANCELED);
5108 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5111 struct io_kiocb *req = wait->private;
5112 struct io_poll_iocb *poll = &req->apoll->poll;
5114 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5117 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5120 static void io_poll_req_insert(struct io_kiocb *req)
5122 struct io_ring_ctx *ctx = req->ctx;
5123 struct hlist_head *list;
5125 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5126 hlist_add_head(&req->hash_node, list);
5129 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5130 struct io_poll_iocb *poll,
5131 struct io_poll_table *ipt, __poll_t mask,
5132 wait_queue_func_t wake_func)
5133 __acquires(&ctx->completion_lock)
5135 struct io_ring_ctx *ctx = req->ctx;
5136 bool cancel = false;
5138 INIT_HLIST_NODE(&req->hash_node);
5139 io_init_poll_iocb(poll, mask, wake_func);
5140 poll->file = req->file;
5141 poll->wait.private = req;
5143 ipt->pt._key = mask;
5146 ipt->nr_entries = 0;
5148 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5149 if (unlikely(!ipt->nr_entries) && !ipt->error)
5150 ipt->error = -EINVAL;
5152 spin_lock_irq(&ctx->completion_lock);
5153 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5154 io_poll_remove_double(req);
5155 if (likely(poll->head)) {
5156 spin_lock(&poll->head->lock);
5157 if (unlikely(list_empty(&poll->wait.entry))) {
5163 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5164 list_del_init(&poll->wait.entry);
5166 WRITE_ONCE(poll->canceled, true);
5167 else if (!poll->done) /* actually waiting for an event */
5168 io_poll_req_insert(req);
5169 spin_unlock(&poll->head->lock);
5181 static int io_arm_poll_handler(struct io_kiocb *req)
5183 const struct io_op_def *def = &io_op_defs[req->opcode];
5184 struct io_ring_ctx *ctx = req->ctx;
5185 struct async_poll *apoll;
5186 struct io_poll_table ipt;
5187 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5190 if (!req->file || !file_can_poll(req->file))
5191 return IO_APOLL_ABORTED;
5192 if (req->flags & REQ_F_POLLED)
5193 return IO_APOLL_ABORTED;
5194 if (!def->pollin && !def->pollout)
5195 return IO_APOLL_ABORTED;
5199 mask |= POLLIN | POLLRDNORM;
5201 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5202 if ((req->opcode == IORING_OP_RECVMSG) &&
5203 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5207 mask |= POLLOUT | POLLWRNORM;
5210 /* if we can't nonblock try, then no point in arming a poll handler */
5211 if (!io_file_supports_nowait(req, rw))
5212 return IO_APOLL_ABORTED;
5214 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5215 if (unlikely(!apoll))
5216 return IO_APOLL_ABORTED;
5217 apoll->double_poll = NULL;
5219 req->flags |= REQ_F_POLLED;
5220 ipt.pt._qproc = io_async_queue_proc;
5222 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5224 if (ret || ipt.error) {
5225 spin_unlock_irq(&ctx->completion_lock);
5227 return IO_APOLL_READY;
5228 return IO_APOLL_ABORTED;
5230 spin_unlock_irq(&ctx->completion_lock);
5231 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5232 mask, apoll->poll.events);
5236 static bool __io_poll_remove_one(struct io_kiocb *req,
5237 struct io_poll_iocb *poll, bool do_cancel)
5238 __must_hold(&req->ctx->completion_lock)
5240 bool do_complete = false;
5244 spin_lock(&poll->head->lock);
5246 WRITE_ONCE(poll->canceled, true);
5247 if (!list_empty(&poll->wait.entry)) {
5248 list_del_init(&poll->wait.entry);
5251 spin_unlock(&poll->head->lock);
5252 hash_del(&req->hash_node);
5256 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5257 __must_hold(&req->ctx->completion_lock)
5261 io_poll_remove_double(req);
5262 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5264 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5265 /* non-poll requests have submit ref still */
5271 static bool io_poll_remove_one(struct io_kiocb *req)
5272 __must_hold(&req->ctx->completion_lock)
5276 do_complete = io_poll_remove_waitqs(req);
5278 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5279 io_commit_cqring(req->ctx);
5281 io_put_req_deferred(req, 1);
5288 * Returns true if we found and killed one or more poll requests
5290 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5293 struct hlist_node *tmp;
5294 struct io_kiocb *req;
5297 spin_lock_irq(&ctx->completion_lock);
5298 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5299 struct hlist_head *list;
5301 list = &ctx->cancel_hash[i];
5302 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5303 if (io_match_task(req, tsk, cancel_all))
5304 posted += io_poll_remove_one(req);
5307 spin_unlock_irq(&ctx->completion_lock);
5310 io_cqring_ev_posted(ctx);
5315 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5317 __must_hold(&ctx->completion_lock)
5319 struct hlist_head *list;
5320 struct io_kiocb *req;
5322 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5323 hlist_for_each_entry(req, list, hash_node) {
5324 if (sqe_addr != req->user_data)
5326 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5333 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5335 __must_hold(&ctx->completion_lock)
5337 struct io_kiocb *req;
5339 req = io_poll_find(ctx, sqe_addr, poll_only);
5342 if (io_poll_remove_one(req))
5348 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5353 events = READ_ONCE(sqe->poll32_events);
5355 events = swahw32(events);
5357 if (!(flags & IORING_POLL_ADD_MULTI))
5358 events |= EPOLLONESHOT;
5359 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5362 static int io_poll_update_prep(struct io_kiocb *req,
5363 const struct io_uring_sqe *sqe)
5365 struct io_poll_update *upd = &req->poll_update;
5368 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5370 if (sqe->ioprio || sqe->buf_index)
5372 flags = READ_ONCE(sqe->len);
5373 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5374 IORING_POLL_ADD_MULTI))
5376 /* meaningless without update */
5377 if (flags == IORING_POLL_ADD_MULTI)
5380 upd->old_user_data = READ_ONCE(sqe->addr);
5381 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5382 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5384 upd->new_user_data = READ_ONCE(sqe->off);
5385 if (!upd->update_user_data && upd->new_user_data)
5387 if (upd->update_events)
5388 upd->events = io_poll_parse_events(sqe, flags);
5389 else if (sqe->poll32_events)
5395 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5398 struct io_kiocb *req = wait->private;
5399 struct io_poll_iocb *poll = &req->poll;
5401 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5404 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5405 struct poll_table_struct *p)
5407 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5409 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5412 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5414 struct io_poll_iocb *poll = &req->poll;
5417 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5419 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5421 flags = READ_ONCE(sqe->len);
5422 if (flags & ~IORING_POLL_ADD_MULTI)
5425 poll->events = io_poll_parse_events(sqe, flags);
5429 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5431 struct io_poll_iocb *poll = &req->poll;
5432 struct io_ring_ctx *ctx = req->ctx;
5433 struct io_poll_table ipt;
5436 ipt.pt._qproc = io_poll_queue_proc;
5438 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5441 if (mask) { /* no async, we'd stolen it */
5443 io_poll_complete(req, mask);
5445 spin_unlock_irq(&ctx->completion_lock);
5448 io_cqring_ev_posted(ctx);
5449 if (poll->events & EPOLLONESHOT)
5455 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5457 struct io_ring_ctx *ctx = req->ctx;
5458 struct io_kiocb *preq;
5462 spin_lock_irq(&ctx->completion_lock);
5463 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5469 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5471 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5476 * Don't allow racy completion with singleshot, as we cannot safely
5477 * update those. For multishot, if we're racing with completion, just
5478 * let completion re-add it.
5480 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5481 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5485 /* we now have a detached poll request. reissue. */
5489 spin_unlock_irq(&ctx->completion_lock);
5491 io_req_complete(req, ret);
5494 /* only mask one event flags, keep behavior flags */
5495 if (req->poll_update.update_events) {
5496 preq->poll.events &= ~0xffff;
5497 preq->poll.events |= req->poll_update.events & 0xffff;
5498 preq->poll.events |= IO_POLL_UNMASK;
5500 if (req->poll_update.update_user_data)
5501 preq->user_data = req->poll_update.new_user_data;
5502 spin_unlock_irq(&ctx->completion_lock);
5504 /* complete update request, we're done with it */
5505 io_req_complete(req, ret);
5508 ret = io_poll_add(preq, issue_flags);
5511 io_req_complete(preq, ret);
5517 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5519 struct io_timeout_data *data = container_of(timer,
5520 struct io_timeout_data, timer);
5521 struct io_kiocb *req = data->req;
5522 struct io_ring_ctx *ctx = req->ctx;
5523 unsigned long flags;
5525 spin_lock_irqsave(&ctx->completion_lock, flags);
5526 list_del_init(&req->timeout.list);
5527 atomic_set(&req->ctx->cq_timeouts,
5528 atomic_read(&req->ctx->cq_timeouts) + 1);
5530 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5531 io_commit_cqring(ctx);
5532 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5534 io_cqring_ev_posted(ctx);
5537 return HRTIMER_NORESTART;
5540 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5542 __must_hold(&ctx->completion_lock)
5544 struct io_timeout_data *io;
5545 struct io_kiocb *req;
5548 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5549 found = user_data == req->user_data;
5554 return ERR_PTR(-ENOENT);
5556 io = req->async_data;
5557 if (hrtimer_try_to_cancel(&io->timer) == -1)
5558 return ERR_PTR(-EALREADY);
5559 list_del_init(&req->timeout.list);
5563 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5564 __must_hold(&ctx->completion_lock)
5566 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5569 return PTR_ERR(req);
5572 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5573 io_put_req_deferred(req, 1);
5577 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5578 struct timespec64 *ts, enum hrtimer_mode mode)
5579 __must_hold(&ctx->completion_lock)
5581 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5582 struct io_timeout_data *data;
5585 return PTR_ERR(req);
5587 req->timeout.off = 0; /* noseq */
5588 data = req->async_data;
5589 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5590 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5591 data->timer.function = io_timeout_fn;
5592 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5596 static int io_timeout_remove_prep(struct io_kiocb *req,
5597 const struct io_uring_sqe *sqe)
5599 struct io_timeout_rem *tr = &req->timeout_rem;
5601 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5603 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5605 if (sqe->ioprio || sqe->buf_index || sqe->len)
5608 tr->addr = READ_ONCE(sqe->addr);
5609 tr->flags = READ_ONCE(sqe->timeout_flags);
5610 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5611 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5613 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5615 } else if (tr->flags) {
5616 /* timeout removal doesn't support flags */
5623 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5625 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5630 * Remove or update an existing timeout command
5632 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5634 struct io_timeout_rem *tr = &req->timeout_rem;
5635 struct io_ring_ctx *ctx = req->ctx;
5638 spin_lock_irq(&ctx->completion_lock);
5639 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5640 ret = io_timeout_cancel(ctx, tr->addr);
5642 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5643 io_translate_timeout_mode(tr->flags));
5645 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5646 io_commit_cqring(ctx);
5647 spin_unlock_irq(&ctx->completion_lock);
5648 io_cqring_ev_posted(ctx);
5655 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5656 bool is_timeout_link)
5658 struct io_timeout_data *data;
5660 u32 off = READ_ONCE(sqe->off);
5662 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5664 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5666 if (off && is_timeout_link)
5668 flags = READ_ONCE(sqe->timeout_flags);
5669 if (flags & ~IORING_TIMEOUT_ABS)
5672 req->timeout.off = off;
5673 if (unlikely(off && !req->ctx->off_timeout_used))
5674 req->ctx->off_timeout_used = true;
5676 if (!req->async_data && io_alloc_async_data(req))
5679 data = req->async_data;
5682 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5685 data->mode = io_translate_timeout_mode(flags);
5686 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5687 if (is_timeout_link)
5688 io_req_track_inflight(req);
5692 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5694 struct io_ring_ctx *ctx = req->ctx;
5695 struct io_timeout_data *data = req->async_data;
5696 struct list_head *entry;
5697 u32 tail, off = req->timeout.off;
5699 spin_lock_irq(&ctx->completion_lock);
5702 * sqe->off holds how many events that need to occur for this
5703 * timeout event to be satisfied. If it isn't set, then this is
5704 * a pure timeout request, sequence isn't used.
5706 if (io_is_timeout_noseq(req)) {
5707 entry = ctx->timeout_list.prev;
5711 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5712 req->timeout.target_seq = tail + off;
5714 /* Update the last seq here in case io_flush_timeouts() hasn't.
5715 * This is safe because ->completion_lock is held, and submissions
5716 * and completions are never mixed in the same ->completion_lock section.
5718 ctx->cq_last_tm_flush = tail;
5721 * Insertion sort, ensuring the first entry in the list is always
5722 * the one we need first.
5724 list_for_each_prev(entry, &ctx->timeout_list) {
5725 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5728 if (io_is_timeout_noseq(nxt))
5730 /* nxt.seq is behind @tail, otherwise would've been completed */
5731 if (off >= nxt->timeout.target_seq - tail)
5735 list_add(&req->timeout.list, entry);
5736 data->timer.function = io_timeout_fn;
5737 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5738 spin_unlock_irq(&ctx->completion_lock);
5742 struct io_cancel_data {
5743 struct io_ring_ctx *ctx;
5747 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5749 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5750 struct io_cancel_data *cd = data;
5752 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5755 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5756 struct io_ring_ctx *ctx)
5758 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5759 enum io_wq_cancel cancel_ret;
5762 if (!tctx || !tctx->io_wq)
5765 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5766 switch (cancel_ret) {
5767 case IO_WQ_CANCEL_OK:
5770 case IO_WQ_CANCEL_RUNNING:
5773 case IO_WQ_CANCEL_NOTFOUND:
5781 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5782 struct io_kiocb *req, __u64 sqe_addr,
5785 unsigned long flags;
5788 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5789 spin_lock_irqsave(&ctx->completion_lock, flags);
5792 ret = io_timeout_cancel(ctx, sqe_addr);
5795 ret = io_poll_cancel(ctx, sqe_addr, false);
5799 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5800 io_commit_cqring(ctx);
5801 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5802 io_cqring_ev_posted(ctx);
5808 static int io_async_cancel_prep(struct io_kiocb *req,
5809 const struct io_uring_sqe *sqe)
5811 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5813 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5815 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5818 req->cancel.addr = READ_ONCE(sqe->addr);
5822 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5824 struct io_ring_ctx *ctx = req->ctx;
5825 u64 sqe_addr = req->cancel.addr;
5826 struct io_tctx_node *node;
5829 /* tasks should wait for their io-wq threads, so safe w/o sync */
5830 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5831 spin_lock_irq(&ctx->completion_lock);
5834 ret = io_timeout_cancel(ctx, sqe_addr);
5837 ret = io_poll_cancel(ctx, sqe_addr, false);
5840 spin_unlock_irq(&ctx->completion_lock);
5842 /* slow path, try all io-wq's */
5843 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5845 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5846 struct io_uring_task *tctx = node->task->io_uring;
5848 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5852 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5854 spin_lock_irq(&ctx->completion_lock);
5856 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5857 io_commit_cqring(ctx);
5858 spin_unlock_irq(&ctx->completion_lock);
5859 io_cqring_ev_posted(ctx);
5867 static int io_rsrc_update_prep(struct io_kiocb *req,
5868 const struct io_uring_sqe *sqe)
5870 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5872 if (sqe->ioprio || sqe->rw_flags)
5875 req->rsrc_update.offset = READ_ONCE(sqe->off);
5876 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5877 if (!req->rsrc_update.nr_args)
5879 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5883 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5885 struct io_ring_ctx *ctx = req->ctx;
5886 struct io_uring_rsrc_update2 up;
5889 if (issue_flags & IO_URING_F_NONBLOCK)
5892 up.offset = req->rsrc_update.offset;
5893 up.data = req->rsrc_update.arg;
5898 mutex_lock(&ctx->uring_lock);
5899 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5900 &up, req->rsrc_update.nr_args);
5901 mutex_unlock(&ctx->uring_lock);
5905 __io_req_complete(req, issue_flags, ret, 0);
5909 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5911 switch (req->opcode) {
5914 case IORING_OP_READV:
5915 case IORING_OP_READ_FIXED:
5916 case IORING_OP_READ:
5917 return io_read_prep(req, sqe);
5918 case IORING_OP_WRITEV:
5919 case IORING_OP_WRITE_FIXED:
5920 case IORING_OP_WRITE:
5921 return io_write_prep(req, sqe);
5922 case IORING_OP_POLL_ADD:
5923 return io_poll_add_prep(req, sqe);
5924 case IORING_OP_POLL_REMOVE:
5925 return io_poll_update_prep(req, sqe);
5926 case IORING_OP_FSYNC:
5927 return io_fsync_prep(req, sqe);
5928 case IORING_OP_SYNC_FILE_RANGE:
5929 return io_sfr_prep(req, sqe);
5930 case IORING_OP_SENDMSG:
5931 case IORING_OP_SEND:
5932 return io_sendmsg_prep(req, sqe);
5933 case IORING_OP_RECVMSG:
5934 case IORING_OP_RECV:
5935 return io_recvmsg_prep(req, sqe);
5936 case IORING_OP_CONNECT:
5937 return io_connect_prep(req, sqe);
5938 case IORING_OP_TIMEOUT:
5939 return io_timeout_prep(req, sqe, false);
5940 case IORING_OP_TIMEOUT_REMOVE:
5941 return io_timeout_remove_prep(req, sqe);
5942 case IORING_OP_ASYNC_CANCEL:
5943 return io_async_cancel_prep(req, sqe);
5944 case IORING_OP_LINK_TIMEOUT:
5945 return io_timeout_prep(req, sqe, true);
5946 case IORING_OP_ACCEPT:
5947 return io_accept_prep(req, sqe);
5948 case IORING_OP_FALLOCATE:
5949 return io_fallocate_prep(req, sqe);
5950 case IORING_OP_OPENAT:
5951 return io_openat_prep(req, sqe);
5952 case IORING_OP_CLOSE:
5953 return io_close_prep(req, sqe);
5954 case IORING_OP_FILES_UPDATE:
5955 return io_rsrc_update_prep(req, sqe);
5956 case IORING_OP_STATX:
5957 return io_statx_prep(req, sqe);
5958 case IORING_OP_FADVISE:
5959 return io_fadvise_prep(req, sqe);
5960 case IORING_OP_MADVISE:
5961 return io_madvise_prep(req, sqe);
5962 case IORING_OP_OPENAT2:
5963 return io_openat2_prep(req, sqe);
5964 case IORING_OP_EPOLL_CTL:
5965 return io_epoll_ctl_prep(req, sqe);
5966 case IORING_OP_SPLICE:
5967 return io_splice_prep(req, sqe);
5968 case IORING_OP_PROVIDE_BUFFERS:
5969 return io_provide_buffers_prep(req, sqe);
5970 case IORING_OP_REMOVE_BUFFERS:
5971 return io_remove_buffers_prep(req, sqe);
5973 return io_tee_prep(req, sqe);
5974 case IORING_OP_SHUTDOWN:
5975 return io_shutdown_prep(req, sqe);
5976 case IORING_OP_RENAMEAT:
5977 return io_renameat_prep(req, sqe);
5978 case IORING_OP_UNLINKAT:
5979 return io_unlinkat_prep(req, sqe);
5982 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5987 static int io_req_prep_async(struct io_kiocb *req)
5989 if (!io_op_defs[req->opcode].needs_async_setup)
5991 if (WARN_ON_ONCE(req->async_data))
5993 if (io_alloc_async_data(req))
5996 switch (req->opcode) {
5997 case IORING_OP_READV:
5998 return io_rw_prep_async(req, READ);
5999 case IORING_OP_WRITEV:
6000 return io_rw_prep_async(req, WRITE);
6001 case IORING_OP_SENDMSG:
6002 return io_sendmsg_prep_async(req);
6003 case IORING_OP_RECVMSG:
6004 return io_recvmsg_prep_async(req);
6005 case IORING_OP_CONNECT:
6006 return io_connect_prep_async(req);
6008 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6013 static u32 io_get_sequence(struct io_kiocb *req)
6015 u32 seq = req->ctx->cached_sq_head;
6017 /* need original cached_sq_head, but it was increased for each req */
6018 io_for_each_link(req, req)
6023 static bool io_drain_req(struct io_kiocb *req)
6025 struct io_kiocb *pos;
6026 struct io_ring_ctx *ctx = req->ctx;
6027 struct io_defer_entry *de;
6032 * If we need to drain a request in the middle of a link, drain the
6033 * head request and the next request/link after the current link.
6034 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6035 * maintained for every request of our link.
6037 if (ctx->drain_next) {
6038 req->flags |= REQ_F_IO_DRAIN;
6039 ctx->drain_next = false;
6041 /* not interested in head, start from the first linked */
6042 io_for_each_link(pos, req->link) {
6043 if (pos->flags & REQ_F_IO_DRAIN) {
6044 ctx->drain_next = true;
6045 req->flags |= REQ_F_IO_DRAIN;
6050 /* Still need defer if there is pending req in defer list. */
6051 if (likely(list_empty_careful(&ctx->defer_list) &&
6052 !(req->flags & REQ_F_IO_DRAIN))) {
6053 ctx->drain_active = false;
6057 seq = io_get_sequence(req);
6058 /* Still a chance to pass the sequence check */
6059 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6062 ret = io_req_prep_async(req);
6065 io_prep_async_link(req);
6066 de = kmalloc(sizeof(*de), GFP_KERNEL);
6070 io_req_complete_failed(req, ret);
6074 spin_lock_irq(&ctx->completion_lock);
6075 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6076 spin_unlock_irq(&ctx->completion_lock);
6078 io_queue_async_work(req);
6082 trace_io_uring_defer(ctx, req, req->user_data);
6085 list_add_tail(&de->list, &ctx->defer_list);
6086 spin_unlock_irq(&ctx->completion_lock);
6090 static void io_clean_op(struct io_kiocb *req)
6092 if (req->flags & REQ_F_BUFFER_SELECTED) {
6093 switch (req->opcode) {
6094 case IORING_OP_READV:
6095 case IORING_OP_READ_FIXED:
6096 case IORING_OP_READ:
6097 kfree((void *)(unsigned long)req->rw.addr);
6099 case IORING_OP_RECVMSG:
6100 case IORING_OP_RECV:
6101 kfree(req->sr_msg.kbuf);
6106 if (req->flags & REQ_F_NEED_CLEANUP) {
6107 switch (req->opcode) {
6108 case IORING_OP_READV:
6109 case IORING_OP_READ_FIXED:
6110 case IORING_OP_READ:
6111 case IORING_OP_WRITEV:
6112 case IORING_OP_WRITE_FIXED:
6113 case IORING_OP_WRITE: {
6114 struct io_async_rw *io = req->async_data;
6116 kfree(io->free_iovec);
6119 case IORING_OP_RECVMSG:
6120 case IORING_OP_SENDMSG: {
6121 struct io_async_msghdr *io = req->async_data;
6123 kfree(io->free_iov);
6126 case IORING_OP_SPLICE:
6128 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6129 io_put_file(req->splice.file_in);
6131 case IORING_OP_OPENAT:
6132 case IORING_OP_OPENAT2:
6133 if (req->open.filename)
6134 putname(req->open.filename);
6136 case IORING_OP_RENAMEAT:
6137 putname(req->rename.oldpath);
6138 putname(req->rename.newpath);
6140 case IORING_OP_UNLINKAT:
6141 putname(req->unlink.filename);
6145 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6146 kfree(req->apoll->double_poll);
6150 if (req->flags & REQ_F_INFLIGHT) {
6151 struct io_uring_task *tctx = req->task->io_uring;
6153 atomic_dec(&tctx->inflight_tracked);
6155 if (req->flags & REQ_F_CREDS)
6156 put_cred(req->creds);
6158 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6161 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6163 struct io_ring_ctx *ctx = req->ctx;
6164 const struct cred *creds = NULL;
6167 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6168 creds = override_creds(req->creds);
6170 switch (req->opcode) {
6172 ret = io_nop(req, issue_flags);
6174 case IORING_OP_READV:
6175 case IORING_OP_READ_FIXED:
6176 case IORING_OP_READ:
6177 ret = io_read(req, issue_flags);
6179 case IORING_OP_WRITEV:
6180 case IORING_OP_WRITE_FIXED:
6181 case IORING_OP_WRITE:
6182 ret = io_write(req, issue_flags);
6184 case IORING_OP_FSYNC:
6185 ret = io_fsync(req, issue_flags);
6187 case IORING_OP_POLL_ADD:
6188 ret = io_poll_add(req, issue_flags);
6190 case IORING_OP_POLL_REMOVE:
6191 ret = io_poll_update(req, issue_flags);
6193 case IORING_OP_SYNC_FILE_RANGE:
6194 ret = io_sync_file_range(req, issue_flags);
6196 case IORING_OP_SENDMSG:
6197 ret = io_sendmsg(req, issue_flags);
6199 case IORING_OP_SEND:
6200 ret = io_send(req, issue_flags);
6202 case IORING_OP_RECVMSG:
6203 ret = io_recvmsg(req, issue_flags);
6205 case IORING_OP_RECV:
6206 ret = io_recv(req, issue_flags);
6208 case IORING_OP_TIMEOUT:
6209 ret = io_timeout(req, issue_flags);
6211 case IORING_OP_TIMEOUT_REMOVE:
6212 ret = io_timeout_remove(req, issue_flags);
6214 case IORING_OP_ACCEPT:
6215 ret = io_accept(req, issue_flags);
6217 case IORING_OP_CONNECT:
6218 ret = io_connect(req, issue_flags);
6220 case IORING_OP_ASYNC_CANCEL:
6221 ret = io_async_cancel(req, issue_flags);
6223 case IORING_OP_FALLOCATE:
6224 ret = io_fallocate(req, issue_flags);
6226 case IORING_OP_OPENAT:
6227 ret = io_openat(req, issue_flags);
6229 case IORING_OP_CLOSE:
6230 ret = io_close(req, issue_flags);
6232 case IORING_OP_FILES_UPDATE:
6233 ret = io_files_update(req, issue_flags);
6235 case IORING_OP_STATX:
6236 ret = io_statx(req, issue_flags);
6238 case IORING_OP_FADVISE:
6239 ret = io_fadvise(req, issue_flags);
6241 case IORING_OP_MADVISE:
6242 ret = io_madvise(req, issue_flags);
6244 case IORING_OP_OPENAT2:
6245 ret = io_openat2(req, issue_flags);
6247 case IORING_OP_EPOLL_CTL:
6248 ret = io_epoll_ctl(req, issue_flags);
6250 case IORING_OP_SPLICE:
6251 ret = io_splice(req, issue_flags);
6253 case IORING_OP_PROVIDE_BUFFERS:
6254 ret = io_provide_buffers(req, issue_flags);
6256 case IORING_OP_REMOVE_BUFFERS:
6257 ret = io_remove_buffers(req, issue_flags);
6260 ret = io_tee(req, issue_flags);
6262 case IORING_OP_SHUTDOWN:
6263 ret = io_shutdown(req, issue_flags);
6265 case IORING_OP_RENAMEAT:
6266 ret = io_renameat(req, issue_flags);
6268 case IORING_OP_UNLINKAT:
6269 ret = io_unlinkat(req, issue_flags);
6277 revert_creds(creds);
6280 /* If the op doesn't have a file, we're not polling for it */
6281 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6282 io_iopoll_req_issued(req);
6287 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6289 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6291 req = io_put_req_find_next(req);
6292 return req ? &req->work : NULL;
6295 static void io_wq_submit_work(struct io_wq_work *work)
6297 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6298 struct io_kiocb *timeout;
6301 timeout = io_prep_linked_timeout(req);
6303 io_queue_linked_timeout(timeout);
6305 if (work->flags & IO_WQ_WORK_CANCEL)
6310 ret = io_issue_sqe(req, 0);
6312 * We can get EAGAIN for polled IO even though we're
6313 * forcing a sync submission from here, since we can't
6314 * wait for request slots on the block side.
6322 /* avoid locking problems by failing it from a clean context */
6324 /* io-wq is going to take one down */
6326 io_req_task_queue_fail(req, ret);
6330 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6333 return &table->files[i];
6336 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6339 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6341 return (struct file *) (slot->file_ptr & FFS_MASK);
6344 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6346 unsigned long file_ptr = (unsigned long) file;
6348 if (__io_file_supports_nowait(file, READ))
6349 file_ptr |= FFS_ASYNC_READ;
6350 if (__io_file_supports_nowait(file, WRITE))
6351 file_ptr |= FFS_ASYNC_WRITE;
6352 if (S_ISREG(file_inode(file)->i_mode))
6353 file_ptr |= FFS_ISREG;
6354 file_slot->file_ptr = file_ptr;
6357 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6358 struct io_kiocb *req, int fd)
6361 unsigned long file_ptr;
6363 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6365 fd = array_index_nospec(fd, ctx->nr_user_files);
6366 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6367 file = (struct file *) (file_ptr & FFS_MASK);
6368 file_ptr &= ~FFS_MASK;
6369 /* mask in overlapping REQ_F and FFS bits */
6370 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6371 io_req_set_rsrc_node(req);
6375 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6376 struct io_submit_state *state,
6377 struct io_kiocb *req, int fd)
6379 struct file *file = __io_file_get(state, fd);
6381 trace_io_uring_file_get(ctx, fd);
6383 /* we don't allow fixed io_uring files */
6384 if (file && unlikely(file->f_op == &io_uring_fops))
6385 io_req_track_inflight(req);
6389 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6390 struct io_submit_state *state,
6391 struct io_kiocb *req, int fd, bool fixed)
6394 return io_file_get_fixed(ctx, req, fd);
6396 return io_file_get_normal(ctx, state, req, fd);
6399 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6401 struct io_timeout_data *data = container_of(timer,
6402 struct io_timeout_data, timer);
6403 struct io_kiocb *prev, *req = data->req;
6404 struct io_ring_ctx *ctx = req->ctx;
6405 unsigned long flags;
6407 spin_lock_irqsave(&ctx->completion_lock, flags);
6408 prev = req->timeout.head;
6409 req->timeout.head = NULL;
6412 * We don't expect the list to be empty, that will only happen if we
6413 * race with the completion of the linked work.
6416 io_remove_next_linked(prev);
6417 if (!req_ref_inc_not_zero(prev))
6420 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6423 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6424 io_put_req_deferred(prev, 1);
6425 io_put_req_deferred(req, 1);
6427 io_req_complete_post(req, -ETIME, 0);
6429 return HRTIMER_NORESTART;
6432 static void io_queue_linked_timeout(struct io_kiocb *req)
6434 struct io_ring_ctx *ctx = req->ctx;
6436 spin_lock_irq(&ctx->completion_lock);
6438 * If the back reference is NULL, then our linked request finished
6439 * before we got a chance to setup the timer
6441 if (req->timeout.head) {
6442 struct io_timeout_data *data = req->async_data;
6444 data->timer.function = io_link_timeout_fn;
6445 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6448 spin_unlock_irq(&ctx->completion_lock);
6449 /* drop submission reference */
6453 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6455 struct io_kiocb *nxt = req->link;
6457 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6458 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6461 nxt->timeout.head = req;
6462 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6463 req->flags |= REQ_F_LINK_TIMEOUT;
6467 static void __io_queue_sqe(struct io_kiocb *req)
6468 __must_hold(&req->ctx->uring_lock)
6470 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6474 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6477 * We async punt it if the file wasn't marked NOWAIT, or if the file
6478 * doesn't support non-blocking read/write attempts
6481 /* drop submission reference */
6482 if (req->flags & REQ_F_COMPLETE_INLINE) {
6483 struct io_ring_ctx *ctx = req->ctx;
6484 struct io_comp_state *cs = &ctx->submit_state.comp;
6486 cs->reqs[cs->nr++] = req;
6487 if (cs->nr == ARRAY_SIZE(cs->reqs))
6488 io_submit_flush_completions(ctx);
6492 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6493 switch (io_arm_poll_handler(req)) {
6494 case IO_APOLL_READY:
6496 case IO_APOLL_ABORTED:
6498 * Queued up for async execution, worker will release
6499 * submit reference when the iocb is actually submitted.
6501 io_queue_async_work(req);
6505 io_req_complete_failed(req, ret);
6508 io_queue_linked_timeout(linked_timeout);
6511 static inline void io_queue_sqe(struct io_kiocb *req)
6512 __must_hold(&req->ctx->uring_lock)
6514 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6517 if (likely(!(req->flags & REQ_F_FORCE_ASYNC))) {
6518 __io_queue_sqe(req);
6520 int ret = io_req_prep_async(req);
6523 io_req_complete_failed(req, ret);
6525 io_queue_async_work(req);
6530 * Check SQE restrictions (opcode and flags).
6532 * Returns 'true' if SQE is allowed, 'false' otherwise.
6534 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6535 struct io_kiocb *req,
6536 unsigned int sqe_flags)
6538 if (likely(!ctx->restricted))
6541 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6544 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6545 ctx->restrictions.sqe_flags_required)
6548 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6549 ctx->restrictions.sqe_flags_required))
6555 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6556 const struct io_uring_sqe *sqe)
6557 __must_hold(&ctx->uring_lock)
6559 struct io_submit_state *state;
6560 unsigned int sqe_flags;
6561 int personality, ret = 0;
6563 /* req is partially pre-initialised, see io_preinit_req() */
6564 req->opcode = READ_ONCE(sqe->opcode);
6565 /* same numerical values with corresponding REQ_F_*, safe to copy */
6566 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6567 req->user_data = READ_ONCE(sqe->user_data);
6569 req->fixed_rsrc_refs = NULL;
6570 /* one is dropped after submission, the other at completion */
6571 atomic_set(&req->refs, 2);
6572 req->task = current;
6574 /* enforce forwards compatibility on users */
6575 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6577 if (unlikely(req->opcode >= IORING_OP_LAST))
6579 if (!io_check_restriction(ctx, req, sqe_flags))
6582 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6583 !io_op_defs[req->opcode].buffer_select)
6585 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6586 ctx->drain_active = true;
6588 personality = READ_ONCE(sqe->personality);
6590 req->creds = xa_load(&ctx->personalities, personality);
6593 get_cred(req->creds);
6594 req->flags |= REQ_F_CREDS;
6596 state = &ctx->submit_state;
6599 * Plug now if we have more than 1 IO left after this, and the target
6600 * is potentially a read/write to block based storage.
6602 if (!state->plug_started && state->ios_left > 1 &&
6603 io_op_defs[req->opcode].plug) {
6604 blk_start_plug(&state->plug);
6605 state->plug_started = true;
6608 if (io_op_defs[req->opcode].needs_file) {
6609 req->file = io_file_get(ctx, state, req, READ_ONCE(sqe->fd),
6610 (sqe_flags & IOSQE_FIXED_FILE));
6611 if (unlikely(!req->file))
6619 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6620 const struct io_uring_sqe *sqe)
6621 __must_hold(&ctx->uring_lock)
6623 struct io_submit_link *link = &ctx->submit_state.link;
6626 ret = io_init_req(ctx, req, sqe);
6627 if (unlikely(ret)) {
6630 /* fail even hard links since we don't submit */
6631 req_set_fail(link->head);
6632 io_req_complete_failed(link->head, -ECANCELED);
6635 io_req_complete_failed(req, ret);
6639 ret = io_req_prep(req, sqe);
6643 /* don't need @sqe from now on */
6644 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6646 ctx->flags & IORING_SETUP_SQPOLL);
6649 * If we already have a head request, queue this one for async
6650 * submittal once the head completes. If we don't have a head but
6651 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6652 * submitted sync once the chain is complete. If none of those
6653 * conditions are true (normal request), then just queue it.
6656 struct io_kiocb *head = link->head;
6658 ret = io_req_prep_async(req);
6661 trace_io_uring_link(ctx, req, head);
6662 link->last->link = req;
6665 /* last request of a link, enqueue the link */
6666 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6671 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6683 * Batched submission is done, ensure local IO is flushed out.
6685 static void io_submit_state_end(struct io_submit_state *state,
6686 struct io_ring_ctx *ctx)
6688 if (state->link.head)
6689 io_queue_sqe(state->link.head);
6691 io_submit_flush_completions(ctx);
6692 if (state->plug_started)
6693 blk_finish_plug(&state->plug);
6694 io_state_file_put(state);
6698 * Start submission side cache.
6700 static void io_submit_state_start(struct io_submit_state *state,
6701 unsigned int max_ios)
6703 state->plug_started = false;
6704 state->ios_left = max_ios;
6705 /* set only head, no need to init link_last in advance */
6706 state->link.head = NULL;
6709 static void io_commit_sqring(struct io_ring_ctx *ctx)
6711 struct io_rings *rings = ctx->rings;
6714 * Ensure any loads from the SQEs are done at this point,
6715 * since once we write the new head, the application could
6716 * write new data to them.
6718 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6722 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6723 * that is mapped by userspace. This means that care needs to be taken to
6724 * ensure that reads are stable, as we cannot rely on userspace always
6725 * being a good citizen. If members of the sqe are validated and then later
6726 * used, it's important that those reads are done through READ_ONCE() to
6727 * prevent a re-load down the line.
6729 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6731 unsigned head, mask = ctx->sq_entries - 1;
6732 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6735 * The cached sq head (or cq tail) serves two purposes:
6737 * 1) allows us to batch the cost of updating the user visible
6739 * 2) allows the kernel side to track the head on its own, even
6740 * though the application is the one updating it.
6742 head = READ_ONCE(ctx->sq_array[sq_idx]);
6743 if (likely(head < ctx->sq_entries))
6744 return &ctx->sq_sqes[head];
6746 /* drop invalid entries */
6748 WRITE_ONCE(ctx->rings->sq_dropped,
6749 READ_ONCE(ctx->rings->sq_dropped) + 1);
6753 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6754 __must_hold(&ctx->uring_lock)
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;
7058 struct io_rings *rings = ctx->rings;
7059 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7063 io_cqring_overflow_flush(ctx, false);
7064 if (io_cqring_events(ctx) >= min_events)
7066 if (!io_run_task_work())
7071 #ifdef CONFIG_COMPAT
7072 if (in_compat_syscall())
7073 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7077 ret = set_user_sigmask(sig, sigsz);
7084 struct timespec64 ts;
7086 if (get_timespec64(&ts, uts))
7088 timeout = timespec64_to_jiffies(&ts);
7091 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7092 iowq.wq.private = current;
7093 INIT_LIST_HEAD(&iowq.wq.entry);
7095 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7096 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7098 trace_io_uring_cqring_wait(ctx, min_events);
7100 /* if we can't even flush overflow, don't wait for more */
7101 if (!io_cqring_overflow_flush(ctx, false)) {
7105 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7106 TASK_INTERRUPTIBLE);
7107 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7108 finish_wait(&ctx->cq_wait, &iowq.wq);
7112 restore_saved_sigmask_unless(ret == -EINTR);
7114 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7117 static void io_free_page_table(void **table, size_t size)
7119 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7121 for (i = 0; i < nr_tables; i++)
7126 static void **io_alloc_page_table(size_t size)
7128 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7129 size_t init_size = size;
7132 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL);
7136 for (i = 0; i < nr_tables; i++) {
7137 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7139 table[i] = kzalloc(this_size, GFP_KERNEL);
7141 io_free_page_table(table, init_size);
7149 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7151 percpu_ref_exit(&ref_node->refs);
7155 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7157 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7158 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7159 unsigned long flags;
7160 bool first_add = false;
7162 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7165 while (!list_empty(&ctx->rsrc_ref_list)) {
7166 node = list_first_entry(&ctx->rsrc_ref_list,
7167 struct io_rsrc_node, node);
7168 /* recycle ref nodes in order */
7171 list_del(&node->node);
7172 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7174 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7177 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7180 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7182 struct io_rsrc_node *ref_node;
7184 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7188 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7193 INIT_LIST_HEAD(&ref_node->node);
7194 INIT_LIST_HEAD(&ref_node->rsrc_list);
7195 ref_node->done = false;
7199 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7200 struct io_rsrc_data *data_to_kill)
7202 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7203 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7206 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7208 rsrc_node->rsrc_data = data_to_kill;
7209 spin_lock_irq(&ctx->rsrc_ref_lock);
7210 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7211 spin_unlock_irq(&ctx->rsrc_ref_lock);
7213 atomic_inc(&data_to_kill->refs);
7214 percpu_ref_kill(&rsrc_node->refs);
7215 ctx->rsrc_node = NULL;
7218 if (!ctx->rsrc_node) {
7219 ctx->rsrc_node = ctx->rsrc_backup_node;
7220 ctx->rsrc_backup_node = NULL;
7224 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7226 if (ctx->rsrc_backup_node)
7228 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7229 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7232 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7236 /* As we may drop ->uring_lock, other task may have started quiesce */
7240 data->quiesce = true;
7242 ret = io_rsrc_node_switch_start(ctx);
7245 io_rsrc_node_switch(ctx, data);
7247 /* kill initial ref, already quiesced if zero */
7248 if (atomic_dec_and_test(&data->refs))
7250 mutex_unlock(&ctx->uring_lock);
7251 flush_delayed_work(&ctx->rsrc_put_work);
7252 ret = wait_for_completion_interruptible(&data->done);
7254 mutex_lock(&ctx->uring_lock);
7258 atomic_inc(&data->refs);
7259 /* wait for all works potentially completing data->done */
7260 flush_delayed_work(&ctx->rsrc_put_work);
7261 reinit_completion(&data->done);
7263 ret = io_run_task_work_sig();
7264 mutex_lock(&ctx->uring_lock);
7266 data->quiesce = false;
7271 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7273 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7274 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7276 return &data->tags[table_idx][off];
7279 static void io_rsrc_data_free(struct io_rsrc_data *data)
7281 size_t size = data->nr * sizeof(data->tags[0][0]);
7284 io_free_page_table((void **)data->tags, size);
7288 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7289 u64 __user *utags, unsigned nr,
7290 struct io_rsrc_data **pdata)
7292 struct io_rsrc_data *data;
7296 data = kzalloc(sizeof(*data), GFP_KERNEL);
7299 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7307 data->do_put = do_put;
7310 for (i = 0; i < nr; i++) {
7311 u64 *tag_slot = io_get_tag_slot(data, i);
7313 if (copy_from_user(tag_slot, &utags[i],
7319 atomic_set(&data->refs, 1);
7320 init_completion(&data->done);
7324 io_rsrc_data_free(data);
7328 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7330 table->files = kvcalloc(nr_files, sizeof(table->files[0]), GFP_KERNEL);
7331 return !!table->files;
7334 static void io_free_file_tables(struct io_file_table *table)
7336 kvfree(table->files);
7337 table->files = NULL;
7340 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7342 #if defined(CONFIG_UNIX)
7343 if (ctx->ring_sock) {
7344 struct sock *sock = ctx->ring_sock->sk;
7345 struct sk_buff *skb;
7347 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7353 for (i = 0; i < ctx->nr_user_files; i++) {
7356 file = io_file_from_index(ctx, i);
7361 io_free_file_tables(&ctx->file_table);
7362 io_rsrc_data_free(ctx->file_data);
7363 ctx->file_data = NULL;
7364 ctx->nr_user_files = 0;
7367 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7371 if (!ctx->file_data)
7373 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7375 __io_sqe_files_unregister(ctx);
7379 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7380 __releases(&sqd->lock)
7382 WARN_ON_ONCE(sqd->thread == current);
7385 * Do the dance but not conditional clear_bit() because it'd race with
7386 * other threads incrementing park_pending and setting the bit.
7388 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7389 if (atomic_dec_return(&sqd->park_pending))
7390 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7391 mutex_unlock(&sqd->lock);
7394 static void io_sq_thread_park(struct io_sq_data *sqd)
7395 __acquires(&sqd->lock)
7397 WARN_ON_ONCE(sqd->thread == current);
7399 atomic_inc(&sqd->park_pending);
7400 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7401 mutex_lock(&sqd->lock);
7403 wake_up_process(sqd->thread);
7406 static void io_sq_thread_stop(struct io_sq_data *sqd)
7408 WARN_ON_ONCE(sqd->thread == current);
7409 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7411 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7412 mutex_lock(&sqd->lock);
7414 wake_up_process(sqd->thread);
7415 mutex_unlock(&sqd->lock);
7416 wait_for_completion(&sqd->exited);
7419 static void io_put_sq_data(struct io_sq_data *sqd)
7421 if (refcount_dec_and_test(&sqd->refs)) {
7422 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7424 io_sq_thread_stop(sqd);
7429 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7431 struct io_sq_data *sqd = ctx->sq_data;
7434 io_sq_thread_park(sqd);
7435 list_del_init(&ctx->sqd_list);
7436 io_sqd_update_thread_idle(sqd);
7437 io_sq_thread_unpark(sqd);
7439 io_put_sq_data(sqd);
7440 ctx->sq_data = NULL;
7444 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7446 struct io_ring_ctx *ctx_attach;
7447 struct io_sq_data *sqd;
7450 f = fdget(p->wq_fd);
7452 return ERR_PTR(-ENXIO);
7453 if (f.file->f_op != &io_uring_fops) {
7455 return ERR_PTR(-EINVAL);
7458 ctx_attach = f.file->private_data;
7459 sqd = ctx_attach->sq_data;
7462 return ERR_PTR(-EINVAL);
7464 if (sqd->task_tgid != current->tgid) {
7466 return ERR_PTR(-EPERM);
7469 refcount_inc(&sqd->refs);
7474 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7477 struct io_sq_data *sqd;
7480 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7481 sqd = io_attach_sq_data(p);
7486 /* fall through for EPERM case, setup new sqd/task */
7487 if (PTR_ERR(sqd) != -EPERM)
7491 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7493 return ERR_PTR(-ENOMEM);
7495 atomic_set(&sqd->park_pending, 0);
7496 refcount_set(&sqd->refs, 1);
7497 INIT_LIST_HEAD(&sqd->ctx_list);
7498 mutex_init(&sqd->lock);
7499 init_waitqueue_head(&sqd->wait);
7500 init_completion(&sqd->exited);
7504 #if defined(CONFIG_UNIX)
7506 * Ensure the UNIX gc is aware of our file set, so we are certain that
7507 * the io_uring can be safely unregistered on process exit, even if we have
7508 * loops in the file referencing.
7510 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7512 struct sock *sk = ctx->ring_sock->sk;
7513 struct scm_fp_list *fpl;
7514 struct sk_buff *skb;
7517 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7521 skb = alloc_skb(0, GFP_KERNEL);
7530 fpl->user = get_uid(current_user());
7531 for (i = 0; i < nr; i++) {
7532 struct file *file = io_file_from_index(ctx, i + offset);
7536 fpl->fp[nr_files] = get_file(file);
7537 unix_inflight(fpl->user, fpl->fp[nr_files]);
7542 fpl->max = SCM_MAX_FD;
7543 fpl->count = nr_files;
7544 UNIXCB(skb).fp = fpl;
7545 skb->destructor = unix_destruct_scm;
7546 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7547 skb_queue_head(&sk->sk_receive_queue, skb);
7549 for (i = 0; i < nr_files; i++)
7560 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7561 * causes regular reference counting to break down. We rely on the UNIX
7562 * garbage collection to take care of this problem for us.
7564 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7566 unsigned left, total;
7570 left = ctx->nr_user_files;
7572 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7574 ret = __io_sqe_files_scm(ctx, this_files, total);
7578 total += this_files;
7584 while (total < ctx->nr_user_files) {
7585 struct file *file = io_file_from_index(ctx, total);
7595 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7601 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7603 struct file *file = prsrc->file;
7604 #if defined(CONFIG_UNIX)
7605 struct sock *sock = ctx->ring_sock->sk;
7606 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7607 struct sk_buff *skb;
7610 __skb_queue_head_init(&list);
7613 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7614 * remove this entry and rearrange the file array.
7616 skb = skb_dequeue(head);
7618 struct scm_fp_list *fp;
7620 fp = UNIXCB(skb).fp;
7621 for (i = 0; i < fp->count; i++) {
7624 if (fp->fp[i] != file)
7627 unix_notinflight(fp->user, fp->fp[i]);
7628 left = fp->count - 1 - i;
7630 memmove(&fp->fp[i], &fp->fp[i + 1],
7631 left * sizeof(struct file *));
7638 __skb_queue_tail(&list, skb);
7648 __skb_queue_tail(&list, skb);
7650 skb = skb_dequeue(head);
7653 if (skb_peek(&list)) {
7654 spin_lock_irq(&head->lock);
7655 while ((skb = __skb_dequeue(&list)) != NULL)
7656 __skb_queue_tail(head, skb);
7657 spin_unlock_irq(&head->lock);
7664 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7666 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7667 struct io_ring_ctx *ctx = rsrc_data->ctx;
7668 struct io_rsrc_put *prsrc, *tmp;
7670 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7671 list_del(&prsrc->list);
7674 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7676 io_ring_submit_lock(ctx, lock_ring);
7677 spin_lock_irq(&ctx->completion_lock);
7678 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7680 io_commit_cqring(ctx);
7681 spin_unlock_irq(&ctx->completion_lock);
7682 io_cqring_ev_posted(ctx);
7683 io_ring_submit_unlock(ctx, lock_ring);
7686 rsrc_data->do_put(ctx, prsrc);
7690 io_rsrc_node_destroy(ref_node);
7691 if (atomic_dec_and_test(&rsrc_data->refs))
7692 complete(&rsrc_data->done);
7695 static void io_rsrc_put_work(struct work_struct *work)
7697 struct io_ring_ctx *ctx;
7698 struct llist_node *node;
7700 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7701 node = llist_del_all(&ctx->rsrc_put_llist);
7704 struct io_rsrc_node *ref_node;
7705 struct llist_node *next = node->next;
7707 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7708 __io_rsrc_put_work(ref_node);
7713 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7714 unsigned nr_args, u64 __user *tags)
7716 __s32 __user *fds = (__s32 __user *) arg;
7725 if (nr_args > IORING_MAX_FIXED_FILES)
7727 ret = io_rsrc_node_switch_start(ctx);
7730 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7736 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7739 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7740 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7744 /* allow sparse sets */
7747 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7754 if (unlikely(!file))
7758 * Don't allow io_uring instances to be registered. If UNIX
7759 * isn't enabled, then this causes a reference cycle and this
7760 * instance can never get freed. If UNIX is enabled we'll
7761 * handle it just fine, but there's still no point in allowing
7762 * a ring fd as it doesn't support regular read/write anyway.
7764 if (file->f_op == &io_uring_fops) {
7768 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7771 ret = io_sqe_files_scm(ctx);
7773 __io_sqe_files_unregister(ctx);
7777 io_rsrc_node_switch(ctx, NULL);
7780 for (i = 0; i < ctx->nr_user_files; i++) {
7781 file = io_file_from_index(ctx, i);
7785 io_free_file_tables(&ctx->file_table);
7786 ctx->nr_user_files = 0;
7788 io_rsrc_data_free(ctx->file_data);
7789 ctx->file_data = NULL;
7793 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7796 #if defined(CONFIG_UNIX)
7797 struct sock *sock = ctx->ring_sock->sk;
7798 struct sk_buff_head *head = &sock->sk_receive_queue;
7799 struct sk_buff *skb;
7802 * See if we can merge this file into an existing skb SCM_RIGHTS
7803 * file set. If there's no room, fall back to allocating a new skb
7804 * and filling it in.
7806 spin_lock_irq(&head->lock);
7807 skb = skb_peek(head);
7809 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7811 if (fpl->count < SCM_MAX_FD) {
7812 __skb_unlink(skb, head);
7813 spin_unlock_irq(&head->lock);
7814 fpl->fp[fpl->count] = get_file(file);
7815 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7817 spin_lock_irq(&head->lock);
7818 __skb_queue_head(head, skb);
7823 spin_unlock_irq(&head->lock);
7830 return __io_sqe_files_scm(ctx, 1, index);
7836 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7837 struct io_rsrc_node *node, void *rsrc)
7839 struct io_rsrc_put *prsrc;
7841 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7845 prsrc->tag = *io_get_tag_slot(data, idx);
7847 list_add(&prsrc->list, &node->rsrc_list);
7851 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7852 struct io_uring_rsrc_update2 *up,
7855 u64 __user *tags = u64_to_user_ptr(up->tags);
7856 __s32 __user *fds = u64_to_user_ptr(up->data);
7857 struct io_rsrc_data *data = ctx->file_data;
7858 struct io_fixed_file *file_slot;
7862 bool needs_switch = false;
7864 if (!ctx->file_data)
7866 if (up->offset + nr_args > ctx->nr_user_files)
7869 for (done = 0; done < nr_args; done++) {
7872 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7873 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7877 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7881 if (fd == IORING_REGISTER_FILES_SKIP)
7884 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7885 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7887 if (file_slot->file_ptr) {
7888 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7889 err = io_queue_rsrc_removal(data, up->offset + done,
7890 ctx->rsrc_node, file);
7893 file_slot->file_ptr = 0;
7894 needs_switch = true;
7903 * Don't allow io_uring instances to be registered. If
7904 * UNIX isn't enabled, then this causes a reference
7905 * cycle and this instance can never get freed. If UNIX
7906 * is enabled we'll handle it just fine, but there's
7907 * still no point in allowing a ring fd as it doesn't
7908 * support regular read/write anyway.
7910 if (file->f_op == &io_uring_fops) {
7915 *io_get_tag_slot(data, up->offset + done) = tag;
7916 io_fixed_file_set(file_slot, file);
7917 err = io_sqe_file_register(ctx, file, i);
7919 file_slot->file_ptr = 0;
7927 io_rsrc_node_switch(ctx, data);
7928 return done ? done : err;
7931 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7932 struct task_struct *task)
7934 struct io_wq_hash *hash;
7935 struct io_wq_data data;
7936 unsigned int concurrency;
7938 mutex_lock(&ctx->uring_lock);
7939 hash = ctx->hash_map;
7941 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7943 mutex_unlock(&ctx->uring_lock);
7944 return ERR_PTR(-ENOMEM);
7946 refcount_set(&hash->refs, 1);
7947 init_waitqueue_head(&hash->wait);
7948 ctx->hash_map = hash;
7950 mutex_unlock(&ctx->uring_lock);
7954 data.free_work = io_wq_free_work;
7955 data.do_work = io_wq_submit_work;
7957 /* Do QD, or 4 * CPUS, whatever is smallest */
7958 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7960 return io_wq_create(concurrency, &data);
7963 static int io_uring_alloc_task_context(struct task_struct *task,
7964 struct io_ring_ctx *ctx)
7966 struct io_uring_task *tctx;
7969 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
7970 if (unlikely(!tctx))
7973 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7974 if (unlikely(ret)) {
7979 tctx->io_wq = io_init_wq_offload(ctx, task);
7980 if (IS_ERR(tctx->io_wq)) {
7981 ret = PTR_ERR(tctx->io_wq);
7982 percpu_counter_destroy(&tctx->inflight);
7988 init_waitqueue_head(&tctx->wait);
7989 atomic_set(&tctx->in_idle, 0);
7990 atomic_set(&tctx->inflight_tracked, 0);
7991 task->io_uring = tctx;
7992 spin_lock_init(&tctx->task_lock);
7993 INIT_WQ_LIST(&tctx->task_list);
7994 init_task_work(&tctx->task_work, tctx_task_work);
7998 void __io_uring_free(struct task_struct *tsk)
8000 struct io_uring_task *tctx = tsk->io_uring;
8002 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8003 WARN_ON_ONCE(tctx->io_wq);
8004 WARN_ON_ONCE(tctx->cached_refs);
8006 percpu_counter_destroy(&tctx->inflight);
8008 tsk->io_uring = NULL;
8011 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8012 struct io_uring_params *p)
8016 /* Retain compatibility with failing for an invalid attach attempt */
8017 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8018 IORING_SETUP_ATTACH_WQ) {
8021 f = fdget(p->wq_fd);
8024 if (f.file->f_op != &io_uring_fops) {
8030 if (ctx->flags & IORING_SETUP_SQPOLL) {
8031 struct task_struct *tsk;
8032 struct io_sq_data *sqd;
8035 sqd = io_get_sq_data(p, &attached);
8041 ctx->sq_creds = get_current_cred();
8043 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8044 if (!ctx->sq_thread_idle)
8045 ctx->sq_thread_idle = HZ;
8047 io_sq_thread_park(sqd);
8048 list_add(&ctx->sqd_list, &sqd->ctx_list);
8049 io_sqd_update_thread_idle(sqd);
8050 /* don't attach to a dying SQPOLL thread, would be racy */
8051 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8052 io_sq_thread_unpark(sqd);
8059 if (p->flags & IORING_SETUP_SQ_AFF) {
8060 int cpu = p->sq_thread_cpu;
8063 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8070 sqd->task_pid = current->pid;
8071 sqd->task_tgid = current->tgid;
8072 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8079 ret = io_uring_alloc_task_context(tsk, ctx);
8080 wake_up_new_task(tsk);
8083 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8084 /* Can't have SQ_AFF without SQPOLL */
8091 complete(&ctx->sq_data->exited);
8093 io_sq_thread_finish(ctx);
8097 static inline void __io_unaccount_mem(struct user_struct *user,
8098 unsigned long nr_pages)
8100 atomic_long_sub(nr_pages, &user->locked_vm);
8103 static inline int __io_account_mem(struct user_struct *user,
8104 unsigned long nr_pages)
8106 unsigned long page_limit, cur_pages, new_pages;
8108 /* Don't allow more pages than we can safely lock */
8109 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8112 cur_pages = atomic_long_read(&user->locked_vm);
8113 new_pages = cur_pages + nr_pages;
8114 if (new_pages > page_limit)
8116 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8117 new_pages) != cur_pages);
8122 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8125 __io_unaccount_mem(ctx->user, nr_pages);
8127 if (ctx->mm_account)
8128 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8131 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8136 ret = __io_account_mem(ctx->user, nr_pages);
8141 if (ctx->mm_account)
8142 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8147 static void io_mem_free(void *ptr)
8154 page = virt_to_head_page(ptr);
8155 if (put_page_testzero(page))
8156 free_compound_page(page);
8159 static void *io_mem_alloc(size_t size)
8161 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8162 __GFP_NORETRY | __GFP_ACCOUNT;
8164 return (void *) __get_free_pages(gfp_flags, get_order(size));
8167 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8170 struct io_rings *rings;
8171 size_t off, sq_array_size;
8173 off = struct_size(rings, cqes, cq_entries);
8174 if (off == SIZE_MAX)
8178 off = ALIGN(off, SMP_CACHE_BYTES);
8186 sq_array_size = array_size(sizeof(u32), sq_entries);
8187 if (sq_array_size == SIZE_MAX)
8190 if (check_add_overflow(off, sq_array_size, &off))
8196 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8198 struct io_mapped_ubuf *imu = *slot;
8201 if (imu != ctx->dummy_ubuf) {
8202 for (i = 0; i < imu->nr_bvecs; i++)
8203 unpin_user_page(imu->bvec[i].bv_page);
8204 if (imu->acct_pages)
8205 io_unaccount_mem(ctx, imu->acct_pages);
8211 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8213 io_buffer_unmap(ctx, &prsrc->buf);
8217 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8221 for (i = 0; i < ctx->nr_user_bufs; i++)
8222 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8223 kfree(ctx->user_bufs);
8224 io_rsrc_data_free(ctx->buf_data);
8225 ctx->user_bufs = NULL;
8226 ctx->buf_data = NULL;
8227 ctx->nr_user_bufs = 0;
8230 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8237 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8239 __io_sqe_buffers_unregister(ctx);
8243 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8244 void __user *arg, unsigned index)
8246 struct iovec __user *src;
8248 #ifdef CONFIG_COMPAT
8250 struct compat_iovec __user *ciovs;
8251 struct compat_iovec ciov;
8253 ciovs = (struct compat_iovec __user *) arg;
8254 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8257 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8258 dst->iov_len = ciov.iov_len;
8262 src = (struct iovec __user *) arg;
8263 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8269 * Not super efficient, but this is just a registration time. And we do cache
8270 * the last compound head, so generally we'll only do a full search if we don't
8273 * We check if the given compound head page has already been accounted, to
8274 * avoid double accounting it. This allows us to account the full size of the
8275 * page, not just the constituent pages of a huge page.
8277 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8278 int nr_pages, struct page *hpage)
8282 /* check current page array */
8283 for (i = 0; i < nr_pages; i++) {
8284 if (!PageCompound(pages[i]))
8286 if (compound_head(pages[i]) == hpage)
8290 /* check previously registered pages */
8291 for (i = 0; i < ctx->nr_user_bufs; i++) {
8292 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8294 for (j = 0; j < imu->nr_bvecs; j++) {
8295 if (!PageCompound(imu->bvec[j].bv_page))
8297 if (compound_head(imu->bvec[j].bv_page) == hpage)
8305 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8306 int nr_pages, struct io_mapped_ubuf *imu,
8307 struct page **last_hpage)
8311 imu->acct_pages = 0;
8312 for (i = 0; i < nr_pages; i++) {
8313 if (!PageCompound(pages[i])) {
8318 hpage = compound_head(pages[i]);
8319 if (hpage == *last_hpage)
8321 *last_hpage = hpage;
8322 if (headpage_already_acct(ctx, pages, i, hpage))
8324 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8328 if (!imu->acct_pages)
8331 ret = io_account_mem(ctx, imu->acct_pages);
8333 imu->acct_pages = 0;
8337 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8338 struct io_mapped_ubuf **pimu,
8339 struct page **last_hpage)
8341 struct io_mapped_ubuf *imu = NULL;
8342 struct vm_area_struct **vmas = NULL;
8343 struct page **pages = NULL;
8344 unsigned long off, start, end, ubuf;
8346 int ret, pret, nr_pages, i;
8348 if (!iov->iov_base) {
8349 *pimu = ctx->dummy_ubuf;
8353 ubuf = (unsigned long) iov->iov_base;
8354 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8355 start = ubuf >> PAGE_SHIFT;
8356 nr_pages = end - start;
8361 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8365 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8370 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8375 mmap_read_lock(current->mm);
8376 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8378 if (pret == nr_pages) {
8379 /* don't support file backed memory */
8380 for (i = 0; i < nr_pages; i++) {
8381 struct vm_area_struct *vma = vmas[i];
8383 if (vma_is_shmem(vma))
8386 !is_file_hugepages(vma->vm_file)) {
8392 ret = pret < 0 ? pret : -EFAULT;
8394 mmap_read_unlock(current->mm);
8397 * if we did partial map, or found file backed vmas,
8398 * release any pages we did get
8401 unpin_user_pages(pages, pret);
8405 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8407 unpin_user_pages(pages, pret);
8411 off = ubuf & ~PAGE_MASK;
8412 size = iov->iov_len;
8413 for (i = 0; i < nr_pages; i++) {
8416 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8417 imu->bvec[i].bv_page = pages[i];
8418 imu->bvec[i].bv_len = vec_len;
8419 imu->bvec[i].bv_offset = off;
8423 /* store original address for later verification */
8425 imu->ubuf_end = ubuf + iov->iov_len;
8426 imu->nr_bvecs = nr_pages;
8437 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8439 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8440 return ctx->user_bufs ? 0 : -ENOMEM;
8443 static int io_buffer_validate(struct iovec *iov)
8445 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8448 * Don't impose further limits on the size and buffer
8449 * constraints here, we'll -EINVAL later when IO is
8450 * submitted if they are wrong.
8453 return iov->iov_len ? -EFAULT : 0;
8457 /* arbitrary limit, but we need something */
8458 if (iov->iov_len > SZ_1G)
8461 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8467 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8468 unsigned int nr_args, u64 __user *tags)
8470 struct page *last_hpage = NULL;
8471 struct io_rsrc_data *data;
8477 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8479 ret = io_rsrc_node_switch_start(ctx);
8482 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8485 ret = io_buffers_map_alloc(ctx, nr_args);
8487 io_rsrc_data_free(data);
8491 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8492 ret = io_copy_iov(ctx, &iov, arg, i);
8495 ret = io_buffer_validate(&iov);
8498 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8503 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8509 WARN_ON_ONCE(ctx->buf_data);
8511 ctx->buf_data = data;
8513 __io_sqe_buffers_unregister(ctx);
8515 io_rsrc_node_switch(ctx, NULL);
8519 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8520 struct io_uring_rsrc_update2 *up,
8521 unsigned int nr_args)
8523 u64 __user *tags = u64_to_user_ptr(up->tags);
8524 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8525 struct page *last_hpage = NULL;
8526 bool needs_switch = false;
8532 if (up->offset + nr_args > ctx->nr_user_bufs)
8535 for (done = 0; done < nr_args; done++) {
8536 struct io_mapped_ubuf *imu;
8537 int offset = up->offset + done;
8540 err = io_copy_iov(ctx, &iov, iovs, done);
8543 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8547 err = io_buffer_validate(&iov);
8550 if (!iov.iov_base && tag) {
8554 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8558 i = array_index_nospec(offset, ctx->nr_user_bufs);
8559 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8560 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8561 ctx->rsrc_node, ctx->user_bufs[i]);
8562 if (unlikely(err)) {
8563 io_buffer_unmap(ctx, &imu);
8566 ctx->user_bufs[i] = NULL;
8567 needs_switch = true;
8570 ctx->user_bufs[i] = imu;
8571 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8575 io_rsrc_node_switch(ctx, ctx->buf_data);
8576 return done ? done : err;
8579 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8581 __s32 __user *fds = arg;
8587 if (copy_from_user(&fd, fds, sizeof(*fds)))
8590 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8591 if (IS_ERR(ctx->cq_ev_fd)) {
8592 int ret = PTR_ERR(ctx->cq_ev_fd);
8594 ctx->cq_ev_fd = NULL;
8601 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8603 if (ctx->cq_ev_fd) {
8604 eventfd_ctx_put(ctx->cq_ev_fd);
8605 ctx->cq_ev_fd = NULL;
8612 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8614 struct io_buffer *buf;
8615 unsigned long index;
8617 xa_for_each(&ctx->io_buffers, index, buf)
8618 __io_remove_buffers(ctx, buf, index, -1U);
8621 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8623 struct io_kiocb *req, *nxt;
8625 list_for_each_entry_safe(req, nxt, list, compl.list) {
8626 if (tsk && req->task != tsk)
8628 list_del(&req->compl.list);
8629 kmem_cache_free(req_cachep, req);
8633 static void io_req_caches_free(struct io_ring_ctx *ctx)
8635 struct io_submit_state *submit_state = &ctx->submit_state;
8636 struct io_comp_state *cs = &ctx->submit_state.comp;
8638 mutex_lock(&ctx->uring_lock);
8640 if (submit_state->free_reqs) {
8641 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8642 submit_state->reqs);
8643 submit_state->free_reqs = 0;
8646 io_flush_cached_locked_reqs(ctx, cs);
8647 io_req_cache_free(&cs->free_list, NULL);
8648 mutex_unlock(&ctx->uring_lock);
8651 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8653 if (data && !atomic_dec_and_test(&data->refs))
8654 wait_for_completion(&data->done);
8657 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8659 io_sq_thread_finish(ctx);
8661 if (ctx->mm_account) {
8662 mmdrop(ctx->mm_account);
8663 ctx->mm_account = NULL;
8666 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8667 io_wait_rsrc_data(ctx->buf_data);
8668 io_wait_rsrc_data(ctx->file_data);
8670 mutex_lock(&ctx->uring_lock);
8672 __io_sqe_buffers_unregister(ctx);
8674 __io_sqe_files_unregister(ctx);
8676 __io_cqring_overflow_flush(ctx, true);
8677 mutex_unlock(&ctx->uring_lock);
8678 io_eventfd_unregister(ctx);
8679 io_destroy_buffers(ctx);
8681 put_cred(ctx->sq_creds);
8683 /* there are no registered resources left, nobody uses it */
8685 io_rsrc_node_destroy(ctx->rsrc_node);
8686 if (ctx->rsrc_backup_node)
8687 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8688 flush_delayed_work(&ctx->rsrc_put_work);
8690 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8691 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8693 #if defined(CONFIG_UNIX)
8694 if (ctx->ring_sock) {
8695 ctx->ring_sock->file = NULL; /* so that iput() is called */
8696 sock_release(ctx->ring_sock);
8700 io_mem_free(ctx->rings);
8701 io_mem_free(ctx->sq_sqes);
8703 percpu_ref_exit(&ctx->refs);
8704 free_uid(ctx->user);
8705 io_req_caches_free(ctx);
8707 io_wq_put_hash(ctx->hash_map);
8708 kfree(ctx->cancel_hash);
8709 kfree(ctx->dummy_ubuf);
8713 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8715 struct io_ring_ctx *ctx = file->private_data;
8718 poll_wait(file, &ctx->poll_wait, wait);
8720 * synchronizes with barrier from wq_has_sleeper call in
8724 if (!io_sqring_full(ctx))
8725 mask |= EPOLLOUT | EPOLLWRNORM;
8728 * Don't flush cqring overflow list here, just do a simple check.
8729 * Otherwise there could possible be ABBA deadlock:
8732 * lock(&ctx->uring_lock);
8734 * lock(&ctx->uring_lock);
8737 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8738 * pushs them to do the flush.
8740 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8741 mask |= EPOLLIN | EPOLLRDNORM;
8746 static int io_uring_fasync(int fd, struct file *file, int on)
8748 struct io_ring_ctx *ctx = file->private_data;
8750 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8753 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8755 const struct cred *creds;
8757 creds = xa_erase(&ctx->personalities, id);
8766 struct io_tctx_exit {
8767 struct callback_head task_work;
8768 struct completion completion;
8769 struct io_ring_ctx *ctx;
8772 static void io_tctx_exit_cb(struct callback_head *cb)
8774 struct io_uring_task *tctx = current->io_uring;
8775 struct io_tctx_exit *work;
8777 work = container_of(cb, struct io_tctx_exit, task_work);
8779 * When @in_idle, we're in cancellation and it's racy to remove the
8780 * node. It'll be removed by the end of cancellation, just ignore it.
8782 if (!atomic_read(&tctx->in_idle))
8783 io_uring_del_tctx_node((unsigned long)work->ctx);
8784 complete(&work->completion);
8787 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8789 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8791 return req->ctx == data;
8794 static void io_ring_exit_work(struct work_struct *work)
8796 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8797 unsigned long timeout = jiffies + HZ * 60 * 5;
8798 struct io_tctx_exit exit;
8799 struct io_tctx_node *node;
8803 * If we're doing polled IO and end up having requests being
8804 * submitted async (out-of-line), then completions can come in while
8805 * we're waiting for refs to drop. We need to reap these manually,
8806 * as nobody else will be looking for them.
8809 io_uring_try_cancel_requests(ctx, NULL, true);
8811 struct io_sq_data *sqd = ctx->sq_data;
8812 struct task_struct *tsk;
8814 io_sq_thread_park(sqd);
8816 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8817 io_wq_cancel_cb(tsk->io_uring->io_wq,
8818 io_cancel_ctx_cb, ctx, true);
8819 io_sq_thread_unpark(sqd);
8822 WARN_ON_ONCE(time_after(jiffies, timeout));
8823 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8825 init_completion(&exit.completion);
8826 init_task_work(&exit.task_work, io_tctx_exit_cb);
8829 * Some may use context even when all refs and requests have been put,
8830 * and they are free to do so while still holding uring_lock or
8831 * completion_lock, see io_req_task_submit(). Apart from other work,
8832 * this lock/unlock section also waits them to finish.
8834 mutex_lock(&ctx->uring_lock);
8835 while (!list_empty(&ctx->tctx_list)) {
8836 WARN_ON_ONCE(time_after(jiffies, timeout));
8838 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8840 /* don't spin on a single task if cancellation failed */
8841 list_rotate_left(&ctx->tctx_list);
8842 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8843 if (WARN_ON_ONCE(ret))
8845 wake_up_process(node->task);
8847 mutex_unlock(&ctx->uring_lock);
8848 wait_for_completion(&exit.completion);
8849 mutex_lock(&ctx->uring_lock);
8851 mutex_unlock(&ctx->uring_lock);
8852 spin_lock_irq(&ctx->completion_lock);
8853 spin_unlock_irq(&ctx->completion_lock);
8855 io_ring_ctx_free(ctx);
8858 /* Returns true if we found and killed one or more timeouts */
8859 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8862 struct io_kiocb *req, *tmp;
8865 spin_lock_irq(&ctx->completion_lock);
8866 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8867 if (io_match_task(req, tsk, cancel_all)) {
8868 io_kill_timeout(req, -ECANCELED);
8873 io_commit_cqring(ctx);
8874 spin_unlock_irq(&ctx->completion_lock);
8876 io_cqring_ev_posted(ctx);
8877 return canceled != 0;
8880 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8882 unsigned long index;
8883 struct creds *creds;
8885 mutex_lock(&ctx->uring_lock);
8886 percpu_ref_kill(&ctx->refs);
8888 __io_cqring_overflow_flush(ctx, true);
8889 xa_for_each(&ctx->personalities, index, creds)
8890 io_unregister_personality(ctx, index);
8891 mutex_unlock(&ctx->uring_lock);
8893 io_kill_timeouts(ctx, NULL, true);
8894 io_poll_remove_all(ctx, NULL, true);
8896 /* if we failed setting up the ctx, we might not have any rings */
8897 io_iopoll_try_reap_events(ctx);
8899 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8901 * Use system_unbound_wq to avoid spawning tons of event kworkers
8902 * if we're exiting a ton of rings at the same time. It just adds
8903 * noise and overhead, there's no discernable change in runtime
8904 * over using system_wq.
8906 queue_work(system_unbound_wq, &ctx->exit_work);
8909 static int io_uring_release(struct inode *inode, struct file *file)
8911 struct io_ring_ctx *ctx = file->private_data;
8913 file->private_data = NULL;
8914 io_ring_ctx_wait_and_kill(ctx);
8918 struct io_task_cancel {
8919 struct task_struct *task;
8923 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8925 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8926 struct io_task_cancel *cancel = data;
8929 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
8930 unsigned long flags;
8931 struct io_ring_ctx *ctx = req->ctx;
8933 /* protect against races with linked timeouts */
8934 spin_lock_irqsave(&ctx->completion_lock, flags);
8935 ret = io_match_task(req, cancel->task, cancel->all);
8936 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8938 ret = io_match_task(req, cancel->task, cancel->all);
8943 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8944 struct task_struct *task, bool cancel_all)
8946 struct io_defer_entry *de;
8949 spin_lock_irq(&ctx->completion_lock);
8950 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8951 if (io_match_task(de->req, task, cancel_all)) {
8952 list_cut_position(&list, &ctx->defer_list, &de->list);
8956 spin_unlock_irq(&ctx->completion_lock);
8957 if (list_empty(&list))
8960 while (!list_empty(&list)) {
8961 de = list_first_entry(&list, struct io_defer_entry, list);
8962 list_del_init(&de->list);
8963 io_req_complete_failed(de->req, -ECANCELED);
8969 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8971 struct io_tctx_node *node;
8972 enum io_wq_cancel cret;
8975 mutex_lock(&ctx->uring_lock);
8976 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8977 struct io_uring_task *tctx = node->task->io_uring;
8980 * io_wq will stay alive while we hold uring_lock, because it's
8981 * killed after ctx nodes, which requires to take the lock.
8983 if (!tctx || !tctx->io_wq)
8985 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8986 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8988 mutex_unlock(&ctx->uring_lock);
8993 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8994 struct task_struct *task,
8997 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
8998 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9001 enum io_wq_cancel cret;
9005 ret |= io_uring_try_cancel_iowq(ctx);
9006 } else if (tctx && tctx->io_wq) {
9008 * Cancels requests of all rings, not only @ctx, but
9009 * it's fine as the task is in exit/exec.
9011 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9013 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9016 /* SQPOLL thread does its own polling */
9017 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9018 (ctx->sq_data && ctx->sq_data->thread == current)) {
9019 while (!list_empty_careful(&ctx->iopoll_list)) {
9020 io_iopoll_try_reap_events(ctx);
9025 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9026 ret |= io_poll_remove_all(ctx, task, cancel_all);
9027 ret |= io_kill_timeouts(ctx, task, cancel_all);
9029 ret |= io_run_task_work();
9036 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9038 struct io_uring_task *tctx = current->io_uring;
9039 struct io_tctx_node *node;
9042 if (unlikely(!tctx)) {
9043 ret = io_uring_alloc_task_context(current, ctx);
9046 tctx = current->io_uring;
9048 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9049 node = kmalloc(sizeof(*node), GFP_KERNEL);
9053 node->task = current;
9055 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9062 mutex_lock(&ctx->uring_lock);
9063 list_add(&node->ctx_node, &ctx->tctx_list);
9064 mutex_unlock(&ctx->uring_lock);
9071 * Note that this task has used io_uring. We use it for cancelation purposes.
9073 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9075 struct io_uring_task *tctx = current->io_uring;
9077 if (likely(tctx && tctx->last == ctx))
9079 return __io_uring_add_tctx_node(ctx);
9083 * Remove this io_uring_file -> task mapping.
9085 static void io_uring_del_tctx_node(unsigned long index)
9087 struct io_uring_task *tctx = current->io_uring;
9088 struct io_tctx_node *node;
9092 node = xa_erase(&tctx->xa, index);
9096 WARN_ON_ONCE(current != node->task);
9097 WARN_ON_ONCE(list_empty(&node->ctx_node));
9099 mutex_lock(&node->ctx->uring_lock);
9100 list_del(&node->ctx_node);
9101 mutex_unlock(&node->ctx->uring_lock);
9103 if (tctx->last == node->ctx)
9108 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9110 struct io_wq *wq = tctx->io_wq;
9111 struct io_tctx_node *node;
9112 unsigned long index;
9114 xa_for_each(&tctx->xa, index, node)
9115 io_uring_del_tctx_node(index);
9118 * Must be after io_uring_del_task_file() (removes nodes under
9119 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9122 io_wq_put_and_exit(wq);
9126 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9129 return atomic_read(&tctx->inflight_tracked);
9130 return percpu_counter_sum(&tctx->inflight);
9133 static void io_uring_drop_tctx_refs(struct task_struct *task)
9135 struct io_uring_task *tctx = task->io_uring;
9136 unsigned int refs = tctx->cached_refs;
9138 tctx->cached_refs = 0;
9139 percpu_counter_sub(&tctx->inflight, refs);
9140 put_task_struct_many(task, refs);
9144 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9145 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9147 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9149 struct io_uring_task *tctx = current->io_uring;
9150 struct io_ring_ctx *ctx;
9154 WARN_ON_ONCE(sqd && sqd->thread != current);
9156 if (!current->io_uring)
9159 io_wq_exit_start(tctx->io_wq);
9161 io_uring_drop_tctx_refs(current);
9162 atomic_inc(&tctx->in_idle);
9164 /* read completions before cancelations */
9165 inflight = tctx_inflight(tctx, !cancel_all);
9170 struct io_tctx_node *node;
9171 unsigned long index;
9173 xa_for_each(&tctx->xa, index, node) {
9174 /* sqpoll task will cancel all its requests */
9175 if (node->ctx->sq_data)
9177 io_uring_try_cancel_requests(node->ctx, current,
9181 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9182 io_uring_try_cancel_requests(ctx, current,
9186 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9188 * If we've seen completions, retry without waiting. This
9189 * avoids a race where a completion comes in before we did
9190 * prepare_to_wait().
9192 if (inflight == tctx_inflight(tctx, !cancel_all))
9194 finish_wait(&tctx->wait, &wait);
9196 atomic_dec(&tctx->in_idle);
9198 io_uring_clean_tctx(tctx);
9200 /* for exec all current's requests should be gone, kill tctx */
9201 __io_uring_free(current);
9205 void __io_uring_cancel(struct files_struct *files)
9207 io_uring_cancel_generic(!files, NULL);
9210 static void *io_uring_validate_mmap_request(struct file *file,
9211 loff_t pgoff, size_t sz)
9213 struct io_ring_ctx *ctx = file->private_data;
9214 loff_t offset = pgoff << PAGE_SHIFT;
9219 case IORING_OFF_SQ_RING:
9220 case IORING_OFF_CQ_RING:
9223 case IORING_OFF_SQES:
9227 return ERR_PTR(-EINVAL);
9230 page = virt_to_head_page(ptr);
9231 if (sz > page_size(page))
9232 return ERR_PTR(-EINVAL);
9239 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9241 size_t sz = vma->vm_end - vma->vm_start;
9245 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9247 return PTR_ERR(ptr);
9249 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9250 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9253 #else /* !CONFIG_MMU */
9255 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9257 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9260 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9262 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9265 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9266 unsigned long addr, unsigned long len,
9267 unsigned long pgoff, unsigned long flags)
9271 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9273 return PTR_ERR(ptr);
9275 return (unsigned long) ptr;
9278 #endif /* !CONFIG_MMU */
9280 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9285 if (!io_sqring_full(ctx))
9287 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9289 if (!io_sqring_full(ctx))
9292 } while (!signal_pending(current));
9294 finish_wait(&ctx->sqo_sq_wait, &wait);
9298 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9299 struct __kernel_timespec __user **ts,
9300 const sigset_t __user **sig)
9302 struct io_uring_getevents_arg arg;
9305 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9306 * is just a pointer to the sigset_t.
9308 if (!(flags & IORING_ENTER_EXT_ARG)) {
9309 *sig = (const sigset_t __user *) argp;
9315 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9316 * timespec and sigset_t pointers if good.
9318 if (*argsz != sizeof(arg))
9320 if (copy_from_user(&arg, argp, sizeof(arg)))
9322 *sig = u64_to_user_ptr(arg.sigmask);
9323 *argsz = arg.sigmask_sz;
9324 *ts = u64_to_user_ptr(arg.ts);
9328 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9329 u32, min_complete, u32, flags, const void __user *, argp,
9332 struct io_ring_ctx *ctx;
9339 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9340 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9344 if (unlikely(!f.file))
9348 if (unlikely(f.file->f_op != &io_uring_fops))
9352 ctx = f.file->private_data;
9353 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9357 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9361 * For SQ polling, the thread will do all submissions and completions.
9362 * Just return the requested submit count, and wake the thread if
9366 if (ctx->flags & IORING_SETUP_SQPOLL) {
9367 io_cqring_overflow_flush(ctx, false);
9369 if (unlikely(ctx->sq_data->thread == NULL)) {
9373 if (flags & IORING_ENTER_SQ_WAKEUP)
9374 wake_up(&ctx->sq_data->wait);
9375 if (flags & IORING_ENTER_SQ_WAIT) {
9376 ret = io_sqpoll_wait_sq(ctx);
9380 submitted = to_submit;
9381 } else if (to_submit) {
9382 ret = io_uring_add_tctx_node(ctx);
9385 mutex_lock(&ctx->uring_lock);
9386 submitted = io_submit_sqes(ctx, to_submit);
9387 mutex_unlock(&ctx->uring_lock);
9389 if (submitted != to_submit)
9392 if (flags & IORING_ENTER_GETEVENTS) {
9393 const sigset_t __user *sig;
9394 struct __kernel_timespec __user *ts;
9396 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9400 min_complete = min(min_complete, ctx->cq_entries);
9403 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9404 * space applications don't need to do io completion events
9405 * polling again, they can rely on io_sq_thread to do polling
9406 * work, which can reduce cpu usage and uring_lock contention.
9408 if (ctx->flags & IORING_SETUP_IOPOLL &&
9409 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9410 ret = io_iopoll_check(ctx, min_complete);
9412 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9417 percpu_ref_put(&ctx->refs);
9420 return submitted ? submitted : ret;
9423 #ifdef CONFIG_PROC_FS
9424 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9425 const struct cred *cred)
9427 struct user_namespace *uns = seq_user_ns(m);
9428 struct group_info *gi;
9433 seq_printf(m, "%5d\n", id);
9434 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9435 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9436 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9437 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9438 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9439 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9440 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9441 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9442 seq_puts(m, "\n\tGroups:\t");
9443 gi = cred->group_info;
9444 for (g = 0; g < gi->ngroups; g++) {
9445 seq_put_decimal_ull(m, g ? " " : "",
9446 from_kgid_munged(uns, gi->gid[g]));
9448 seq_puts(m, "\n\tCapEff:\t");
9449 cap = cred->cap_effective;
9450 CAP_FOR_EACH_U32(__capi)
9451 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9456 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9458 struct io_sq_data *sq = NULL;
9463 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9464 * since fdinfo case grabs it in the opposite direction of normal use
9465 * cases. If we fail to get the lock, we just don't iterate any
9466 * structures that could be going away outside the io_uring mutex.
9468 has_lock = mutex_trylock(&ctx->uring_lock);
9470 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9476 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9477 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9478 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9479 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9480 struct file *f = io_file_from_index(ctx, i);
9483 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9485 seq_printf(m, "%5u: <none>\n", i);
9487 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9488 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9489 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9490 unsigned int len = buf->ubuf_end - buf->ubuf;
9492 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9494 if (has_lock && !xa_empty(&ctx->personalities)) {
9495 unsigned long index;
9496 const struct cred *cred;
9498 seq_printf(m, "Personalities:\n");
9499 xa_for_each(&ctx->personalities, index, cred)
9500 io_uring_show_cred(m, index, cred);
9502 seq_printf(m, "PollList:\n");
9503 spin_lock_irq(&ctx->completion_lock);
9504 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9505 struct hlist_head *list = &ctx->cancel_hash[i];
9506 struct io_kiocb *req;
9508 hlist_for_each_entry(req, list, hash_node)
9509 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9510 req->task->task_works != NULL);
9512 spin_unlock_irq(&ctx->completion_lock);
9514 mutex_unlock(&ctx->uring_lock);
9517 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9519 struct io_ring_ctx *ctx = f->private_data;
9521 if (percpu_ref_tryget(&ctx->refs)) {
9522 __io_uring_show_fdinfo(ctx, m);
9523 percpu_ref_put(&ctx->refs);
9528 static const struct file_operations io_uring_fops = {
9529 .release = io_uring_release,
9530 .mmap = io_uring_mmap,
9532 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9533 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9535 .poll = io_uring_poll,
9536 .fasync = io_uring_fasync,
9537 #ifdef CONFIG_PROC_FS
9538 .show_fdinfo = io_uring_show_fdinfo,
9542 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9543 struct io_uring_params *p)
9545 struct io_rings *rings;
9546 size_t size, sq_array_offset;
9548 /* make sure these are sane, as we already accounted them */
9549 ctx->sq_entries = p->sq_entries;
9550 ctx->cq_entries = p->cq_entries;
9552 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9553 if (size == SIZE_MAX)
9556 rings = io_mem_alloc(size);
9561 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9562 rings->sq_ring_mask = p->sq_entries - 1;
9563 rings->cq_ring_mask = p->cq_entries - 1;
9564 rings->sq_ring_entries = p->sq_entries;
9565 rings->cq_ring_entries = p->cq_entries;
9567 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9568 if (size == SIZE_MAX) {
9569 io_mem_free(ctx->rings);
9574 ctx->sq_sqes = io_mem_alloc(size);
9575 if (!ctx->sq_sqes) {
9576 io_mem_free(ctx->rings);
9584 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9588 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9592 ret = io_uring_add_tctx_node(ctx);
9597 fd_install(fd, file);
9602 * Allocate an anonymous fd, this is what constitutes the application
9603 * visible backing of an io_uring instance. The application mmaps this
9604 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9605 * we have to tie this fd to a socket for file garbage collection purposes.
9607 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9610 #if defined(CONFIG_UNIX)
9613 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9616 return ERR_PTR(ret);
9619 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9620 O_RDWR | O_CLOEXEC);
9621 #if defined(CONFIG_UNIX)
9623 sock_release(ctx->ring_sock);
9624 ctx->ring_sock = NULL;
9626 ctx->ring_sock->file = file;
9632 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9633 struct io_uring_params __user *params)
9635 struct io_ring_ctx *ctx;
9641 if (entries > IORING_MAX_ENTRIES) {
9642 if (!(p->flags & IORING_SETUP_CLAMP))
9644 entries = IORING_MAX_ENTRIES;
9648 * Use twice as many entries for the CQ ring. It's possible for the
9649 * application to drive a higher depth than the size of the SQ ring,
9650 * since the sqes are only used at submission time. This allows for
9651 * some flexibility in overcommitting a bit. If the application has
9652 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9653 * of CQ ring entries manually.
9655 p->sq_entries = roundup_pow_of_two(entries);
9656 if (p->flags & IORING_SETUP_CQSIZE) {
9658 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9659 * to a power-of-two, if it isn't already. We do NOT impose
9660 * any cq vs sq ring sizing.
9664 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9665 if (!(p->flags & IORING_SETUP_CLAMP))
9667 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9669 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9670 if (p->cq_entries < p->sq_entries)
9673 p->cq_entries = 2 * p->sq_entries;
9676 ctx = io_ring_ctx_alloc(p);
9679 ctx->compat = in_compat_syscall();
9680 if (!capable(CAP_IPC_LOCK))
9681 ctx->user = get_uid(current_user());
9684 * This is just grabbed for accounting purposes. When a process exits,
9685 * the mm is exited and dropped before the files, hence we need to hang
9686 * on to this mm purely for the purposes of being able to unaccount
9687 * memory (locked/pinned vm). It's not used for anything else.
9689 mmgrab(current->mm);
9690 ctx->mm_account = current->mm;
9692 ret = io_allocate_scq_urings(ctx, p);
9696 ret = io_sq_offload_create(ctx, p);
9699 /* always set a rsrc node */
9700 ret = io_rsrc_node_switch_start(ctx);
9703 io_rsrc_node_switch(ctx, NULL);
9705 memset(&p->sq_off, 0, sizeof(p->sq_off));
9706 p->sq_off.head = offsetof(struct io_rings, sq.head);
9707 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9708 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9709 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9710 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9711 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9712 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9714 memset(&p->cq_off, 0, sizeof(p->cq_off));
9715 p->cq_off.head = offsetof(struct io_rings, cq.head);
9716 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9717 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9718 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9719 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9720 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9721 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9723 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9724 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9725 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9726 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9727 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9728 IORING_FEAT_RSRC_TAGS;
9730 if (copy_to_user(params, p, sizeof(*p))) {
9735 file = io_uring_get_file(ctx);
9737 ret = PTR_ERR(file);
9742 * Install ring fd as the very last thing, so we don't risk someone
9743 * having closed it before we finish setup
9745 ret = io_uring_install_fd(ctx, file);
9747 /* fput will clean it up */
9752 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9755 io_ring_ctx_wait_and_kill(ctx);
9760 * Sets up an aio uring context, and returns the fd. Applications asks for a
9761 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9762 * params structure passed in.
9764 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9766 struct io_uring_params p;
9769 if (copy_from_user(&p, params, sizeof(p)))
9771 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9776 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9777 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9778 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9779 IORING_SETUP_R_DISABLED))
9782 return io_uring_create(entries, &p, params);
9785 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9786 struct io_uring_params __user *, params)
9788 return io_uring_setup(entries, params);
9791 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9793 struct io_uring_probe *p;
9797 size = struct_size(p, ops, nr_args);
9798 if (size == SIZE_MAX)
9800 p = kzalloc(size, GFP_KERNEL);
9805 if (copy_from_user(p, arg, size))
9808 if (memchr_inv(p, 0, size))
9811 p->last_op = IORING_OP_LAST - 1;
9812 if (nr_args > IORING_OP_LAST)
9813 nr_args = IORING_OP_LAST;
9815 for (i = 0; i < nr_args; i++) {
9817 if (!io_op_defs[i].not_supported)
9818 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9823 if (copy_to_user(arg, p, size))
9830 static int io_register_personality(struct io_ring_ctx *ctx)
9832 const struct cred *creds;
9836 creds = get_current_cred();
9838 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9839 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9847 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9848 unsigned int nr_args)
9850 struct io_uring_restriction *res;
9854 /* Restrictions allowed only if rings started disabled */
9855 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9858 /* We allow only a single restrictions registration */
9859 if (ctx->restrictions.registered)
9862 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9865 size = array_size(nr_args, sizeof(*res));
9866 if (size == SIZE_MAX)
9869 res = memdup_user(arg, size);
9871 return PTR_ERR(res);
9875 for (i = 0; i < nr_args; i++) {
9876 switch (res[i].opcode) {
9877 case IORING_RESTRICTION_REGISTER_OP:
9878 if (res[i].register_op >= IORING_REGISTER_LAST) {
9883 __set_bit(res[i].register_op,
9884 ctx->restrictions.register_op);
9886 case IORING_RESTRICTION_SQE_OP:
9887 if (res[i].sqe_op >= IORING_OP_LAST) {
9892 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9894 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9895 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9897 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9898 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9907 /* Reset all restrictions if an error happened */
9909 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9911 ctx->restrictions.registered = true;
9917 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9919 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9922 if (ctx->restrictions.registered)
9923 ctx->restricted = 1;
9925 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9926 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9927 wake_up(&ctx->sq_data->wait);
9931 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9932 struct io_uring_rsrc_update2 *up,
9940 if (check_add_overflow(up->offset, nr_args, &tmp))
9942 err = io_rsrc_node_switch_start(ctx);
9947 case IORING_RSRC_FILE:
9948 return __io_sqe_files_update(ctx, up, nr_args);
9949 case IORING_RSRC_BUFFER:
9950 return __io_sqe_buffers_update(ctx, up, nr_args);
9955 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9958 struct io_uring_rsrc_update2 up;
9962 memset(&up, 0, sizeof(up));
9963 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9965 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9968 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9969 unsigned size, unsigned type)
9971 struct io_uring_rsrc_update2 up;
9973 if (size != sizeof(up))
9975 if (copy_from_user(&up, arg, sizeof(up)))
9977 if (!up.nr || up.resv)
9979 return __io_register_rsrc_update(ctx, type, &up, up.nr);
9982 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9983 unsigned int size, unsigned int type)
9985 struct io_uring_rsrc_register rr;
9987 /* keep it extendible */
9988 if (size != sizeof(rr))
9991 memset(&rr, 0, sizeof(rr));
9992 if (copy_from_user(&rr, arg, size))
9994 if (!rr.nr || rr.resv || rr.resv2)
9998 case IORING_RSRC_FILE:
9999 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10000 rr.nr, u64_to_user_ptr(rr.tags));
10001 case IORING_RSRC_BUFFER:
10002 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10003 rr.nr, u64_to_user_ptr(rr.tags));
10008 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10011 struct io_uring_task *tctx = current->io_uring;
10012 cpumask_var_t new_mask;
10015 if (!tctx || !tctx->io_wq)
10018 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10021 cpumask_clear(new_mask);
10022 if (len > cpumask_size())
10023 len = cpumask_size();
10025 if (copy_from_user(new_mask, arg, len)) {
10026 free_cpumask_var(new_mask);
10030 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10031 free_cpumask_var(new_mask);
10035 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10037 struct io_uring_task *tctx = current->io_uring;
10039 if (!tctx || !tctx->io_wq)
10042 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10045 static bool io_register_op_must_quiesce(int op)
10048 case IORING_REGISTER_BUFFERS:
10049 case IORING_UNREGISTER_BUFFERS:
10050 case IORING_REGISTER_FILES:
10051 case IORING_UNREGISTER_FILES:
10052 case IORING_REGISTER_FILES_UPDATE:
10053 case IORING_REGISTER_PROBE:
10054 case IORING_REGISTER_PERSONALITY:
10055 case IORING_UNREGISTER_PERSONALITY:
10056 case IORING_REGISTER_FILES2:
10057 case IORING_REGISTER_FILES_UPDATE2:
10058 case IORING_REGISTER_BUFFERS2:
10059 case IORING_REGISTER_BUFFERS_UPDATE:
10060 case IORING_REGISTER_IOWQ_AFF:
10061 case IORING_UNREGISTER_IOWQ_AFF:
10068 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10072 percpu_ref_kill(&ctx->refs);
10075 * Drop uring mutex before waiting for references to exit. If another
10076 * thread is currently inside io_uring_enter() it might need to grab the
10077 * uring_lock to make progress. If we hold it here across the drain
10078 * wait, then we can deadlock. It's safe to drop the mutex here, since
10079 * no new references will come in after we've killed the percpu ref.
10081 mutex_unlock(&ctx->uring_lock);
10083 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10086 ret = io_run_task_work_sig();
10087 } while (ret >= 0);
10088 mutex_lock(&ctx->uring_lock);
10091 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10095 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10096 void __user *arg, unsigned nr_args)
10097 __releases(ctx->uring_lock)
10098 __acquires(ctx->uring_lock)
10103 * We're inside the ring mutex, if the ref is already dying, then
10104 * someone else killed the ctx or is already going through
10105 * io_uring_register().
10107 if (percpu_ref_is_dying(&ctx->refs))
10110 if (ctx->restricted) {
10111 if (opcode >= IORING_REGISTER_LAST)
10113 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10114 if (!test_bit(opcode, ctx->restrictions.register_op))
10118 if (io_register_op_must_quiesce(opcode)) {
10119 ret = io_ctx_quiesce(ctx);
10125 case IORING_REGISTER_BUFFERS:
10126 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10128 case IORING_UNREGISTER_BUFFERS:
10130 if (arg || nr_args)
10132 ret = io_sqe_buffers_unregister(ctx);
10134 case IORING_REGISTER_FILES:
10135 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10137 case IORING_UNREGISTER_FILES:
10139 if (arg || nr_args)
10141 ret = io_sqe_files_unregister(ctx);
10143 case IORING_REGISTER_FILES_UPDATE:
10144 ret = io_register_files_update(ctx, arg, nr_args);
10146 case IORING_REGISTER_EVENTFD:
10147 case IORING_REGISTER_EVENTFD_ASYNC:
10151 ret = io_eventfd_register(ctx, arg);
10154 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10155 ctx->eventfd_async = 1;
10157 ctx->eventfd_async = 0;
10159 case IORING_UNREGISTER_EVENTFD:
10161 if (arg || nr_args)
10163 ret = io_eventfd_unregister(ctx);
10165 case IORING_REGISTER_PROBE:
10167 if (!arg || nr_args > 256)
10169 ret = io_probe(ctx, arg, nr_args);
10171 case IORING_REGISTER_PERSONALITY:
10173 if (arg || nr_args)
10175 ret = io_register_personality(ctx);
10177 case IORING_UNREGISTER_PERSONALITY:
10181 ret = io_unregister_personality(ctx, nr_args);
10183 case IORING_REGISTER_ENABLE_RINGS:
10185 if (arg || nr_args)
10187 ret = io_register_enable_rings(ctx);
10189 case IORING_REGISTER_RESTRICTIONS:
10190 ret = io_register_restrictions(ctx, arg, nr_args);
10192 case IORING_REGISTER_FILES2:
10193 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10195 case IORING_REGISTER_FILES_UPDATE2:
10196 ret = io_register_rsrc_update(ctx, arg, nr_args,
10199 case IORING_REGISTER_BUFFERS2:
10200 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10202 case IORING_REGISTER_BUFFERS_UPDATE:
10203 ret = io_register_rsrc_update(ctx, arg, nr_args,
10204 IORING_RSRC_BUFFER);
10206 case IORING_REGISTER_IOWQ_AFF:
10208 if (!arg || !nr_args)
10210 ret = io_register_iowq_aff(ctx, arg, nr_args);
10212 case IORING_UNREGISTER_IOWQ_AFF:
10214 if (arg || nr_args)
10216 ret = io_unregister_iowq_aff(ctx);
10223 if (io_register_op_must_quiesce(opcode)) {
10224 /* bring the ctx back to life */
10225 percpu_ref_reinit(&ctx->refs);
10226 reinit_completion(&ctx->ref_comp);
10231 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10232 void __user *, arg, unsigned int, nr_args)
10234 struct io_ring_ctx *ctx;
10243 if (f.file->f_op != &io_uring_fops)
10246 ctx = f.file->private_data;
10248 io_run_task_work();
10250 mutex_lock(&ctx->uring_lock);
10251 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10252 mutex_unlock(&ctx->uring_lock);
10253 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10254 ctx->cq_ev_fd != NULL, ret);
10260 static int __init io_uring_init(void)
10262 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10263 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10264 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10267 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10268 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10269 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10270 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10271 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10272 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10273 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10274 BUILD_BUG_SQE_ELEM(8, __u64, off);
10275 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10276 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10277 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10278 BUILD_BUG_SQE_ELEM(24, __u32, len);
10279 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10280 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10281 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10282 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10283 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10284 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10285 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10286 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10287 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10288 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10289 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10290 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10291 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10292 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10293 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10294 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10295 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10296 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10297 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10298 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10300 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10301 sizeof(struct io_uring_rsrc_update));
10302 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10303 sizeof(struct io_uring_rsrc_update2));
10304 /* should fit into one byte */
10305 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10307 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10308 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10310 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10314 __initcall(io_uring_init);