1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/tracehook.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
93 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96 #define IORING_MAX_FIXED_FILES (1U << 15)
97 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
98 IORING_REGISTER_LAST + IORING_OP_LAST)
100 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
101 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
102 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
104 #define IORING_MAX_REG_BUFFERS (1U << 14)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
109 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
110 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
112 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
115 u32 head ____cacheline_aligned_in_smp;
116 u32 tail ____cacheline_aligned_in_smp;
120 * This data is shared with the application through the mmap at offsets
121 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
123 * The offsets to the member fields are published through struct
124 * io_sqring_offsets when calling io_uring_setup.
128 * Head and tail offsets into the ring; the offsets need to be
129 * masked to get valid indices.
131 * The kernel controls head of the sq ring and the tail of the cq ring,
132 * and the application controls tail of the sq ring and the head of the
135 struct io_uring sq, cq;
137 * Bitmasks to apply to head and tail offsets (constant, equals
140 u32 sq_ring_mask, cq_ring_mask;
141 /* Ring sizes (constant, power of 2) */
142 u32 sq_ring_entries, cq_ring_entries;
144 * Number of invalid entries dropped by the kernel due to
145 * invalid index stored in array
147 * Written by the kernel, shouldn't be modified by the
148 * application (i.e. get number of "new events" by comparing to
151 * After a new SQ head value was read by the application this
152 * counter includes all submissions that were dropped reaching
153 * the new SQ head (and possibly more).
159 * Written by the kernel, shouldn't be modified by the
162 * The application needs a full memory barrier before checking
163 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
169 * Written by the application, shouldn't be modified by the
174 * Number of completion events lost because the queue was full;
175 * this should be avoided by the application by making sure
176 * there are not more requests pending than there is space in
177 * the completion queue.
179 * Written by the kernel, shouldn't be modified by the
180 * application (i.e. get number of "new events" by comparing to
183 * As completion events come in out of order this counter is not
184 * ordered with any other data.
188 * Ring buffer of completion events.
190 * The kernel writes completion events fresh every time they are
191 * produced, so the application is allowed to modify pending
194 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
197 enum io_uring_cmd_flags {
198 IO_URING_F_NONBLOCK = 1,
199 IO_URING_F_COMPLETE_DEFER = 2,
202 struct io_mapped_ubuf {
205 unsigned int nr_bvecs;
206 unsigned long acct_pages;
207 struct bio_vec bvec[];
212 struct io_overflow_cqe {
213 struct io_uring_cqe cqe;
214 struct list_head list;
217 struct io_fixed_file {
218 /* file * with additional FFS_* flags */
219 unsigned long file_ptr;
223 struct list_head list;
228 struct io_mapped_ubuf *buf;
232 struct io_file_table {
233 struct io_fixed_file *files;
236 struct io_rsrc_node {
237 struct percpu_ref refs;
238 struct list_head node;
239 struct list_head rsrc_list;
240 struct io_rsrc_data *rsrc_data;
241 struct llist_node llist;
245 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
247 struct io_rsrc_data {
248 struct io_ring_ctx *ctx;
254 struct completion done;
259 struct list_head list;
265 struct io_restriction {
266 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
267 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
268 u8 sqe_flags_allowed;
269 u8 sqe_flags_required;
274 IO_SQ_THREAD_SHOULD_STOP = 0,
275 IO_SQ_THREAD_SHOULD_PARK,
280 atomic_t park_pending;
283 /* ctx's that are using this sqd */
284 struct list_head ctx_list;
286 struct task_struct *thread;
287 struct wait_queue_head wait;
289 unsigned sq_thread_idle;
295 struct completion exited;
298 #define IO_COMPL_BATCH 32
299 #define IO_REQ_CACHE_SIZE 32
300 #define IO_REQ_ALLOC_BATCH 8
302 struct io_submit_link {
303 struct io_kiocb *head;
304 struct io_kiocb *last;
307 struct io_submit_state {
308 struct blk_plug plug;
309 struct io_submit_link link;
312 * io_kiocb alloc cache
314 void *reqs[IO_REQ_CACHE_SIZE];
315 unsigned int free_reqs;
320 * Batch completion logic
322 struct io_kiocb *compl_reqs[IO_COMPL_BATCH];
323 unsigned int compl_nr;
324 /* inline/task_work completion list, under ->uring_lock */
325 struct list_head free_list;
327 unsigned int ios_left;
331 /* const or read-mostly hot data */
333 struct percpu_ref refs;
335 struct io_rings *rings;
337 unsigned int compat: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int off_timeout_used: 1;
342 unsigned int drain_active: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 struct io_file_table file_table;
372 unsigned nr_user_files;
373 unsigned nr_user_bufs;
374 struct io_mapped_ubuf **user_bufs;
376 struct io_submit_state submit_state;
377 struct list_head timeout_list;
378 struct list_head cq_overflow_list;
379 struct xarray io_buffers;
380 struct xarray personalities;
382 unsigned sq_thread_idle;
383 } ____cacheline_aligned_in_smp;
385 /* IRQ completion list, under ->completion_lock */
386 struct list_head locked_free_list;
387 unsigned int locked_free_nr;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
395 unsigned long check_cq_overflow;
398 unsigned cached_cq_tail;
400 struct eventfd_ctx *cq_ev_fd;
401 struct wait_queue_head poll_wait;
402 struct wait_queue_head cq_wait;
404 atomic_t cq_timeouts;
405 struct fasync_struct *cq_fasync;
406 unsigned cq_last_tm_flush;
407 } ____cacheline_aligned_in_smp;
410 spinlock_t completion_lock;
412 spinlock_t timeout_lock;
415 * ->iopoll_list is protected by the ctx->uring_lock for
416 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417 * For SQPOLL, only the single threaded io_sq_thread() will
418 * manipulate the list, hence no extra locking is needed there.
420 struct list_head iopoll_list;
421 struct hlist_head *cancel_hash;
422 unsigned cancel_hash_bits;
423 bool poll_multi_queue;
424 } ____cacheline_aligned_in_smp;
426 struct io_restriction restrictions;
428 /* slow path rsrc auxilary data, used by update/register */
430 struct io_rsrc_node *rsrc_backup_node;
431 struct io_mapped_ubuf *dummy_ubuf;
432 struct io_rsrc_data *file_data;
433 struct io_rsrc_data *buf_data;
435 struct delayed_work rsrc_put_work;
436 struct llist_head rsrc_put_llist;
437 struct list_head rsrc_ref_list;
438 spinlock_t rsrc_ref_lock;
441 /* Keep this last, we don't need it for the fast path */
443 #if defined(CONFIG_UNIX)
444 struct socket *ring_sock;
446 /* hashed buffered write serialization */
447 struct io_wq_hash *hash_map;
449 /* Only used for accounting purposes */
450 struct user_struct *user;
451 struct mm_struct *mm_account;
453 /* ctx exit and cancelation */
454 struct llist_head fallback_llist;
455 struct delayed_work fallback_work;
456 struct work_struct exit_work;
457 struct list_head tctx_list;
458 struct completion ref_comp;
462 struct io_uring_task {
463 /* submission side */
466 struct wait_queue_head wait;
467 const struct io_ring_ctx *last;
469 struct percpu_counter inflight;
470 atomic_t inflight_tracked;
473 spinlock_t task_lock;
474 struct io_wq_work_list task_list;
475 struct callback_head task_work;
480 * First field must be the file pointer in all the
481 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
483 struct io_poll_iocb {
485 struct wait_queue_head *head;
489 struct wait_queue_entry wait;
492 struct io_poll_update {
498 bool update_user_data;
506 struct io_timeout_data {
507 struct io_kiocb *req;
508 struct hrtimer timer;
509 struct timespec64 ts;
510 enum hrtimer_mode mode;
515 struct sockaddr __user *addr;
516 int __user *addr_len;
518 unsigned long nofile;
538 struct list_head list;
539 /* head of the link, used by linked timeouts only */
540 struct io_kiocb *head;
541 /* for linked completions */
542 struct io_kiocb *prev;
545 struct io_timeout_rem {
550 struct timespec64 ts;
555 /* NOTE: kiocb has the file as the first member, so don't do it here */
563 struct sockaddr __user *addr;
570 struct compat_msghdr __user *umsg_compat;
571 struct user_msghdr __user *umsg;
577 struct io_buffer *kbuf;
583 struct filename *filename;
585 unsigned long nofile;
588 struct io_rsrc_update {
614 struct epoll_event event;
618 struct file *file_out;
619 struct file *file_in;
626 struct io_provide_buf {
640 const char __user *filename;
641 struct statx __user *buffer;
653 struct filename *oldpath;
654 struct filename *newpath;
662 struct filename *filename;
665 struct io_completion {
670 struct io_async_connect {
671 struct sockaddr_storage address;
674 struct io_async_msghdr {
675 struct iovec fast_iov[UIO_FASTIOV];
676 /* points to an allocated iov, if NULL we use fast_iov instead */
677 struct iovec *free_iov;
678 struct sockaddr __user *uaddr;
680 struct sockaddr_storage addr;
684 struct iovec fast_iov[UIO_FASTIOV];
685 const struct iovec *free_iovec;
686 struct iov_iter iter;
688 struct wait_page_queue wpq;
692 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
693 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
694 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
695 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
696 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
697 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
699 /* first byte is taken by user flags, shift it to not overlap */
704 REQ_F_LINK_TIMEOUT_BIT,
705 REQ_F_NEED_CLEANUP_BIT,
707 REQ_F_BUFFER_SELECTED_BIT,
708 REQ_F_COMPLETE_INLINE_BIT,
710 REQ_F_DONT_REISSUE_BIT,
713 REQ_F_ARM_LTIMEOUT_BIT,
714 /* keep async read/write and isreg together and in order */
715 REQ_F_NOWAIT_READ_BIT,
716 REQ_F_NOWAIT_WRITE_BIT,
719 /* not a real bit, just to check we're not overflowing the space */
725 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
726 /* drain existing IO first */
727 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
729 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
730 /* doesn't sever on completion < 0 */
731 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
733 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
734 /* IOSQE_BUFFER_SELECT */
735 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
737 /* fail rest of links */
738 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
739 /* on inflight list, should be cancelled and waited on exit reliably */
740 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
741 /* read/write uses file position */
742 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
743 /* must not punt to workers */
744 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
745 /* has or had linked timeout */
746 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
748 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
749 /* already went through poll handler */
750 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
751 /* buffer already selected */
752 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
753 /* completion is deferred through io_comp_state */
754 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
755 /* caller should reissue async */
756 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
757 /* don't attempt request reissue, see io_rw_reissue() */
758 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
759 /* supports async reads */
760 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
761 /* supports async writes */
762 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
764 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
765 /* has creds assigned */
766 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
767 /* skip refcounting if not set */
768 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
769 /* there is a linked timeout that has to be armed */
770 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
774 struct io_poll_iocb poll;
775 struct io_poll_iocb *double_poll;
778 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
780 struct io_task_work {
782 struct io_wq_work_node node;
783 struct llist_node fallback_node;
785 io_req_tw_func_t func;
789 IORING_RSRC_FILE = 0,
790 IORING_RSRC_BUFFER = 1,
794 * NOTE! Each of the iocb union members has the file pointer
795 * as the first entry in their struct definition. So you can
796 * access the file pointer through any of the sub-structs,
797 * or directly as just 'ki_filp' in this struct.
803 struct io_poll_iocb poll;
804 struct io_poll_update poll_update;
805 struct io_accept accept;
807 struct io_cancel cancel;
808 struct io_timeout timeout;
809 struct io_timeout_rem timeout_rem;
810 struct io_connect connect;
811 struct io_sr_msg sr_msg;
813 struct io_close close;
814 struct io_rsrc_update rsrc_update;
815 struct io_fadvise fadvise;
816 struct io_madvise madvise;
817 struct io_epoll epoll;
818 struct io_splice splice;
819 struct io_provide_buf pbuf;
820 struct io_statx statx;
821 struct io_shutdown shutdown;
822 struct io_rename rename;
823 struct io_unlink unlink;
824 /* use only after cleaning per-op data, see io_clean_op() */
825 struct io_completion compl;
828 /* opcode allocated if it needs to store data for async defer */
831 /* polled IO has completed */
837 struct io_ring_ctx *ctx;
840 struct task_struct *task;
843 struct io_kiocb *link;
844 struct percpu_ref *fixed_rsrc_refs;
846 /* used with ctx->iopoll_list with reads/writes */
847 struct list_head inflight_entry;
848 struct io_task_work io_task_work;
849 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
850 struct hlist_node hash_node;
851 struct async_poll *apoll;
852 struct io_wq_work work;
853 const struct cred *creds;
855 /* store used ubuf, so we can prevent reloading */
856 struct io_mapped_ubuf *imu;
859 struct io_tctx_node {
860 struct list_head ctx_node;
861 struct task_struct *task;
862 struct io_ring_ctx *ctx;
865 struct io_defer_entry {
866 struct list_head list;
867 struct io_kiocb *req;
872 /* needs req->file assigned */
873 unsigned needs_file : 1;
874 /* hash wq insertion if file is a regular file */
875 unsigned hash_reg_file : 1;
876 /* unbound wq insertion if file is a non-regular file */
877 unsigned unbound_nonreg_file : 1;
878 /* opcode is not supported by this kernel */
879 unsigned not_supported : 1;
880 /* set if opcode supports polled "wait" */
882 unsigned pollout : 1;
883 /* op supports buffer selection */
884 unsigned buffer_select : 1;
885 /* do prep async if is going to be punted */
886 unsigned needs_async_setup : 1;
887 /* should block plug */
889 /* size of async data needed, if any */
890 unsigned short async_size;
893 static const struct io_op_def io_op_defs[] = {
894 [IORING_OP_NOP] = {},
895 [IORING_OP_READV] = {
897 .unbound_nonreg_file = 1,
900 .needs_async_setup = 1,
902 .async_size = sizeof(struct io_async_rw),
904 [IORING_OP_WRITEV] = {
907 .unbound_nonreg_file = 1,
909 .needs_async_setup = 1,
911 .async_size = sizeof(struct io_async_rw),
913 [IORING_OP_FSYNC] = {
916 [IORING_OP_READ_FIXED] = {
918 .unbound_nonreg_file = 1,
921 .async_size = sizeof(struct io_async_rw),
923 [IORING_OP_WRITE_FIXED] = {
926 .unbound_nonreg_file = 1,
929 .async_size = sizeof(struct io_async_rw),
931 [IORING_OP_POLL_ADD] = {
933 .unbound_nonreg_file = 1,
935 [IORING_OP_POLL_REMOVE] = {},
936 [IORING_OP_SYNC_FILE_RANGE] = {
939 [IORING_OP_SENDMSG] = {
941 .unbound_nonreg_file = 1,
943 .needs_async_setup = 1,
944 .async_size = sizeof(struct io_async_msghdr),
946 [IORING_OP_RECVMSG] = {
948 .unbound_nonreg_file = 1,
951 .needs_async_setup = 1,
952 .async_size = sizeof(struct io_async_msghdr),
954 [IORING_OP_TIMEOUT] = {
955 .async_size = sizeof(struct io_timeout_data),
957 [IORING_OP_TIMEOUT_REMOVE] = {
958 /* used by timeout updates' prep() */
960 [IORING_OP_ACCEPT] = {
962 .unbound_nonreg_file = 1,
965 [IORING_OP_ASYNC_CANCEL] = {},
966 [IORING_OP_LINK_TIMEOUT] = {
967 .async_size = sizeof(struct io_timeout_data),
969 [IORING_OP_CONNECT] = {
971 .unbound_nonreg_file = 1,
973 .needs_async_setup = 1,
974 .async_size = sizeof(struct io_async_connect),
976 [IORING_OP_FALLOCATE] = {
979 [IORING_OP_OPENAT] = {},
980 [IORING_OP_CLOSE] = {},
981 [IORING_OP_FILES_UPDATE] = {},
982 [IORING_OP_STATX] = {},
985 .unbound_nonreg_file = 1,
989 .async_size = sizeof(struct io_async_rw),
991 [IORING_OP_WRITE] = {
993 .unbound_nonreg_file = 1,
996 .async_size = sizeof(struct io_async_rw),
998 [IORING_OP_FADVISE] = {
1001 [IORING_OP_MADVISE] = {},
1002 [IORING_OP_SEND] = {
1004 .unbound_nonreg_file = 1,
1007 [IORING_OP_RECV] = {
1009 .unbound_nonreg_file = 1,
1013 [IORING_OP_OPENAT2] = {
1015 [IORING_OP_EPOLL_CTL] = {
1016 .unbound_nonreg_file = 1,
1018 [IORING_OP_SPLICE] = {
1021 .unbound_nonreg_file = 1,
1023 [IORING_OP_PROVIDE_BUFFERS] = {},
1024 [IORING_OP_REMOVE_BUFFERS] = {},
1028 .unbound_nonreg_file = 1,
1030 [IORING_OP_SHUTDOWN] = {
1033 [IORING_OP_RENAMEAT] = {},
1034 [IORING_OP_UNLINKAT] = {},
1037 /* requests with any of those set should undergo io_disarm_next() */
1038 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1040 static bool io_disarm_next(struct io_kiocb *req);
1041 static void io_uring_del_tctx_node(unsigned long index);
1042 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1043 struct task_struct *task,
1045 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1047 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1048 long res, unsigned int cflags);
1049 static void io_put_req(struct io_kiocb *req);
1050 static void io_put_req_deferred(struct io_kiocb *req);
1051 static void io_dismantle_req(struct io_kiocb *req);
1052 static void io_queue_linked_timeout(struct io_kiocb *req);
1053 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1054 struct io_uring_rsrc_update2 *up,
1056 static void io_clean_op(struct io_kiocb *req);
1057 static struct file *io_file_get(struct io_ring_ctx *ctx,
1058 struct io_kiocb *req, int fd, bool fixed);
1059 static void __io_queue_sqe(struct io_kiocb *req);
1060 static void io_rsrc_put_work(struct work_struct *work);
1062 static void io_req_task_queue(struct io_kiocb *req);
1063 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1064 static int io_req_prep_async(struct io_kiocb *req);
1066 static struct kmem_cache *req_cachep;
1068 static const struct file_operations io_uring_fops;
1070 struct sock *io_uring_get_socket(struct file *file)
1072 #if defined(CONFIG_UNIX)
1073 if (file->f_op == &io_uring_fops) {
1074 struct io_ring_ctx *ctx = file->private_data;
1076 return ctx->ring_sock->sk;
1081 EXPORT_SYMBOL(io_uring_get_socket);
1083 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1086 mutex_lock(&ctx->uring_lock);
1091 #define io_for_each_link(pos, head) \
1092 for (pos = (head); pos; pos = pos->link)
1095 * Shamelessly stolen from the mm implementation of page reference checking,
1096 * see commit f958d7b528b1 for details.
1098 #define req_ref_zero_or_close_to_overflow(req) \
1099 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1101 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1103 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1104 return atomic_inc_not_zero(&req->refs);
1107 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1109 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1112 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1113 return atomic_dec_and_test(&req->refs);
1116 static inline void req_ref_put(struct io_kiocb *req)
1118 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1119 WARN_ON_ONCE(req_ref_put_and_test(req));
1122 static inline void req_ref_get(struct io_kiocb *req)
1124 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1125 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1126 atomic_inc(&req->refs);
1129 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1131 if (!(req->flags & REQ_F_REFCOUNT)) {
1132 req->flags |= REQ_F_REFCOUNT;
1133 atomic_set(&req->refs, nr);
1137 static inline void io_req_set_refcount(struct io_kiocb *req)
1139 __io_req_set_refcount(req, 1);
1142 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1144 struct io_ring_ctx *ctx = req->ctx;
1146 if (!req->fixed_rsrc_refs) {
1147 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1148 percpu_ref_get(req->fixed_rsrc_refs);
1152 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1154 bool got = percpu_ref_tryget(ref);
1156 /* already at zero, wait for ->release() */
1158 wait_for_completion(compl);
1159 percpu_ref_resurrect(ref);
1161 percpu_ref_put(ref);
1164 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1167 struct io_kiocb *req;
1169 if (task && head->task != task)
1174 io_for_each_link(req, head) {
1175 if (req->flags & REQ_F_INFLIGHT)
1181 static inline void req_set_fail(struct io_kiocb *req)
1183 req->flags |= REQ_F_FAIL;
1186 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1188 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1190 complete(&ctx->ref_comp);
1193 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1195 return !req->timeout.off;
1198 static void io_fallback_req_func(struct work_struct *work)
1200 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1201 fallback_work.work);
1202 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1203 struct io_kiocb *req, *tmp;
1204 bool locked = false;
1206 percpu_ref_get(&ctx->refs);
1207 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1208 req->io_task_work.func(req, &locked);
1211 if (ctx->submit_state.compl_nr)
1212 io_submit_flush_completions(ctx);
1213 mutex_unlock(&ctx->uring_lock);
1215 percpu_ref_put(&ctx->refs);
1219 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1221 struct io_ring_ctx *ctx;
1224 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1229 * Use 5 bits less than the max cq entries, that should give us around
1230 * 32 entries per hash list if totally full and uniformly spread.
1232 hash_bits = ilog2(p->cq_entries);
1236 ctx->cancel_hash_bits = hash_bits;
1237 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1239 if (!ctx->cancel_hash)
1241 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1243 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1244 if (!ctx->dummy_ubuf)
1246 /* set invalid range, so io_import_fixed() fails meeting it */
1247 ctx->dummy_ubuf->ubuf = -1UL;
1249 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1250 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1253 ctx->flags = p->flags;
1254 init_waitqueue_head(&ctx->sqo_sq_wait);
1255 INIT_LIST_HEAD(&ctx->sqd_list);
1256 init_waitqueue_head(&ctx->poll_wait);
1257 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1258 init_completion(&ctx->ref_comp);
1259 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1260 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1261 mutex_init(&ctx->uring_lock);
1262 init_waitqueue_head(&ctx->cq_wait);
1263 spin_lock_init(&ctx->completion_lock);
1264 spin_lock_init(&ctx->timeout_lock);
1265 INIT_LIST_HEAD(&ctx->iopoll_list);
1266 INIT_LIST_HEAD(&ctx->defer_list);
1267 INIT_LIST_HEAD(&ctx->timeout_list);
1268 spin_lock_init(&ctx->rsrc_ref_lock);
1269 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1270 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1271 init_llist_head(&ctx->rsrc_put_llist);
1272 INIT_LIST_HEAD(&ctx->tctx_list);
1273 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1274 INIT_LIST_HEAD(&ctx->locked_free_list);
1275 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1278 kfree(ctx->dummy_ubuf);
1279 kfree(ctx->cancel_hash);
1284 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1286 struct io_rings *r = ctx->rings;
1288 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1292 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1294 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1295 struct io_ring_ctx *ctx = req->ctx;
1297 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1303 #define FFS_ASYNC_READ 0x1UL
1304 #define FFS_ASYNC_WRITE 0x2UL
1306 #define FFS_ISREG 0x4UL
1308 #define FFS_ISREG 0x0UL
1310 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1312 static inline bool io_req_ffs_set(struct io_kiocb *req)
1314 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1317 static void io_req_track_inflight(struct io_kiocb *req)
1319 if (!(req->flags & REQ_F_INFLIGHT)) {
1320 req->flags |= REQ_F_INFLIGHT;
1321 atomic_inc(¤t->io_uring->inflight_tracked);
1325 static inline void io_unprep_linked_timeout(struct io_kiocb *req)
1327 req->flags &= ~REQ_F_LINK_TIMEOUT;
1330 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1332 if (WARN_ON_ONCE(!req->link))
1335 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1336 req->flags |= REQ_F_LINK_TIMEOUT;
1338 /* linked timeouts should have two refs once prep'ed */
1339 io_req_set_refcount(req);
1340 __io_req_set_refcount(req->link, 2);
1344 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1346 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1348 return __io_prep_linked_timeout(req);
1351 static void io_prep_async_work(struct io_kiocb *req)
1353 const struct io_op_def *def = &io_op_defs[req->opcode];
1354 struct io_ring_ctx *ctx = req->ctx;
1356 if (!(req->flags & REQ_F_CREDS)) {
1357 req->flags |= REQ_F_CREDS;
1358 req->creds = get_current_cred();
1361 req->work.list.next = NULL;
1362 req->work.flags = 0;
1363 if (req->flags & REQ_F_FORCE_ASYNC)
1364 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1366 if (req->flags & REQ_F_ISREG) {
1367 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1368 io_wq_hash_work(&req->work, file_inode(req->file));
1369 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1370 if (def->unbound_nonreg_file)
1371 req->work.flags |= IO_WQ_WORK_UNBOUND;
1374 switch (req->opcode) {
1375 case IORING_OP_SPLICE:
1377 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1378 req->work.flags |= IO_WQ_WORK_UNBOUND;
1383 static void io_prep_async_link(struct io_kiocb *req)
1385 struct io_kiocb *cur;
1387 if (req->flags & REQ_F_LINK_TIMEOUT) {
1388 struct io_ring_ctx *ctx = req->ctx;
1390 spin_lock(&ctx->completion_lock);
1391 io_for_each_link(cur, req)
1392 io_prep_async_work(cur);
1393 spin_unlock(&ctx->completion_lock);
1395 io_for_each_link(cur, req)
1396 io_prep_async_work(cur);
1400 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1402 struct io_ring_ctx *ctx = req->ctx;
1403 struct io_kiocb *link = io_prep_linked_timeout(req);
1404 struct io_uring_task *tctx = req->task->io_uring;
1406 /* must not take the lock, NULL it as a precaution */
1410 BUG_ON(!tctx->io_wq);
1412 /* init ->work of the whole link before punting */
1413 io_prep_async_link(req);
1416 * Not expected to happen, but if we do have a bug where this _can_
1417 * happen, catch it here and ensure the request is marked as
1418 * canceled. That will make io-wq go through the usual work cancel
1419 * procedure rather than attempt to run this request (or create a new
1422 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1423 req->work.flags |= IO_WQ_WORK_CANCEL;
1425 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1426 &req->work, req->flags);
1427 io_wq_enqueue(tctx->io_wq, &req->work);
1429 io_queue_linked_timeout(link);
1432 static void io_kill_timeout(struct io_kiocb *req, int status)
1433 __must_hold(&req->ctx->completion_lock)
1434 __must_hold(&req->ctx->timeout_lock)
1436 struct io_timeout_data *io = req->async_data;
1438 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1439 atomic_set(&req->ctx->cq_timeouts,
1440 atomic_read(&req->ctx->cq_timeouts) + 1);
1441 list_del_init(&req->timeout.list);
1442 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1443 io_put_req_deferred(req);
1447 static void io_queue_deferred(struct io_ring_ctx *ctx)
1449 while (!list_empty(&ctx->defer_list)) {
1450 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1451 struct io_defer_entry, list);
1453 if (req_need_defer(de->req, de->seq))
1455 list_del_init(&de->list);
1456 io_req_task_queue(de->req);
1461 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1462 __must_hold(&ctx->completion_lock)
1464 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1466 spin_lock_irq(&ctx->timeout_lock);
1467 while (!list_empty(&ctx->timeout_list)) {
1468 u32 events_needed, events_got;
1469 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1470 struct io_kiocb, timeout.list);
1472 if (io_is_timeout_noseq(req))
1476 * Since seq can easily wrap around over time, subtract
1477 * the last seq at which timeouts were flushed before comparing.
1478 * Assuming not more than 2^31-1 events have happened since,
1479 * these subtractions won't have wrapped, so we can check if
1480 * target is in [last_seq, current_seq] by comparing the two.
1482 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1483 events_got = seq - ctx->cq_last_tm_flush;
1484 if (events_got < events_needed)
1487 list_del_init(&req->timeout.list);
1488 io_kill_timeout(req, 0);
1490 ctx->cq_last_tm_flush = seq;
1491 spin_unlock_irq(&ctx->timeout_lock);
1494 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1496 if (ctx->off_timeout_used)
1497 io_flush_timeouts(ctx);
1498 if (ctx->drain_active)
1499 io_queue_deferred(ctx);
1502 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1504 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1505 __io_commit_cqring_flush(ctx);
1506 /* order cqe stores with ring update */
1507 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1510 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1512 struct io_rings *r = ctx->rings;
1514 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1517 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1519 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1522 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1524 struct io_rings *rings = ctx->rings;
1525 unsigned tail, mask = ctx->cq_entries - 1;
1528 * writes to the cq entry need to come after reading head; the
1529 * control dependency is enough as we're using WRITE_ONCE to
1532 if (__io_cqring_events(ctx) == ctx->cq_entries)
1535 tail = ctx->cached_cq_tail++;
1536 return &rings->cqes[tail & mask];
1539 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1541 if (likely(!ctx->cq_ev_fd))
1543 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1545 return !ctx->eventfd_async || io_wq_current_is_worker();
1549 * This should only get called when at least one event has been posted.
1550 * Some applications rely on the eventfd notification count only changing
1551 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1552 * 1:1 relationship between how many times this function is called (and
1553 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1555 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1558 * wake_up_all() may seem excessive, but io_wake_function() and
1559 * io_should_wake() handle the termination of the loop and only
1560 * wake as many waiters as we need to.
1562 if (wq_has_sleeper(&ctx->cq_wait))
1563 wake_up_all(&ctx->cq_wait);
1564 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1565 wake_up(&ctx->sq_data->wait);
1566 if (io_should_trigger_evfd(ctx))
1567 eventfd_signal(ctx->cq_ev_fd, 1);
1568 if (waitqueue_active(&ctx->poll_wait)) {
1569 wake_up_interruptible(&ctx->poll_wait);
1570 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1574 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1576 if (ctx->flags & IORING_SETUP_SQPOLL) {
1577 if (wq_has_sleeper(&ctx->cq_wait))
1578 wake_up_all(&ctx->cq_wait);
1580 if (io_should_trigger_evfd(ctx))
1581 eventfd_signal(ctx->cq_ev_fd, 1);
1582 if (waitqueue_active(&ctx->poll_wait)) {
1583 wake_up_interruptible(&ctx->poll_wait);
1584 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1588 /* Returns true if there are no backlogged entries after the flush */
1589 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1591 bool all_flushed, posted;
1593 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1597 spin_lock(&ctx->completion_lock);
1598 while (!list_empty(&ctx->cq_overflow_list)) {
1599 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1600 struct io_overflow_cqe *ocqe;
1604 ocqe = list_first_entry(&ctx->cq_overflow_list,
1605 struct io_overflow_cqe, list);
1607 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1609 io_account_cq_overflow(ctx);
1612 list_del(&ocqe->list);
1616 all_flushed = list_empty(&ctx->cq_overflow_list);
1618 clear_bit(0, &ctx->check_cq_overflow);
1619 WRITE_ONCE(ctx->rings->sq_flags,
1620 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1624 io_commit_cqring(ctx);
1625 spin_unlock(&ctx->completion_lock);
1627 io_cqring_ev_posted(ctx);
1631 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1635 if (test_bit(0, &ctx->check_cq_overflow)) {
1636 /* iopoll syncs against uring_lock, not completion_lock */
1637 if (ctx->flags & IORING_SETUP_IOPOLL)
1638 mutex_lock(&ctx->uring_lock);
1639 ret = __io_cqring_overflow_flush(ctx, false);
1640 if (ctx->flags & IORING_SETUP_IOPOLL)
1641 mutex_unlock(&ctx->uring_lock);
1647 /* must to be called somewhat shortly after putting a request */
1648 static inline void io_put_task(struct task_struct *task, int nr)
1650 struct io_uring_task *tctx = task->io_uring;
1652 if (likely(task == current)) {
1653 tctx->cached_refs += nr;
1655 percpu_counter_sub(&tctx->inflight, nr);
1656 if (unlikely(atomic_read(&tctx->in_idle)))
1657 wake_up(&tctx->wait);
1658 put_task_struct_many(task, nr);
1662 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1663 long res, unsigned int cflags)
1665 struct io_overflow_cqe *ocqe;
1667 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1670 * If we're in ring overflow flush mode, or in task cancel mode,
1671 * or cannot allocate an overflow entry, then we need to drop it
1674 io_account_cq_overflow(ctx);
1677 if (list_empty(&ctx->cq_overflow_list)) {
1678 set_bit(0, &ctx->check_cq_overflow);
1679 WRITE_ONCE(ctx->rings->sq_flags,
1680 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1683 ocqe->cqe.user_data = user_data;
1684 ocqe->cqe.res = res;
1685 ocqe->cqe.flags = cflags;
1686 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1690 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1691 long res, unsigned int cflags)
1693 struct io_uring_cqe *cqe;
1695 trace_io_uring_complete(ctx, user_data, res, cflags);
1698 * If we can't get a cq entry, userspace overflowed the
1699 * submission (by quite a lot). Increment the overflow count in
1702 cqe = io_get_cqe(ctx);
1704 WRITE_ONCE(cqe->user_data, user_data);
1705 WRITE_ONCE(cqe->res, res);
1706 WRITE_ONCE(cqe->flags, cflags);
1709 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1712 /* not as hot to bloat with inlining */
1713 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1714 long res, unsigned int cflags)
1716 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1719 static void io_req_complete_post(struct io_kiocb *req, long res,
1720 unsigned int cflags)
1722 struct io_ring_ctx *ctx = req->ctx;
1724 spin_lock(&ctx->completion_lock);
1725 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1727 * If we're the last reference to this request, add to our locked
1730 if (req_ref_put_and_test(req)) {
1731 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1732 if (req->flags & IO_DISARM_MASK)
1733 io_disarm_next(req);
1735 io_req_task_queue(req->link);
1739 io_dismantle_req(req);
1740 io_put_task(req->task, 1);
1741 list_add(&req->inflight_entry, &ctx->locked_free_list);
1742 ctx->locked_free_nr++;
1744 if (!percpu_ref_tryget(&ctx->refs))
1747 io_commit_cqring(ctx);
1748 spin_unlock(&ctx->completion_lock);
1751 io_cqring_ev_posted(ctx);
1752 percpu_ref_put(&ctx->refs);
1756 static inline bool io_req_needs_clean(struct io_kiocb *req)
1758 return req->flags & IO_REQ_CLEAN_FLAGS;
1761 static void io_req_complete_state(struct io_kiocb *req, long res,
1762 unsigned int cflags)
1764 if (io_req_needs_clean(req))
1767 req->compl.cflags = cflags;
1768 req->flags |= REQ_F_COMPLETE_INLINE;
1771 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1772 long res, unsigned cflags)
1774 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1775 io_req_complete_state(req, res, cflags);
1777 io_req_complete_post(req, res, cflags);
1780 static inline void io_req_complete(struct io_kiocb *req, long res)
1782 __io_req_complete(req, 0, res, 0);
1785 static void io_req_complete_failed(struct io_kiocb *req, long res)
1788 io_req_complete_post(req, res, 0);
1792 * Don't initialise the fields below on every allocation, but do that in
1793 * advance and keep them valid across allocations.
1795 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1799 req->async_data = NULL;
1800 /* not necessary, but safer to zero */
1804 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1805 struct io_submit_state *state)
1807 spin_lock(&ctx->completion_lock);
1808 list_splice_init(&ctx->locked_free_list, &state->free_list);
1809 ctx->locked_free_nr = 0;
1810 spin_unlock(&ctx->completion_lock);
1813 /* Returns true IFF there are requests in the cache */
1814 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1816 struct io_submit_state *state = &ctx->submit_state;
1820 * If we have more than a batch's worth of requests in our IRQ side
1821 * locked cache, grab the lock and move them over to our submission
1824 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1825 io_flush_cached_locked_reqs(ctx, state);
1827 nr = state->free_reqs;
1828 while (!list_empty(&state->free_list)) {
1829 struct io_kiocb *req = list_first_entry(&state->free_list,
1830 struct io_kiocb, inflight_entry);
1832 list_del(&req->inflight_entry);
1833 state->reqs[nr++] = req;
1834 if (nr == ARRAY_SIZE(state->reqs))
1838 state->free_reqs = nr;
1843 * A request might get retired back into the request caches even before opcode
1844 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1845 * Because of that, io_alloc_req() should be called only under ->uring_lock
1846 * and with extra caution to not get a request that is still worked on.
1848 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1849 __must_hold(&ctx->uring_lock)
1851 struct io_submit_state *state = &ctx->submit_state;
1852 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1855 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1857 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1860 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1864 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1865 * retry single alloc to be on the safe side.
1867 if (unlikely(ret <= 0)) {
1868 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1869 if (!state->reqs[0])
1874 for (i = 0; i < ret; i++)
1875 io_preinit_req(state->reqs[i], ctx);
1876 state->free_reqs = ret;
1879 return state->reqs[state->free_reqs];
1882 static inline void io_put_file(struct file *file)
1888 static void io_dismantle_req(struct io_kiocb *req)
1890 unsigned int flags = req->flags;
1892 if (io_req_needs_clean(req))
1894 if (!(flags & REQ_F_FIXED_FILE))
1895 io_put_file(req->file);
1896 if (req->fixed_rsrc_refs)
1897 percpu_ref_put(req->fixed_rsrc_refs);
1898 if (req->async_data) {
1899 kfree(req->async_data);
1900 req->async_data = NULL;
1904 static void __io_free_req(struct io_kiocb *req)
1906 struct io_ring_ctx *ctx = req->ctx;
1908 io_dismantle_req(req);
1909 io_put_task(req->task, 1);
1911 spin_lock(&ctx->completion_lock);
1912 list_add(&req->inflight_entry, &ctx->locked_free_list);
1913 ctx->locked_free_nr++;
1914 spin_unlock(&ctx->completion_lock);
1916 percpu_ref_put(&ctx->refs);
1919 static inline void io_remove_next_linked(struct io_kiocb *req)
1921 struct io_kiocb *nxt = req->link;
1923 req->link = nxt->link;
1927 static bool io_kill_linked_timeout(struct io_kiocb *req)
1928 __must_hold(&req->ctx->completion_lock)
1929 __must_hold(&req->ctx->timeout_lock)
1931 struct io_kiocb *link = req->link;
1933 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1934 struct io_timeout_data *io = link->async_data;
1936 io_remove_next_linked(req);
1937 link->timeout.head = NULL;
1938 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1939 io_cqring_fill_event(link->ctx, link->user_data,
1941 io_put_req_deferred(link);
1948 static void io_fail_links(struct io_kiocb *req)
1949 __must_hold(&req->ctx->completion_lock)
1951 struct io_kiocb *nxt, *link = req->link;
1958 trace_io_uring_fail_link(req, link);
1959 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1960 io_put_req_deferred(link);
1965 static bool io_disarm_next(struct io_kiocb *req)
1966 __must_hold(&req->ctx->completion_lock)
1968 bool posted = false;
1970 if (req->flags & REQ_F_ARM_LTIMEOUT) {
1971 struct io_kiocb *link = req->link;
1973 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1974 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
1975 io_remove_next_linked(req);
1976 io_cqring_fill_event(link->ctx, link->user_data,
1978 io_put_req_deferred(link);
1981 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
1982 struct io_ring_ctx *ctx = req->ctx;
1984 spin_lock_irq(&ctx->timeout_lock);
1985 posted = io_kill_linked_timeout(req);
1986 spin_unlock_irq(&ctx->timeout_lock);
1988 if (unlikely((req->flags & REQ_F_FAIL) &&
1989 !(req->flags & REQ_F_HARDLINK))) {
1990 posted |= (req->link != NULL);
1996 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1998 struct io_kiocb *nxt;
2001 * If LINK is set, we have dependent requests in this chain. If we
2002 * didn't fail this request, queue the first one up, moving any other
2003 * dependencies to the next request. In case of failure, fail the rest
2006 if (req->flags & IO_DISARM_MASK) {
2007 struct io_ring_ctx *ctx = req->ctx;
2010 spin_lock(&ctx->completion_lock);
2011 posted = io_disarm_next(req);
2013 io_commit_cqring(req->ctx);
2014 spin_unlock(&ctx->completion_lock);
2016 io_cqring_ev_posted(ctx);
2023 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2025 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2027 return __io_req_find_next(req);
2030 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2035 if (ctx->submit_state.compl_nr)
2036 io_submit_flush_completions(ctx);
2037 mutex_unlock(&ctx->uring_lock);
2040 percpu_ref_put(&ctx->refs);
2043 static void tctx_task_work(struct callback_head *cb)
2045 bool locked = false;
2046 struct io_ring_ctx *ctx = NULL;
2047 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2051 struct io_wq_work_node *node;
2053 spin_lock_irq(&tctx->task_lock);
2054 node = tctx->task_list.first;
2055 INIT_WQ_LIST(&tctx->task_list);
2057 tctx->task_running = false;
2058 spin_unlock_irq(&tctx->task_lock);
2063 struct io_wq_work_node *next = node->next;
2064 struct io_kiocb *req = container_of(node, struct io_kiocb,
2067 if (req->ctx != ctx) {
2068 ctx_flush_and_put(ctx, &locked);
2070 /* if not contended, grab and improve batching */
2071 locked = mutex_trylock(&ctx->uring_lock);
2072 percpu_ref_get(&ctx->refs);
2074 req->io_task_work.func(req, &locked);
2081 ctx_flush_and_put(ctx, &locked);
2084 static void io_req_task_work_add(struct io_kiocb *req)
2086 struct task_struct *tsk = req->task;
2087 struct io_uring_task *tctx = tsk->io_uring;
2088 enum task_work_notify_mode notify;
2089 struct io_wq_work_node *node;
2090 unsigned long flags;
2093 WARN_ON_ONCE(!tctx);
2095 spin_lock_irqsave(&tctx->task_lock, flags);
2096 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2097 running = tctx->task_running;
2099 tctx->task_running = true;
2100 spin_unlock_irqrestore(&tctx->task_lock, flags);
2102 /* task_work already pending, we're done */
2107 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2108 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2109 * processing task_work. There's no reliable way to tell if TWA_RESUME
2112 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2113 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2114 wake_up_process(tsk);
2118 spin_lock_irqsave(&tctx->task_lock, flags);
2119 tctx->task_running = false;
2120 node = tctx->task_list.first;
2121 INIT_WQ_LIST(&tctx->task_list);
2122 spin_unlock_irqrestore(&tctx->task_lock, flags);
2125 req = container_of(node, struct io_kiocb, io_task_work.node);
2127 if (llist_add(&req->io_task_work.fallback_node,
2128 &req->ctx->fallback_llist))
2129 schedule_delayed_work(&req->ctx->fallback_work, 1);
2133 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2135 struct io_ring_ctx *ctx = req->ctx;
2137 /* ctx is guaranteed to stay alive while we hold uring_lock */
2138 io_tw_lock(ctx, locked);
2139 io_req_complete_failed(req, req->result);
2142 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2144 struct io_ring_ctx *ctx = req->ctx;
2146 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2147 io_tw_lock(ctx, locked);
2148 /* req->task == current here, checking PF_EXITING is safe */
2149 if (likely(!(req->task->flags & PF_EXITING)))
2150 __io_queue_sqe(req);
2152 io_req_complete_failed(req, -EFAULT);
2155 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2158 req->io_task_work.func = io_req_task_cancel;
2159 io_req_task_work_add(req);
2162 static void io_req_task_queue(struct io_kiocb *req)
2164 req->io_task_work.func = io_req_task_submit;
2165 io_req_task_work_add(req);
2168 static void io_req_task_queue_reissue(struct io_kiocb *req)
2170 req->io_task_work.func = io_queue_async_work;
2171 io_req_task_work_add(req);
2174 static inline void io_queue_next(struct io_kiocb *req)
2176 struct io_kiocb *nxt = io_req_find_next(req);
2179 io_req_task_queue(nxt);
2182 static void io_free_req(struct io_kiocb *req)
2188 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2194 struct task_struct *task;
2199 static inline void io_init_req_batch(struct req_batch *rb)
2206 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2207 struct req_batch *rb)
2210 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2212 io_put_task(rb->task, rb->task_refs);
2215 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2216 struct io_submit_state *state)
2219 io_dismantle_req(req);
2221 if (req->task != rb->task) {
2223 io_put_task(rb->task, rb->task_refs);
2224 rb->task = req->task;
2230 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2231 state->reqs[state->free_reqs++] = req;
2233 list_add(&req->inflight_entry, &state->free_list);
2236 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2237 __must_hold(&ctx->uring_lock)
2239 struct io_submit_state *state = &ctx->submit_state;
2240 int i, nr = state->compl_nr;
2241 struct req_batch rb;
2243 spin_lock(&ctx->completion_lock);
2244 for (i = 0; i < nr; i++) {
2245 struct io_kiocb *req = state->compl_reqs[i];
2247 __io_cqring_fill_event(ctx, req->user_data, req->result,
2250 io_commit_cqring(ctx);
2251 spin_unlock(&ctx->completion_lock);
2252 io_cqring_ev_posted(ctx);
2254 io_init_req_batch(&rb);
2255 for (i = 0; i < nr; i++) {
2256 struct io_kiocb *req = state->compl_reqs[i];
2258 if (req_ref_put_and_test(req))
2259 io_req_free_batch(&rb, req, &ctx->submit_state);
2262 io_req_free_batch_finish(ctx, &rb);
2263 state->compl_nr = 0;
2267 * Drop reference to request, return next in chain (if there is one) if this
2268 * was the last reference to this request.
2270 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2272 struct io_kiocb *nxt = NULL;
2274 if (req_ref_put_and_test(req)) {
2275 nxt = io_req_find_next(req);
2281 static inline void io_put_req(struct io_kiocb *req)
2283 if (req_ref_put_and_test(req))
2287 static inline void io_put_req_deferred(struct io_kiocb *req)
2289 if (req_ref_put_and_test(req)) {
2290 req->io_task_work.func = io_free_req_work;
2291 io_req_task_work_add(req);
2295 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2297 /* See comment at the top of this file */
2299 return __io_cqring_events(ctx);
2302 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2304 struct io_rings *rings = ctx->rings;
2306 /* make sure SQ entry isn't read before tail */
2307 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2310 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2312 unsigned int cflags;
2314 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2315 cflags |= IORING_CQE_F_BUFFER;
2316 req->flags &= ~REQ_F_BUFFER_SELECTED;
2321 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2323 struct io_buffer *kbuf;
2325 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2327 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2328 return io_put_kbuf(req, kbuf);
2331 static inline bool io_run_task_work(void)
2333 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2334 __set_current_state(TASK_RUNNING);
2335 tracehook_notify_signal();
2343 * Find and free completed poll iocbs
2345 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2346 struct list_head *done)
2348 struct req_batch rb;
2349 struct io_kiocb *req;
2351 /* order with ->result store in io_complete_rw_iopoll() */
2354 io_init_req_batch(&rb);
2355 while (!list_empty(done)) {
2356 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2357 list_del(&req->inflight_entry);
2359 if (READ_ONCE(req->result) == -EAGAIN &&
2360 !(req->flags & REQ_F_DONT_REISSUE)) {
2361 req->iopoll_completed = 0;
2362 io_req_task_queue_reissue(req);
2366 __io_cqring_fill_event(ctx, req->user_data, req->result,
2367 io_put_rw_kbuf(req));
2370 if (req_ref_put_and_test(req))
2371 io_req_free_batch(&rb, req, &ctx->submit_state);
2374 io_commit_cqring(ctx);
2375 io_cqring_ev_posted_iopoll(ctx);
2376 io_req_free_batch_finish(ctx, &rb);
2379 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2382 struct io_kiocb *req, *tmp;
2387 * Only spin for completions if we don't have multiple devices hanging
2388 * off our complete list, and we're under the requested amount.
2390 spin = !ctx->poll_multi_queue && *nr_events < min;
2392 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2393 struct kiocb *kiocb = &req->rw.kiocb;
2397 * Move completed and retryable entries to our local lists.
2398 * If we find a request that requires polling, break out
2399 * and complete those lists first, if we have entries there.
2401 if (READ_ONCE(req->iopoll_completed)) {
2402 list_move_tail(&req->inflight_entry, &done);
2405 if (!list_empty(&done))
2408 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2409 if (unlikely(ret < 0))
2414 /* iopoll may have completed current req */
2415 if (READ_ONCE(req->iopoll_completed))
2416 list_move_tail(&req->inflight_entry, &done);
2419 if (!list_empty(&done))
2420 io_iopoll_complete(ctx, nr_events, &done);
2426 * We can't just wait for polled events to come to us, we have to actively
2427 * find and complete them.
2429 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2431 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2434 mutex_lock(&ctx->uring_lock);
2435 while (!list_empty(&ctx->iopoll_list)) {
2436 unsigned int nr_events = 0;
2438 io_do_iopoll(ctx, &nr_events, 0);
2440 /* let it sleep and repeat later if can't complete a request */
2444 * Ensure we allow local-to-the-cpu processing to take place,
2445 * in this case we need to ensure that we reap all events.
2446 * Also let task_work, etc. to progress by releasing the mutex
2448 if (need_resched()) {
2449 mutex_unlock(&ctx->uring_lock);
2451 mutex_lock(&ctx->uring_lock);
2454 mutex_unlock(&ctx->uring_lock);
2457 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2459 unsigned int nr_events = 0;
2463 * We disallow the app entering submit/complete with polling, but we
2464 * still need to lock the ring to prevent racing with polled issue
2465 * that got punted to a workqueue.
2467 mutex_lock(&ctx->uring_lock);
2469 * Don't enter poll loop if we already have events pending.
2470 * If we do, we can potentially be spinning for commands that
2471 * already triggered a CQE (eg in error).
2473 if (test_bit(0, &ctx->check_cq_overflow))
2474 __io_cqring_overflow_flush(ctx, false);
2475 if (io_cqring_events(ctx))
2479 * If a submit got punted to a workqueue, we can have the
2480 * application entering polling for a command before it gets
2481 * issued. That app will hold the uring_lock for the duration
2482 * of the poll right here, so we need to take a breather every
2483 * now and then to ensure that the issue has a chance to add
2484 * the poll to the issued list. Otherwise we can spin here
2485 * forever, while the workqueue is stuck trying to acquire the
2488 if (list_empty(&ctx->iopoll_list)) {
2489 u32 tail = ctx->cached_cq_tail;
2491 mutex_unlock(&ctx->uring_lock);
2493 mutex_lock(&ctx->uring_lock);
2495 /* some requests don't go through iopoll_list */
2496 if (tail != ctx->cached_cq_tail ||
2497 list_empty(&ctx->iopoll_list))
2500 ret = io_do_iopoll(ctx, &nr_events, min);
2501 } while (!ret && nr_events < min && !need_resched());
2503 mutex_unlock(&ctx->uring_lock);
2507 static void kiocb_end_write(struct io_kiocb *req)
2510 * Tell lockdep we inherited freeze protection from submission
2513 if (req->flags & REQ_F_ISREG) {
2514 struct super_block *sb = file_inode(req->file)->i_sb;
2516 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2522 static bool io_resubmit_prep(struct io_kiocb *req)
2524 struct io_async_rw *rw = req->async_data;
2527 return !io_req_prep_async(req);
2528 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2529 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2533 static bool io_rw_should_reissue(struct io_kiocb *req)
2535 umode_t mode = file_inode(req->file)->i_mode;
2536 struct io_ring_ctx *ctx = req->ctx;
2538 if (!S_ISBLK(mode) && !S_ISREG(mode))
2540 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2541 !(ctx->flags & IORING_SETUP_IOPOLL)))
2544 * If ref is dying, we might be running poll reap from the exit work.
2545 * Don't attempt to reissue from that path, just let it fail with
2548 if (percpu_ref_is_dying(&ctx->refs))
2551 * Play it safe and assume not safe to re-import and reissue if we're
2552 * not in the original thread group (or in task context).
2554 if (!same_thread_group(req->task, current) || !in_task())
2559 static bool io_resubmit_prep(struct io_kiocb *req)
2563 static bool io_rw_should_reissue(struct io_kiocb *req)
2569 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2571 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2572 kiocb_end_write(req);
2573 if (res != req->result) {
2574 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2575 io_rw_should_reissue(req)) {
2576 req->flags |= REQ_F_REISSUE;
2585 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2587 unsigned int cflags = io_put_rw_kbuf(req);
2588 long res = req->result;
2591 struct io_ring_ctx *ctx = req->ctx;
2592 struct io_submit_state *state = &ctx->submit_state;
2594 io_req_complete_state(req, res, cflags);
2595 state->compl_reqs[state->compl_nr++] = req;
2596 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2597 io_submit_flush_completions(ctx);
2599 io_req_complete_post(req, res, cflags);
2603 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2604 unsigned int issue_flags)
2606 if (__io_complete_rw_common(req, res))
2608 __io_req_complete(req, 0, req->result, io_put_rw_kbuf(req));
2611 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2613 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2615 if (__io_complete_rw_common(req, res))
2618 req->io_task_work.func = io_req_task_complete;
2619 io_req_task_work_add(req);
2622 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2624 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2626 if (kiocb->ki_flags & IOCB_WRITE)
2627 kiocb_end_write(req);
2628 if (unlikely(res != req->result)) {
2629 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2630 io_resubmit_prep(req))) {
2632 req->flags |= REQ_F_DONT_REISSUE;
2636 WRITE_ONCE(req->result, res);
2637 /* order with io_iopoll_complete() checking ->result */
2639 WRITE_ONCE(req->iopoll_completed, 1);
2643 * After the iocb has been issued, it's safe to be found on the poll list.
2644 * Adding the kiocb to the list AFTER submission ensures that we don't
2645 * find it from a io_do_iopoll() thread before the issuer is done
2646 * accessing the kiocb cookie.
2648 static void io_iopoll_req_issued(struct io_kiocb *req)
2650 struct io_ring_ctx *ctx = req->ctx;
2651 const bool in_async = io_wq_current_is_worker();
2653 /* workqueue context doesn't hold uring_lock, grab it now */
2654 if (unlikely(in_async))
2655 mutex_lock(&ctx->uring_lock);
2658 * Track whether we have multiple files in our lists. This will impact
2659 * how we do polling eventually, not spinning if we're on potentially
2660 * different devices.
2662 if (list_empty(&ctx->iopoll_list)) {
2663 ctx->poll_multi_queue = false;
2664 } else if (!ctx->poll_multi_queue) {
2665 struct io_kiocb *list_req;
2666 unsigned int queue_num0, queue_num1;
2668 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2671 if (list_req->file != req->file) {
2672 ctx->poll_multi_queue = true;
2674 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2675 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2676 if (queue_num0 != queue_num1)
2677 ctx->poll_multi_queue = true;
2682 * For fast devices, IO may have already completed. If it has, add
2683 * it to the front so we find it first.
2685 if (READ_ONCE(req->iopoll_completed))
2686 list_add(&req->inflight_entry, &ctx->iopoll_list);
2688 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2690 if (unlikely(in_async)) {
2692 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2693 * in sq thread task context or in io worker task context. If
2694 * current task context is sq thread, we don't need to check
2695 * whether should wake up sq thread.
2697 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2698 wq_has_sleeper(&ctx->sq_data->wait))
2699 wake_up(&ctx->sq_data->wait);
2701 mutex_unlock(&ctx->uring_lock);
2705 static bool io_bdev_nowait(struct block_device *bdev)
2707 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2711 * If we tracked the file through the SCM inflight mechanism, we could support
2712 * any file. For now, just ensure that anything potentially problematic is done
2715 static bool __io_file_supports_nowait(struct file *file, int rw)
2717 umode_t mode = file_inode(file)->i_mode;
2719 if (S_ISBLK(mode)) {
2720 if (IS_ENABLED(CONFIG_BLOCK) &&
2721 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2727 if (S_ISREG(mode)) {
2728 if (IS_ENABLED(CONFIG_BLOCK) &&
2729 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2730 file->f_op != &io_uring_fops)
2735 /* any ->read/write should understand O_NONBLOCK */
2736 if (file->f_flags & O_NONBLOCK)
2739 if (!(file->f_mode & FMODE_NOWAIT))
2743 return file->f_op->read_iter != NULL;
2745 return file->f_op->write_iter != NULL;
2748 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2750 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2752 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2755 return __io_file_supports_nowait(req->file, rw);
2758 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2760 struct io_ring_ctx *ctx = req->ctx;
2761 struct kiocb *kiocb = &req->rw.kiocb;
2762 struct file *file = req->file;
2766 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2767 req->flags |= REQ_F_ISREG;
2769 kiocb->ki_pos = READ_ONCE(sqe->off);
2770 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2771 req->flags |= REQ_F_CUR_POS;
2772 kiocb->ki_pos = file->f_pos;
2774 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2775 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2776 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2780 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2781 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2782 req->flags |= REQ_F_NOWAIT;
2784 ioprio = READ_ONCE(sqe->ioprio);
2786 ret = ioprio_check_cap(ioprio);
2790 kiocb->ki_ioprio = ioprio;
2792 kiocb->ki_ioprio = get_current_ioprio();
2794 if (ctx->flags & IORING_SETUP_IOPOLL) {
2795 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2796 !kiocb->ki_filp->f_op->iopoll)
2799 kiocb->ki_flags |= IOCB_HIPRI;
2800 kiocb->ki_complete = io_complete_rw_iopoll;
2801 req->iopoll_completed = 0;
2803 if (kiocb->ki_flags & IOCB_HIPRI)
2805 kiocb->ki_complete = io_complete_rw;
2808 if (req->opcode == IORING_OP_READ_FIXED ||
2809 req->opcode == IORING_OP_WRITE_FIXED) {
2811 io_req_set_rsrc_node(req);
2814 req->rw.addr = READ_ONCE(sqe->addr);
2815 req->rw.len = READ_ONCE(sqe->len);
2816 req->buf_index = READ_ONCE(sqe->buf_index);
2820 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2826 case -ERESTARTNOINTR:
2827 case -ERESTARTNOHAND:
2828 case -ERESTART_RESTARTBLOCK:
2830 * We can't just restart the syscall, since previously
2831 * submitted sqes may already be in progress. Just fail this
2837 kiocb->ki_complete(kiocb, ret, 0);
2841 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2842 unsigned int issue_flags)
2844 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2845 struct io_async_rw *io = req->async_data;
2846 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2848 /* add previously done IO, if any */
2849 if (io && io->bytes_done > 0) {
2851 ret = io->bytes_done;
2853 ret += io->bytes_done;
2856 if (req->flags & REQ_F_CUR_POS)
2857 req->file->f_pos = kiocb->ki_pos;
2858 if (ret >= 0 && check_reissue)
2859 __io_complete_rw(req, ret, 0, issue_flags);
2861 io_rw_done(kiocb, ret);
2863 if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2864 req->flags &= ~REQ_F_REISSUE;
2865 if (io_resubmit_prep(req)) {
2866 io_req_task_queue_reissue(req);
2869 __io_req_complete(req, issue_flags, ret,
2870 io_put_rw_kbuf(req));
2875 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2876 struct io_mapped_ubuf *imu)
2878 size_t len = req->rw.len;
2879 u64 buf_end, buf_addr = req->rw.addr;
2882 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2884 /* not inside the mapped region */
2885 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2889 * May not be a start of buffer, set size appropriately
2890 * and advance us to the beginning.
2892 offset = buf_addr - imu->ubuf;
2893 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2897 * Don't use iov_iter_advance() here, as it's really slow for
2898 * using the latter parts of a big fixed buffer - it iterates
2899 * over each segment manually. We can cheat a bit here, because
2902 * 1) it's a BVEC iter, we set it up
2903 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2904 * first and last bvec
2906 * So just find our index, and adjust the iterator afterwards.
2907 * If the offset is within the first bvec (or the whole first
2908 * bvec, just use iov_iter_advance(). This makes it easier
2909 * since we can just skip the first segment, which may not
2910 * be PAGE_SIZE aligned.
2912 const struct bio_vec *bvec = imu->bvec;
2914 if (offset <= bvec->bv_len) {
2915 iov_iter_advance(iter, offset);
2917 unsigned long seg_skip;
2919 /* skip first vec */
2920 offset -= bvec->bv_len;
2921 seg_skip = 1 + (offset >> PAGE_SHIFT);
2923 iter->bvec = bvec + seg_skip;
2924 iter->nr_segs -= seg_skip;
2925 iter->count -= bvec->bv_len + offset;
2926 iter->iov_offset = offset & ~PAGE_MASK;
2933 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2935 struct io_ring_ctx *ctx = req->ctx;
2936 struct io_mapped_ubuf *imu = req->imu;
2937 u16 index, buf_index = req->buf_index;
2940 if (unlikely(buf_index >= ctx->nr_user_bufs))
2942 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2943 imu = READ_ONCE(ctx->user_bufs[index]);
2946 return __io_import_fixed(req, rw, iter, imu);
2949 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2952 mutex_unlock(&ctx->uring_lock);
2955 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2958 * "Normal" inline submissions always hold the uring_lock, since we
2959 * grab it from the system call. Same is true for the SQPOLL offload.
2960 * The only exception is when we've detached the request and issue it
2961 * from an async worker thread, grab the lock for that case.
2964 mutex_lock(&ctx->uring_lock);
2967 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2968 int bgid, struct io_buffer *kbuf,
2971 struct io_buffer *head;
2973 if (req->flags & REQ_F_BUFFER_SELECTED)
2976 io_ring_submit_lock(req->ctx, needs_lock);
2978 lockdep_assert_held(&req->ctx->uring_lock);
2980 head = xa_load(&req->ctx->io_buffers, bgid);
2982 if (!list_empty(&head->list)) {
2983 kbuf = list_last_entry(&head->list, struct io_buffer,
2985 list_del(&kbuf->list);
2988 xa_erase(&req->ctx->io_buffers, bgid);
2990 if (*len > kbuf->len)
2993 kbuf = ERR_PTR(-ENOBUFS);
2996 io_ring_submit_unlock(req->ctx, needs_lock);
3001 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3004 struct io_buffer *kbuf;
3007 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3008 bgid = req->buf_index;
3009 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3012 req->rw.addr = (u64) (unsigned long) kbuf;
3013 req->flags |= REQ_F_BUFFER_SELECTED;
3014 return u64_to_user_ptr(kbuf->addr);
3017 #ifdef CONFIG_COMPAT
3018 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3021 struct compat_iovec __user *uiov;
3022 compat_ssize_t clen;
3026 uiov = u64_to_user_ptr(req->rw.addr);
3027 if (!access_ok(uiov, sizeof(*uiov)))
3029 if (__get_user(clen, &uiov->iov_len))
3035 buf = io_rw_buffer_select(req, &len, needs_lock);
3037 return PTR_ERR(buf);
3038 iov[0].iov_base = buf;
3039 iov[0].iov_len = (compat_size_t) len;
3044 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3047 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3051 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3054 len = iov[0].iov_len;
3057 buf = io_rw_buffer_select(req, &len, needs_lock);
3059 return PTR_ERR(buf);
3060 iov[0].iov_base = buf;
3061 iov[0].iov_len = len;
3065 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3068 if (req->flags & REQ_F_BUFFER_SELECTED) {
3069 struct io_buffer *kbuf;
3071 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3072 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3073 iov[0].iov_len = kbuf->len;
3076 if (req->rw.len != 1)
3079 #ifdef CONFIG_COMPAT
3080 if (req->ctx->compat)
3081 return io_compat_import(req, iov, needs_lock);
3084 return __io_iov_buffer_select(req, iov, needs_lock);
3087 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3088 struct iov_iter *iter, bool needs_lock)
3090 void __user *buf = u64_to_user_ptr(req->rw.addr);
3091 size_t sqe_len = req->rw.len;
3092 u8 opcode = req->opcode;
3095 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3097 return io_import_fixed(req, rw, iter);
3100 /* buffer index only valid with fixed read/write, or buffer select */
3101 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3104 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3105 if (req->flags & REQ_F_BUFFER_SELECT) {
3106 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3108 return PTR_ERR(buf);
3109 req->rw.len = sqe_len;
3112 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3117 if (req->flags & REQ_F_BUFFER_SELECT) {
3118 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3120 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3125 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3129 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3131 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3135 * For files that don't have ->read_iter() and ->write_iter(), handle them
3136 * by looping over ->read() or ->write() manually.
3138 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3140 struct kiocb *kiocb = &req->rw.kiocb;
3141 struct file *file = req->file;
3145 * Don't support polled IO through this interface, and we can't
3146 * support non-blocking either. For the latter, this just causes
3147 * the kiocb to be handled from an async context.
3149 if (kiocb->ki_flags & IOCB_HIPRI)
3151 if (kiocb->ki_flags & IOCB_NOWAIT)
3154 while (iov_iter_count(iter)) {
3158 if (!iov_iter_is_bvec(iter)) {
3159 iovec = iov_iter_iovec(iter);
3161 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3162 iovec.iov_len = req->rw.len;
3166 nr = file->f_op->read(file, iovec.iov_base,
3167 iovec.iov_len, io_kiocb_ppos(kiocb));
3169 nr = file->f_op->write(file, iovec.iov_base,
3170 iovec.iov_len, io_kiocb_ppos(kiocb));
3179 if (nr != iovec.iov_len)
3183 iov_iter_advance(iter, nr);
3189 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3190 const struct iovec *fast_iov, struct iov_iter *iter)
3192 struct io_async_rw *rw = req->async_data;
3194 memcpy(&rw->iter, iter, sizeof(*iter));
3195 rw->free_iovec = iovec;
3197 /* can only be fixed buffers, no need to do anything */
3198 if (iov_iter_is_bvec(iter))
3201 unsigned iov_off = 0;
3203 rw->iter.iov = rw->fast_iov;
3204 if (iter->iov != fast_iov) {
3205 iov_off = iter->iov - fast_iov;
3206 rw->iter.iov += iov_off;
3208 if (rw->fast_iov != fast_iov)
3209 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3210 sizeof(struct iovec) * iter->nr_segs);
3212 req->flags |= REQ_F_NEED_CLEANUP;
3216 static inline int io_alloc_async_data(struct io_kiocb *req)
3218 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3219 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3220 return req->async_data == NULL;
3223 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3224 const struct iovec *fast_iov,
3225 struct iov_iter *iter, bool force)
3227 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3229 if (!req->async_data) {
3230 if (io_alloc_async_data(req)) {
3235 io_req_map_rw(req, iovec, fast_iov, iter);
3240 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3242 struct io_async_rw *iorw = req->async_data;
3243 struct iovec *iov = iorw->fast_iov;
3246 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3247 if (unlikely(ret < 0))
3250 iorw->bytes_done = 0;
3251 iorw->free_iovec = iov;
3253 req->flags |= REQ_F_NEED_CLEANUP;
3257 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3259 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3261 return io_prep_rw(req, sqe);
3265 * This is our waitqueue callback handler, registered through lock_page_async()
3266 * when we initially tried to do the IO with the iocb armed our waitqueue.
3267 * This gets called when the page is unlocked, and we generally expect that to
3268 * happen when the page IO is completed and the page is now uptodate. This will
3269 * queue a task_work based retry of the operation, attempting to copy the data
3270 * again. If the latter fails because the page was NOT uptodate, then we will
3271 * do a thread based blocking retry of the operation. That's the unexpected
3274 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3275 int sync, void *arg)
3277 struct wait_page_queue *wpq;
3278 struct io_kiocb *req = wait->private;
3279 struct wait_page_key *key = arg;
3281 wpq = container_of(wait, struct wait_page_queue, wait);
3283 if (!wake_page_match(wpq, key))
3286 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3287 list_del_init(&wait->entry);
3288 io_req_task_queue(req);
3293 * This controls whether a given IO request should be armed for async page
3294 * based retry. If we return false here, the request is handed to the async
3295 * worker threads for retry. If we're doing buffered reads on a regular file,
3296 * we prepare a private wait_page_queue entry and retry the operation. This
3297 * will either succeed because the page is now uptodate and unlocked, or it
3298 * will register a callback when the page is unlocked at IO completion. Through
3299 * that callback, io_uring uses task_work to setup a retry of the operation.
3300 * That retry will attempt the buffered read again. The retry will generally
3301 * succeed, or in rare cases where it fails, we then fall back to using the
3302 * async worker threads for a blocking retry.
3304 static bool io_rw_should_retry(struct io_kiocb *req)
3306 struct io_async_rw *rw = req->async_data;
3307 struct wait_page_queue *wait = &rw->wpq;
3308 struct kiocb *kiocb = &req->rw.kiocb;
3310 /* never retry for NOWAIT, we just complete with -EAGAIN */
3311 if (req->flags & REQ_F_NOWAIT)
3314 /* Only for buffered IO */
3315 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3319 * just use poll if we can, and don't attempt if the fs doesn't
3320 * support callback based unlocks
3322 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3325 wait->wait.func = io_async_buf_func;
3326 wait->wait.private = req;
3327 wait->wait.flags = 0;
3328 INIT_LIST_HEAD(&wait->wait.entry);
3329 kiocb->ki_flags |= IOCB_WAITQ;
3330 kiocb->ki_flags &= ~IOCB_NOWAIT;
3331 kiocb->ki_waitq = wait;
3335 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3337 if (req->file->f_op->read_iter)
3338 return call_read_iter(req->file, &req->rw.kiocb, iter);
3339 else if (req->file->f_op->read)
3340 return loop_rw_iter(READ, req, iter);
3345 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3347 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3348 struct kiocb *kiocb = &req->rw.kiocb;
3349 struct iov_iter __iter, *iter = &__iter;
3350 struct io_async_rw *rw = req->async_data;
3351 ssize_t io_size, ret, ret2;
3352 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3358 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3362 io_size = iov_iter_count(iter);
3363 req->result = io_size;
3365 /* Ensure we clear previously set non-block flag */
3366 if (!force_nonblock)
3367 kiocb->ki_flags &= ~IOCB_NOWAIT;
3369 kiocb->ki_flags |= IOCB_NOWAIT;
3371 /* If the file doesn't support async, just async punt */
3372 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3373 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3374 return ret ?: -EAGAIN;
3377 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3378 if (unlikely(ret)) {
3383 ret = io_iter_do_read(req, iter);
3385 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3386 req->flags &= ~REQ_F_REISSUE;
3387 /* IOPOLL retry should happen for io-wq threads */
3388 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3390 /* no retry on NONBLOCK nor RWF_NOWAIT */
3391 if (req->flags & REQ_F_NOWAIT)
3393 /* some cases will consume bytes even on error returns */
3394 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3396 } else if (ret == -EIOCBQUEUED) {
3398 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3399 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3400 /* read all, failed, already did sync or don't want to retry */
3404 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3409 rw = req->async_data;
3410 /* now use our persistent iterator, if we aren't already */
3415 rw->bytes_done += ret;
3416 /* if we can retry, do so with the callbacks armed */
3417 if (!io_rw_should_retry(req)) {
3418 kiocb->ki_flags &= ~IOCB_WAITQ;
3423 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3424 * we get -EIOCBQUEUED, then we'll get a notification when the
3425 * desired page gets unlocked. We can also get a partial read
3426 * here, and if we do, then just retry at the new offset.
3428 ret = io_iter_do_read(req, iter);
3429 if (ret == -EIOCBQUEUED)
3431 /* we got some bytes, but not all. retry. */
3432 kiocb->ki_flags &= ~IOCB_WAITQ;
3433 } while (ret > 0 && ret < io_size);
3435 kiocb_done(kiocb, ret, issue_flags);
3437 /* it's faster to check here then delegate to kfree */
3443 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3445 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3447 return io_prep_rw(req, sqe);
3450 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3452 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3453 struct kiocb *kiocb = &req->rw.kiocb;
3454 struct iov_iter __iter, *iter = &__iter;
3455 struct io_async_rw *rw = req->async_data;
3456 ssize_t ret, ret2, io_size;
3457 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3463 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3467 io_size = iov_iter_count(iter);
3468 req->result = io_size;
3470 /* Ensure we clear previously set non-block flag */
3471 if (!force_nonblock)
3472 kiocb->ki_flags &= ~IOCB_NOWAIT;
3474 kiocb->ki_flags |= IOCB_NOWAIT;
3476 /* If the file doesn't support async, just async punt */
3477 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3480 /* file path doesn't support NOWAIT for non-direct_IO */
3481 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3482 (req->flags & REQ_F_ISREG))
3485 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3490 * Open-code file_start_write here to grab freeze protection,
3491 * which will be released by another thread in
3492 * io_complete_rw(). Fool lockdep by telling it the lock got
3493 * released so that it doesn't complain about the held lock when
3494 * we return to userspace.
3496 if (req->flags & REQ_F_ISREG) {
3497 sb_start_write(file_inode(req->file)->i_sb);
3498 __sb_writers_release(file_inode(req->file)->i_sb,
3501 kiocb->ki_flags |= IOCB_WRITE;
3503 if (req->file->f_op->write_iter)
3504 ret2 = call_write_iter(req->file, kiocb, iter);
3505 else if (req->file->f_op->write)
3506 ret2 = loop_rw_iter(WRITE, req, iter);
3510 if (req->flags & REQ_F_REISSUE) {
3511 req->flags &= ~REQ_F_REISSUE;
3516 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3517 * retry them without IOCB_NOWAIT.
3519 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3521 /* no retry on NONBLOCK nor RWF_NOWAIT */
3522 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3524 if (!force_nonblock || ret2 != -EAGAIN) {
3525 /* IOPOLL retry should happen for io-wq threads */
3526 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3529 kiocb_done(kiocb, ret2, issue_flags);
3532 /* some cases will consume bytes even on error returns */
3533 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3534 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3535 return ret ?: -EAGAIN;
3538 /* it's reportedly faster than delegating the null check to kfree() */
3544 static int io_renameat_prep(struct io_kiocb *req,
3545 const struct io_uring_sqe *sqe)
3547 struct io_rename *ren = &req->rename;
3548 const char __user *oldf, *newf;
3550 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3552 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3554 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3557 ren->old_dfd = READ_ONCE(sqe->fd);
3558 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3559 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3560 ren->new_dfd = READ_ONCE(sqe->len);
3561 ren->flags = READ_ONCE(sqe->rename_flags);
3563 ren->oldpath = getname(oldf);
3564 if (IS_ERR(ren->oldpath))
3565 return PTR_ERR(ren->oldpath);
3567 ren->newpath = getname(newf);
3568 if (IS_ERR(ren->newpath)) {
3569 putname(ren->oldpath);
3570 return PTR_ERR(ren->newpath);
3573 req->flags |= REQ_F_NEED_CLEANUP;
3577 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3579 struct io_rename *ren = &req->rename;
3582 if (issue_flags & IO_URING_F_NONBLOCK)
3585 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3586 ren->newpath, ren->flags);
3588 req->flags &= ~REQ_F_NEED_CLEANUP;
3591 io_req_complete(req, ret);
3595 static int io_unlinkat_prep(struct io_kiocb *req,
3596 const struct io_uring_sqe *sqe)
3598 struct io_unlink *un = &req->unlink;
3599 const char __user *fname;
3601 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3603 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3606 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3609 un->dfd = READ_ONCE(sqe->fd);
3611 un->flags = READ_ONCE(sqe->unlink_flags);
3612 if (un->flags & ~AT_REMOVEDIR)
3615 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3616 un->filename = getname(fname);
3617 if (IS_ERR(un->filename))
3618 return PTR_ERR(un->filename);
3620 req->flags |= REQ_F_NEED_CLEANUP;
3624 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3626 struct io_unlink *un = &req->unlink;
3629 if (issue_flags & IO_URING_F_NONBLOCK)
3632 if (un->flags & AT_REMOVEDIR)
3633 ret = do_rmdir(un->dfd, un->filename);
3635 ret = do_unlinkat(un->dfd, un->filename);
3637 req->flags &= ~REQ_F_NEED_CLEANUP;
3640 io_req_complete(req, ret);
3644 static int io_shutdown_prep(struct io_kiocb *req,
3645 const struct io_uring_sqe *sqe)
3647 #if defined(CONFIG_NET)
3648 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3650 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3651 sqe->buf_index || sqe->splice_fd_in))
3654 req->shutdown.how = READ_ONCE(sqe->len);
3661 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3663 #if defined(CONFIG_NET)
3664 struct socket *sock;
3667 if (issue_flags & IO_URING_F_NONBLOCK)
3670 sock = sock_from_file(req->file);
3671 if (unlikely(!sock))
3674 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3677 io_req_complete(req, ret);
3684 static int __io_splice_prep(struct io_kiocb *req,
3685 const struct io_uring_sqe *sqe)
3687 struct io_splice *sp = &req->splice;
3688 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3690 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3694 sp->len = READ_ONCE(sqe->len);
3695 sp->flags = READ_ONCE(sqe->splice_flags);
3697 if (unlikely(sp->flags & ~valid_flags))
3700 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3701 (sp->flags & SPLICE_F_FD_IN_FIXED));
3704 req->flags |= REQ_F_NEED_CLEANUP;
3708 static int io_tee_prep(struct io_kiocb *req,
3709 const struct io_uring_sqe *sqe)
3711 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3713 return __io_splice_prep(req, sqe);
3716 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3718 struct io_splice *sp = &req->splice;
3719 struct file *in = sp->file_in;
3720 struct file *out = sp->file_out;
3721 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3724 if (issue_flags & IO_URING_F_NONBLOCK)
3727 ret = do_tee(in, out, sp->len, flags);
3729 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3731 req->flags &= ~REQ_F_NEED_CLEANUP;
3735 io_req_complete(req, ret);
3739 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3741 struct io_splice *sp = &req->splice;
3743 sp->off_in = READ_ONCE(sqe->splice_off_in);
3744 sp->off_out = READ_ONCE(sqe->off);
3745 return __io_splice_prep(req, sqe);
3748 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3750 struct io_splice *sp = &req->splice;
3751 struct file *in = sp->file_in;
3752 struct file *out = sp->file_out;
3753 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3754 loff_t *poff_in, *poff_out;
3757 if (issue_flags & IO_URING_F_NONBLOCK)
3760 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3761 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3764 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3766 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3768 req->flags &= ~REQ_F_NEED_CLEANUP;
3772 io_req_complete(req, ret);
3777 * IORING_OP_NOP just posts a completion event, nothing else.
3779 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3781 struct io_ring_ctx *ctx = req->ctx;
3783 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3786 __io_req_complete(req, issue_flags, 0, 0);
3790 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3792 struct io_ring_ctx *ctx = req->ctx;
3797 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3799 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
3803 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3804 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3807 req->sync.off = READ_ONCE(sqe->off);
3808 req->sync.len = READ_ONCE(sqe->len);
3812 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3814 loff_t end = req->sync.off + req->sync.len;
3817 /* fsync always requires a blocking context */
3818 if (issue_flags & IO_URING_F_NONBLOCK)
3821 ret = vfs_fsync_range(req->file, req->sync.off,
3822 end > 0 ? end : LLONG_MAX,
3823 req->sync.flags & IORING_FSYNC_DATASYNC);
3826 io_req_complete(req, ret);
3830 static int io_fallocate_prep(struct io_kiocb *req,
3831 const struct io_uring_sqe *sqe)
3833 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
3836 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3839 req->sync.off = READ_ONCE(sqe->off);
3840 req->sync.len = READ_ONCE(sqe->addr);
3841 req->sync.mode = READ_ONCE(sqe->len);
3845 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3849 /* fallocate always requiring blocking context */
3850 if (issue_flags & IO_URING_F_NONBLOCK)
3852 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3856 io_req_complete(req, ret);
3860 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3862 const char __user *fname;
3865 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3867 if (unlikely(sqe->ioprio || sqe->buf_index || sqe->splice_fd_in))
3869 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3872 /* open.how should be already initialised */
3873 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3874 req->open.how.flags |= O_LARGEFILE;
3876 req->open.dfd = READ_ONCE(sqe->fd);
3877 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3878 req->open.filename = getname(fname);
3879 if (IS_ERR(req->open.filename)) {
3880 ret = PTR_ERR(req->open.filename);
3881 req->open.filename = NULL;
3884 req->open.nofile = rlimit(RLIMIT_NOFILE);
3885 req->flags |= REQ_F_NEED_CLEANUP;
3889 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3891 u64 mode = READ_ONCE(sqe->len);
3892 u64 flags = READ_ONCE(sqe->open_flags);
3894 req->open.how = build_open_how(flags, mode);
3895 return __io_openat_prep(req, sqe);
3898 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3900 struct open_how __user *how;
3904 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3905 len = READ_ONCE(sqe->len);
3906 if (len < OPEN_HOW_SIZE_VER0)
3909 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3914 return __io_openat_prep(req, sqe);
3917 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3919 struct open_flags op;
3922 bool resolve_nonblock;
3925 ret = build_open_flags(&req->open.how, &op);
3928 nonblock_set = op.open_flag & O_NONBLOCK;
3929 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3930 if (issue_flags & IO_URING_F_NONBLOCK) {
3932 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3933 * it'll always -EAGAIN
3935 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3937 op.lookup_flags |= LOOKUP_CACHED;
3938 op.open_flag |= O_NONBLOCK;
3941 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3945 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3948 * We could hang on to this 'fd' on retrying, but seems like
3949 * marginal gain for something that is now known to be a slower
3950 * path. So just put it, and we'll get a new one when we retry.
3954 ret = PTR_ERR(file);
3955 /* only retry if RESOLVE_CACHED wasn't already set by application */
3956 if (ret == -EAGAIN &&
3957 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3962 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3963 file->f_flags &= ~O_NONBLOCK;
3964 fsnotify_open(file);
3965 fd_install(ret, file);
3967 putname(req->open.filename);
3968 req->flags &= ~REQ_F_NEED_CLEANUP;
3971 __io_req_complete(req, issue_flags, ret, 0);
3975 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3977 return io_openat2(req, issue_flags);
3980 static int io_remove_buffers_prep(struct io_kiocb *req,
3981 const struct io_uring_sqe *sqe)
3983 struct io_provide_buf *p = &req->pbuf;
3986 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
3990 tmp = READ_ONCE(sqe->fd);
3991 if (!tmp || tmp > USHRT_MAX)
3994 memset(p, 0, sizeof(*p));
3996 p->bgid = READ_ONCE(sqe->buf_group);
4000 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4001 int bgid, unsigned nbufs)
4005 /* shouldn't happen */
4009 /* the head kbuf is the list itself */
4010 while (!list_empty(&buf->list)) {
4011 struct io_buffer *nxt;
4013 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4014 list_del(&nxt->list);
4021 xa_erase(&ctx->io_buffers, bgid);
4026 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4028 struct io_provide_buf *p = &req->pbuf;
4029 struct io_ring_ctx *ctx = req->ctx;
4030 struct io_buffer *head;
4032 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4034 io_ring_submit_lock(ctx, !force_nonblock);
4036 lockdep_assert_held(&ctx->uring_lock);
4039 head = xa_load(&ctx->io_buffers, p->bgid);
4041 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4045 /* complete before unlock, IOPOLL may need the lock */
4046 __io_req_complete(req, issue_flags, ret, 0);
4047 io_ring_submit_unlock(ctx, !force_nonblock);
4051 static int io_provide_buffers_prep(struct io_kiocb *req,
4052 const struct io_uring_sqe *sqe)
4054 unsigned long size, tmp_check;
4055 struct io_provide_buf *p = &req->pbuf;
4058 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4061 tmp = READ_ONCE(sqe->fd);
4062 if (!tmp || tmp > USHRT_MAX)
4065 p->addr = READ_ONCE(sqe->addr);
4066 p->len = READ_ONCE(sqe->len);
4068 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4071 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4074 size = (unsigned long)p->len * p->nbufs;
4075 if (!access_ok(u64_to_user_ptr(p->addr), size))
4078 p->bgid = READ_ONCE(sqe->buf_group);
4079 tmp = READ_ONCE(sqe->off);
4080 if (tmp > USHRT_MAX)
4086 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4088 struct io_buffer *buf;
4089 u64 addr = pbuf->addr;
4090 int i, bid = pbuf->bid;
4092 for (i = 0; i < pbuf->nbufs; i++) {
4093 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4098 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4103 INIT_LIST_HEAD(&buf->list);
4106 list_add_tail(&buf->list, &(*head)->list);
4110 return i ? i : -ENOMEM;
4113 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4115 struct io_provide_buf *p = &req->pbuf;
4116 struct io_ring_ctx *ctx = req->ctx;
4117 struct io_buffer *head, *list;
4119 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4121 io_ring_submit_lock(ctx, !force_nonblock);
4123 lockdep_assert_held(&ctx->uring_lock);
4125 list = head = xa_load(&ctx->io_buffers, p->bgid);
4127 ret = io_add_buffers(p, &head);
4128 if (ret >= 0 && !list) {
4129 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4131 __io_remove_buffers(ctx, head, p->bgid, -1U);
4135 /* complete before unlock, IOPOLL may need the lock */
4136 __io_req_complete(req, issue_flags, ret, 0);
4137 io_ring_submit_unlock(ctx, !force_nonblock);
4141 static int io_epoll_ctl_prep(struct io_kiocb *req,
4142 const struct io_uring_sqe *sqe)
4144 #if defined(CONFIG_EPOLL)
4145 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4147 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4150 req->epoll.epfd = READ_ONCE(sqe->fd);
4151 req->epoll.op = READ_ONCE(sqe->len);
4152 req->epoll.fd = READ_ONCE(sqe->off);
4154 if (ep_op_has_event(req->epoll.op)) {
4155 struct epoll_event __user *ev;
4157 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4158 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4168 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4170 #if defined(CONFIG_EPOLL)
4171 struct io_epoll *ie = &req->epoll;
4173 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4175 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4176 if (force_nonblock && ret == -EAGAIN)
4181 __io_req_complete(req, issue_flags, ret, 0);
4188 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4190 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4191 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4193 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4196 req->madvise.addr = READ_ONCE(sqe->addr);
4197 req->madvise.len = READ_ONCE(sqe->len);
4198 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4205 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4207 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4208 struct io_madvise *ma = &req->madvise;
4211 if (issue_flags & IO_URING_F_NONBLOCK)
4214 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4217 io_req_complete(req, ret);
4224 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4226 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4228 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4231 req->fadvise.offset = READ_ONCE(sqe->off);
4232 req->fadvise.len = READ_ONCE(sqe->len);
4233 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4237 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4239 struct io_fadvise *fa = &req->fadvise;
4242 if (issue_flags & IO_URING_F_NONBLOCK) {
4243 switch (fa->advice) {
4244 case POSIX_FADV_NORMAL:
4245 case POSIX_FADV_RANDOM:
4246 case POSIX_FADV_SEQUENTIAL:
4253 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4256 __io_req_complete(req, issue_flags, ret, 0);
4260 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4262 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4264 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4266 if (req->flags & REQ_F_FIXED_FILE)
4269 req->statx.dfd = READ_ONCE(sqe->fd);
4270 req->statx.mask = READ_ONCE(sqe->len);
4271 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4272 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4273 req->statx.flags = READ_ONCE(sqe->statx_flags);
4278 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4280 struct io_statx *ctx = &req->statx;
4283 if (issue_flags & IO_URING_F_NONBLOCK)
4286 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4291 io_req_complete(req, ret);
4295 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4297 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4299 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4300 sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4302 if (req->flags & REQ_F_FIXED_FILE)
4305 req->close.fd = READ_ONCE(sqe->fd);
4309 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4311 struct files_struct *files = current->files;
4312 struct io_close *close = &req->close;
4313 struct fdtable *fdt;
4314 struct file *file = NULL;
4317 spin_lock(&files->file_lock);
4318 fdt = files_fdtable(files);
4319 if (close->fd >= fdt->max_fds) {
4320 spin_unlock(&files->file_lock);
4323 file = fdt->fd[close->fd];
4324 if (!file || file->f_op == &io_uring_fops) {
4325 spin_unlock(&files->file_lock);
4330 /* if the file has a flush method, be safe and punt to async */
4331 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4332 spin_unlock(&files->file_lock);
4336 ret = __close_fd_get_file(close->fd, &file);
4337 spin_unlock(&files->file_lock);
4344 /* No ->flush() or already async, safely close from here */
4345 ret = filp_close(file, current->files);
4351 __io_req_complete(req, issue_flags, ret, 0);
4355 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4357 struct io_ring_ctx *ctx = req->ctx;
4359 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4361 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4365 req->sync.off = READ_ONCE(sqe->off);
4366 req->sync.len = READ_ONCE(sqe->len);
4367 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4371 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4375 /* sync_file_range always requires a blocking context */
4376 if (issue_flags & IO_URING_F_NONBLOCK)
4379 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4383 io_req_complete(req, ret);
4387 #if defined(CONFIG_NET)
4388 static int io_setup_async_msg(struct io_kiocb *req,
4389 struct io_async_msghdr *kmsg)
4391 struct io_async_msghdr *async_msg = req->async_data;
4395 if (io_alloc_async_data(req)) {
4396 kfree(kmsg->free_iov);
4399 async_msg = req->async_data;
4400 req->flags |= REQ_F_NEED_CLEANUP;
4401 memcpy(async_msg, kmsg, sizeof(*kmsg));
4402 async_msg->msg.msg_name = &async_msg->addr;
4403 /* if were using fast_iov, set it to the new one */
4404 if (!async_msg->free_iov)
4405 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4410 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4411 struct io_async_msghdr *iomsg)
4413 iomsg->msg.msg_name = &iomsg->addr;
4414 iomsg->free_iov = iomsg->fast_iov;
4415 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4416 req->sr_msg.msg_flags, &iomsg->free_iov);
4419 static int io_sendmsg_prep_async(struct io_kiocb *req)
4423 ret = io_sendmsg_copy_hdr(req, req->async_data);
4425 req->flags |= REQ_F_NEED_CLEANUP;
4429 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4431 struct io_sr_msg *sr = &req->sr_msg;
4433 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4436 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4437 sr->len = READ_ONCE(sqe->len);
4438 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4439 if (sr->msg_flags & MSG_DONTWAIT)
4440 req->flags |= REQ_F_NOWAIT;
4442 #ifdef CONFIG_COMPAT
4443 if (req->ctx->compat)
4444 sr->msg_flags |= MSG_CMSG_COMPAT;
4449 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4451 struct io_async_msghdr iomsg, *kmsg;
4452 struct socket *sock;
4457 sock = sock_from_file(req->file);
4458 if (unlikely(!sock))
4461 kmsg = req->async_data;
4463 ret = io_sendmsg_copy_hdr(req, &iomsg);
4469 flags = req->sr_msg.msg_flags;
4470 if (issue_flags & IO_URING_F_NONBLOCK)
4471 flags |= MSG_DONTWAIT;
4472 if (flags & MSG_WAITALL)
4473 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4475 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4476 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4477 return io_setup_async_msg(req, kmsg);
4478 if (ret == -ERESTARTSYS)
4481 /* fast path, check for non-NULL to avoid function call */
4483 kfree(kmsg->free_iov);
4484 req->flags &= ~REQ_F_NEED_CLEANUP;
4487 __io_req_complete(req, issue_flags, ret, 0);
4491 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4493 struct io_sr_msg *sr = &req->sr_msg;
4496 struct socket *sock;
4501 sock = sock_from_file(req->file);
4502 if (unlikely(!sock))
4505 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4509 msg.msg_name = NULL;
4510 msg.msg_control = NULL;
4511 msg.msg_controllen = 0;
4512 msg.msg_namelen = 0;
4514 flags = req->sr_msg.msg_flags;
4515 if (issue_flags & IO_URING_F_NONBLOCK)
4516 flags |= MSG_DONTWAIT;
4517 if (flags & MSG_WAITALL)
4518 min_ret = iov_iter_count(&msg.msg_iter);
4520 msg.msg_flags = flags;
4521 ret = sock_sendmsg(sock, &msg);
4522 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4524 if (ret == -ERESTARTSYS)
4529 __io_req_complete(req, issue_flags, ret, 0);
4533 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4534 struct io_async_msghdr *iomsg)
4536 struct io_sr_msg *sr = &req->sr_msg;
4537 struct iovec __user *uiov;
4541 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4542 &iomsg->uaddr, &uiov, &iov_len);
4546 if (req->flags & REQ_F_BUFFER_SELECT) {
4549 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4551 sr->len = iomsg->fast_iov[0].iov_len;
4552 iomsg->free_iov = NULL;
4554 iomsg->free_iov = iomsg->fast_iov;
4555 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4556 &iomsg->free_iov, &iomsg->msg.msg_iter,
4565 #ifdef CONFIG_COMPAT
4566 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4567 struct io_async_msghdr *iomsg)
4569 struct io_sr_msg *sr = &req->sr_msg;
4570 struct compat_iovec __user *uiov;
4575 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4580 uiov = compat_ptr(ptr);
4581 if (req->flags & REQ_F_BUFFER_SELECT) {
4582 compat_ssize_t clen;
4586 if (!access_ok(uiov, sizeof(*uiov)))
4588 if (__get_user(clen, &uiov->iov_len))
4593 iomsg->free_iov = NULL;
4595 iomsg->free_iov = iomsg->fast_iov;
4596 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4597 UIO_FASTIOV, &iomsg->free_iov,
4598 &iomsg->msg.msg_iter, true);
4607 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4608 struct io_async_msghdr *iomsg)
4610 iomsg->msg.msg_name = &iomsg->addr;
4612 #ifdef CONFIG_COMPAT
4613 if (req->ctx->compat)
4614 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4617 return __io_recvmsg_copy_hdr(req, iomsg);
4620 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4623 struct io_sr_msg *sr = &req->sr_msg;
4624 struct io_buffer *kbuf;
4626 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4631 req->flags |= REQ_F_BUFFER_SELECTED;
4635 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4637 return io_put_kbuf(req, req->sr_msg.kbuf);
4640 static int io_recvmsg_prep_async(struct io_kiocb *req)
4644 ret = io_recvmsg_copy_hdr(req, req->async_data);
4646 req->flags |= REQ_F_NEED_CLEANUP;
4650 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4652 struct io_sr_msg *sr = &req->sr_msg;
4654 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4657 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4658 sr->len = READ_ONCE(sqe->len);
4659 sr->bgid = READ_ONCE(sqe->buf_group);
4660 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4661 if (sr->msg_flags & MSG_DONTWAIT)
4662 req->flags |= REQ_F_NOWAIT;
4664 #ifdef CONFIG_COMPAT
4665 if (req->ctx->compat)
4666 sr->msg_flags |= MSG_CMSG_COMPAT;
4671 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4673 struct io_async_msghdr iomsg, *kmsg;
4674 struct socket *sock;
4675 struct io_buffer *kbuf;
4678 int ret, cflags = 0;
4679 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4681 sock = sock_from_file(req->file);
4682 if (unlikely(!sock))
4685 kmsg = req->async_data;
4687 ret = io_recvmsg_copy_hdr(req, &iomsg);
4693 if (req->flags & REQ_F_BUFFER_SELECT) {
4694 kbuf = io_recv_buffer_select(req, !force_nonblock);
4696 return PTR_ERR(kbuf);
4697 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4698 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4699 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4700 1, req->sr_msg.len);
4703 flags = req->sr_msg.msg_flags;
4705 flags |= MSG_DONTWAIT;
4706 if (flags & MSG_WAITALL)
4707 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4709 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4710 kmsg->uaddr, flags);
4711 if (force_nonblock && ret == -EAGAIN)
4712 return io_setup_async_msg(req, kmsg);
4713 if (ret == -ERESTARTSYS)
4716 if (req->flags & REQ_F_BUFFER_SELECTED)
4717 cflags = io_put_recv_kbuf(req);
4718 /* fast path, check for non-NULL to avoid function call */
4720 kfree(kmsg->free_iov);
4721 req->flags &= ~REQ_F_NEED_CLEANUP;
4722 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4724 __io_req_complete(req, issue_flags, ret, cflags);
4728 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4730 struct io_buffer *kbuf;
4731 struct io_sr_msg *sr = &req->sr_msg;
4733 void __user *buf = sr->buf;
4734 struct socket *sock;
4738 int ret, cflags = 0;
4739 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4741 sock = sock_from_file(req->file);
4742 if (unlikely(!sock))
4745 if (req->flags & REQ_F_BUFFER_SELECT) {
4746 kbuf = io_recv_buffer_select(req, !force_nonblock);
4748 return PTR_ERR(kbuf);
4749 buf = u64_to_user_ptr(kbuf->addr);
4752 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4756 msg.msg_name = NULL;
4757 msg.msg_control = NULL;
4758 msg.msg_controllen = 0;
4759 msg.msg_namelen = 0;
4760 msg.msg_iocb = NULL;
4763 flags = req->sr_msg.msg_flags;
4765 flags |= MSG_DONTWAIT;
4766 if (flags & MSG_WAITALL)
4767 min_ret = iov_iter_count(&msg.msg_iter);
4769 ret = sock_recvmsg(sock, &msg, flags);
4770 if (force_nonblock && ret == -EAGAIN)
4772 if (ret == -ERESTARTSYS)
4775 if (req->flags & REQ_F_BUFFER_SELECTED)
4776 cflags = io_put_recv_kbuf(req);
4777 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4779 __io_req_complete(req, issue_flags, ret, cflags);
4783 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4785 struct io_accept *accept = &req->accept;
4787 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4789 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4792 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4793 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4794 accept->flags = READ_ONCE(sqe->accept_flags);
4795 accept->nofile = rlimit(RLIMIT_NOFILE);
4799 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4801 struct io_accept *accept = &req->accept;
4802 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4803 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4806 if (req->file->f_flags & O_NONBLOCK)
4807 req->flags |= REQ_F_NOWAIT;
4809 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4810 accept->addr_len, accept->flags,
4812 if (ret == -EAGAIN && force_nonblock)
4815 if (ret == -ERESTARTSYS)
4819 __io_req_complete(req, issue_flags, ret, 0);
4823 static int io_connect_prep_async(struct io_kiocb *req)
4825 struct io_async_connect *io = req->async_data;
4826 struct io_connect *conn = &req->connect;
4828 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4831 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4833 struct io_connect *conn = &req->connect;
4835 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4837 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
4841 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4842 conn->addr_len = READ_ONCE(sqe->addr2);
4846 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4848 struct io_async_connect __io, *io;
4849 unsigned file_flags;
4851 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4853 if (req->async_data) {
4854 io = req->async_data;
4856 ret = move_addr_to_kernel(req->connect.addr,
4857 req->connect.addr_len,
4864 file_flags = force_nonblock ? O_NONBLOCK : 0;
4866 ret = __sys_connect_file(req->file, &io->address,
4867 req->connect.addr_len, file_flags);
4868 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4869 if (req->async_data)
4871 if (io_alloc_async_data(req)) {
4875 memcpy(req->async_data, &__io, sizeof(__io));
4878 if (ret == -ERESTARTSYS)
4883 __io_req_complete(req, issue_flags, ret, 0);
4886 #else /* !CONFIG_NET */
4887 #define IO_NETOP_FN(op) \
4888 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4890 return -EOPNOTSUPP; \
4893 #define IO_NETOP_PREP(op) \
4895 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4897 return -EOPNOTSUPP; \
4900 #define IO_NETOP_PREP_ASYNC(op) \
4902 static int io_##op##_prep_async(struct io_kiocb *req) \
4904 return -EOPNOTSUPP; \
4907 IO_NETOP_PREP_ASYNC(sendmsg);
4908 IO_NETOP_PREP_ASYNC(recvmsg);
4909 IO_NETOP_PREP_ASYNC(connect);
4910 IO_NETOP_PREP(accept);
4913 #endif /* CONFIG_NET */
4915 struct io_poll_table {
4916 struct poll_table_struct pt;
4917 struct io_kiocb *req;
4922 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4923 __poll_t mask, io_req_tw_func_t func)
4925 /* for instances that support it check for an event match first: */
4926 if (mask && !(mask & poll->events))
4929 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4931 list_del_init(&poll->wait.entry);
4934 req->io_task_work.func = func;
4937 * If this fails, then the task is exiting. When a task exits, the
4938 * work gets canceled, so just cancel this request as well instead
4939 * of executing it. We can't safely execute it anyway, as we may not
4940 * have the needed state needed for it anyway.
4942 io_req_task_work_add(req);
4946 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4947 __acquires(&req->ctx->completion_lock)
4949 struct io_ring_ctx *ctx = req->ctx;
4951 /* req->task == current here, checking PF_EXITING is safe */
4952 if (unlikely(req->task->flags & PF_EXITING))
4953 WRITE_ONCE(poll->canceled, true);
4955 if (!req->result && !READ_ONCE(poll->canceled)) {
4956 struct poll_table_struct pt = { ._key = poll->events };
4958 req->result = vfs_poll(req->file, &pt) & poll->events;
4961 spin_lock(&ctx->completion_lock);
4962 if (!req->result && !READ_ONCE(poll->canceled)) {
4963 add_wait_queue(poll->head, &poll->wait);
4970 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4972 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4973 if (req->opcode == IORING_OP_POLL_ADD)
4974 return req->async_data;
4975 return req->apoll->double_poll;
4978 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4980 if (req->opcode == IORING_OP_POLL_ADD)
4982 return &req->apoll->poll;
4985 static void io_poll_remove_double(struct io_kiocb *req)
4986 __must_hold(&req->ctx->completion_lock)
4988 struct io_poll_iocb *poll = io_poll_get_double(req);
4990 lockdep_assert_held(&req->ctx->completion_lock);
4992 if (poll && poll->head) {
4993 struct wait_queue_head *head = poll->head;
4995 spin_lock_irq(&head->lock);
4996 list_del_init(&poll->wait.entry);
4997 if (poll->wait.private)
5000 spin_unlock_irq(&head->lock);
5004 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
5005 __must_hold(&req->ctx->completion_lock)
5007 struct io_ring_ctx *ctx = req->ctx;
5008 unsigned flags = IORING_CQE_F_MORE;
5011 if (READ_ONCE(req->poll.canceled)) {
5013 req->poll.events |= EPOLLONESHOT;
5015 error = mangle_poll(mask);
5017 if (req->poll.events & EPOLLONESHOT)
5019 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
5020 req->poll.done = true;
5023 if (flags & IORING_CQE_F_MORE)
5026 io_commit_cqring(ctx);
5027 return !(flags & IORING_CQE_F_MORE);
5030 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5032 struct io_ring_ctx *ctx = req->ctx;
5033 struct io_kiocb *nxt;
5035 if (io_poll_rewait(req, &req->poll)) {
5036 spin_unlock(&ctx->completion_lock);
5040 done = io_poll_complete(req, req->result);
5042 io_poll_remove_double(req);
5043 hash_del(&req->hash_node);
5046 add_wait_queue(req->poll.head, &req->poll.wait);
5048 spin_unlock(&ctx->completion_lock);
5049 io_cqring_ev_posted(ctx);
5052 nxt = io_put_req_find_next(req);
5054 io_req_task_submit(nxt, locked);
5059 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
5060 int sync, void *key)
5062 struct io_kiocb *req = wait->private;
5063 struct io_poll_iocb *poll = io_poll_get_single(req);
5064 __poll_t mask = key_to_poll(key);
5065 unsigned long flags;
5067 /* for instances that support it check for an event match first: */
5068 if (mask && !(mask & poll->events))
5070 if (!(poll->events & EPOLLONESHOT))
5071 return poll->wait.func(&poll->wait, mode, sync, key);
5073 list_del_init(&wait->entry);
5078 spin_lock_irqsave(&poll->head->lock, flags);
5079 done = list_empty(&poll->wait.entry);
5081 list_del_init(&poll->wait.entry);
5082 /* make sure double remove sees this as being gone */
5083 wait->private = NULL;
5084 spin_unlock_irqrestore(&poll->head->lock, flags);
5086 /* use wait func handler, so it matches the rq type */
5087 poll->wait.func(&poll->wait, mode, sync, key);
5094 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5095 wait_queue_func_t wake_func)
5099 poll->canceled = false;
5100 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5101 /* mask in events that we always want/need */
5102 poll->events = events | IO_POLL_UNMASK;
5103 INIT_LIST_HEAD(&poll->wait.entry);
5104 init_waitqueue_func_entry(&poll->wait, wake_func);
5107 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5108 struct wait_queue_head *head,
5109 struct io_poll_iocb **poll_ptr)
5111 struct io_kiocb *req = pt->req;
5114 * The file being polled uses multiple waitqueues for poll handling
5115 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5118 if (unlikely(pt->nr_entries)) {
5119 struct io_poll_iocb *poll_one = poll;
5121 /* double add on the same waitqueue head, ignore */
5122 if (poll_one->head == head)
5124 /* already have a 2nd entry, fail a third attempt */
5126 if ((*poll_ptr)->head == head)
5128 pt->error = -EINVAL;
5132 * Can't handle multishot for double wait for now, turn it
5133 * into one-shot mode.
5135 if (!(poll_one->events & EPOLLONESHOT))
5136 poll_one->events |= EPOLLONESHOT;
5137 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5139 pt->error = -ENOMEM;
5142 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5144 poll->wait.private = req;
5151 if (poll->events & EPOLLEXCLUSIVE)
5152 add_wait_queue_exclusive(head, &poll->wait);
5154 add_wait_queue(head, &poll->wait);
5157 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5158 struct poll_table_struct *p)
5160 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5161 struct async_poll *apoll = pt->req->apoll;
5163 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5166 static void io_async_task_func(struct io_kiocb *req, bool *locked)
5168 struct async_poll *apoll = req->apoll;
5169 struct io_ring_ctx *ctx = req->ctx;
5171 trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5173 if (io_poll_rewait(req, &apoll->poll)) {
5174 spin_unlock(&ctx->completion_lock);
5178 hash_del(&req->hash_node);
5179 io_poll_remove_double(req);
5180 spin_unlock(&ctx->completion_lock);
5182 if (!READ_ONCE(apoll->poll.canceled))
5183 io_req_task_submit(req, locked);
5185 io_req_complete_failed(req, -ECANCELED);
5188 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5191 struct io_kiocb *req = wait->private;
5192 struct io_poll_iocb *poll = &req->apoll->poll;
5194 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5197 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5200 static void io_poll_req_insert(struct io_kiocb *req)
5202 struct io_ring_ctx *ctx = req->ctx;
5203 struct hlist_head *list;
5205 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5206 hlist_add_head(&req->hash_node, list);
5209 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5210 struct io_poll_iocb *poll,
5211 struct io_poll_table *ipt, __poll_t mask,
5212 wait_queue_func_t wake_func)
5213 __acquires(&ctx->completion_lock)
5215 struct io_ring_ctx *ctx = req->ctx;
5216 bool cancel = false;
5218 INIT_HLIST_NODE(&req->hash_node);
5219 io_init_poll_iocb(poll, mask, wake_func);
5220 poll->file = req->file;
5221 poll->wait.private = req;
5223 ipt->pt._key = mask;
5226 ipt->nr_entries = 0;
5228 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5229 if (unlikely(!ipt->nr_entries) && !ipt->error)
5230 ipt->error = -EINVAL;
5232 spin_lock(&ctx->completion_lock);
5233 if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5234 io_poll_remove_double(req);
5235 if (likely(poll->head)) {
5236 spin_lock_irq(&poll->head->lock);
5237 if (unlikely(list_empty(&poll->wait.entry))) {
5243 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5244 list_del_init(&poll->wait.entry);
5246 WRITE_ONCE(poll->canceled, true);
5247 else if (!poll->done) /* actually waiting for an event */
5248 io_poll_req_insert(req);
5249 spin_unlock_irq(&poll->head->lock);
5261 static int io_arm_poll_handler(struct io_kiocb *req)
5263 const struct io_op_def *def = &io_op_defs[req->opcode];
5264 struct io_ring_ctx *ctx = req->ctx;
5265 struct async_poll *apoll;
5266 struct io_poll_table ipt;
5267 __poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5270 if (!req->file || !file_can_poll(req->file))
5271 return IO_APOLL_ABORTED;
5272 if (req->flags & REQ_F_POLLED)
5273 return IO_APOLL_ABORTED;
5274 if (!def->pollin && !def->pollout)
5275 return IO_APOLL_ABORTED;
5279 mask |= POLLIN | POLLRDNORM;
5281 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5282 if ((req->opcode == IORING_OP_RECVMSG) &&
5283 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5287 mask |= POLLOUT | POLLWRNORM;
5290 /* if we can't nonblock try, then no point in arming a poll handler */
5291 if (!io_file_supports_nowait(req, rw))
5292 return IO_APOLL_ABORTED;
5294 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5295 if (unlikely(!apoll))
5296 return IO_APOLL_ABORTED;
5297 apoll->double_poll = NULL;
5299 req->flags |= REQ_F_POLLED;
5300 ipt.pt._qproc = io_async_queue_proc;
5301 io_req_set_refcount(req);
5303 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5305 spin_unlock(&ctx->completion_lock);
5306 if (ret || ipt.error)
5307 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5309 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5310 mask, apoll->poll.events);
5314 static bool __io_poll_remove_one(struct io_kiocb *req,
5315 struct io_poll_iocb *poll, bool do_cancel)
5316 __must_hold(&req->ctx->completion_lock)
5318 bool do_complete = false;
5322 spin_lock_irq(&poll->head->lock);
5324 WRITE_ONCE(poll->canceled, true);
5325 if (!list_empty(&poll->wait.entry)) {
5326 list_del_init(&poll->wait.entry);
5329 spin_unlock_irq(&poll->head->lock);
5330 hash_del(&req->hash_node);
5334 static bool io_poll_remove_one(struct io_kiocb *req)
5335 __must_hold(&req->ctx->completion_lock)
5339 io_poll_remove_double(req);
5340 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5343 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5344 io_commit_cqring(req->ctx);
5346 io_put_req_deferred(req);
5352 * Returns true if we found and killed one or more poll requests
5354 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5357 struct hlist_node *tmp;
5358 struct io_kiocb *req;
5361 spin_lock(&ctx->completion_lock);
5362 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5363 struct hlist_head *list;
5365 list = &ctx->cancel_hash[i];
5366 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5367 if (io_match_task(req, tsk, cancel_all))
5368 posted += io_poll_remove_one(req);
5371 spin_unlock(&ctx->completion_lock);
5374 io_cqring_ev_posted(ctx);
5379 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5381 __must_hold(&ctx->completion_lock)
5383 struct hlist_head *list;
5384 struct io_kiocb *req;
5386 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5387 hlist_for_each_entry(req, list, hash_node) {
5388 if (sqe_addr != req->user_data)
5390 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5397 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5399 __must_hold(&ctx->completion_lock)
5401 struct io_kiocb *req;
5403 req = io_poll_find(ctx, sqe_addr, poll_only);
5406 if (io_poll_remove_one(req))
5412 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5417 events = READ_ONCE(sqe->poll32_events);
5419 events = swahw32(events);
5421 if (!(flags & IORING_POLL_ADD_MULTI))
5422 events |= EPOLLONESHOT;
5423 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5426 static int io_poll_update_prep(struct io_kiocb *req,
5427 const struct io_uring_sqe *sqe)
5429 struct io_poll_update *upd = &req->poll_update;
5432 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5434 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5436 flags = READ_ONCE(sqe->len);
5437 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5438 IORING_POLL_ADD_MULTI))
5440 /* meaningless without update */
5441 if (flags == IORING_POLL_ADD_MULTI)
5444 upd->old_user_data = READ_ONCE(sqe->addr);
5445 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5446 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5448 upd->new_user_data = READ_ONCE(sqe->off);
5449 if (!upd->update_user_data && upd->new_user_data)
5451 if (upd->update_events)
5452 upd->events = io_poll_parse_events(sqe, flags);
5453 else if (sqe->poll32_events)
5459 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5462 struct io_kiocb *req = wait->private;
5463 struct io_poll_iocb *poll = &req->poll;
5465 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5468 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5469 struct poll_table_struct *p)
5471 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5473 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5476 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5478 struct io_poll_iocb *poll = &req->poll;
5481 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5483 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5485 flags = READ_ONCE(sqe->len);
5486 if (flags & ~IORING_POLL_ADD_MULTI)
5489 io_req_set_refcount(req);
5490 poll->events = io_poll_parse_events(sqe, flags);
5494 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5496 struct io_poll_iocb *poll = &req->poll;
5497 struct io_ring_ctx *ctx = req->ctx;
5498 struct io_poll_table ipt;
5501 ipt.pt._qproc = io_poll_queue_proc;
5503 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5506 if (mask) { /* no async, we'd stolen it */
5508 io_poll_complete(req, mask);
5510 spin_unlock(&ctx->completion_lock);
5513 io_cqring_ev_posted(ctx);
5514 if (poll->events & EPOLLONESHOT)
5520 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5522 struct io_ring_ctx *ctx = req->ctx;
5523 struct io_kiocb *preq;
5527 spin_lock(&ctx->completion_lock);
5528 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5534 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5536 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5541 * Don't allow racy completion with singleshot, as we cannot safely
5542 * update those. For multishot, if we're racing with completion, just
5543 * let completion re-add it.
5545 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5546 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5550 /* we now have a detached poll request. reissue. */
5554 spin_unlock(&ctx->completion_lock);
5556 io_req_complete(req, ret);
5559 /* only mask one event flags, keep behavior flags */
5560 if (req->poll_update.update_events) {
5561 preq->poll.events &= ~0xffff;
5562 preq->poll.events |= req->poll_update.events & 0xffff;
5563 preq->poll.events |= IO_POLL_UNMASK;
5565 if (req->poll_update.update_user_data)
5566 preq->user_data = req->poll_update.new_user_data;
5567 spin_unlock(&ctx->completion_lock);
5569 /* complete update request, we're done with it */
5570 io_req_complete(req, ret);
5573 ret = io_poll_add(preq, issue_flags);
5576 io_req_complete(preq, ret);
5582 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5585 io_req_complete_post(req, -ETIME, 0);
5588 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5590 struct io_timeout_data *data = container_of(timer,
5591 struct io_timeout_data, timer);
5592 struct io_kiocb *req = data->req;
5593 struct io_ring_ctx *ctx = req->ctx;
5594 unsigned long flags;
5596 spin_lock_irqsave(&ctx->timeout_lock, flags);
5597 list_del_init(&req->timeout.list);
5598 atomic_set(&req->ctx->cq_timeouts,
5599 atomic_read(&req->ctx->cq_timeouts) + 1);
5600 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5602 req->io_task_work.func = io_req_task_timeout;
5603 io_req_task_work_add(req);
5604 return HRTIMER_NORESTART;
5607 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5609 __must_hold(&ctx->timeout_lock)
5611 struct io_timeout_data *io;
5612 struct io_kiocb *req;
5615 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5616 found = user_data == req->user_data;
5621 return ERR_PTR(-ENOENT);
5623 io = req->async_data;
5624 if (hrtimer_try_to_cancel(&io->timer) == -1)
5625 return ERR_PTR(-EALREADY);
5626 list_del_init(&req->timeout.list);
5630 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5631 __must_hold(&ctx->completion_lock)
5632 __must_hold(&ctx->timeout_lock)
5634 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5637 return PTR_ERR(req);
5640 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5641 io_put_req_deferred(req);
5645 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5646 struct timespec64 *ts, enum hrtimer_mode mode)
5647 __must_hold(&ctx->timeout_lock)
5649 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5650 struct io_timeout_data *data;
5653 return PTR_ERR(req);
5655 req->timeout.off = 0; /* noseq */
5656 data = req->async_data;
5657 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5658 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5659 data->timer.function = io_timeout_fn;
5660 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5664 static int io_timeout_remove_prep(struct io_kiocb *req,
5665 const struct io_uring_sqe *sqe)
5667 struct io_timeout_rem *tr = &req->timeout_rem;
5669 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5671 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5673 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
5676 tr->addr = READ_ONCE(sqe->addr);
5677 tr->flags = READ_ONCE(sqe->timeout_flags);
5678 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5679 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5681 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5683 } else if (tr->flags) {
5684 /* timeout removal doesn't support flags */
5691 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5693 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5698 * Remove or update an existing timeout command
5700 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5702 struct io_timeout_rem *tr = &req->timeout_rem;
5703 struct io_ring_ctx *ctx = req->ctx;
5706 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
5707 spin_lock(&ctx->completion_lock);
5708 spin_lock_irq(&ctx->timeout_lock);
5709 ret = io_timeout_cancel(ctx, tr->addr);
5710 spin_unlock_irq(&ctx->timeout_lock);
5711 spin_unlock(&ctx->completion_lock);
5713 spin_lock_irq(&ctx->timeout_lock);
5714 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5715 io_translate_timeout_mode(tr->flags));
5716 spin_unlock_irq(&ctx->timeout_lock);
5721 io_req_complete_post(req, ret, 0);
5725 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5726 bool is_timeout_link)
5728 struct io_timeout_data *data;
5730 u32 off = READ_ONCE(sqe->off);
5732 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5734 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
5737 if (off && is_timeout_link)
5739 flags = READ_ONCE(sqe->timeout_flags);
5740 if (flags & ~IORING_TIMEOUT_ABS)
5743 req->timeout.off = off;
5744 if (unlikely(off && !req->ctx->off_timeout_used))
5745 req->ctx->off_timeout_used = true;
5747 if (!req->async_data && io_alloc_async_data(req))
5750 data = req->async_data;
5753 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5756 data->mode = io_translate_timeout_mode(flags);
5757 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5759 if (is_timeout_link) {
5760 struct io_submit_link *link = &req->ctx->submit_state.link;
5764 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
5766 req->timeout.head = link->last;
5767 link->last->flags |= REQ_F_ARM_LTIMEOUT;
5772 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5774 struct io_ring_ctx *ctx = req->ctx;
5775 struct io_timeout_data *data = req->async_data;
5776 struct list_head *entry;
5777 u32 tail, off = req->timeout.off;
5779 spin_lock_irq(&ctx->timeout_lock);
5782 * sqe->off holds how many events that need to occur for this
5783 * timeout event to be satisfied. If it isn't set, then this is
5784 * a pure timeout request, sequence isn't used.
5786 if (io_is_timeout_noseq(req)) {
5787 entry = ctx->timeout_list.prev;
5791 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5792 req->timeout.target_seq = tail + off;
5794 /* Update the last seq here in case io_flush_timeouts() hasn't.
5795 * This is safe because ->completion_lock is held, and submissions
5796 * and completions are never mixed in the same ->completion_lock section.
5798 ctx->cq_last_tm_flush = tail;
5801 * Insertion sort, ensuring the first entry in the list is always
5802 * the one we need first.
5804 list_for_each_prev(entry, &ctx->timeout_list) {
5805 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5808 if (io_is_timeout_noseq(nxt))
5810 /* nxt.seq is behind @tail, otherwise would've been completed */
5811 if (off >= nxt->timeout.target_seq - tail)
5815 list_add(&req->timeout.list, entry);
5816 data->timer.function = io_timeout_fn;
5817 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5818 spin_unlock_irq(&ctx->timeout_lock);
5822 struct io_cancel_data {
5823 struct io_ring_ctx *ctx;
5827 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5829 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5830 struct io_cancel_data *cd = data;
5832 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5835 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5836 struct io_ring_ctx *ctx)
5838 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5839 enum io_wq_cancel cancel_ret;
5842 if (!tctx || !tctx->io_wq)
5845 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5846 switch (cancel_ret) {
5847 case IO_WQ_CANCEL_OK:
5850 case IO_WQ_CANCEL_RUNNING:
5853 case IO_WQ_CANCEL_NOTFOUND:
5861 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
5863 struct io_ring_ctx *ctx = req->ctx;
5866 WARN_ON_ONCE(req->task != current);
5868 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5872 spin_lock(&ctx->completion_lock);
5873 spin_lock_irq(&ctx->timeout_lock);
5874 ret = io_timeout_cancel(ctx, sqe_addr);
5875 spin_unlock_irq(&ctx->timeout_lock);
5878 ret = io_poll_cancel(ctx, sqe_addr, false);
5880 spin_unlock(&ctx->completion_lock);
5884 static int io_async_cancel_prep(struct io_kiocb *req,
5885 const struct io_uring_sqe *sqe)
5887 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5889 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5891 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
5895 req->cancel.addr = READ_ONCE(sqe->addr);
5899 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5901 struct io_ring_ctx *ctx = req->ctx;
5902 u64 sqe_addr = req->cancel.addr;
5903 struct io_tctx_node *node;
5906 ret = io_try_cancel_userdata(req, sqe_addr);
5910 /* slow path, try all io-wq's */
5911 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5913 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5914 struct io_uring_task *tctx = node->task->io_uring;
5916 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5920 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5924 io_req_complete_post(req, ret, 0);
5928 static int io_rsrc_update_prep(struct io_kiocb *req,
5929 const struct io_uring_sqe *sqe)
5931 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5933 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
5936 req->rsrc_update.offset = READ_ONCE(sqe->off);
5937 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5938 if (!req->rsrc_update.nr_args)
5940 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5944 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5946 struct io_ring_ctx *ctx = req->ctx;
5947 struct io_uring_rsrc_update2 up;
5950 if (issue_flags & IO_URING_F_NONBLOCK)
5953 up.offset = req->rsrc_update.offset;
5954 up.data = req->rsrc_update.arg;
5959 mutex_lock(&ctx->uring_lock);
5960 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5961 &up, req->rsrc_update.nr_args);
5962 mutex_unlock(&ctx->uring_lock);
5966 __io_req_complete(req, issue_flags, ret, 0);
5970 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5972 switch (req->opcode) {
5975 case IORING_OP_READV:
5976 case IORING_OP_READ_FIXED:
5977 case IORING_OP_READ:
5978 return io_read_prep(req, sqe);
5979 case IORING_OP_WRITEV:
5980 case IORING_OP_WRITE_FIXED:
5981 case IORING_OP_WRITE:
5982 return io_write_prep(req, sqe);
5983 case IORING_OP_POLL_ADD:
5984 return io_poll_add_prep(req, sqe);
5985 case IORING_OP_POLL_REMOVE:
5986 return io_poll_update_prep(req, sqe);
5987 case IORING_OP_FSYNC:
5988 return io_fsync_prep(req, sqe);
5989 case IORING_OP_SYNC_FILE_RANGE:
5990 return io_sfr_prep(req, sqe);
5991 case IORING_OP_SENDMSG:
5992 case IORING_OP_SEND:
5993 return io_sendmsg_prep(req, sqe);
5994 case IORING_OP_RECVMSG:
5995 case IORING_OP_RECV:
5996 return io_recvmsg_prep(req, sqe);
5997 case IORING_OP_CONNECT:
5998 return io_connect_prep(req, sqe);
5999 case IORING_OP_TIMEOUT:
6000 return io_timeout_prep(req, sqe, false);
6001 case IORING_OP_TIMEOUT_REMOVE:
6002 return io_timeout_remove_prep(req, sqe);
6003 case IORING_OP_ASYNC_CANCEL:
6004 return io_async_cancel_prep(req, sqe);
6005 case IORING_OP_LINK_TIMEOUT:
6006 return io_timeout_prep(req, sqe, true);
6007 case IORING_OP_ACCEPT:
6008 return io_accept_prep(req, sqe);
6009 case IORING_OP_FALLOCATE:
6010 return io_fallocate_prep(req, sqe);
6011 case IORING_OP_OPENAT:
6012 return io_openat_prep(req, sqe);
6013 case IORING_OP_CLOSE:
6014 return io_close_prep(req, sqe);
6015 case IORING_OP_FILES_UPDATE:
6016 return io_rsrc_update_prep(req, sqe);
6017 case IORING_OP_STATX:
6018 return io_statx_prep(req, sqe);
6019 case IORING_OP_FADVISE:
6020 return io_fadvise_prep(req, sqe);
6021 case IORING_OP_MADVISE:
6022 return io_madvise_prep(req, sqe);
6023 case IORING_OP_OPENAT2:
6024 return io_openat2_prep(req, sqe);
6025 case IORING_OP_EPOLL_CTL:
6026 return io_epoll_ctl_prep(req, sqe);
6027 case IORING_OP_SPLICE:
6028 return io_splice_prep(req, sqe);
6029 case IORING_OP_PROVIDE_BUFFERS:
6030 return io_provide_buffers_prep(req, sqe);
6031 case IORING_OP_REMOVE_BUFFERS:
6032 return io_remove_buffers_prep(req, sqe);
6034 return io_tee_prep(req, sqe);
6035 case IORING_OP_SHUTDOWN:
6036 return io_shutdown_prep(req, sqe);
6037 case IORING_OP_RENAMEAT:
6038 return io_renameat_prep(req, sqe);
6039 case IORING_OP_UNLINKAT:
6040 return io_unlinkat_prep(req, sqe);
6043 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6048 static int io_req_prep_async(struct io_kiocb *req)
6050 if (!io_op_defs[req->opcode].needs_async_setup)
6052 if (WARN_ON_ONCE(req->async_data))
6054 if (io_alloc_async_data(req))
6057 switch (req->opcode) {
6058 case IORING_OP_READV:
6059 return io_rw_prep_async(req, READ);
6060 case IORING_OP_WRITEV:
6061 return io_rw_prep_async(req, WRITE);
6062 case IORING_OP_SENDMSG:
6063 return io_sendmsg_prep_async(req);
6064 case IORING_OP_RECVMSG:
6065 return io_recvmsg_prep_async(req);
6066 case IORING_OP_CONNECT:
6067 return io_connect_prep_async(req);
6069 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6074 static u32 io_get_sequence(struct io_kiocb *req)
6076 u32 seq = req->ctx->cached_sq_head;
6078 /* need original cached_sq_head, but it was increased for each req */
6079 io_for_each_link(req, req)
6084 static bool io_drain_req(struct io_kiocb *req)
6086 struct io_kiocb *pos;
6087 struct io_ring_ctx *ctx = req->ctx;
6088 struct io_defer_entry *de;
6093 * If we need to drain a request in the middle of a link, drain the
6094 * head request and the next request/link after the current link.
6095 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6096 * maintained for every request of our link.
6098 if (ctx->drain_next) {
6099 req->flags |= REQ_F_IO_DRAIN;
6100 ctx->drain_next = false;
6102 /* not interested in head, start from the first linked */
6103 io_for_each_link(pos, req->link) {
6104 if (pos->flags & REQ_F_IO_DRAIN) {
6105 ctx->drain_next = true;
6106 req->flags |= REQ_F_IO_DRAIN;
6111 /* Still need defer if there is pending req in defer list. */
6112 if (likely(list_empty_careful(&ctx->defer_list) &&
6113 !(req->flags & REQ_F_IO_DRAIN))) {
6114 ctx->drain_active = false;
6118 seq = io_get_sequence(req);
6119 /* Still a chance to pass the sequence check */
6120 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6123 ret = io_req_prep_async(req);
6126 io_prep_async_link(req);
6127 de = kmalloc(sizeof(*de), GFP_KERNEL);
6131 io_req_complete_failed(req, ret);
6135 spin_lock(&ctx->completion_lock);
6136 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6137 spin_unlock(&ctx->completion_lock);
6139 io_queue_async_work(req, NULL);
6143 trace_io_uring_defer(ctx, req, req->user_data);
6146 list_add_tail(&de->list, &ctx->defer_list);
6147 spin_unlock(&ctx->completion_lock);
6151 static void io_clean_op(struct io_kiocb *req)
6153 if (req->flags & REQ_F_BUFFER_SELECTED) {
6154 switch (req->opcode) {
6155 case IORING_OP_READV:
6156 case IORING_OP_READ_FIXED:
6157 case IORING_OP_READ:
6158 kfree((void *)(unsigned long)req->rw.addr);
6160 case IORING_OP_RECVMSG:
6161 case IORING_OP_RECV:
6162 kfree(req->sr_msg.kbuf);
6167 if (req->flags & REQ_F_NEED_CLEANUP) {
6168 switch (req->opcode) {
6169 case IORING_OP_READV:
6170 case IORING_OP_READ_FIXED:
6171 case IORING_OP_READ:
6172 case IORING_OP_WRITEV:
6173 case IORING_OP_WRITE_FIXED:
6174 case IORING_OP_WRITE: {
6175 struct io_async_rw *io = req->async_data;
6177 kfree(io->free_iovec);
6180 case IORING_OP_RECVMSG:
6181 case IORING_OP_SENDMSG: {
6182 struct io_async_msghdr *io = req->async_data;
6184 kfree(io->free_iov);
6187 case IORING_OP_SPLICE:
6189 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6190 io_put_file(req->splice.file_in);
6192 case IORING_OP_OPENAT:
6193 case IORING_OP_OPENAT2:
6194 if (req->open.filename)
6195 putname(req->open.filename);
6197 case IORING_OP_RENAMEAT:
6198 putname(req->rename.oldpath);
6199 putname(req->rename.newpath);
6201 case IORING_OP_UNLINKAT:
6202 putname(req->unlink.filename);
6206 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6207 kfree(req->apoll->double_poll);
6211 if (req->flags & REQ_F_INFLIGHT) {
6212 struct io_uring_task *tctx = req->task->io_uring;
6214 atomic_dec(&tctx->inflight_tracked);
6216 if (req->flags & REQ_F_CREDS)
6217 put_cred(req->creds);
6219 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6222 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6224 struct io_ring_ctx *ctx = req->ctx;
6225 const struct cred *creds = NULL;
6228 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6229 creds = override_creds(req->creds);
6231 switch (req->opcode) {
6233 ret = io_nop(req, issue_flags);
6235 case IORING_OP_READV:
6236 case IORING_OP_READ_FIXED:
6237 case IORING_OP_READ:
6238 ret = io_read(req, issue_flags);
6240 case IORING_OP_WRITEV:
6241 case IORING_OP_WRITE_FIXED:
6242 case IORING_OP_WRITE:
6243 ret = io_write(req, issue_flags);
6245 case IORING_OP_FSYNC:
6246 ret = io_fsync(req, issue_flags);
6248 case IORING_OP_POLL_ADD:
6249 ret = io_poll_add(req, issue_flags);
6251 case IORING_OP_POLL_REMOVE:
6252 ret = io_poll_update(req, issue_flags);
6254 case IORING_OP_SYNC_FILE_RANGE:
6255 ret = io_sync_file_range(req, issue_flags);
6257 case IORING_OP_SENDMSG:
6258 ret = io_sendmsg(req, issue_flags);
6260 case IORING_OP_SEND:
6261 ret = io_send(req, issue_flags);
6263 case IORING_OP_RECVMSG:
6264 ret = io_recvmsg(req, issue_flags);
6266 case IORING_OP_RECV:
6267 ret = io_recv(req, issue_flags);
6269 case IORING_OP_TIMEOUT:
6270 ret = io_timeout(req, issue_flags);
6272 case IORING_OP_TIMEOUT_REMOVE:
6273 ret = io_timeout_remove(req, issue_flags);
6275 case IORING_OP_ACCEPT:
6276 ret = io_accept(req, issue_flags);
6278 case IORING_OP_CONNECT:
6279 ret = io_connect(req, issue_flags);
6281 case IORING_OP_ASYNC_CANCEL:
6282 ret = io_async_cancel(req, issue_flags);
6284 case IORING_OP_FALLOCATE:
6285 ret = io_fallocate(req, issue_flags);
6287 case IORING_OP_OPENAT:
6288 ret = io_openat(req, issue_flags);
6290 case IORING_OP_CLOSE:
6291 ret = io_close(req, issue_flags);
6293 case IORING_OP_FILES_UPDATE:
6294 ret = io_files_update(req, issue_flags);
6296 case IORING_OP_STATX:
6297 ret = io_statx(req, issue_flags);
6299 case IORING_OP_FADVISE:
6300 ret = io_fadvise(req, issue_flags);
6302 case IORING_OP_MADVISE:
6303 ret = io_madvise(req, issue_flags);
6305 case IORING_OP_OPENAT2:
6306 ret = io_openat2(req, issue_flags);
6308 case IORING_OP_EPOLL_CTL:
6309 ret = io_epoll_ctl(req, issue_flags);
6311 case IORING_OP_SPLICE:
6312 ret = io_splice(req, issue_flags);
6314 case IORING_OP_PROVIDE_BUFFERS:
6315 ret = io_provide_buffers(req, issue_flags);
6317 case IORING_OP_REMOVE_BUFFERS:
6318 ret = io_remove_buffers(req, issue_flags);
6321 ret = io_tee(req, issue_flags);
6323 case IORING_OP_SHUTDOWN:
6324 ret = io_shutdown(req, issue_flags);
6326 case IORING_OP_RENAMEAT:
6327 ret = io_renameat(req, issue_flags);
6329 case IORING_OP_UNLINKAT:
6330 ret = io_unlinkat(req, issue_flags);
6338 revert_creds(creds);
6341 /* If the op doesn't have a file, we're not polling for it */
6342 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6343 io_iopoll_req_issued(req);
6348 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6350 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6352 req = io_put_req_find_next(req);
6353 return req ? &req->work : NULL;
6356 static void io_wq_submit_work(struct io_wq_work *work)
6358 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6359 struct io_kiocb *timeout;
6362 /* one will be dropped by ->io_free_work() after returning to io-wq */
6363 if (!(req->flags & REQ_F_REFCOUNT))
6364 __io_req_set_refcount(req, 2);
6368 timeout = io_prep_linked_timeout(req);
6370 io_queue_linked_timeout(timeout);
6372 if (work->flags & IO_WQ_WORK_CANCEL)
6377 ret = io_issue_sqe(req, 0);
6379 * We can get EAGAIN for polled IO even though we're
6380 * forcing a sync submission from here, since we can't
6381 * wait for request slots on the block side.
6389 /* avoid locking problems by failing it from a clean context */
6391 io_req_task_queue_fail(req, ret);
6394 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6397 return &table->files[i];
6400 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6403 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6405 return (struct file *) (slot->file_ptr & FFS_MASK);
6408 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6410 unsigned long file_ptr = (unsigned long) file;
6412 if (__io_file_supports_nowait(file, READ))
6413 file_ptr |= FFS_ASYNC_READ;
6414 if (__io_file_supports_nowait(file, WRITE))
6415 file_ptr |= FFS_ASYNC_WRITE;
6416 if (S_ISREG(file_inode(file)->i_mode))
6417 file_ptr |= FFS_ISREG;
6418 file_slot->file_ptr = file_ptr;
6421 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6422 struct io_kiocb *req, int fd)
6425 unsigned long file_ptr;
6427 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6429 fd = array_index_nospec(fd, ctx->nr_user_files);
6430 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6431 file = (struct file *) (file_ptr & FFS_MASK);
6432 file_ptr &= ~FFS_MASK;
6433 /* mask in overlapping REQ_F and FFS bits */
6434 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6435 io_req_set_rsrc_node(req);
6439 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6440 struct io_kiocb *req, int fd)
6442 struct file *file = fget(fd);
6444 trace_io_uring_file_get(ctx, fd);
6446 /* we don't allow fixed io_uring files */
6447 if (file && unlikely(file->f_op == &io_uring_fops))
6448 io_req_track_inflight(req);
6452 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6453 struct io_kiocb *req, int fd, bool fixed)
6456 return io_file_get_fixed(ctx, req, fd);
6458 return io_file_get_normal(ctx, req, fd);
6461 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6463 struct io_kiocb *prev = req->timeout.prev;
6467 ret = io_try_cancel_userdata(req, prev->user_data);
6468 io_req_complete_post(req, ret ?: -ETIME, 0);
6471 io_req_complete_post(req, -ETIME, 0);
6475 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6477 struct io_timeout_data *data = container_of(timer,
6478 struct io_timeout_data, timer);
6479 struct io_kiocb *prev, *req = data->req;
6480 struct io_ring_ctx *ctx = req->ctx;
6481 unsigned long flags;
6483 spin_lock_irqsave(&ctx->timeout_lock, flags);
6484 prev = req->timeout.head;
6485 req->timeout.head = NULL;
6488 * We don't expect the list to be empty, that will only happen if we
6489 * race with the completion of the linked work.
6492 io_remove_next_linked(prev);
6493 if (!req_ref_inc_not_zero(prev))
6496 req->timeout.prev = prev;
6497 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6499 req->io_task_work.func = io_req_task_link_timeout;
6500 io_req_task_work_add(req);
6501 return HRTIMER_NORESTART;
6504 static void io_queue_linked_timeout(struct io_kiocb *req)
6506 struct io_ring_ctx *ctx = req->ctx;
6508 spin_lock_irq(&ctx->timeout_lock);
6510 * If the back reference is NULL, then our linked request finished
6511 * before we got a chance to setup the timer
6513 if (req->timeout.head) {
6514 struct io_timeout_data *data = req->async_data;
6516 data->timer.function = io_link_timeout_fn;
6517 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6520 spin_unlock_irq(&ctx->timeout_lock);
6521 /* drop submission reference */
6525 static void __io_queue_sqe(struct io_kiocb *req)
6526 __must_hold(&req->ctx->uring_lock)
6528 struct io_kiocb *linked_timeout;
6532 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6535 * We async punt it if the file wasn't marked NOWAIT, or if the file
6536 * doesn't support non-blocking read/write attempts
6539 if (req->flags & REQ_F_COMPLETE_INLINE) {
6540 struct io_ring_ctx *ctx = req->ctx;
6541 struct io_submit_state *state = &ctx->submit_state;
6543 state->compl_reqs[state->compl_nr++] = req;
6544 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6545 io_submit_flush_completions(ctx);
6549 linked_timeout = io_prep_linked_timeout(req);
6551 io_queue_linked_timeout(linked_timeout);
6552 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6553 linked_timeout = io_prep_linked_timeout(req);
6555 switch (io_arm_poll_handler(req)) {
6556 case IO_APOLL_READY:
6558 io_unprep_linked_timeout(req);
6560 case IO_APOLL_ABORTED:
6562 * Queued up for async execution, worker will release
6563 * submit reference when the iocb is actually submitted.
6565 io_queue_async_work(req, NULL);
6570 io_queue_linked_timeout(linked_timeout);
6572 io_req_complete_failed(req, ret);
6576 static inline void io_queue_sqe(struct io_kiocb *req)
6577 __must_hold(&req->ctx->uring_lock)
6579 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6582 if (likely(!(req->flags & REQ_F_FORCE_ASYNC))) {
6583 __io_queue_sqe(req);
6585 int ret = io_req_prep_async(req);
6588 io_req_complete_failed(req, ret);
6590 io_queue_async_work(req, NULL);
6595 * Check SQE restrictions (opcode and flags).
6597 * Returns 'true' if SQE is allowed, 'false' otherwise.
6599 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6600 struct io_kiocb *req,
6601 unsigned int sqe_flags)
6603 if (likely(!ctx->restricted))
6606 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6609 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6610 ctx->restrictions.sqe_flags_required)
6613 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6614 ctx->restrictions.sqe_flags_required))
6620 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6621 const struct io_uring_sqe *sqe)
6622 __must_hold(&ctx->uring_lock)
6624 struct io_submit_state *state;
6625 unsigned int sqe_flags;
6626 int personality, ret = 0;
6628 /* req is partially pre-initialised, see io_preinit_req() */
6629 req->opcode = READ_ONCE(sqe->opcode);
6630 /* same numerical values with corresponding REQ_F_*, safe to copy */
6631 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6632 req->user_data = READ_ONCE(sqe->user_data);
6634 req->fixed_rsrc_refs = NULL;
6635 req->task = current;
6637 /* enforce forwards compatibility on users */
6638 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6640 if (unlikely(req->opcode >= IORING_OP_LAST))
6642 if (!io_check_restriction(ctx, req, sqe_flags))
6645 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6646 !io_op_defs[req->opcode].buffer_select)
6648 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
6649 ctx->drain_active = true;
6651 personality = READ_ONCE(sqe->personality);
6653 req->creds = xa_load(&ctx->personalities, personality);
6656 get_cred(req->creds);
6657 req->flags |= REQ_F_CREDS;
6659 state = &ctx->submit_state;
6662 * Plug now if we have more than 1 IO left after this, and the target
6663 * is potentially a read/write to block based storage.
6665 if (!state->plug_started && state->ios_left > 1 &&
6666 io_op_defs[req->opcode].plug) {
6667 blk_start_plug(&state->plug);
6668 state->plug_started = true;
6671 if (io_op_defs[req->opcode].needs_file) {
6672 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
6673 (sqe_flags & IOSQE_FIXED_FILE));
6674 if (unlikely(!req->file))
6682 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6683 const struct io_uring_sqe *sqe)
6684 __must_hold(&ctx->uring_lock)
6686 struct io_submit_link *link = &ctx->submit_state.link;
6689 ret = io_init_req(ctx, req, sqe);
6690 if (unlikely(ret)) {
6693 /* fail even hard links since we don't submit */
6694 req_set_fail(link->head);
6695 io_req_complete_failed(link->head, -ECANCELED);
6698 io_req_complete_failed(req, ret);
6702 ret = io_req_prep(req, sqe);
6706 /* don't need @sqe from now on */
6707 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
6709 ctx->flags & IORING_SETUP_SQPOLL);
6712 * If we already have a head request, queue this one for async
6713 * submittal once the head completes. If we don't have a head but
6714 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6715 * submitted sync once the chain is complete. If none of those
6716 * conditions are true (normal request), then just queue it.
6719 struct io_kiocb *head = link->head;
6721 ret = io_req_prep_async(req);
6724 trace_io_uring_link(ctx, req, head);
6725 link->last->link = req;
6728 /* last request of a link, enqueue the link */
6729 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6734 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6746 * Batched submission is done, ensure local IO is flushed out.
6748 static void io_submit_state_end(struct io_submit_state *state,
6749 struct io_ring_ctx *ctx)
6751 if (state->link.head)
6752 io_queue_sqe(state->link.head);
6753 if (state->compl_nr)
6754 io_submit_flush_completions(ctx);
6755 if (state->plug_started)
6756 blk_finish_plug(&state->plug);
6760 * Start submission side cache.
6762 static void io_submit_state_start(struct io_submit_state *state,
6763 unsigned int max_ios)
6765 state->plug_started = false;
6766 state->ios_left = max_ios;
6767 /* set only head, no need to init link_last in advance */
6768 state->link.head = NULL;
6771 static void io_commit_sqring(struct io_ring_ctx *ctx)
6773 struct io_rings *rings = ctx->rings;
6776 * Ensure any loads from the SQEs are done at this point,
6777 * since once we write the new head, the application could
6778 * write new data to them.
6780 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6784 * Fetch an sqe, if one is available. Note this returns a pointer to memory
6785 * that is mapped by userspace. This means that care needs to be taken to
6786 * ensure that reads are stable, as we cannot rely on userspace always
6787 * being a good citizen. If members of the sqe are validated and then later
6788 * used, it's important that those reads are done through READ_ONCE() to
6789 * prevent a re-load down the line.
6791 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6793 unsigned head, mask = ctx->sq_entries - 1;
6794 unsigned sq_idx = ctx->cached_sq_head++ & mask;
6797 * The cached sq head (or cq tail) serves two purposes:
6799 * 1) allows us to batch the cost of updating the user visible
6801 * 2) allows the kernel side to track the head on its own, even
6802 * though the application is the one updating it.
6804 head = READ_ONCE(ctx->sq_array[sq_idx]);
6805 if (likely(head < ctx->sq_entries))
6806 return &ctx->sq_sqes[head];
6808 /* drop invalid entries */
6810 WRITE_ONCE(ctx->rings->sq_dropped,
6811 READ_ONCE(ctx->rings->sq_dropped) + 1);
6815 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6816 __must_hold(&ctx->uring_lock)
6818 struct io_uring_task *tctx;
6821 /* make sure SQ entry isn't read before tail */
6822 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6823 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6826 tctx = current->io_uring;
6827 tctx->cached_refs -= nr;
6828 if (unlikely(tctx->cached_refs < 0)) {
6829 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
6831 percpu_counter_add(&tctx->inflight, refill);
6832 refcount_add(refill, ¤t->usage);
6833 tctx->cached_refs += refill;
6835 io_submit_state_start(&ctx->submit_state, nr);
6837 while (submitted < nr) {
6838 const struct io_uring_sqe *sqe;
6839 struct io_kiocb *req;
6841 req = io_alloc_req(ctx);
6842 if (unlikely(!req)) {
6844 submitted = -EAGAIN;
6847 sqe = io_get_sqe(ctx);
6848 if (unlikely(!sqe)) {
6849 kmem_cache_free(req_cachep, req);
6852 /* will complete beyond this point, count as submitted */
6854 if (io_submit_sqe(ctx, req, sqe))
6858 if (unlikely(submitted != nr)) {
6859 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6860 int unused = nr - ref_used;
6862 current->io_uring->cached_refs += unused;
6863 percpu_ref_put_many(&ctx->refs, unused);
6866 io_submit_state_end(&ctx->submit_state, ctx);
6867 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6868 io_commit_sqring(ctx);
6873 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
6875 return READ_ONCE(sqd->state);
6878 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6880 /* Tell userspace we may need a wakeup call */
6881 spin_lock(&ctx->completion_lock);
6882 WRITE_ONCE(ctx->rings->sq_flags,
6883 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
6884 spin_unlock(&ctx->completion_lock);
6887 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6889 spin_lock(&ctx->completion_lock);
6890 WRITE_ONCE(ctx->rings->sq_flags,
6891 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
6892 spin_unlock(&ctx->completion_lock);
6895 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6897 unsigned int to_submit;
6900 to_submit = io_sqring_entries(ctx);
6901 /* if we're handling multiple rings, cap submit size for fairness */
6902 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
6903 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
6905 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6906 unsigned nr_events = 0;
6907 const struct cred *creds = NULL;
6909 if (ctx->sq_creds != current_cred())
6910 creds = override_creds(ctx->sq_creds);
6912 mutex_lock(&ctx->uring_lock);
6913 if (!list_empty(&ctx->iopoll_list))
6914 io_do_iopoll(ctx, &nr_events, 0);
6917 * Don't submit if refs are dying, good for io_uring_register(),
6918 * but also it is relied upon by io_ring_exit_work()
6920 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6921 !(ctx->flags & IORING_SETUP_R_DISABLED))
6922 ret = io_submit_sqes(ctx, to_submit);
6923 mutex_unlock(&ctx->uring_lock);
6925 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
6926 wake_up(&ctx->sqo_sq_wait);
6928 revert_creds(creds);
6934 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6936 struct io_ring_ctx *ctx;
6937 unsigned sq_thread_idle = 0;
6939 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6940 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6941 sqd->sq_thread_idle = sq_thread_idle;
6944 static bool io_sqd_handle_event(struct io_sq_data *sqd)
6946 bool did_sig = false;
6947 struct ksignal ksig;
6949 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6950 signal_pending(current)) {
6951 mutex_unlock(&sqd->lock);
6952 if (signal_pending(current))
6953 did_sig = get_signal(&ksig);
6955 mutex_lock(&sqd->lock);
6957 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6960 static int io_sq_thread(void *data)
6962 struct io_sq_data *sqd = data;
6963 struct io_ring_ctx *ctx;
6964 unsigned long timeout = 0;
6965 char buf[TASK_COMM_LEN];
6968 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6969 set_task_comm(current, buf);
6971 if (sqd->sq_cpu != -1)
6972 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6974 set_cpus_allowed_ptr(current, cpu_online_mask);
6975 current->flags |= PF_NO_SETAFFINITY;
6977 mutex_lock(&sqd->lock);
6979 bool cap_entries, sqt_spin = false;
6981 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
6982 if (io_sqd_handle_event(sqd))
6984 timeout = jiffies + sqd->sq_thread_idle;
6987 cap_entries = !list_is_singular(&sqd->ctx_list);
6988 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6989 int ret = __io_sq_thread(ctx, cap_entries);
6991 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6994 if (io_run_task_work())
6997 if (sqt_spin || !time_after(jiffies, timeout)) {
7000 timeout = jiffies + sqd->sq_thread_idle;
7004 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7005 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7006 bool needs_sched = true;
7008 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7009 io_ring_set_wakeup_flag(ctx);
7011 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7012 !list_empty_careful(&ctx->iopoll_list)) {
7013 needs_sched = false;
7016 if (io_sqring_entries(ctx)) {
7017 needs_sched = false;
7023 mutex_unlock(&sqd->lock);
7025 mutex_lock(&sqd->lock);
7027 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7028 io_ring_clear_wakeup_flag(ctx);
7031 finish_wait(&sqd->wait, &wait);
7032 timeout = jiffies + sqd->sq_thread_idle;
7035 io_uring_cancel_generic(true, sqd);
7037 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7038 io_ring_set_wakeup_flag(ctx);
7040 mutex_unlock(&sqd->lock);
7042 complete(&sqd->exited);
7046 struct io_wait_queue {
7047 struct wait_queue_entry wq;
7048 struct io_ring_ctx *ctx;
7050 unsigned nr_timeouts;
7053 static inline bool io_should_wake(struct io_wait_queue *iowq)
7055 struct io_ring_ctx *ctx = iowq->ctx;
7056 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7059 * Wake up if we have enough events, or if a timeout occurred since we
7060 * started waiting. For timeouts, we always want to return to userspace,
7061 * regardless of event count.
7063 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7066 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7067 int wake_flags, void *key)
7069 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7073 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7074 * the task, and the next invocation will do it.
7076 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7077 return autoremove_wake_function(curr, mode, wake_flags, key);
7081 static int io_run_task_work_sig(void)
7083 if (io_run_task_work())
7085 if (!signal_pending(current))
7087 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7088 return -ERESTARTSYS;
7092 /* when returns >0, the caller should retry */
7093 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7094 struct io_wait_queue *iowq,
7095 signed long *timeout)
7099 /* make sure we run task_work before checking for signals */
7100 ret = io_run_task_work_sig();
7101 if (ret || io_should_wake(iowq))
7103 /* let the caller flush overflows, retry */
7104 if (test_bit(0, &ctx->check_cq_overflow))
7107 *timeout = schedule_timeout(*timeout);
7108 return !*timeout ? -ETIME : 1;
7112 * Wait until events become available, if we don't already have some. The
7113 * application must reap them itself, as they reside on the shared cq ring.
7115 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7116 const sigset_t __user *sig, size_t sigsz,
7117 struct __kernel_timespec __user *uts)
7119 struct io_wait_queue iowq;
7120 struct io_rings *rings = ctx->rings;
7121 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7125 io_cqring_overflow_flush(ctx);
7126 if (io_cqring_events(ctx) >= min_events)
7128 if (!io_run_task_work())
7133 #ifdef CONFIG_COMPAT
7134 if (in_compat_syscall())
7135 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7139 ret = set_user_sigmask(sig, sigsz);
7146 struct timespec64 ts;
7148 if (get_timespec64(&ts, uts))
7150 timeout = timespec64_to_jiffies(&ts);
7153 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7154 iowq.wq.private = current;
7155 INIT_LIST_HEAD(&iowq.wq.entry);
7157 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7158 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7160 trace_io_uring_cqring_wait(ctx, min_events);
7162 /* if we can't even flush overflow, don't wait for more */
7163 if (!io_cqring_overflow_flush(ctx)) {
7167 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7168 TASK_INTERRUPTIBLE);
7169 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7170 finish_wait(&ctx->cq_wait, &iowq.wq);
7174 restore_saved_sigmask_unless(ret == -EINTR);
7176 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7179 static void io_free_page_table(void **table, size_t size)
7181 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7183 for (i = 0; i < nr_tables; i++)
7188 static void **io_alloc_page_table(size_t size)
7190 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7191 size_t init_size = size;
7194 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7198 for (i = 0; i < nr_tables; i++) {
7199 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7201 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7203 io_free_page_table(table, init_size);
7211 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7213 percpu_ref_exit(&ref_node->refs);
7217 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7219 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7220 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7221 unsigned long flags;
7222 bool first_add = false;
7224 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7227 while (!list_empty(&ctx->rsrc_ref_list)) {
7228 node = list_first_entry(&ctx->rsrc_ref_list,
7229 struct io_rsrc_node, node);
7230 /* recycle ref nodes in order */
7233 list_del(&node->node);
7234 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7236 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7239 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7242 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7244 struct io_rsrc_node *ref_node;
7246 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7250 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7255 INIT_LIST_HEAD(&ref_node->node);
7256 INIT_LIST_HEAD(&ref_node->rsrc_list);
7257 ref_node->done = false;
7261 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7262 struct io_rsrc_data *data_to_kill)
7264 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7265 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7268 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7270 rsrc_node->rsrc_data = data_to_kill;
7271 spin_lock_irq(&ctx->rsrc_ref_lock);
7272 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7273 spin_unlock_irq(&ctx->rsrc_ref_lock);
7275 atomic_inc(&data_to_kill->refs);
7276 percpu_ref_kill(&rsrc_node->refs);
7277 ctx->rsrc_node = NULL;
7280 if (!ctx->rsrc_node) {
7281 ctx->rsrc_node = ctx->rsrc_backup_node;
7282 ctx->rsrc_backup_node = NULL;
7286 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7288 if (ctx->rsrc_backup_node)
7290 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7291 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7294 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7298 /* As we may drop ->uring_lock, other task may have started quiesce */
7302 data->quiesce = true;
7304 ret = io_rsrc_node_switch_start(ctx);
7307 io_rsrc_node_switch(ctx, data);
7309 /* kill initial ref, already quiesced if zero */
7310 if (atomic_dec_and_test(&data->refs))
7312 mutex_unlock(&ctx->uring_lock);
7313 flush_delayed_work(&ctx->rsrc_put_work);
7314 ret = wait_for_completion_interruptible(&data->done);
7316 mutex_lock(&ctx->uring_lock);
7320 atomic_inc(&data->refs);
7321 /* wait for all works potentially completing data->done */
7322 flush_delayed_work(&ctx->rsrc_put_work);
7323 reinit_completion(&data->done);
7325 ret = io_run_task_work_sig();
7326 mutex_lock(&ctx->uring_lock);
7328 data->quiesce = false;
7333 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7335 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7336 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7338 return &data->tags[table_idx][off];
7341 static void io_rsrc_data_free(struct io_rsrc_data *data)
7343 size_t size = data->nr * sizeof(data->tags[0][0]);
7346 io_free_page_table((void **)data->tags, size);
7350 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7351 u64 __user *utags, unsigned nr,
7352 struct io_rsrc_data **pdata)
7354 struct io_rsrc_data *data;
7358 data = kzalloc(sizeof(*data), GFP_KERNEL);
7361 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7369 data->do_put = do_put;
7372 for (i = 0; i < nr; i++) {
7373 u64 *tag_slot = io_get_tag_slot(data, i);
7375 if (copy_from_user(tag_slot, &utags[i],
7381 atomic_set(&data->refs, 1);
7382 init_completion(&data->done);
7386 io_rsrc_data_free(data);
7390 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7392 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7393 GFP_KERNEL_ACCOUNT);
7394 return !!table->files;
7397 static void io_free_file_tables(struct io_file_table *table)
7399 kvfree(table->files);
7400 table->files = NULL;
7403 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7405 #if defined(CONFIG_UNIX)
7406 if (ctx->ring_sock) {
7407 struct sock *sock = ctx->ring_sock->sk;
7408 struct sk_buff *skb;
7410 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7416 for (i = 0; i < ctx->nr_user_files; i++) {
7419 file = io_file_from_index(ctx, i);
7424 io_free_file_tables(&ctx->file_table);
7425 io_rsrc_data_free(ctx->file_data);
7426 ctx->file_data = NULL;
7427 ctx->nr_user_files = 0;
7430 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7434 if (!ctx->file_data)
7436 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7438 __io_sqe_files_unregister(ctx);
7442 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7443 __releases(&sqd->lock)
7445 WARN_ON_ONCE(sqd->thread == current);
7448 * Do the dance but not conditional clear_bit() because it'd race with
7449 * other threads incrementing park_pending and setting the bit.
7451 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7452 if (atomic_dec_return(&sqd->park_pending))
7453 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7454 mutex_unlock(&sqd->lock);
7457 static void io_sq_thread_park(struct io_sq_data *sqd)
7458 __acquires(&sqd->lock)
7460 WARN_ON_ONCE(sqd->thread == current);
7462 atomic_inc(&sqd->park_pending);
7463 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7464 mutex_lock(&sqd->lock);
7466 wake_up_process(sqd->thread);
7469 static void io_sq_thread_stop(struct io_sq_data *sqd)
7471 WARN_ON_ONCE(sqd->thread == current);
7472 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7474 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7475 mutex_lock(&sqd->lock);
7477 wake_up_process(sqd->thread);
7478 mutex_unlock(&sqd->lock);
7479 wait_for_completion(&sqd->exited);
7482 static void io_put_sq_data(struct io_sq_data *sqd)
7484 if (refcount_dec_and_test(&sqd->refs)) {
7485 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7487 io_sq_thread_stop(sqd);
7492 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7494 struct io_sq_data *sqd = ctx->sq_data;
7497 io_sq_thread_park(sqd);
7498 list_del_init(&ctx->sqd_list);
7499 io_sqd_update_thread_idle(sqd);
7500 io_sq_thread_unpark(sqd);
7502 io_put_sq_data(sqd);
7503 ctx->sq_data = NULL;
7507 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7509 struct io_ring_ctx *ctx_attach;
7510 struct io_sq_data *sqd;
7513 f = fdget(p->wq_fd);
7515 return ERR_PTR(-ENXIO);
7516 if (f.file->f_op != &io_uring_fops) {
7518 return ERR_PTR(-EINVAL);
7521 ctx_attach = f.file->private_data;
7522 sqd = ctx_attach->sq_data;
7525 return ERR_PTR(-EINVAL);
7527 if (sqd->task_tgid != current->tgid) {
7529 return ERR_PTR(-EPERM);
7532 refcount_inc(&sqd->refs);
7537 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7540 struct io_sq_data *sqd;
7543 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7544 sqd = io_attach_sq_data(p);
7549 /* fall through for EPERM case, setup new sqd/task */
7550 if (PTR_ERR(sqd) != -EPERM)
7554 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7556 return ERR_PTR(-ENOMEM);
7558 atomic_set(&sqd->park_pending, 0);
7559 refcount_set(&sqd->refs, 1);
7560 INIT_LIST_HEAD(&sqd->ctx_list);
7561 mutex_init(&sqd->lock);
7562 init_waitqueue_head(&sqd->wait);
7563 init_completion(&sqd->exited);
7567 #if defined(CONFIG_UNIX)
7569 * Ensure the UNIX gc is aware of our file set, so we are certain that
7570 * the io_uring can be safely unregistered on process exit, even if we have
7571 * loops in the file referencing.
7573 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7575 struct sock *sk = ctx->ring_sock->sk;
7576 struct scm_fp_list *fpl;
7577 struct sk_buff *skb;
7580 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7584 skb = alloc_skb(0, GFP_KERNEL);
7593 fpl->user = get_uid(current_user());
7594 for (i = 0; i < nr; i++) {
7595 struct file *file = io_file_from_index(ctx, i + offset);
7599 fpl->fp[nr_files] = get_file(file);
7600 unix_inflight(fpl->user, fpl->fp[nr_files]);
7605 fpl->max = SCM_MAX_FD;
7606 fpl->count = nr_files;
7607 UNIXCB(skb).fp = fpl;
7608 skb->destructor = unix_destruct_scm;
7609 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7610 skb_queue_head(&sk->sk_receive_queue, skb);
7612 for (i = 0; i < nr_files; i++)
7623 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7624 * causes regular reference counting to break down. We rely on the UNIX
7625 * garbage collection to take care of this problem for us.
7627 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7629 unsigned left, total;
7633 left = ctx->nr_user_files;
7635 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7637 ret = __io_sqe_files_scm(ctx, this_files, total);
7641 total += this_files;
7647 while (total < ctx->nr_user_files) {
7648 struct file *file = io_file_from_index(ctx, total);
7658 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7664 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7666 struct file *file = prsrc->file;
7667 #if defined(CONFIG_UNIX)
7668 struct sock *sock = ctx->ring_sock->sk;
7669 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7670 struct sk_buff *skb;
7673 __skb_queue_head_init(&list);
7676 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7677 * remove this entry and rearrange the file array.
7679 skb = skb_dequeue(head);
7681 struct scm_fp_list *fp;
7683 fp = UNIXCB(skb).fp;
7684 for (i = 0; i < fp->count; i++) {
7687 if (fp->fp[i] != file)
7690 unix_notinflight(fp->user, fp->fp[i]);
7691 left = fp->count - 1 - i;
7693 memmove(&fp->fp[i], &fp->fp[i + 1],
7694 left * sizeof(struct file *));
7701 __skb_queue_tail(&list, skb);
7711 __skb_queue_tail(&list, skb);
7713 skb = skb_dequeue(head);
7716 if (skb_peek(&list)) {
7717 spin_lock_irq(&head->lock);
7718 while ((skb = __skb_dequeue(&list)) != NULL)
7719 __skb_queue_tail(head, skb);
7720 spin_unlock_irq(&head->lock);
7727 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7729 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7730 struct io_ring_ctx *ctx = rsrc_data->ctx;
7731 struct io_rsrc_put *prsrc, *tmp;
7733 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7734 list_del(&prsrc->list);
7737 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7739 io_ring_submit_lock(ctx, lock_ring);
7740 spin_lock(&ctx->completion_lock);
7741 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7743 io_commit_cqring(ctx);
7744 spin_unlock(&ctx->completion_lock);
7745 io_cqring_ev_posted(ctx);
7746 io_ring_submit_unlock(ctx, lock_ring);
7749 rsrc_data->do_put(ctx, prsrc);
7753 io_rsrc_node_destroy(ref_node);
7754 if (atomic_dec_and_test(&rsrc_data->refs))
7755 complete(&rsrc_data->done);
7758 static void io_rsrc_put_work(struct work_struct *work)
7760 struct io_ring_ctx *ctx;
7761 struct llist_node *node;
7763 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7764 node = llist_del_all(&ctx->rsrc_put_llist);
7767 struct io_rsrc_node *ref_node;
7768 struct llist_node *next = node->next;
7770 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7771 __io_rsrc_put_work(ref_node);
7776 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7777 unsigned nr_args, u64 __user *tags)
7779 __s32 __user *fds = (__s32 __user *) arg;
7788 if (nr_args > IORING_MAX_FIXED_FILES)
7790 if (nr_args > rlimit(RLIMIT_NOFILE))
7792 ret = io_rsrc_node_switch_start(ctx);
7795 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
7801 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7804 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7805 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7809 /* allow sparse sets */
7812 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
7819 if (unlikely(!file))
7823 * Don't allow io_uring instances to be registered. If UNIX
7824 * isn't enabled, then this causes a reference cycle and this
7825 * instance can never get freed. If UNIX is enabled we'll
7826 * handle it just fine, but there's still no point in allowing
7827 * a ring fd as it doesn't support regular read/write anyway.
7829 if (file->f_op == &io_uring_fops) {
7833 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7836 ret = io_sqe_files_scm(ctx);
7838 __io_sqe_files_unregister(ctx);
7842 io_rsrc_node_switch(ctx, NULL);
7845 for (i = 0; i < ctx->nr_user_files; i++) {
7846 file = io_file_from_index(ctx, i);
7850 io_free_file_tables(&ctx->file_table);
7851 ctx->nr_user_files = 0;
7853 io_rsrc_data_free(ctx->file_data);
7854 ctx->file_data = NULL;
7858 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7861 #if defined(CONFIG_UNIX)
7862 struct sock *sock = ctx->ring_sock->sk;
7863 struct sk_buff_head *head = &sock->sk_receive_queue;
7864 struct sk_buff *skb;
7867 * See if we can merge this file into an existing skb SCM_RIGHTS
7868 * file set. If there's no room, fall back to allocating a new skb
7869 * and filling it in.
7871 spin_lock_irq(&head->lock);
7872 skb = skb_peek(head);
7874 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7876 if (fpl->count < SCM_MAX_FD) {
7877 __skb_unlink(skb, head);
7878 spin_unlock_irq(&head->lock);
7879 fpl->fp[fpl->count] = get_file(file);
7880 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7882 spin_lock_irq(&head->lock);
7883 __skb_queue_head(head, skb);
7888 spin_unlock_irq(&head->lock);
7895 return __io_sqe_files_scm(ctx, 1, index);
7901 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7902 struct io_rsrc_node *node, void *rsrc)
7904 struct io_rsrc_put *prsrc;
7906 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7910 prsrc->tag = *io_get_tag_slot(data, idx);
7912 list_add(&prsrc->list, &node->rsrc_list);
7916 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7917 struct io_uring_rsrc_update2 *up,
7920 u64 __user *tags = u64_to_user_ptr(up->tags);
7921 __s32 __user *fds = u64_to_user_ptr(up->data);
7922 struct io_rsrc_data *data = ctx->file_data;
7923 struct io_fixed_file *file_slot;
7927 bool needs_switch = false;
7929 if (!ctx->file_data)
7931 if (up->offset + nr_args > ctx->nr_user_files)
7934 for (done = 0; done < nr_args; done++) {
7937 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7938 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7942 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7946 if (fd == IORING_REGISTER_FILES_SKIP)
7949 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7950 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7952 if (file_slot->file_ptr) {
7953 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7954 err = io_queue_rsrc_removal(data, up->offset + done,
7955 ctx->rsrc_node, file);
7958 file_slot->file_ptr = 0;
7959 needs_switch = true;
7968 * Don't allow io_uring instances to be registered. If
7969 * UNIX isn't enabled, then this causes a reference
7970 * cycle and this instance can never get freed. If UNIX
7971 * is enabled we'll handle it just fine, but there's
7972 * still no point in allowing a ring fd as it doesn't
7973 * support regular read/write anyway.
7975 if (file->f_op == &io_uring_fops) {
7980 *io_get_tag_slot(data, up->offset + done) = tag;
7981 io_fixed_file_set(file_slot, file);
7982 err = io_sqe_file_register(ctx, file, i);
7984 file_slot->file_ptr = 0;
7992 io_rsrc_node_switch(ctx, data);
7993 return done ? done : err;
7996 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7997 struct task_struct *task)
7999 struct io_wq_hash *hash;
8000 struct io_wq_data data;
8001 unsigned int concurrency;
8003 mutex_lock(&ctx->uring_lock);
8004 hash = ctx->hash_map;
8006 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8008 mutex_unlock(&ctx->uring_lock);
8009 return ERR_PTR(-ENOMEM);
8011 refcount_set(&hash->refs, 1);
8012 init_waitqueue_head(&hash->wait);
8013 ctx->hash_map = hash;
8015 mutex_unlock(&ctx->uring_lock);
8019 data.free_work = io_wq_free_work;
8020 data.do_work = io_wq_submit_work;
8022 /* Do QD, or 4 * CPUS, whatever is smallest */
8023 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8025 return io_wq_create(concurrency, &data);
8028 static int io_uring_alloc_task_context(struct task_struct *task,
8029 struct io_ring_ctx *ctx)
8031 struct io_uring_task *tctx;
8034 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8035 if (unlikely(!tctx))
8038 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8039 if (unlikely(ret)) {
8044 tctx->io_wq = io_init_wq_offload(ctx, task);
8045 if (IS_ERR(tctx->io_wq)) {
8046 ret = PTR_ERR(tctx->io_wq);
8047 percpu_counter_destroy(&tctx->inflight);
8053 init_waitqueue_head(&tctx->wait);
8054 atomic_set(&tctx->in_idle, 0);
8055 atomic_set(&tctx->inflight_tracked, 0);
8056 task->io_uring = tctx;
8057 spin_lock_init(&tctx->task_lock);
8058 INIT_WQ_LIST(&tctx->task_list);
8059 init_task_work(&tctx->task_work, tctx_task_work);
8063 void __io_uring_free(struct task_struct *tsk)
8065 struct io_uring_task *tctx = tsk->io_uring;
8067 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8068 WARN_ON_ONCE(tctx->io_wq);
8069 WARN_ON_ONCE(tctx->cached_refs);
8071 percpu_counter_destroy(&tctx->inflight);
8073 tsk->io_uring = NULL;
8076 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8077 struct io_uring_params *p)
8081 /* Retain compatibility with failing for an invalid attach attempt */
8082 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8083 IORING_SETUP_ATTACH_WQ) {
8086 f = fdget(p->wq_fd);
8089 if (f.file->f_op != &io_uring_fops) {
8095 if (ctx->flags & IORING_SETUP_SQPOLL) {
8096 struct task_struct *tsk;
8097 struct io_sq_data *sqd;
8100 sqd = io_get_sq_data(p, &attached);
8106 ctx->sq_creds = get_current_cred();
8108 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8109 if (!ctx->sq_thread_idle)
8110 ctx->sq_thread_idle = HZ;
8112 io_sq_thread_park(sqd);
8113 list_add(&ctx->sqd_list, &sqd->ctx_list);
8114 io_sqd_update_thread_idle(sqd);
8115 /* don't attach to a dying SQPOLL thread, would be racy */
8116 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8117 io_sq_thread_unpark(sqd);
8124 if (p->flags & IORING_SETUP_SQ_AFF) {
8125 int cpu = p->sq_thread_cpu;
8128 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8135 sqd->task_pid = current->pid;
8136 sqd->task_tgid = current->tgid;
8137 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8144 ret = io_uring_alloc_task_context(tsk, ctx);
8145 wake_up_new_task(tsk);
8148 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8149 /* Can't have SQ_AFF without SQPOLL */
8156 complete(&ctx->sq_data->exited);
8158 io_sq_thread_finish(ctx);
8162 static inline void __io_unaccount_mem(struct user_struct *user,
8163 unsigned long nr_pages)
8165 atomic_long_sub(nr_pages, &user->locked_vm);
8168 static inline int __io_account_mem(struct user_struct *user,
8169 unsigned long nr_pages)
8171 unsigned long page_limit, cur_pages, new_pages;
8173 /* Don't allow more pages than we can safely lock */
8174 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8177 cur_pages = atomic_long_read(&user->locked_vm);
8178 new_pages = cur_pages + nr_pages;
8179 if (new_pages > page_limit)
8181 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8182 new_pages) != cur_pages);
8187 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8190 __io_unaccount_mem(ctx->user, nr_pages);
8192 if (ctx->mm_account)
8193 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8196 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8201 ret = __io_account_mem(ctx->user, nr_pages);
8206 if (ctx->mm_account)
8207 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8212 static void io_mem_free(void *ptr)
8219 page = virt_to_head_page(ptr);
8220 if (put_page_testzero(page))
8221 free_compound_page(page);
8224 static void *io_mem_alloc(size_t size)
8226 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8227 __GFP_NORETRY | __GFP_ACCOUNT;
8229 return (void *) __get_free_pages(gfp_flags, get_order(size));
8232 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8235 struct io_rings *rings;
8236 size_t off, sq_array_size;
8238 off = struct_size(rings, cqes, cq_entries);
8239 if (off == SIZE_MAX)
8243 off = ALIGN(off, SMP_CACHE_BYTES);
8251 sq_array_size = array_size(sizeof(u32), sq_entries);
8252 if (sq_array_size == SIZE_MAX)
8255 if (check_add_overflow(off, sq_array_size, &off))
8261 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8263 struct io_mapped_ubuf *imu = *slot;
8266 if (imu != ctx->dummy_ubuf) {
8267 for (i = 0; i < imu->nr_bvecs; i++)
8268 unpin_user_page(imu->bvec[i].bv_page);
8269 if (imu->acct_pages)
8270 io_unaccount_mem(ctx, imu->acct_pages);
8276 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8278 io_buffer_unmap(ctx, &prsrc->buf);
8282 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8286 for (i = 0; i < ctx->nr_user_bufs; i++)
8287 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8288 kfree(ctx->user_bufs);
8289 io_rsrc_data_free(ctx->buf_data);
8290 ctx->user_bufs = NULL;
8291 ctx->buf_data = NULL;
8292 ctx->nr_user_bufs = 0;
8295 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8302 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8304 __io_sqe_buffers_unregister(ctx);
8308 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8309 void __user *arg, unsigned index)
8311 struct iovec __user *src;
8313 #ifdef CONFIG_COMPAT
8315 struct compat_iovec __user *ciovs;
8316 struct compat_iovec ciov;
8318 ciovs = (struct compat_iovec __user *) arg;
8319 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8322 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8323 dst->iov_len = ciov.iov_len;
8327 src = (struct iovec __user *) arg;
8328 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8334 * Not super efficient, but this is just a registration time. And we do cache
8335 * the last compound head, so generally we'll only do a full search if we don't
8338 * We check if the given compound head page has already been accounted, to
8339 * avoid double accounting it. This allows us to account the full size of the
8340 * page, not just the constituent pages of a huge page.
8342 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8343 int nr_pages, struct page *hpage)
8347 /* check current page array */
8348 for (i = 0; i < nr_pages; i++) {
8349 if (!PageCompound(pages[i]))
8351 if (compound_head(pages[i]) == hpage)
8355 /* check previously registered pages */
8356 for (i = 0; i < ctx->nr_user_bufs; i++) {
8357 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8359 for (j = 0; j < imu->nr_bvecs; j++) {
8360 if (!PageCompound(imu->bvec[j].bv_page))
8362 if (compound_head(imu->bvec[j].bv_page) == hpage)
8370 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8371 int nr_pages, struct io_mapped_ubuf *imu,
8372 struct page **last_hpage)
8376 imu->acct_pages = 0;
8377 for (i = 0; i < nr_pages; i++) {
8378 if (!PageCompound(pages[i])) {
8383 hpage = compound_head(pages[i]);
8384 if (hpage == *last_hpage)
8386 *last_hpage = hpage;
8387 if (headpage_already_acct(ctx, pages, i, hpage))
8389 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8393 if (!imu->acct_pages)
8396 ret = io_account_mem(ctx, imu->acct_pages);
8398 imu->acct_pages = 0;
8402 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8403 struct io_mapped_ubuf **pimu,
8404 struct page **last_hpage)
8406 struct io_mapped_ubuf *imu = NULL;
8407 struct vm_area_struct **vmas = NULL;
8408 struct page **pages = NULL;
8409 unsigned long off, start, end, ubuf;
8411 int ret, pret, nr_pages, i;
8413 if (!iov->iov_base) {
8414 *pimu = ctx->dummy_ubuf;
8418 ubuf = (unsigned long) iov->iov_base;
8419 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8420 start = ubuf >> PAGE_SHIFT;
8421 nr_pages = end - start;
8426 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8430 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8435 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8440 mmap_read_lock(current->mm);
8441 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8443 if (pret == nr_pages) {
8444 /* don't support file backed memory */
8445 for (i = 0; i < nr_pages; i++) {
8446 struct vm_area_struct *vma = vmas[i];
8448 if (vma_is_shmem(vma))
8451 !is_file_hugepages(vma->vm_file)) {
8457 ret = pret < 0 ? pret : -EFAULT;
8459 mmap_read_unlock(current->mm);
8462 * if we did partial map, or found file backed vmas,
8463 * release any pages we did get
8466 unpin_user_pages(pages, pret);
8470 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8472 unpin_user_pages(pages, pret);
8476 off = ubuf & ~PAGE_MASK;
8477 size = iov->iov_len;
8478 for (i = 0; i < nr_pages; i++) {
8481 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8482 imu->bvec[i].bv_page = pages[i];
8483 imu->bvec[i].bv_len = vec_len;
8484 imu->bvec[i].bv_offset = off;
8488 /* store original address for later verification */
8490 imu->ubuf_end = ubuf + iov->iov_len;
8491 imu->nr_bvecs = nr_pages;
8502 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8504 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8505 return ctx->user_bufs ? 0 : -ENOMEM;
8508 static int io_buffer_validate(struct iovec *iov)
8510 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8513 * Don't impose further limits on the size and buffer
8514 * constraints here, we'll -EINVAL later when IO is
8515 * submitted if they are wrong.
8518 return iov->iov_len ? -EFAULT : 0;
8522 /* arbitrary limit, but we need something */
8523 if (iov->iov_len > SZ_1G)
8526 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8532 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8533 unsigned int nr_args, u64 __user *tags)
8535 struct page *last_hpage = NULL;
8536 struct io_rsrc_data *data;
8542 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
8544 ret = io_rsrc_node_switch_start(ctx);
8547 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
8550 ret = io_buffers_map_alloc(ctx, nr_args);
8552 io_rsrc_data_free(data);
8556 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8557 ret = io_copy_iov(ctx, &iov, arg, i);
8560 ret = io_buffer_validate(&iov);
8563 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
8568 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8574 WARN_ON_ONCE(ctx->buf_data);
8576 ctx->buf_data = data;
8578 __io_sqe_buffers_unregister(ctx);
8580 io_rsrc_node_switch(ctx, NULL);
8584 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8585 struct io_uring_rsrc_update2 *up,
8586 unsigned int nr_args)
8588 u64 __user *tags = u64_to_user_ptr(up->tags);
8589 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8590 struct page *last_hpage = NULL;
8591 bool needs_switch = false;
8597 if (up->offset + nr_args > ctx->nr_user_bufs)
8600 for (done = 0; done < nr_args; done++) {
8601 struct io_mapped_ubuf *imu;
8602 int offset = up->offset + done;
8605 err = io_copy_iov(ctx, &iov, iovs, done);
8608 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8612 err = io_buffer_validate(&iov);
8615 if (!iov.iov_base && tag) {
8619 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8623 i = array_index_nospec(offset, ctx->nr_user_bufs);
8624 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
8625 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8626 ctx->rsrc_node, ctx->user_bufs[i]);
8627 if (unlikely(err)) {
8628 io_buffer_unmap(ctx, &imu);
8631 ctx->user_bufs[i] = NULL;
8632 needs_switch = true;
8635 ctx->user_bufs[i] = imu;
8636 *io_get_tag_slot(ctx->buf_data, offset) = tag;
8640 io_rsrc_node_switch(ctx, ctx->buf_data);
8641 return done ? done : err;
8644 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8646 __s32 __user *fds = arg;
8652 if (copy_from_user(&fd, fds, sizeof(*fds)))
8655 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8656 if (IS_ERR(ctx->cq_ev_fd)) {
8657 int ret = PTR_ERR(ctx->cq_ev_fd);
8659 ctx->cq_ev_fd = NULL;
8666 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8668 if (ctx->cq_ev_fd) {
8669 eventfd_ctx_put(ctx->cq_ev_fd);
8670 ctx->cq_ev_fd = NULL;
8677 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8679 struct io_buffer *buf;
8680 unsigned long index;
8682 xa_for_each(&ctx->io_buffers, index, buf)
8683 __io_remove_buffers(ctx, buf, index, -1U);
8686 static void io_req_cache_free(struct list_head *list)
8688 struct io_kiocb *req, *nxt;
8690 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
8691 list_del(&req->inflight_entry);
8692 kmem_cache_free(req_cachep, req);
8696 static void io_req_caches_free(struct io_ring_ctx *ctx)
8698 struct io_submit_state *state = &ctx->submit_state;
8700 mutex_lock(&ctx->uring_lock);
8702 if (state->free_reqs) {
8703 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
8704 state->free_reqs = 0;
8707 io_flush_cached_locked_reqs(ctx, state);
8708 io_req_cache_free(&state->free_list);
8709 mutex_unlock(&ctx->uring_lock);
8712 static void io_wait_rsrc_data(struct io_rsrc_data *data)
8714 if (data && !atomic_dec_and_test(&data->refs))
8715 wait_for_completion(&data->done);
8718 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8720 io_sq_thread_finish(ctx);
8722 if (ctx->mm_account) {
8723 mmdrop(ctx->mm_account);
8724 ctx->mm_account = NULL;
8727 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
8728 io_wait_rsrc_data(ctx->buf_data);
8729 io_wait_rsrc_data(ctx->file_data);
8731 mutex_lock(&ctx->uring_lock);
8733 __io_sqe_buffers_unregister(ctx);
8735 __io_sqe_files_unregister(ctx);
8737 __io_cqring_overflow_flush(ctx, true);
8738 mutex_unlock(&ctx->uring_lock);
8739 io_eventfd_unregister(ctx);
8740 io_destroy_buffers(ctx);
8742 put_cred(ctx->sq_creds);
8744 /* there are no registered resources left, nobody uses it */
8746 io_rsrc_node_destroy(ctx->rsrc_node);
8747 if (ctx->rsrc_backup_node)
8748 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8749 flush_delayed_work(&ctx->rsrc_put_work);
8751 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8752 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8754 #if defined(CONFIG_UNIX)
8755 if (ctx->ring_sock) {
8756 ctx->ring_sock->file = NULL; /* so that iput() is called */
8757 sock_release(ctx->ring_sock);
8761 io_mem_free(ctx->rings);
8762 io_mem_free(ctx->sq_sqes);
8764 percpu_ref_exit(&ctx->refs);
8765 free_uid(ctx->user);
8766 io_req_caches_free(ctx);
8768 io_wq_put_hash(ctx->hash_map);
8769 kfree(ctx->cancel_hash);
8770 kfree(ctx->dummy_ubuf);
8774 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8776 struct io_ring_ctx *ctx = file->private_data;
8779 poll_wait(file, &ctx->poll_wait, wait);
8781 * synchronizes with barrier from wq_has_sleeper call in
8785 if (!io_sqring_full(ctx))
8786 mask |= EPOLLOUT | EPOLLWRNORM;
8789 * Don't flush cqring overflow list here, just do a simple check.
8790 * Otherwise there could possible be ABBA deadlock:
8793 * lock(&ctx->uring_lock);
8795 * lock(&ctx->uring_lock);
8798 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8799 * pushs them to do the flush.
8801 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
8802 mask |= EPOLLIN | EPOLLRDNORM;
8807 static int io_uring_fasync(int fd, struct file *file, int on)
8809 struct io_ring_ctx *ctx = file->private_data;
8811 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8814 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8816 const struct cred *creds;
8818 creds = xa_erase(&ctx->personalities, id);
8827 struct io_tctx_exit {
8828 struct callback_head task_work;
8829 struct completion completion;
8830 struct io_ring_ctx *ctx;
8833 static void io_tctx_exit_cb(struct callback_head *cb)
8835 struct io_uring_task *tctx = current->io_uring;
8836 struct io_tctx_exit *work;
8838 work = container_of(cb, struct io_tctx_exit, task_work);
8840 * When @in_idle, we're in cancellation and it's racy to remove the
8841 * node. It'll be removed by the end of cancellation, just ignore it.
8843 if (!atomic_read(&tctx->in_idle))
8844 io_uring_del_tctx_node((unsigned long)work->ctx);
8845 complete(&work->completion);
8848 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8850 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8852 return req->ctx == data;
8855 static void io_ring_exit_work(struct work_struct *work)
8857 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8858 unsigned long timeout = jiffies + HZ * 60 * 5;
8859 unsigned long interval = HZ / 20;
8860 struct io_tctx_exit exit;
8861 struct io_tctx_node *node;
8865 * If we're doing polled IO and end up having requests being
8866 * submitted async (out-of-line), then completions can come in while
8867 * we're waiting for refs to drop. We need to reap these manually,
8868 * as nobody else will be looking for them.
8871 io_uring_try_cancel_requests(ctx, NULL, true);
8873 struct io_sq_data *sqd = ctx->sq_data;
8874 struct task_struct *tsk;
8876 io_sq_thread_park(sqd);
8878 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8879 io_wq_cancel_cb(tsk->io_uring->io_wq,
8880 io_cancel_ctx_cb, ctx, true);
8881 io_sq_thread_unpark(sqd);
8884 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
8885 /* there is little hope left, don't run it too often */
8888 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
8890 init_completion(&exit.completion);
8891 init_task_work(&exit.task_work, io_tctx_exit_cb);
8894 * Some may use context even when all refs and requests have been put,
8895 * and they are free to do so while still holding uring_lock or
8896 * completion_lock, see io_req_task_submit(). Apart from other work,
8897 * this lock/unlock section also waits them to finish.
8899 mutex_lock(&ctx->uring_lock);
8900 while (!list_empty(&ctx->tctx_list)) {
8901 WARN_ON_ONCE(time_after(jiffies, timeout));
8903 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8905 /* don't spin on a single task if cancellation failed */
8906 list_rotate_left(&ctx->tctx_list);
8907 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8908 if (WARN_ON_ONCE(ret))
8910 wake_up_process(node->task);
8912 mutex_unlock(&ctx->uring_lock);
8913 wait_for_completion(&exit.completion);
8914 mutex_lock(&ctx->uring_lock);
8916 mutex_unlock(&ctx->uring_lock);
8917 spin_lock(&ctx->completion_lock);
8918 spin_unlock(&ctx->completion_lock);
8920 io_ring_ctx_free(ctx);
8923 /* Returns true if we found and killed one or more timeouts */
8924 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8927 struct io_kiocb *req, *tmp;
8930 spin_lock(&ctx->completion_lock);
8931 spin_lock_irq(&ctx->timeout_lock);
8932 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8933 if (io_match_task(req, tsk, cancel_all)) {
8934 io_kill_timeout(req, -ECANCELED);
8938 spin_unlock_irq(&ctx->timeout_lock);
8940 io_commit_cqring(ctx);
8941 spin_unlock(&ctx->completion_lock);
8943 io_cqring_ev_posted(ctx);
8944 return canceled != 0;
8947 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8949 unsigned long index;
8950 struct creds *creds;
8952 mutex_lock(&ctx->uring_lock);
8953 percpu_ref_kill(&ctx->refs);
8955 __io_cqring_overflow_flush(ctx, true);
8956 xa_for_each(&ctx->personalities, index, creds)
8957 io_unregister_personality(ctx, index);
8958 mutex_unlock(&ctx->uring_lock);
8960 io_kill_timeouts(ctx, NULL, true);
8961 io_poll_remove_all(ctx, NULL, true);
8963 /* if we failed setting up the ctx, we might not have any rings */
8964 io_iopoll_try_reap_events(ctx);
8966 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8968 * Use system_unbound_wq to avoid spawning tons of event kworkers
8969 * if we're exiting a ton of rings at the same time. It just adds
8970 * noise and overhead, there's no discernable change in runtime
8971 * over using system_wq.
8973 queue_work(system_unbound_wq, &ctx->exit_work);
8976 static int io_uring_release(struct inode *inode, struct file *file)
8978 struct io_ring_ctx *ctx = file->private_data;
8980 file->private_data = NULL;
8981 io_ring_ctx_wait_and_kill(ctx);
8985 struct io_task_cancel {
8986 struct task_struct *task;
8990 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8992 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8993 struct io_task_cancel *cancel = data;
8996 if (!cancel->all && (req->flags & REQ_F_LINK_TIMEOUT)) {
8997 struct io_ring_ctx *ctx = req->ctx;
8999 /* protect against races with linked timeouts */
9000 spin_lock(&ctx->completion_lock);
9001 ret = io_match_task(req, cancel->task, cancel->all);
9002 spin_unlock(&ctx->completion_lock);
9004 ret = io_match_task(req, cancel->task, cancel->all);
9009 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9010 struct task_struct *task, bool cancel_all)
9012 struct io_defer_entry *de;
9015 spin_lock(&ctx->completion_lock);
9016 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9017 if (io_match_task(de->req, task, cancel_all)) {
9018 list_cut_position(&list, &ctx->defer_list, &de->list);
9022 spin_unlock(&ctx->completion_lock);
9023 if (list_empty(&list))
9026 while (!list_empty(&list)) {
9027 de = list_first_entry(&list, struct io_defer_entry, list);
9028 list_del_init(&de->list);
9029 io_req_complete_failed(de->req, -ECANCELED);
9035 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9037 struct io_tctx_node *node;
9038 enum io_wq_cancel cret;
9041 mutex_lock(&ctx->uring_lock);
9042 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9043 struct io_uring_task *tctx = node->task->io_uring;
9046 * io_wq will stay alive while we hold uring_lock, because it's
9047 * killed after ctx nodes, which requires to take the lock.
9049 if (!tctx || !tctx->io_wq)
9051 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9052 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9054 mutex_unlock(&ctx->uring_lock);
9059 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9060 struct task_struct *task,
9063 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9064 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9067 enum io_wq_cancel cret;
9071 ret |= io_uring_try_cancel_iowq(ctx);
9072 } else if (tctx && tctx->io_wq) {
9074 * Cancels requests of all rings, not only @ctx, but
9075 * it's fine as the task is in exit/exec.
9077 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9079 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9082 /* SQPOLL thread does its own polling */
9083 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9084 (ctx->sq_data && ctx->sq_data->thread == current)) {
9085 while (!list_empty_careful(&ctx->iopoll_list)) {
9086 io_iopoll_try_reap_events(ctx);
9091 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9092 ret |= io_poll_remove_all(ctx, task, cancel_all);
9093 ret |= io_kill_timeouts(ctx, task, cancel_all);
9095 ret |= io_run_task_work();
9102 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9104 struct io_uring_task *tctx = current->io_uring;
9105 struct io_tctx_node *node;
9108 if (unlikely(!tctx)) {
9109 ret = io_uring_alloc_task_context(current, ctx);
9112 tctx = current->io_uring;
9114 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9115 node = kmalloc(sizeof(*node), GFP_KERNEL);
9119 node->task = current;
9121 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9128 mutex_lock(&ctx->uring_lock);
9129 list_add(&node->ctx_node, &ctx->tctx_list);
9130 mutex_unlock(&ctx->uring_lock);
9137 * Note that this task has used io_uring. We use it for cancelation purposes.
9139 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9141 struct io_uring_task *tctx = current->io_uring;
9143 if (likely(tctx && tctx->last == ctx))
9145 return __io_uring_add_tctx_node(ctx);
9149 * Remove this io_uring_file -> task mapping.
9151 static void io_uring_del_tctx_node(unsigned long index)
9153 struct io_uring_task *tctx = current->io_uring;
9154 struct io_tctx_node *node;
9158 node = xa_erase(&tctx->xa, index);
9162 WARN_ON_ONCE(current != node->task);
9163 WARN_ON_ONCE(list_empty(&node->ctx_node));
9165 mutex_lock(&node->ctx->uring_lock);
9166 list_del(&node->ctx_node);
9167 mutex_unlock(&node->ctx->uring_lock);
9169 if (tctx->last == node->ctx)
9174 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9176 struct io_wq *wq = tctx->io_wq;
9177 struct io_tctx_node *node;
9178 unsigned long index;
9180 xa_for_each(&tctx->xa, index, node)
9181 io_uring_del_tctx_node(index);
9184 * Must be after io_uring_del_task_file() (removes nodes under
9185 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9188 io_wq_put_and_exit(wq);
9192 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9195 return atomic_read(&tctx->inflight_tracked);
9196 return percpu_counter_sum(&tctx->inflight);
9199 static void io_uring_drop_tctx_refs(struct task_struct *task)
9201 struct io_uring_task *tctx = task->io_uring;
9202 unsigned int refs = tctx->cached_refs;
9205 tctx->cached_refs = 0;
9206 percpu_counter_sub(&tctx->inflight, refs);
9207 put_task_struct_many(task, refs);
9212 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9213 * requests. @sqd should be not-null IIF it's an SQPOLL thread cancellation.
9215 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9217 struct io_uring_task *tctx = current->io_uring;
9218 struct io_ring_ctx *ctx;
9222 WARN_ON_ONCE(sqd && sqd->thread != current);
9224 if (!current->io_uring)
9227 io_wq_exit_start(tctx->io_wq);
9229 atomic_inc(&tctx->in_idle);
9231 io_uring_drop_tctx_refs(current);
9232 /* read completions before cancelations */
9233 inflight = tctx_inflight(tctx, !cancel_all);
9238 struct io_tctx_node *node;
9239 unsigned long index;
9241 xa_for_each(&tctx->xa, index, node) {
9242 /* sqpoll task will cancel all its requests */
9243 if (node->ctx->sq_data)
9245 io_uring_try_cancel_requests(node->ctx, current,
9249 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9250 io_uring_try_cancel_requests(ctx, current,
9254 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9255 io_uring_drop_tctx_refs(current);
9257 * If we've seen completions, retry without waiting. This
9258 * avoids a race where a completion comes in before we did
9259 * prepare_to_wait().
9261 if (inflight == tctx_inflight(tctx, !cancel_all))
9263 finish_wait(&tctx->wait, &wait);
9265 atomic_dec(&tctx->in_idle);
9267 io_uring_clean_tctx(tctx);
9269 /* for exec all current's requests should be gone, kill tctx */
9270 __io_uring_free(current);
9274 void __io_uring_cancel(bool cancel_all)
9276 io_uring_cancel_generic(cancel_all, NULL);
9279 static void *io_uring_validate_mmap_request(struct file *file,
9280 loff_t pgoff, size_t sz)
9282 struct io_ring_ctx *ctx = file->private_data;
9283 loff_t offset = pgoff << PAGE_SHIFT;
9288 case IORING_OFF_SQ_RING:
9289 case IORING_OFF_CQ_RING:
9292 case IORING_OFF_SQES:
9296 return ERR_PTR(-EINVAL);
9299 page = virt_to_head_page(ptr);
9300 if (sz > page_size(page))
9301 return ERR_PTR(-EINVAL);
9308 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9310 size_t sz = vma->vm_end - vma->vm_start;
9314 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9316 return PTR_ERR(ptr);
9318 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9319 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9322 #else /* !CONFIG_MMU */
9324 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9326 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9329 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9331 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9334 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9335 unsigned long addr, unsigned long len,
9336 unsigned long pgoff, unsigned long flags)
9340 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9342 return PTR_ERR(ptr);
9344 return (unsigned long) ptr;
9347 #endif /* !CONFIG_MMU */
9349 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9354 if (!io_sqring_full(ctx))
9356 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9358 if (!io_sqring_full(ctx))
9361 } while (!signal_pending(current));
9363 finish_wait(&ctx->sqo_sq_wait, &wait);
9367 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9368 struct __kernel_timespec __user **ts,
9369 const sigset_t __user **sig)
9371 struct io_uring_getevents_arg arg;
9374 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9375 * is just a pointer to the sigset_t.
9377 if (!(flags & IORING_ENTER_EXT_ARG)) {
9378 *sig = (const sigset_t __user *) argp;
9384 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9385 * timespec and sigset_t pointers if good.
9387 if (*argsz != sizeof(arg))
9389 if (copy_from_user(&arg, argp, sizeof(arg)))
9391 *sig = u64_to_user_ptr(arg.sigmask);
9392 *argsz = arg.sigmask_sz;
9393 *ts = u64_to_user_ptr(arg.ts);
9397 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9398 u32, min_complete, u32, flags, const void __user *, argp,
9401 struct io_ring_ctx *ctx;
9408 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9409 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9413 if (unlikely(!f.file))
9417 if (unlikely(f.file->f_op != &io_uring_fops))
9421 ctx = f.file->private_data;
9422 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9426 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9430 * For SQ polling, the thread will do all submissions and completions.
9431 * Just return the requested submit count, and wake the thread if
9435 if (ctx->flags & IORING_SETUP_SQPOLL) {
9436 io_cqring_overflow_flush(ctx);
9438 if (unlikely(ctx->sq_data->thread == NULL)) {
9442 if (flags & IORING_ENTER_SQ_WAKEUP)
9443 wake_up(&ctx->sq_data->wait);
9444 if (flags & IORING_ENTER_SQ_WAIT) {
9445 ret = io_sqpoll_wait_sq(ctx);
9449 submitted = to_submit;
9450 } else if (to_submit) {
9451 ret = io_uring_add_tctx_node(ctx);
9454 mutex_lock(&ctx->uring_lock);
9455 submitted = io_submit_sqes(ctx, to_submit);
9456 mutex_unlock(&ctx->uring_lock);
9458 if (submitted != to_submit)
9461 if (flags & IORING_ENTER_GETEVENTS) {
9462 const sigset_t __user *sig;
9463 struct __kernel_timespec __user *ts;
9465 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9469 min_complete = min(min_complete, ctx->cq_entries);
9472 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9473 * space applications don't need to do io completion events
9474 * polling again, they can rely on io_sq_thread to do polling
9475 * work, which can reduce cpu usage and uring_lock contention.
9477 if (ctx->flags & IORING_SETUP_IOPOLL &&
9478 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9479 ret = io_iopoll_check(ctx, min_complete);
9481 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9486 percpu_ref_put(&ctx->refs);
9489 return submitted ? submitted : ret;
9492 #ifdef CONFIG_PROC_FS
9493 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9494 const struct cred *cred)
9496 struct user_namespace *uns = seq_user_ns(m);
9497 struct group_info *gi;
9502 seq_printf(m, "%5d\n", id);
9503 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9504 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9505 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9506 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9507 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9508 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9509 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9510 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9511 seq_puts(m, "\n\tGroups:\t");
9512 gi = cred->group_info;
9513 for (g = 0; g < gi->ngroups; g++) {
9514 seq_put_decimal_ull(m, g ? " " : "",
9515 from_kgid_munged(uns, gi->gid[g]));
9517 seq_puts(m, "\n\tCapEff:\t");
9518 cap = cred->cap_effective;
9519 CAP_FOR_EACH_U32(__capi)
9520 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9525 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9527 struct io_sq_data *sq = NULL;
9532 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9533 * since fdinfo case grabs it in the opposite direction of normal use
9534 * cases. If we fail to get the lock, we just don't iterate any
9535 * structures that could be going away outside the io_uring mutex.
9537 has_lock = mutex_trylock(&ctx->uring_lock);
9539 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9545 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9546 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9547 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9548 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9549 struct file *f = io_file_from_index(ctx, i);
9552 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9554 seq_printf(m, "%5u: <none>\n", i);
9556 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9557 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9558 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9559 unsigned int len = buf->ubuf_end - buf->ubuf;
9561 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9563 if (has_lock && !xa_empty(&ctx->personalities)) {
9564 unsigned long index;
9565 const struct cred *cred;
9567 seq_printf(m, "Personalities:\n");
9568 xa_for_each(&ctx->personalities, index, cred)
9569 io_uring_show_cred(m, index, cred);
9571 seq_printf(m, "PollList:\n");
9572 spin_lock(&ctx->completion_lock);
9573 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9574 struct hlist_head *list = &ctx->cancel_hash[i];
9575 struct io_kiocb *req;
9577 hlist_for_each_entry(req, list, hash_node)
9578 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9579 req->task->task_works != NULL);
9581 spin_unlock(&ctx->completion_lock);
9583 mutex_unlock(&ctx->uring_lock);
9586 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9588 struct io_ring_ctx *ctx = f->private_data;
9590 if (percpu_ref_tryget(&ctx->refs)) {
9591 __io_uring_show_fdinfo(ctx, m);
9592 percpu_ref_put(&ctx->refs);
9597 static const struct file_operations io_uring_fops = {
9598 .release = io_uring_release,
9599 .mmap = io_uring_mmap,
9601 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9602 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9604 .poll = io_uring_poll,
9605 .fasync = io_uring_fasync,
9606 #ifdef CONFIG_PROC_FS
9607 .show_fdinfo = io_uring_show_fdinfo,
9611 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9612 struct io_uring_params *p)
9614 struct io_rings *rings;
9615 size_t size, sq_array_offset;
9617 /* make sure these are sane, as we already accounted them */
9618 ctx->sq_entries = p->sq_entries;
9619 ctx->cq_entries = p->cq_entries;
9621 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9622 if (size == SIZE_MAX)
9625 rings = io_mem_alloc(size);
9630 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9631 rings->sq_ring_mask = p->sq_entries - 1;
9632 rings->cq_ring_mask = p->cq_entries - 1;
9633 rings->sq_ring_entries = p->sq_entries;
9634 rings->cq_ring_entries = p->cq_entries;
9636 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9637 if (size == SIZE_MAX) {
9638 io_mem_free(ctx->rings);
9643 ctx->sq_sqes = io_mem_alloc(size);
9644 if (!ctx->sq_sqes) {
9645 io_mem_free(ctx->rings);
9653 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9657 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9661 ret = io_uring_add_tctx_node(ctx);
9666 fd_install(fd, file);
9671 * Allocate an anonymous fd, this is what constitutes the application
9672 * visible backing of an io_uring instance. The application mmaps this
9673 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9674 * we have to tie this fd to a socket for file garbage collection purposes.
9676 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9679 #if defined(CONFIG_UNIX)
9682 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9685 return ERR_PTR(ret);
9688 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9689 O_RDWR | O_CLOEXEC);
9690 #if defined(CONFIG_UNIX)
9692 sock_release(ctx->ring_sock);
9693 ctx->ring_sock = NULL;
9695 ctx->ring_sock->file = file;
9701 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9702 struct io_uring_params __user *params)
9704 struct io_ring_ctx *ctx;
9710 if (entries > IORING_MAX_ENTRIES) {
9711 if (!(p->flags & IORING_SETUP_CLAMP))
9713 entries = IORING_MAX_ENTRIES;
9717 * Use twice as many entries for the CQ ring. It's possible for the
9718 * application to drive a higher depth than the size of the SQ ring,
9719 * since the sqes are only used at submission time. This allows for
9720 * some flexibility in overcommitting a bit. If the application has
9721 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9722 * of CQ ring entries manually.
9724 p->sq_entries = roundup_pow_of_two(entries);
9725 if (p->flags & IORING_SETUP_CQSIZE) {
9727 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9728 * to a power-of-two, if it isn't already. We do NOT impose
9729 * any cq vs sq ring sizing.
9733 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9734 if (!(p->flags & IORING_SETUP_CLAMP))
9736 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9738 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9739 if (p->cq_entries < p->sq_entries)
9742 p->cq_entries = 2 * p->sq_entries;
9745 ctx = io_ring_ctx_alloc(p);
9748 ctx->compat = in_compat_syscall();
9749 if (!capable(CAP_IPC_LOCK))
9750 ctx->user = get_uid(current_user());
9753 * This is just grabbed for accounting purposes. When a process exits,
9754 * the mm is exited and dropped before the files, hence we need to hang
9755 * on to this mm purely for the purposes of being able to unaccount
9756 * memory (locked/pinned vm). It's not used for anything else.
9758 mmgrab(current->mm);
9759 ctx->mm_account = current->mm;
9761 ret = io_allocate_scq_urings(ctx, p);
9765 ret = io_sq_offload_create(ctx, p);
9768 /* always set a rsrc node */
9769 ret = io_rsrc_node_switch_start(ctx);
9772 io_rsrc_node_switch(ctx, NULL);
9774 memset(&p->sq_off, 0, sizeof(p->sq_off));
9775 p->sq_off.head = offsetof(struct io_rings, sq.head);
9776 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9777 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9778 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9779 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9780 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9781 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9783 memset(&p->cq_off, 0, sizeof(p->cq_off));
9784 p->cq_off.head = offsetof(struct io_rings, cq.head);
9785 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9786 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9787 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9788 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9789 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9790 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9792 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9793 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9794 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9795 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9796 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
9797 IORING_FEAT_RSRC_TAGS;
9799 if (copy_to_user(params, p, sizeof(*p))) {
9804 file = io_uring_get_file(ctx);
9806 ret = PTR_ERR(file);
9811 * Install ring fd as the very last thing, so we don't risk someone
9812 * having closed it before we finish setup
9814 ret = io_uring_install_fd(ctx, file);
9816 /* fput will clean it up */
9821 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9824 io_ring_ctx_wait_and_kill(ctx);
9829 * Sets up an aio uring context, and returns the fd. Applications asks for a
9830 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9831 * params structure passed in.
9833 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9835 struct io_uring_params p;
9838 if (copy_from_user(&p, params, sizeof(p)))
9840 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9845 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9846 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9847 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9848 IORING_SETUP_R_DISABLED))
9851 return io_uring_create(entries, &p, params);
9854 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9855 struct io_uring_params __user *, params)
9857 return io_uring_setup(entries, params);
9860 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9862 struct io_uring_probe *p;
9866 size = struct_size(p, ops, nr_args);
9867 if (size == SIZE_MAX)
9869 p = kzalloc(size, GFP_KERNEL);
9874 if (copy_from_user(p, arg, size))
9877 if (memchr_inv(p, 0, size))
9880 p->last_op = IORING_OP_LAST - 1;
9881 if (nr_args > IORING_OP_LAST)
9882 nr_args = IORING_OP_LAST;
9884 for (i = 0; i < nr_args; i++) {
9886 if (!io_op_defs[i].not_supported)
9887 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9892 if (copy_to_user(arg, p, size))
9899 static int io_register_personality(struct io_ring_ctx *ctx)
9901 const struct cred *creds;
9905 creds = get_current_cred();
9907 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9908 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9916 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9917 unsigned int nr_args)
9919 struct io_uring_restriction *res;
9923 /* Restrictions allowed only if rings started disabled */
9924 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9927 /* We allow only a single restrictions registration */
9928 if (ctx->restrictions.registered)
9931 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9934 size = array_size(nr_args, sizeof(*res));
9935 if (size == SIZE_MAX)
9938 res = memdup_user(arg, size);
9940 return PTR_ERR(res);
9944 for (i = 0; i < nr_args; i++) {
9945 switch (res[i].opcode) {
9946 case IORING_RESTRICTION_REGISTER_OP:
9947 if (res[i].register_op >= IORING_REGISTER_LAST) {
9952 __set_bit(res[i].register_op,
9953 ctx->restrictions.register_op);
9955 case IORING_RESTRICTION_SQE_OP:
9956 if (res[i].sqe_op >= IORING_OP_LAST) {
9961 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9963 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9964 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9966 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9967 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9976 /* Reset all restrictions if an error happened */
9978 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9980 ctx->restrictions.registered = true;
9986 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9988 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9991 if (ctx->restrictions.registered)
9992 ctx->restricted = 1;
9994 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9995 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9996 wake_up(&ctx->sq_data->wait);
10000 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10001 struct io_uring_rsrc_update2 *up,
10009 if (check_add_overflow(up->offset, nr_args, &tmp))
10011 err = io_rsrc_node_switch_start(ctx);
10016 case IORING_RSRC_FILE:
10017 return __io_sqe_files_update(ctx, up, nr_args);
10018 case IORING_RSRC_BUFFER:
10019 return __io_sqe_buffers_update(ctx, up, nr_args);
10024 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10027 struct io_uring_rsrc_update2 up;
10031 memset(&up, 0, sizeof(up));
10032 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10034 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10037 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10038 unsigned size, unsigned type)
10040 struct io_uring_rsrc_update2 up;
10042 if (size != sizeof(up))
10044 if (copy_from_user(&up, arg, sizeof(up)))
10046 if (!up.nr || up.resv)
10048 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10051 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10052 unsigned int size, unsigned int type)
10054 struct io_uring_rsrc_register rr;
10056 /* keep it extendible */
10057 if (size != sizeof(rr))
10060 memset(&rr, 0, sizeof(rr));
10061 if (copy_from_user(&rr, arg, size))
10063 if (!rr.nr || rr.resv || rr.resv2)
10067 case IORING_RSRC_FILE:
10068 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10069 rr.nr, u64_to_user_ptr(rr.tags));
10070 case IORING_RSRC_BUFFER:
10071 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10072 rr.nr, u64_to_user_ptr(rr.tags));
10077 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10080 struct io_uring_task *tctx = current->io_uring;
10081 cpumask_var_t new_mask;
10084 if (!tctx || !tctx->io_wq)
10087 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10090 cpumask_clear(new_mask);
10091 if (len > cpumask_size())
10092 len = cpumask_size();
10094 if (copy_from_user(new_mask, arg, len)) {
10095 free_cpumask_var(new_mask);
10099 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10100 free_cpumask_var(new_mask);
10104 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10106 struct io_uring_task *tctx = current->io_uring;
10108 if (!tctx || !tctx->io_wq)
10111 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10114 static bool io_register_op_must_quiesce(int op)
10117 case IORING_REGISTER_BUFFERS:
10118 case IORING_UNREGISTER_BUFFERS:
10119 case IORING_REGISTER_FILES:
10120 case IORING_UNREGISTER_FILES:
10121 case IORING_REGISTER_FILES_UPDATE:
10122 case IORING_REGISTER_PROBE:
10123 case IORING_REGISTER_PERSONALITY:
10124 case IORING_UNREGISTER_PERSONALITY:
10125 case IORING_REGISTER_FILES2:
10126 case IORING_REGISTER_FILES_UPDATE2:
10127 case IORING_REGISTER_BUFFERS2:
10128 case IORING_REGISTER_BUFFERS_UPDATE:
10129 case IORING_REGISTER_IOWQ_AFF:
10130 case IORING_UNREGISTER_IOWQ_AFF:
10137 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10141 percpu_ref_kill(&ctx->refs);
10144 * Drop uring mutex before waiting for references to exit. If another
10145 * thread is currently inside io_uring_enter() it might need to grab the
10146 * uring_lock to make progress. If we hold it here across the drain
10147 * wait, then we can deadlock. It's safe to drop the mutex here, since
10148 * no new references will come in after we've killed the percpu ref.
10150 mutex_unlock(&ctx->uring_lock);
10152 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10155 ret = io_run_task_work_sig();
10156 } while (ret >= 0);
10157 mutex_lock(&ctx->uring_lock);
10160 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10164 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10165 void __user *arg, unsigned nr_args)
10166 __releases(ctx->uring_lock)
10167 __acquires(ctx->uring_lock)
10172 * We're inside the ring mutex, if the ref is already dying, then
10173 * someone else killed the ctx or is already going through
10174 * io_uring_register().
10176 if (percpu_ref_is_dying(&ctx->refs))
10179 if (ctx->restricted) {
10180 if (opcode >= IORING_REGISTER_LAST)
10182 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10183 if (!test_bit(opcode, ctx->restrictions.register_op))
10187 if (io_register_op_must_quiesce(opcode)) {
10188 ret = io_ctx_quiesce(ctx);
10194 case IORING_REGISTER_BUFFERS:
10195 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10197 case IORING_UNREGISTER_BUFFERS:
10199 if (arg || nr_args)
10201 ret = io_sqe_buffers_unregister(ctx);
10203 case IORING_REGISTER_FILES:
10204 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10206 case IORING_UNREGISTER_FILES:
10208 if (arg || nr_args)
10210 ret = io_sqe_files_unregister(ctx);
10212 case IORING_REGISTER_FILES_UPDATE:
10213 ret = io_register_files_update(ctx, arg, nr_args);
10215 case IORING_REGISTER_EVENTFD:
10216 case IORING_REGISTER_EVENTFD_ASYNC:
10220 ret = io_eventfd_register(ctx, arg);
10223 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10224 ctx->eventfd_async = 1;
10226 ctx->eventfd_async = 0;
10228 case IORING_UNREGISTER_EVENTFD:
10230 if (arg || nr_args)
10232 ret = io_eventfd_unregister(ctx);
10234 case IORING_REGISTER_PROBE:
10236 if (!arg || nr_args > 256)
10238 ret = io_probe(ctx, arg, nr_args);
10240 case IORING_REGISTER_PERSONALITY:
10242 if (arg || nr_args)
10244 ret = io_register_personality(ctx);
10246 case IORING_UNREGISTER_PERSONALITY:
10250 ret = io_unregister_personality(ctx, nr_args);
10252 case IORING_REGISTER_ENABLE_RINGS:
10254 if (arg || nr_args)
10256 ret = io_register_enable_rings(ctx);
10258 case IORING_REGISTER_RESTRICTIONS:
10259 ret = io_register_restrictions(ctx, arg, nr_args);
10261 case IORING_REGISTER_FILES2:
10262 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10264 case IORING_REGISTER_FILES_UPDATE2:
10265 ret = io_register_rsrc_update(ctx, arg, nr_args,
10268 case IORING_REGISTER_BUFFERS2:
10269 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10271 case IORING_REGISTER_BUFFERS_UPDATE:
10272 ret = io_register_rsrc_update(ctx, arg, nr_args,
10273 IORING_RSRC_BUFFER);
10275 case IORING_REGISTER_IOWQ_AFF:
10277 if (!arg || !nr_args)
10279 ret = io_register_iowq_aff(ctx, arg, nr_args);
10281 case IORING_UNREGISTER_IOWQ_AFF:
10283 if (arg || nr_args)
10285 ret = io_unregister_iowq_aff(ctx);
10292 if (io_register_op_must_quiesce(opcode)) {
10293 /* bring the ctx back to life */
10294 percpu_ref_reinit(&ctx->refs);
10295 reinit_completion(&ctx->ref_comp);
10300 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10301 void __user *, arg, unsigned int, nr_args)
10303 struct io_ring_ctx *ctx;
10312 if (f.file->f_op != &io_uring_fops)
10315 ctx = f.file->private_data;
10317 io_run_task_work();
10319 mutex_lock(&ctx->uring_lock);
10320 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10321 mutex_unlock(&ctx->uring_lock);
10322 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10323 ctx->cq_ev_fd != NULL, ret);
10329 static int __init io_uring_init(void)
10331 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10332 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10333 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10336 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10337 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10338 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10339 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10340 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10341 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10342 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10343 BUILD_BUG_SQE_ELEM(8, __u64, off);
10344 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10345 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10346 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10347 BUILD_BUG_SQE_ELEM(24, __u32, len);
10348 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10349 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10350 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10351 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10352 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10353 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10354 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10355 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10356 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10357 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10358 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10359 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10360 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10361 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10362 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10363 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10364 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10365 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10366 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10367 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10369 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
10370 sizeof(struct io_uring_rsrc_update));
10371 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
10372 sizeof(struct io_uring_rsrc_update2));
10373 /* should fit into one byte */
10374 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
10376 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10377 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10379 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10383 __initcall(io_uring_init);