1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/tracehook.h>
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
86 #include <uapi/linux/io_uring.h>
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
93 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96 #define IORING_MAX_FIXED_FILES (1U << 15)
97 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
98 IORING_REGISTER_LAST + IORING_OP_LAST)
100 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
101 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
102 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
104 #define IORING_MAX_REG_BUFFERS (1U << 14)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
109 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
110 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
112 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
115 u32 head ____cacheline_aligned_in_smp;
116 u32 tail ____cacheline_aligned_in_smp;
120 * This data is shared with the application through the mmap at offsets
121 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
123 * The offsets to the member fields are published through struct
124 * io_sqring_offsets when calling io_uring_setup.
128 * Head and tail offsets into the ring; the offsets need to be
129 * masked to get valid indices.
131 * The kernel controls head of the sq ring and the tail of the cq ring,
132 * and the application controls tail of the sq ring and the head of the
135 struct io_uring sq, cq;
137 * Bitmasks to apply to head and tail offsets (constant, equals
140 u32 sq_ring_mask, cq_ring_mask;
141 /* Ring sizes (constant, power of 2) */
142 u32 sq_ring_entries, cq_ring_entries;
144 * Number of invalid entries dropped by the kernel due to
145 * invalid index stored in array
147 * Written by the kernel, shouldn't be modified by the
148 * application (i.e. get number of "new events" by comparing to
151 * After a new SQ head value was read by the application this
152 * counter includes all submissions that were dropped reaching
153 * the new SQ head (and possibly more).
159 * Written by the kernel, shouldn't be modified by the
162 * The application needs a full memory barrier before checking
163 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
169 * Written by the application, shouldn't be modified by the
174 * Number of completion events lost because the queue was full;
175 * this should be avoided by the application by making sure
176 * there are not more requests pending than there is space in
177 * the completion queue.
179 * Written by the kernel, shouldn't be modified by the
180 * application (i.e. get number of "new events" by comparing to
183 * As completion events come in out of order this counter is not
184 * ordered with any other data.
188 * Ring buffer of completion events.
190 * The kernel writes completion events fresh every time they are
191 * produced, so the application is allowed to modify pending
194 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
197 enum io_uring_cmd_flags {
198 IO_URING_F_NONBLOCK = 1,
199 IO_URING_F_COMPLETE_DEFER = 2,
202 struct io_mapped_ubuf {
205 unsigned int nr_bvecs;
206 unsigned long acct_pages;
207 struct bio_vec bvec[];
212 struct io_overflow_cqe {
213 struct io_uring_cqe cqe;
214 struct list_head list;
217 struct io_fixed_file {
218 /* file * with additional FFS_* flags */
219 unsigned long file_ptr;
223 struct list_head list;
228 struct io_mapped_ubuf *buf;
232 struct io_file_table {
233 struct io_fixed_file *files;
236 struct io_rsrc_node {
237 struct percpu_ref refs;
238 struct list_head node;
239 struct list_head rsrc_list;
240 struct io_rsrc_data *rsrc_data;
241 struct llist_node llist;
245 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
247 struct io_rsrc_data {
248 struct io_ring_ctx *ctx;
254 struct completion done;
259 struct list_head list;
265 struct io_restriction {
266 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
267 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
268 u8 sqe_flags_allowed;
269 u8 sqe_flags_required;
274 IO_SQ_THREAD_SHOULD_STOP = 0,
275 IO_SQ_THREAD_SHOULD_PARK,
280 atomic_t park_pending;
283 /* ctx's that are using this sqd */
284 struct list_head ctx_list;
286 struct task_struct *thread;
287 struct wait_queue_head wait;
289 unsigned sq_thread_idle;
295 struct completion exited;
298 #define IO_COMPL_BATCH 32
299 #define IO_REQ_CACHE_SIZE 32
300 #define IO_REQ_ALLOC_BATCH 8
302 struct io_submit_link {
303 struct io_kiocb *head;
304 struct io_kiocb *last;
307 struct io_submit_state {
308 struct blk_plug plug;
309 struct io_submit_link link;
312 * io_kiocb alloc cache
314 void *reqs[IO_REQ_CACHE_SIZE];
315 unsigned int free_reqs;
320 * Batch completion logic
322 struct io_kiocb *compl_reqs[IO_COMPL_BATCH];
323 unsigned int compl_nr;
324 /* inline/task_work completion list, under ->uring_lock */
325 struct list_head free_list;
327 unsigned int ios_left;
331 /* const or read-mostly hot data */
333 struct percpu_ref refs;
335 struct io_rings *rings;
337 unsigned int compat: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int off_timeout_used: 1;
342 unsigned int drain_active: 1;
343 } ____cacheline_aligned_in_smp;
345 /* submission data */
347 struct mutex uring_lock;
350 * Ring buffer of indices into array of io_uring_sqe, which is
351 * mmapped by the application using the IORING_OFF_SQES offset.
353 * This indirection could e.g. be used to assign fixed
354 * io_uring_sqe entries to operations and only submit them to
355 * the queue when needed.
357 * The kernel modifies neither the indices array nor the entries
361 struct io_uring_sqe *sq_sqes;
362 unsigned cached_sq_head;
364 struct list_head defer_list;
367 * Fixed resources fast path, should be accessed only under
368 * uring_lock, and updated through io_uring_register(2)
370 struct io_rsrc_node *rsrc_node;
371 struct io_file_table file_table;
372 unsigned nr_user_files;
373 unsigned nr_user_bufs;
374 struct io_mapped_ubuf **user_bufs;
376 struct io_submit_state submit_state;
377 struct list_head timeout_list;
378 struct list_head ltimeout_list;
379 struct list_head cq_overflow_list;
380 struct xarray io_buffers;
381 struct xarray personalities;
383 unsigned sq_thread_idle;
384 } ____cacheline_aligned_in_smp;
386 /* IRQ completion list, under ->completion_lock */
387 struct list_head locked_free_list;
388 unsigned int locked_free_nr;
390 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
391 struct io_sq_data *sq_data; /* if using sq thread polling */
393 struct wait_queue_head sqo_sq_wait;
394 struct list_head sqd_list;
396 unsigned long check_cq_overflow;
399 unsigned cached_cq_tail;
401 struct eventfd_ctx *cq_ev_fd;
402 struct wait_queue_head poll_wait;
403 struct wait_queue_head cq_wait;
405 atomic_t cq_timeouts;
406 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;
460 bool iowq_limits_set;
464 struct io_uring_task {
465 /* submission side */
468 struct wait_queue_head wait;
469 const struct io_ring_ctx *last;
471 struct percpu_counter inflight;
472 atomic_t inflight_tracked;
475 spinlock_t task_lock;
476 struct io_wq_work_list task_list;
477 struct callback_head task_work;
482 * First field must be the file pointer in all the
483 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
485 struct io_poll_iocb {
487 struct wait_queue_head *head;
489 struct wait_queue_entry wait;
492 struct io_poll_update {
498 bool update_user_data;
507 struct io_timeout_data {
508 struct io_kiocb *req;
509 struct hrtimer timer;
510 struct timespec64 ts;
511 enum hrtimer_mode mode;
517 struct sockaddr __user *addr;
518 int __user *addr_len;
521 unsigned long nofile;
541 struct list_head list;
542 /* head of the link, used by linked timeouts only */
543 struct io_kiocb *head;
544 /* for linked completions */
545 struct io_kiocb *prev;
548 struct io_timeout_rem {
553 struct timespec64 ts;
559 /* NOTE: kiocb has the file as the first member, so don't do it here */
567 struct sockaddr __user *addr;
574 struct compat_msghdr __user *umsg_compat;
575 struct user_msghdr __user *umsg;
581 struct io_buffer *kbuf;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
674 struct filename *filename;
680 struct filename *oldpath;
681 struct filename *newpath;
688 struct filename *oldpath;
689 struct filename *newpath;
693 struct io_completion {
698 struct io_async_connect {
699 struct sockaddr_storage address;
702 struct io_async_msghdr {
703 struct iovec fast_iov[UIO_FASTIOV];
704 /* points to an allocated iov, if NULL we use fast_iov instead */
705 struct iovec *free_iov;
706 struct sockaddr __user *uaddr;
708 struct sockaddr_storage addr;
712 struct iovec fast_iov[UIO_FASTIOV];
713 const struct iovec *free_iovec;
714 struct iov_iter iter;
715 struct iov_iter_state iter_state;
717 struct wait_page_queue wpq;
721 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
722 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
723 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
724 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
725 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
726 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
728 /* first byte is taken by user flags, shift it to not overlap */
733 REQ_F_LINK_TIMEOUT_BIT,
734 REQ_F_NEED_CLEANUP_BIT,
736 REQ_F_BUFFER_SELECTED_BIT,
737 REQ_F_COMPLETE_INLINE_BIT,
741 REQ_F_ARM_LTIMEOUT_BIT,
742 /* keep async read/write and isreg together and in order */
743 REQ_F_NOWAIT_READ_BIT,
744 REQ_F_NOWAIT_WRITE_BIT,
747 /* not a real bit, just to check we're not overflowing the space */
753 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
754 /* drain existing IO first */
755 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
757 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
758 /* doesn't sever on completion < 0 */
759 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
761 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
762 /* IOSQE_BUFFER_SELECT */
763 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
765 /* fail rest of links */
766 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
767 /* on inflight list, should be cancelled and waited on exit reliably */
768 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
769 /* read/write uses file position */
770 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
771 /* must not punt to workers */
772 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
773 /* has or had linked timeout */
774 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
776 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
777 /* already went through poll handler */
778 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
779 /* buffer already selected */
780 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
781 /* completion is deferred through io_comp_state */
782 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
783 /* caller should reissue async */
784 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
785 /* supports async reads */
786 REQ_F_NOWAIT_READ = BIT(REQ_F_NOWAIT_READ_BIT),
787 /* supports async writes */
788 REQ_F_NOWAIT_WRITE = BIT(REQ_F_NOWAIT_WRITE_BIT),
790 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
791 /* has creds assigned */
792 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
793 /* skip refcounting if not set */
794 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
795 /* there is a linked timeout that has to be armed */
796 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
800 struct io_poll_iocb poll;
801 struct io_poll_iocb *double_poll;
804 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
806 struct io_task_work {
808 struct io_wq_work_node node;
809 struct llist_node fallback_node;
811 io_req_tw_func_t func;
815 IORING_RSRC_FILE = 0,
816 IORING_RSRC_BUFFER = 1,
820 * NOTE! Each of the iocb union members has the file pointer
821 * as the first entry in their struct definition. So you can
822 * access the file pointer through any of the sub-structs,
823 * or directly as just 'ki_filp' in this struct.
829 struct io_poll_iocb poll;
830 struct io_poll_update poll_update;
831 struct io_accept accept;
833 struct io_cancel cancel;
834 struct io_timeout timeout;
835 struct io_timeout_rem timeout_rem;
836 struct io_connect connect;
837 struct io_sr_msg sr_msg;
839 struct io_close close;
840 struct io_rsrc_update rsrc_update;
841 struct io_fadvise fadvise;
842 struct io_madvise madvise;
843 struct io_epoll epoll;
844 struct io_splice splice;
845 struct io_provide_buf pbuf;
846 struct io_statx statx;
847 struct io_shutdown shutdown;
848 struct io_rename rename;
849 struct io_unlink unlink;
850 struct io_mkdir mkdir;
851 struct io_symlink symlink;
852 struct io_hardlink hardlink;
853 /* use only after cleaning per-op data, see io_clean_op() */
854 struct io_completion compl;
857 /* opcode allocated if it needs to store data for async defer */
860 /* polled IO has completed */
866 struct io_ring_ctx *ctx;
869 struct task_struct *task;
872 struct io_kiocb *link;
873 struct percpu_ref *fixed_rsrc_refs;
875 /* used with ctx->iopoll_list with reads/writes */
876 struct list_head inflight_entry;
877 struct io_task_work io_task_work;
878 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
879 struct hlist_node hash_node;
880 struct async_poll *apoll;
881 struct io_wq_work work;
882 const struct cred *creds;
884 /* store used ubuf, so we can prevent reloading */
885 struct io_mapped_ubuf *imu;
886 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
887 struct io_buffer *kbuf;
891 struct io_tctx_node {
892 struct list_head ctx_node;
893 struct task_struct *task;
894 struct io_ring_ctx *ctx;
897 struct io_defer_entry {
898 struct list_head list;
899 struct io_kiocb *req;
904 /* needs req->file assigned */
905 unsigned needs_file : 1;
906 /* hash wq insertion if file is a regular file */
907 unsigned hash_reg_file : 1;
908 /* unbound wq insertion if file is a non-regular file */
909 unsigned unbound_nonreg_file : 1;
910 /* opcode is not supported by this kernel */
911 unsigned not_supported : 1;
912 /* set if opcode supports polled "wait" */
914 unsigned pollout : 1;
915 /* op supports buffer selection */
916 unsigned buffer_select : 1;
917 /* do prep async if is going to be punted */
918 unsigned needs_async_setup : 1;
919 /* should block plug */
921 /* size of async data needed, if any */
922 unsigned short async_size;
925 static const struct io_op_def io_op_defs[] = {
926 [IORING_OP_NOP] = {},
927 [IORING_OP_READV] = {
929 .unbound_nonreg_file = 1,
932 .needs_async_setup = 1,
934 .async_size = sizeof(struct io_async_rw),
936 [IORING_OP_WRITEV] = {
939 .unbound_nonreg_file = 1,
941 .needs_async_setup = 1,
943 .async_size = sizeof(struct io_async_rw),
945 [IORING_OP_FSYNC] = {
948 [IORING_OP_READ_FIXED] = {
950 .unbound_nonreg_file = 1,
953 .async_size = sizeof(struct io_async_rw),
955 [IORING_OP_WRITE_FIXED] = {
958 .unbound_nonreg_file = 1,
961 .async_size = sizeof(struct io_async_rw),
963 [IORING_OP_POLL_ADD] = {
965 .unbound_nonreg_file = 1,
967 [IORING_OP_POLL_REMOVE] = {},
968 [IORING_OP_SYNC_FILE_RANGE] = {
971 [IORING_OP_SENDMSG] = {
973 .unbound_nonreg_file = 1,
975 .needs_async_setup = 1,
976 .async_size = sizeof(struct io_async_msghdr),
978 [IORING_OP_RECVMSG] = {
980 .unbound_nonreg_file = 1,
983 .needs_async_setup = 1,
984 .async_size = sizeof(struct io_async_msghdr),
986 [IORING_OP_TIMEOUT] = {
987 .async_size = sizeof(struct io_timeout_data),
989 [IORING_OP_TIMEOUT_REMOVE] = {
990 /* used by timeout updates' prep() */
992 [IORING_OP_ACCEPT] = {
994 .unbound_nonreg_file = 1,
997 [IORING_OP_ASYNC_CANCEL] = {},
998 [IORING_OP_LINK_TIMEOUT] = {
999 .async_size = sizeof(struct io_timeout_data),
1001 [IORING_OP_CONNECT] = {
1003 .unbound_nonreg_file = 1,
1005 .needs_async_setup = 1,
1006 .async_size = sizeof(struct io_async_connect),
1008 [IORING_OP_FALLOCATE] = {
1011 [IORING_OP_OPENAT] = {},
1012 [IORING_OP_CLOSE] = {},
1013 [IORING_OP_FILES_UPDATE] = {},
1014 [IORING_OP_STATX] = {},
1015 [IORING_OP_READ] = {
1017 .unbound_nonreg_file = 1,
1021 .async_size = sizeof(struct io_async_rw),
1023 [IORING_OP_WRITE] = {
1026 .unbound_nonreg_file = 1,
1029 .async_size = sizeof(struct io_async_rw),
1031 [IORING_OP_FADVISE] = {
1034 [IORING_OP_MADVISE] = {},
1035 [IORING_OP_SEND] = {
1037 .unbound_nonreg_file = 1,
1040 [IORING_OP_RECV] = {
1042 .unbound_nonreg_file = 1,
1046 [IORING_OP_OPENAT2] = {
1048 [IORING_OP_EPOLL_CTL] = {
1049 .unbound_nonreg_file = 1,
1051 [IORING_OP_SPLICE] = {
1054 .unbound_nonreg_file = 1,
1056 [IORING_OP_PROVIDE_BUFFERS] = {},
1057 [IORING_OP_REMOVE_BUFFERS] = {},
1061 .unbound_nonreg_file = 1,
1063 [IORING_OP_SHUTDOWN] = {
1066 [IORING_OP_RENAMEAT] = {},
1067 [IORING_OP_UNLINKAT] = {},
1068 [IORING_OP_MKDIRAT] = {},
1069 [IORING_OP_SYMLINKAT] = {},
1070 [IORING_OP_LINKAT] = {},
1073 /* requests with any of those set should undergo io_disarm_next() */
1074 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1076 static bool io_disarm_next(struct io_kiocb *req);
1077 static void io_uring_del_tctx_node(unsigned long index);
1078 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1079 struct task_struct *task,
1081 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1083 static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1085 static void io_put_req(struct io_kiocb *req);
1086 static void io_put_req_deferred(struct io_kiocb *req);
1087 static void io_dismantle_req(struct io_kiocb *req);
1088 static void io_queue_linked_timeout(struct io_kiocb *req);
1089 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1090 struct io_uring_rsrc_update2 *up,
1092 static void io_clean_op(struct io_kiocb *req);
1093 static struct file *io_file_get(struct io_ring_ctx *ctx,
1094 struct io_kiocb *req, int fd, bool fixed);
1095 static void __io_queue_sqe(struct io_kiocb *req);
1096 static void io_rsrc_put_work(struct work_struct *work);
1098 static void io_req_task_queue(struct io_kiocb *req);
1099 static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1100 static int io_req_prep_async(struct io_kiocb *req);
1102 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1103 unsigned int issue_flags, u32 slot_index);
1104 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1106 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1108 static struct kmem_cache *req_cachep;
1110 static const struct file_operations io_uring_fops;
1112 struct sock *io_uring_get_socket(struct file *file)
1114 #if defined(CONFIG_UNIX)
1115 if (file->f_op == &io_uring_fops) {
1116 struct io_ring_ctx *ctx = file->private_data;
1118 return ctx->ring_sock->sk;
1123 EXPORT_SYMBOL(io_uring_get_socket);
1125 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1128 mutex_lock(&ctx->uring_lock);
1133 #define io_for_each_link(pos, head) \
1134 for (pos = (head); pos; pos = pos->link)
1137 * Shamelessly stolen from the mm implementation of page reference checking,
1138 * see commit f958d7b528b1 for details.
1140 #define req_ref_zero_or_close_to_overflow(req) \
1141 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1143 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1145 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1146 return atomic_inc_not_zero(&req->refs);
1149 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1151 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1154 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1155 return atomic_dec_and_test(&req->refs);
1158 static inline void req_ref_put(struct io_kiocb *req)
1160 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1161 WARN_ON_ONCE(req_ref_put_and_test(req));
1164 static inline void req_ref_get(struct io_kiocb *req)
1166 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1167 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1168 atomic_inc(&req->refs);
1171 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1173 if (!(req->flags & REQ_F_REFCOUNT)) {
1174 req->flags |= REQ_F_REFCOUNT;
1175 atomic_set(&req->refs, nr);
1179 static inline void io_req_set_refcount(struct io_kiocb *req)
1181 __io_req_set_refcount(req, 1);
1184 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1186 struct io_ring_ctx *ctx = req->ctx;
1188 if (!req->fixed_rsrc_refs) {
1189 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1190 percpu_ref_get(req->fixed_rsrc_refs);
1194 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1196 bool got = percpu_ref_tryget(ref);
1198 /* already at zero, wait for ->release() */
1200 wait_for_completion(compl);
1201 percpu_ref_resurrect(ref);
1203 percpu_ref_put(ref);
1206 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1208 __must_hold(&req->ctx->timeout_lock)
1210 struct io_kiocb *req;
1212 if (task && head->task != task)
1217 io_for_each_link(req, head) {
1218 if (req->flags & REQ_F_INFLIGHT)
1224 static bool io_match_linked(struct io_kiocb *head)
1226 struct io_kiocb *req;
1228 io_for_each_link(req, head) {
1229 if (req->flags & REQ_F_INFLIGHT)
1236 * As io_match_task() but protected against racing with linked timeouts.
1237 * User must not hold timeout_lock.
1239 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1244 if (task && head->task != task)
1249 if (head->flags & REQ_F_LINK_TIMEOUT) {
1250 struct io_ring_ctx *ctx = head->ctx;
1252 /* protect against races with linked timeouts */
1253 spin_lock_irq(&ctx->timeout_lock);
1254 matched = io_match_linked(head);
1255 spin_unlock_irq(&ctx->timeout_lock);
1257 matched = io_match_linked(head);
1262 static inline void req_set_fail(struct io_kiocb *req)
1264 req->flags |= REQ_F_FAIL;
1267 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1273 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1275 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1277 complete(&ctx->ref_comp);
1280 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1282 return !req->timeout.off;
1285 static void io_fallback_req_func(struct work_struct *work)
1287 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1288 fallback_work.work);
1289 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1290 struct io_kiocb *req, *tmp;
1291 bool locked = false;
1293 percpu_ref_get(&ctx->refs);
1294 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1295 req->io_task_work.func(req, &locked);
1298 if (ctx->submit_state.compl_nr)
1299 io_submit_flush_completions(ctx);
1300 mutex_unlock(&ctx->uring_lock);
1302 percpu_ref_put(&ctx->refs);
1306 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1308 struct io_ring_ctx *ctx;
1311 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1316 * Use 5 bits less than the max cq entries, that should give us around
1317 * 32 entries per hash list if totally full and uniformly spread.
1319 hash_bits = ilog2(p->cq_entries);
1323 ctx->cancel_hash_bits = hash_bits;
1324 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1326 if (!ctx->cancel_hash)
1328 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1330 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1331 if (!ctx->dummy_ubuf)
1333 /* set invalid range, so io_import_fixed() fails meeting it */
1334 ctx->dummy_ubuf->ubuf = -1UL;
1336 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1337 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1340 ctx->flags = p->flags;
1341 init_waitqueue_head(&ctx->sqo_sq_wait);
1342 INIT_LIST_HEAD(&ctx->sqd_list);
1343 init_waitqueue_head(&ctx->poll_wait);
1344 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1345 init_completion(&ctx->ref_comp);
1346 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1347 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1348 mutex_init(&ctx->uring_lock);
1349 init_waitqueue_head(&ctx->cq_wait);
1350 spin_lock_init(&ctx->completion_lock);
1351 spin_lock_init(&ctx->timeout_lock);
1352 INIT_LIST_HEAD(&ctx->iopoll_list);
1353 INIT_LIST_HEAD(&ctx->defer_list);
1354 INIT_LIST_HEAD(&ctx->timeout_list);
1355 INIT_LIST_HEAD(&ctx->ltimeout_list);
1356 spin_lock_init(&ctx->rsrc_ref_lock);
1357 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1358 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1359 init_llist_head(&ctx->rsrc_put_llist);
1360 INIT_LIST_HEAD(&ctx->tctx_list);
1361 INIT_LIST_HEAD(&ctx->submit_state.free_list);
1362 INIT_LIST_HEAD(&ctx->locked_free_list);
1363 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1366 kfree(ctx->dummy_ubuf);
1367 kfree(ctx->cancel_hash);
1372 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1374 struct io_rings *r = ctx->rings;
1376 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1380 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1382 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1383 struct io_ring_ctx *ctx = req->ctx;
1385 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1391 #define FFS_ASYNC_READ 0x1UL
1392 #define FFS_ASYNC_WRITE 0x2UL
1394 #define FFS_ISREG 0x4UL
1396 #define FFS_ISREG 0x0UL
1398 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1400 static inline bool io_req_ffs_set(struct io_kiocb *req)
1402 return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1405 static void io_req_track_inflight(struct io_kiocb *req)
1407 if (!(req->flags & REQ_F_INFLIGHT)) {
1408 req->flags |= REQ_F_INFLIGHT;
1409 atomic_inc(&req->task->io_uring->inflight_tracked);
1413 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1415 if (WARN_ON_ONCE(!req->link))
1418 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1419 req->flags |= REQ_F_LINK_TIMEOUT;
1421 /* linked timeouts should have two refs once prep'ed */
1422 io_req_set_refcount(req);
1423 __io_req_set_refcount(req->link, 2);
1427 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1429 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1431 return __io_prep_linked_timeout(req);
1434 static void io_prep_async_work(struct io_kiocb *req)
1436 const struct io_op_def *def = &io_op_defs[req->opcode];
1437 struct io_ring_ctx *ctx = req->ctx;
1439 if (!(req->flags & REQ_F_CREDS)) {
1440 req->flags |= REQ_F_CREDS;
1441 req->creds = get_current_cred();
1444 req->work.list.next = NULL;
1445 req->work.flags = 0;
1446 if (req->flags & REQ_F_FORCE_ASYNC)
1447 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1449 if (req->flags & REQ_F_ISREG) {
1450 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1451 io_wq_hash_work(&req->work, file_inode(req->file));
1452 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1453 if (def->unbound_nonreg_file)
1454 req->work.flags |= IO_WQ_WORK_UNBOUND;
1458 static void io_prep_async_link(struct io_kiocb *req)
1460 struct io_kiocb *cur;
1462 if (req->flags & REQ_F_LINK_TIMEOUT) {
1463 struct io_ring_ctx *ctx = req->ctx;
1465 spin_lock_irq(&ctx->timeout_lock);
1466 io_for_each_link(cur, req)
1467 io_prep_async_work(cur);
1468 spin_unlock_irq(&ctx->timeout_lock);
1470 io_for_each_link(cur, req)
1471 io_prep_async_work(cur);
1475 static void io_queue_async_work(struct io_kiocb *req, bool *locked)
1477 struct io_ring_ctx *ctx = req->ctx;
1478 struct io_kiocb *link = io_prep_linked_timeout(req);
1479 struct io_uring_task *tctx = req->task->io_uring;
1481 /* must not take the lock, NULL it as a precaution */
1485 BUG_ON(!tctx->io_wq);
1487 /* init ->work of the whole link before punting */
1488 io_prep_async_link(req);
1491 * Not expected to happen, but if we do have a bug where this _can_
1492 * happen, catch it here and ensure the request is marked as
1493 * canceled. That will make io-wq go through the usual work cancel
1494 * procedure rather than attempt to run this request (or create a new
1497 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1498 req->work.flags |= IO_WQ_WORK_CANCEL;
1500 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1501 &req->work, req->flags);
1502 io_wq_enqueue(tctx->io_wq, &req->work);
1504 io_queue_linked_timeout(link);
1507 static void io_kill_timeout(struct io_kiocb *req, int status)
1508 __must_hold(&req->ctx->completion_lock)
1509 __must_hold(&req->ctx->timeout_lock)
1511 struct io_timeout_data *io = req->async_data;
1513 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1516 atomic_set(&req->ctx->cq_timeouts,
1517 atomic_read(&req->ctx->cq_timeouts) + 1);
1518 list_del_init(&req->timeout.list);
1519 io_fill_cqe_req(req, status, 0);
1520 io_put_req_deferred(req);
1524 static void io_queue_deferred(struct io_ring_ctx *ctx)
1526 while (!list_empty(&ctx->defer_list)) {
1527 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1528 struct io_defer_entry, list);
1530 if (req_need_defer(de->req, de->seq))
1532 list_del_init(&de->list);
1533 io_req_task_queue(de->req);
1538 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1539 __must_hold(&ctx->completion_lock)
1541 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1542 struct io_kiocb *req, *tmp;
1544 spin_lock_irq(&ctx->timeout_lock);
1545 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1546 u32 events_needed, events_got;
1548 if (io_is_timeout_noseq(req))
1552 * Since seq can easily wrap around over time, subtract
1553 * the last seq at which timeouts were flushed before comparing.
1554 * Assuming not more than 2^31-1 events have happened since,
1555 * these subtractions won't have wrapped, so we can check if
1556 * target is in [last_seq, current_seq] by comparing the two.
1558 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1559 events_got = seq - ctx->cq_last_tm_flush;
1560 if (events_got < events_needed)
1563 io_kill_timeout(req, 0);
1565 ctx->cq_last_tm_flush = seq;
1566 spin_unlock_irq(&ctx->timeout_lock);
1569 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1571 if (ctx->off_timeout_used)
1572 io_flush_timeouts(ctx);
1573 if (ctx->drain_active)
1574 io_queue_deferred(ctx);
1577 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1579 if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1580 __io_commit_cqring_flush(ctx);
1581 /* order cqe stores with ring update */
1582 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1585 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1587 struct io_rings *r = ctx->rings;
1589 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1592 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1594 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1597 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1599 struct io_rings *rings = ctx->rings;
1600 unsigned tail, mask = ctx->cq_entries - 1;
1603 * writes to the cq entry need to come after reading head; the
1604 * control dependency is enough as we're using WRITE_ONCE to
1607 if (__io_cqring_events(ctx) == ctx->cq_entries)
1610 tail = ctx->cached_cq_tail++;
1611 return &rings->cqes[tail & mask];
1614 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1616 if (likely(!ctx->cq_ev_fd))
1618 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1620 return !ctx->eventfd_async || io_wq_current_is_worker();
1624 * This should only get called when at least one event has been posted.
1625 * Some applications rely on the eventfd notification count only changing
1626 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1627 * 1:1 relationship between how many times this function is called (and
1628 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1630 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1633 * wake_up_all() may seem excessive, but io_wake_function() and
1634 * io_should_wake() handle the termination of the loop and only
1635 * wake as many waiters as we need to.
1637 if (wq_has_sleeper(&ctx->cq_wait))
1638 wake_up_all(&ctx->cq_wait);
1639 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1640 wake_up(&ctx->sq_data->wait);
1641 if (io_should_trigger_evfd(ctx))
1642 eventfd_signal(ctx->cq_ev_fd, 1);
1643 if (waitqueue_active(&ctx->poll_wait))
1644 wake_up_interruptible(&ctx->poll_wait);
1647 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1649 /* see waitqueue_active() comment */
1652 if (ctx->flags & IORING_SETUP_SQPOLL) {
1653 if (waitqueue_active(&ctx->cq_wait))
1654 wake_up_all(&ctx->cq_wait);
1656 if (io_should_trigger_evfd(ctx))
1657 eventfd_signal(ctx->cq_ev_fd, 1);
1658 if (waitqueue_active(&ctx->poll_wait))
1659 wake_up_interruptible(&ctx->poll_wait);
1662 /* Returns true if there are no backlogged entries after the flush */
1663 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1665 bool all_flushed, posted;
1667 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1671 spin_lock(&ctx->completion_lock);
1672 while (!list_empty(&ctx->cq_overflow_list)) {
1673 struct io_uring_cqe *cqe = io_get_cqe(ctx);
1674 struct io_overflow_cqe *ocqe;
1678 ocqe = list_first_entry(&ctx->cq_overflow_list,
1679 struct io_overflow_cqe, list);
1681 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1683 io_account_cq_overflow(ctx);
1686 list_del(&ocqe->list);
1690 all_flushed = list_empty(&ctx->cq_overflow_list);
1692 clear_bit(0, &ctx->check_cq_overflow);
1693 WRITE_ONCE(ctx->rings->sq_flags,
1694 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1698 io_commit_cqring(ctx);
1699 spin_unlock(&ctx->completion_lock);
1701 io_cqring_ev_posted(ctx);
1705 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1709 if (test_bit(0, &ctx->check_cq_overflow)) {
1710 /* iopoll syncs against uring_lock, not completion_lock */
1711 if (ctx->flags & IORING_SETUP_IOPOLL)
1712 mutex_lock(&ctx->uring_lock);
1713 ret = __io_cqring_overflow_flush(ctx, false);
1714 if (ctx->flags & IORING_SETUP_IOPOLL)
1715 mutex_unlock(&ctx->uring_lock);
1721 /* must to be called somewhat shortly after putting a request */
1722 static inline void io_put_task(struct task_struct *task, int nr)
1724 struct io_uring_task *tctx = task->io_uring;
1726 if (likely(task == current)) {
1727 tctx->cached_refs += nr;
1729 percpu_counter_sub(&tctx->inflight, nr);
1730 if (unlikely(atomic_read(&tctx->in_idle)))
1731 wake_up(&tctx->wait);
1732 put_task_struct_many(task, nr);
1736 static void io_task_refs_refill(struct io_uring_task *tctx)
1738 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1740 percpu_counter_add(&tctx->inflight, refill);
1741 refcount_add(refill, ¤t->usage);
1742 tctx->cached_refs += refill;
1745 static inline void io_get_task_refs(int nr)
1747 struct io_uring_task *tctx = current->io_uring;
1749 tctx->cached_refs -= nr;
1750 if (unlikely(tctx->cached_refs < 0))
1751 io_task_refs_refill(tctx);
1754 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
1756 struct io_uring_task *tctx = task->io_uring;
1757 unsigned int refs = tctx->cached_refs;
1760 tctx->cached_refs = 0;
1761 percpu_counter_sub(&tctx->inflight, refs);
1762 put_task_struct_many(task, refs);
1766 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1767 s32 res, u32 cflags)
1769 struct io_overflow_cqe *ocqe;
1771 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1774 * If we're in ring overflow flush mode, or in task cancel mode,
1775 * or cannot allocate an overflow entry, then we need to drop it
1778 io_account_cq_overflow(ctx);
1781 if (list_empty(&ctx->cq_overflow_list)) {
1782 set_bit(0, &ctx->check_cq_overflow);
1783 WRITE_ONCE(ctx->rings->sq_flags,
1784 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1787 ocqe->cqe.user_data = user_data;
1788 ocqe->cqe.res = res;
1789 ocqe->cqe.flags = cflags;
1790 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1794 static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
1795 s32 res, u32 cflags)
1797 struct io_uring_cqe *cqe;
1799 trace_io_uring_complete(ctx, user_data, res, cflags);
1802 * If we can't get a cq entry, userspace overflowed the
1803 * submission (by quite a lot). Increment the overflow count in
1806 cqe = io_get_cqe(ctx);
1808 WRITE_ONCE(cqe->user_data, user_data);
1809 WRITE_ONCE(cqe->res, res);
1810 WRITE_ONCE(cqe->flags, cflags);
1813 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1816 static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
1818 __io_fill_cqe(req->ctx, req->user_data, res, cflags);
1821 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
1822 s32 res, u32 cflags)
1825 return __io_fill_cqe(ctx, user_data, res, cflags);
1828 static void io_req_complete_post(struct io_kiocb *req, s32 res,
1831 struct io_ring_ctx *ctx = req->ctx;
1833 spin_lock(&ctx->completion_lock);
1834 __io_fill_cqe(ctx, req->user_data, res, cflags);
1836 * If we're the last reference to this request, add to our locked
1839 if (req_ref_put_and_test(req)) {
1840 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1841 if (req->flags & IO_DISARM_MASK)
1842 io_disarm_next(req);
1844 io_req_task_queue(req->link);
1848 io_dismantle_req(req);
1849 io_put_task(req->task, 1);
1850 list_add(&req->inflight_entry, &ctx->locked_free_list);
1851 ctx->locked_free_nr++;
1853 if (!percpu_ref_tryget(&ctx->refs))
1856 io_commit_cqring(ctx);
1857 spin_unlock(&ctx->completion_lock);
1860 io_cqring_ev_posted(ctx);
1861 percpu_ref_put(&ctx->refs);
1865 static inline bool io_req_needs_clean(struct io_kiocb *req)
1867 return req->flags & IO_REQ_CLEAN_FLAGS;
1870 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
1873 if (io_req_needs_clean(req))
1876 req->compl.cflags = cflags;
1877 req->flags |= REQ_F_COMPLETE_INLINE;
1880 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1881 s32 res, u32 cflags)
1883 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1884 io_req_complete_state(req, res, cflags);
1886 io_req_complete_post(req, res, cflags);
1889 static inline void io_req_complete(struct io_kiocb *req, s32 res)
1891 __io_req_complete(req, 0, res, 0);
1894 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
1897 io_req_complete_post(req, res, 0);
1900 static void io_req_complete_fail_submit(struct io_kiocb *req)
1903 * We don't submit, fail them all, for that replace hardlinks with
1904 * normal links. Extra REQ_F_LINK is tolerated.
1906 req->flags &= ~REQ_F_HARDLINK;
1907 req->flags |= REQ_F_LINK;
1908 io_req_complete_failed(req, req->result);
1912 * Don't initialise the fields below on every allocation, but do that in
1913 * advance and keep them valid across allocations.
1915 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1919 req->async_data = NULL;
1920 /* not necessary, but safer to zero */
1924 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1925 struct io_submit_state *state)
1927 spin_lock(&ctx->completion_lock);
1928 list_splice_init(&ctx->locked_free_list, &state->free_list);
1929 ctx->locked_free_nr = 0;
1930 spin_unlock(&ctx->completion_lock);
1933 /* Returns true IFF there are requests in the cache */
1934 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1936 struct io_submit_state *state = &ctx->submit_state;
1940 * If we have more than a batch's worth of requests in our IRQ side
1941 * locked cache, grab the lock and move them over to our submission
1944 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1945 io_flush_cached_locked_reqs(ctx, state);
1947 nr = state->free_reqs;
1948 while (!list_empty(&state->free_list)) {
1949 struct io_kiocb *req = list_first_entry(&state->free_list,
1950 struct io_kiocb, inflight_entry);
1952 list_del(&req->inflight_entry);
1953 state->reqs[nr++] = req;
1954 if (nr == ARRAY_SIZE(state->reqs))
1958 state->free_reqs = nr;
1963 * A request might get retired back into the request caches even before opcode
1964 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
1965 * Because of that, io_alloc_req() should be called only under ->uring_lock
1966 * and with extra caution to not get a request that is still worked on.
1968 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1969 __must_hold(&ctx->uring_lock)
1971 struct io_submit_state *state = &ctx->submit_state;
1972 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1975 BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1977 if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1980 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1984 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1985 * retry single alloc to be on the safe side.
1987 if (unlikely(ret <= 0)) {
1988 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1989 if (!state->reqs[0])
1994 for (i = 0; i < ret; i++)
1995 io_preinit_req(state->reqs[i], ctx);
1996 state->free_reqs = ret;
1999 return state->reqs[state->free_reqs];
2002 static inline void io_put_file(struct file *file)
2008 static void io_dismantle_req(struct io_kiocb *req)
2010 unsigned int flags = req->flags;
2012 if (io_req_needs_clean(req))
2014 if (!(flags & REQ_F_FIXED_FILE))
2015 io_put_file(req->file);
2016 if (req->fixed_rsrc_refs)
2017 percpu_ref_put(req->fixed_rsrc_refs);
2018 if (req->async_data) {
2019 kfree(req->async_data);
2020 req->async_data = NULL;
2024 static void __io_free_req(struct io_kiocb *req)
2026 struct io_ring_ctx *ctx = req->ctx;
2028 io_dismantle_req(req);
2029 io_put_task(req->task, 1);
2031 spin_lock(&ctx->completion_lock);
2032 list_add(&req->inflight_entry, &ctx->locked_free_list);
2033 ctx->locked_free_nr++;
2034 spin_unlock(&ctx->completion_lock);
2036 percpu_ref_put(&ctx->refs);
2039 static inline void io_remove_next_linked(struct io_kiocb *req)
2041 struct io_kiocb *nxt = req->link;
2043 req->link = nxt->link;
2047 static bool io_kill_linked_timeout(struct io_kiocb *req)
2048 __must_hold(&req->ctx->completion_lock)
2049 __must_hold(&req->ctx->timeout_lock)
2051 struct io_kiocb *link = req->link;
2053 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2054 struct io_timeout_data *io = link->async_data;
2056 io_remove_next_linked(req);
2057 link->timeout.head = NULL;
2058 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2059 list_del(&link->timeout.list);
2060 io_fill_cqe_req(link, -ECANCELED, 0);
2061 io_put_req_deferred(link);
2068 static void io_fail_links(struct io_kiocb *req)
2069 __must_hold(&req->ctx->completion_lock)
2071 struct io_kiocb *nxt, *link = req->link;
2075 long res = -ECANCELED;
2077 if (link->flags & REQ_F_FAIL)
2083 trace_io_uring_fail_link(req, link);
2084 io_fill_cqe_req(link, res, 0);
2085 io_put_req_deferred(link);
2090 static bool io_disarm_next(struct io_kiocb *req)
2091 __must_hold(&req->ctx->completion_lock)
2093 bool posted = false;
2095 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2096 struct io_kiocb *link = req->link;
2098 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2099 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2100 io_remove_next_linked(req);
2101 io_fill_cqe_req(link, -ECANCELED, 0);
2102 io_put_req_deferred(link);
2105 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2106 struct io_ring_ctx *ctx = req->ctx;
2108 spin_lock_irq(&ctx->timeout_lock);
2109 posted = io_kill_linked_timeout(req);
2110 spin_unlock_irq(&ctx->timeout_lock);
2112 if (unlikely((req->flags & REQ_F_FAIL) &&
2113 !(req->flags & REQ_F_HARDLINK))) {
2114 posted |= (req->link != NULL);
2120 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
2122 struct io_kiocb *nxt;
2125 * If LINK is set, we have dependent requests in this chain. If we
2126 * didn't fail this request, queue the first one up, moving any other
2127 * dependencies to the next request. In case of failure, fail the rest
2130 if (req->flags & IO_DISARM_MASK) {
2131 struct io_ring_ctx *ctx = req->ctx;
2134 spin_lock(&ctx->completion_lock);
2135 posted = io_disarm_next(req);
2137 io_commit_cqring(req->ctx);
2138 spin_unlock(&ctx->completion_lock);
2140 io_cqring_ev_posted(ctx);
2147 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2149 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2151 return __io_req_find_next(req);
2154 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2159 if (ctx->submit_state.compl_nr)
2160 io_submit_flush_completions(ctx);
2161 mutex_unlock(&ctx->uring_lock);
2164 percpu_ref_put(&ctx->refs);
2167 static void tctx_task_work(struct callback_head *cb)
2169 bool locked = false;
2170 struct io_ring_ctx *ctx = NULL;
2171 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2175 struct io_wq_work_node *node;
2177 if (!tctx->task_list.first && locked && ctx->submit_state.compl_nr)
2178 io_submit_flush_completions(ctx);
2180 spin_lock_irq(&tctx->task_lock);
2181 node = tctx->task_list.first;
2182 INIT_WQ_LIST(&tctx->task_list);
2184 tctx->task_running = false;
2185 spin_unlock_irq(&tctx->task_lock);
2190 struct io_wq_work_node *next = node->next;
2191 struct io_kiocb *req = container_of(node, struct io_kiocb,
2194 if (req->ctx != ctx) {
2195 ctx_flush_and_put(ctx, &locked);
2197 /* if not contended, grab and improve batching */
2198 locked = mutex_trylock(&ctx->uring_lock);
2199 percpu_ref_get(&ctx->refs);
2201 req->io_task_work.func(req, &locked);
2208 ctx_flush_and_put(ctx, &locked);
2210 /* relaxed read is enough as only the task itself sets ->in_idle */
2211 if (unlikely(atomic_read(&tctx->in_idle)))
2212 io_uring_drop_tctx_refs(current);
2215 static void io_req_task_work_add(struct io_kiocb *req)
2217 struct task_struct *tsk = req->task;
2218 struct io_uring_task *tctx = tsk->io_uring;
2219 enum task_work_notify_mode notify;
2220 struct io_wq_work_node *node;
2221 unsigned long flags;
2224 WARN_ON_ONCE(!tctx);
2226 spin_lock_irqsave(&tctx->task_lock, flags);
2227 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2228 running = tctx->task_running;
2230 tctx->task_running = true;
2231 spin_unlock_irqrestore(&tctx->task_lock, flags);
2233 /* task_work already pending, we're done */
2238 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2239 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2240 * processing task_work. There's no reliable way to tell if TWA_RESUME
2243 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2244 if (!task_work_add(tsk, &tctx->task_work, notify)) {
2245 wake_up_process(tsk);
2249 spin_lock_irqsave(&tctx->task_lock, flags);
2250 tctx->task_running = false;
2251 node = tctx->task_list.first;
2252 INIT_WQ_LIST(&tctx->task_list);
2253 spin_unlock_irqrestore(&tctx->task_lock, flags);
2256 req = container_of(node, struct io_kiocb, io_task_work.node);
2258 if (llist_add(&req->io_task_work.fallback_node,
2259 &req->ctx->fallback_llist))
2260 schedule_delayed_work(&req->ctx->fallback_work, 1);
2264 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2266 struct io_ring_ctx *ctx = req->ctx;
2268 /* not needed for normal modes, but SQPOLL depends on it */
2269 io_tw_lock(ctx, locked);
2270 io_req_complete_failed(req, req->result);
2273 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2275 struct io_ring_ctx *ctx = req->ctx;
2277 io_tw_lock(ctx, locked);
2278 /* req->task == current here, checking PF_EXITING is safe */
2279 if (likely(!(req->task->flags & PF_EXITING)))
2280 __io_queue_sqe(req);
2282 io_req_complete_failed(req, -EFAULT);
2285 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2288 req->io_task_work.func = io_req_task_cancel;
2289 io_req_task_work_add(req);
2292 static void io_req_task_queue(struct io_kiocb *req)
2294 req->io_task_work.func = io_req_task_submit;
2295 io_req_task_work_add(req);
2298 static void io_req_task_queue_reissue(struct io_kiocb *req)
2300 req->io_task_work.func = io_queue_async_work;
2301 io_req_task_work_add(req);
2304 static inline void io_queue_next(struct io_kiocb *req)
2306 struct io_kiocb *nxt = io_req_find_next(req);
2309 io_req_task_queue(nxt);
2312 static void io_free_req(struct io_kiocb *req)
2318 static void io_free_req_work(struct io_kiocb *req, bool *locked)
2324 struct task_struct *task;
2329 static inline void io_init_req_batch(struct req_batch *rb)
2336 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2337 struct req_batch *rb)
2340 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2342 io_put_task(rb->task, rb->task_refs);
2345 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2346 struct io_submit_state *state)
2349 io_dismantle_req(req);
2351 if (req->task != rb->task) {
2353 io_put_task(rb->task, rb->task_refs);
2354 rb->task = req->task;
2360 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2361 state->reqs[state->free_reqs++] = req;
2363 list_add(&req->inflight_entry, &state->free_list);
2366 static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2367 __must_hold(&ctx->uring_lock)
2369 struct io_submit_state *state = &ctx->submit_state;
2370 int i, nr = state->compl_nr;
2371 struct req_batch rb;
2373 spin_lock(&ctx->completion_lock);
2374 for (i = 0; i < nr; i++) {
2375 struct io_kiocb *req = state->compl_reqs[i];
2377 __io_fill_cqe(ctx, req->user_data, req->result,
2380 io_commit_cqring(ctx);
2381 spin_unlock(&ctx->completion_lock);
2382 io_cqring_ev_posted(ctx);
2384 io_init_req_batch(&rb);
2385 for (i = 0; i < nr; i++) {
2386 struct io_kiocb *req = state->compl_reqs[i];
2388 if (req_ref_put_and_test(req))
2389 io_req_free_batch(&rb, req, &ctx->submit_state);
2392 io_req_free_batch_finish(ctx, &rb);
2393 state->compl_nr = 0;
2397 * Drop reference to request, return next in chain (if there is one) if this
2398 * was the last reference to this request.
2400 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2402 struct io_kiocb *nxt = NULL;
2404 if (req_ref_put_and_test(req)) {
2405 nxt = io_req_find_next(req);
2411 static inline void io_put_req(struct io_kiocb *req)
2413 if (req_ref_put_and_test(req))
2417 static inline void io_put_req_deferred(struct io_kiocb *req)
2419 if (req_ref_put_and_test(req)) {
2420 req->io_task_work.func = io_free_req_work;
2421 io_req_task_work_add(req);
2425 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2427 /* See comment at the top of this file */
2429 return __io_cqring_events(ctx);
2432 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2434 struct io_rings *rings = ctx->rings;
2436 /* make sure SQ entry isn't read before tail */
2437 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2440 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2442 unsigned int cflags;
2444 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2445 cflags |= IORING_CQE_F_BUFFER;
2446 req->flags &= ~REQ_F_BUFFER_SELECTED;
2451 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2453 struct io_buffer *kbuf;
2455 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
2457 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2458 return io_put_kbuf(req, kbuf);
2461 static inline bool io_run_task_work(void)
2463 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2464 __set_current_state(TASK_RUNNING);
2465 tracehook_notify_signal();
2473 * Find and free completed poll iocbs
2475 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2476 struct list_head *done)
2478 struct req_batch rb;
2479 struct io_kiocb *req;
2481 /* order with ->result store in io_complete_rw_iopoll() */
2484 io_init_req_batch(&rb);
2485 while (!list_empty(done)) {
2486 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2487 list_del(&req->inflight_entry);
2489 io_fill_cqe_req(req, req->result, io_put_rw_kbuf(req));
2492 if (req_ref_put_and_test(req))
2493 io_req_free_batch(&rb, req, &ctx->submit_state);
2496 io_commit_cqring(ctx);
2497 io_cqring_ev_posted_iopoll(ctx);
2498 io_req_free_batch_finish(ctx, &rb);
2501 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2504 struct io_kiocb *req, *tmp;
2509 * Only spin for completions if we don't have multiple devices hanging
2510 * off our complete list, and we're under the requested amount.
2512 spin = !ctx->poll_multi_queue && *nr_events < min;
2514 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2515 struct kiocb *kiocb = &req->rw.kiocb;
2519 * Move completed and retryable entries to our local lists.
2520 * If we find a request that requires polling, break out
2521 * and complete those lists first, if we have entries there.
2523 if (READ_ONCE(req->iopoll_completed)) {
2524 list_move_tail(&req->inflight_entry, &done);
2527 if (!list_empty(&done))
2530 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2531 if (unlikely(ret < 0))
2536 /* iopoll may have completed current req */
2537 if (READ_ONCE(req->iopoll_completed))
2538 list_move_tail(&req->inflight_entry, &done);
2541 if (!list_empty(&done))
2542 io_iopoll_complete(ctx, nr_events, &done);
2548 * We can't just wait for polled events to come to us, we have to actively
2549 * find and complete them.
2551 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2553 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2556 mutex_lock(&ctx->uring_lock);
2557 while (!list_empty(&ctx->iopoll_list)) {
2558 unsigned int nr_events = 0;
2560 io_do_iopoll(ctx, &nr_events, 0);
2562 /* let it sleep and repeat later if can't complete a request */
2566 * Ensure we allow local-to-the-cpu processing to take place,
2567 * in this case we need to ensure that we reap all events.
2568 * Also let task_work, etc. to progress by releasing the mutex
2570 if (need_resched()) {
2571 mutex_unlock(&ctx->uring_lock);
2573 mutex_lock(&ctx->uring_lock);
2576 mutex_unlock(&ctx->uring_lock);
2579 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2581 unsigned int nr_events = 0;
2585 * We disallow the app entering submit/complete with polling, but we
2586 * still need to lock the ring to prevent racing with polled issue
2587 * that got punted to a workqueue.
2589 mutex_lock(&ctx->uring_lock);
2591 * Don't enter poll loop if we already have events pending.
2592 * If we do, we can potentially be spinning for commands that
2593 * already triggered a CQE (eg in error).
2595 if (test_bit(0, &ctx->check_cq_overflow))
2596 __io_cqring_overflow_flush(ctx, false);
2597 if (io_cqring_events(ctx))
2601 * If a submit got punted to a workqueue, we can have the
2602 * application entering polling for a command before it gets
2603 * issued. That app will hold the uring_lock for the duration
2604 * of the poll right here, so we need to take a breather every
2605 * now and then to ensure that the issue has a chance to add
2606 * the poll to the issued list. Otherwise we can spin here
2607 * forever, while the workqueue is stuck trying to acquire the
2610 if (list_empty(&ctx->iopoll_list)) {
2611 u32 tail = ctx->cached_cq_tail;
2613 mutex_unlock(&ctx->uring_lock);
2615 mutex_lock(&ctx->uring_lock);
2617 /* some requests don't go through iopoll_list */
2618 if (tail != ctx->cached_cq_tail ||
2619 list_empty(&ctx->iopoll_list))
2622 ret = io_do_iopoll(ctx, &nr_events, min);
2623 } while (!ret && nr_events < min && !need_resched());
2625 mutex_unlock(&ctx->uring_lock);
2629 static void kiocb_end_write(struct io_kiocb *req)
2632 * Tell lockdep we inherited freeze protection from submission
2635 if (req->flags & REQ_F_ISREG) {
2636 struct super_block *sb = file_inode(req->file)->i_sb;
2638 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2644 static bool io_resubmit_prep(struct io_kiocb *req)
2646 struct io_async_rw *rw = req->async_data;
2649 return !io_req_prep_async(req);
2650 iov_iter_restore(&rw->iter, &rw->iter_state);
2654 static bool io_rw_should_reissue(struct io_kiocb *req)
2656 umode_t mode = file_inode(req->file)->i_mode;
2657 struct io_ring_ctx *ctx = req->ctx;
2659 if (!S_ISBLK(mode) && !S_ISREG(mode))
2661 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2662 !(ctx->flags & IORING_SETUP_IOPOLL)))
2665 * If ref is dying, we might be running poll reap from the exit work.
2666 * Don't attempt to reissue from that path, just let it fail with
2669 if (percpu_ref_is_dying(&ctx->refs))
2672 * Play it safe and assume not safe to re-import and reissue if we're
2673 * not in the original thread group (or in task context).
2675 if (!same_thread_group(req->task, current) || !in_task())
2680 static bool io_resubmit_prep(struct io_kiocb *req)
2684 static bool io_rw_should_reissue(struct io_kiocb *req)
2690 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
2692 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
2693 kiocb_end_write(req);
2694 fsnotify_modify(req->file);
2696 fsnotify_access(req->file);
2698 if (res != req->result) {
2699 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2700 io_rw_should_reissue(req)) {
2701 req->flags |= REQ_F_REISSUE;
2710 static void io_req_task_complete(struct io_kiocb *req, bool *locked)
2712 unsigned int cflags = io_put_rw_kbuf(req);
2713 int res = req->result;
2716 struct io_ring_ctx *ctx = req->ctx;
2717 struct io_submit_state *state = &ctx->submit_state;
2719 io_req_complete_state(req, res, cflags);
2720 state->compl_reqs[state->compl_nr++] = req;
2721 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
2722 io_submit_flush_completions(ctx);
2724 io_req_complete_post(req, res, cflags);
2728 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2729 unsigned int issue_flags)
2731 if (__io_complete_rw_common(req, res))
2733 __io_req_complete(req, issue_flags, req->result, io_put_rw_kbuf(req));
2736 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2738 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2740 if (__io_complete_rw_common(req, res))
2743 req->io_task_work.func = io_req_task_complete;
2744 io_req_task_work_add(req);
2747 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2749 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2751 if (kiocb->ki_flags & IOCB_WRITE)
2752 kiocb_end_write(req);
2753 if (unlikely(res != req->result)) {
2754 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2755 req->flags |= REQ_F_REISSUE;
2760 WRITE_ONCE(req->result, res);
2761 /* order with io_iopoll_complete() checking ->result */
2763 WRITE_ONCE(req->iopoll_completed, 1);
2767 * After the iocb has been issued, it's safe to be found on the poll list.
2768 * Adding the kiocb to the list AFTER submission ensures that we don't
2769 * find it from a io_do_iopoll() thread before the issuer is done
2770 * accessing the kiocb cookie.
2772 static void io_iopoll_req_issued(struct io_kiocb *req)
2774 struct io_ring_ctx *ctx = req->ctx;
2775 const bool in_async = io_wq_current_is_worker();
2777 /* workqueue context doesn't hold uring_lock, grab it now */
2778 if (unlikely(in_async))
2779 mutex_lock(&ctx->uring_lock);
2782 * Track whether we have multiple files in our lists. This will impact
2783 * how we do polling eventually, not spinning if we're on potentially
2784 * different devices.
2786 if (list_empty(&ctx->iopoll_list)) {
2787 ctx->poll_multi_queue = false;
2788 } else if (!ctx->poll_multi_queue) {
2789 struct io_kiocb *list_req;
2790 unsigned int queue_num0, queue_num1;
2792 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2795 if (list_req->file != req->file) {
2796 ctx->poll_multi_queue = true;
2798 queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2799 queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2800 if (queue_num0 != queue_num1)
2801 ctx->poll_multi_queue = true;
2806 * For fast devices, IO may have already completed. If it has, add
2807 * it to the front so we find it first.
2809 if (READ_ONCE(req->iopoll_completed))
2810 list_add(&req->inflight_entry, &ctx->iopoll_list);
2812 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2814 if (unlikely(in_async)) {
2816 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2817 * in sq thread task context or in io worker task context. If
2818 * current task context is sq thread, we don't need to check
2819 * whether should wake up sq thread.
2821 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2822 wq_has_sleeper(&ctx->sq_data->wait))
2823 wake_up(&ctx->sq_data->wait);
2825 mutex_unlock(&ctx->uring_lock);
2829 static bool io_bdev_nowait(struct block_device *bdev)
2831 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2835 * If we tracked the file through the SCM inflight mechanism, we could support
2836 * any file. For now, just ensure that anything potentially problematic is done
2839 static bool __io_file_supports_nowait(struct file *file, int rw)
2841 umode_t mode = file_inode(file)->i_mode;
2843 if (S_ISBLK(mode)) {
2844 if (IS_ENABLED(CONFIG_BLOCK) &&
2845 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2851 if (S_ISREG(mode)) {
2852 if (IS_ENABLED(CONFIG_BLOCK) &&
2853 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2854 file->f_op != &io_uring_fops)
2859 /* any ->read/write should understand O_NONBLOCK */
2860 if (file->f_flags & O_NONBLOCK)
2863 if (!(file->f_mode & FMODE_NOWAIT))
2867 return file->f_op->read_iter != NULL;
2869 return file->f_op->write_iter != NULL;
2872 static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2874 if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2876 else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2879 return __io_file_supports_nowait(req->file, rw);
2882 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2885 struct io_ring_ctx *ctx = req->ctx;
2886 struct kiocb *kiocb = &req->rw.kiocb;
2887 struct file *file = req->file;
2891 if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2892 req->flags |= REQ_F_ISREG;
2894 kiocb->ki_pos = READ_ONCE(sqe->off);
2895 if (kiocb->ki_pos == -1) {
2896 if (!(file->f_mode & FMODE_STREAM)) {
2897 req->flags |= REQ_F_CUR_POS;
2898 kiocb->ki_pos = file->f_pos;
2903 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2904 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2905 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2910 * If the file is marked O_NONBLOCK, still allow retry for it if it
2911 * supports async. Otherwise it's impossible to use O_NONBLOCK files
2912 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
2914 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
2915 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req, rw)))
2916 req->flags |= REQ_F_NOWAIT;
2918 ioprio = READ_ONCE(sqe->ioprio);
2920 ret = ioprio_check_cap(ioprio);
2924 kiocb->ki_ioprio = ioprio;
2926 kiocb->ki_ioprio = get_current_ioprio();
2928 if (ctx->flags & IORING_SETUP_IOPOLL) {
2929 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2930 !kiocb->ki_filp->f_op->iopoll)
2933 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
2934 kiocb->ki_complete = io_complete_rw_iopoll;
2935 req->iopoll_completed = 0;
2937 if (kiocb->ki_flags & IOCB_HIPRI)
2939 kiocb->ki_complete = io_complete_rw;
2942 /* used for fixed read/write too - just read unconditionally */
2943 req->buf_index = READ_ONCE(sqe->buf_index);
2946 if (req->opcode == IORING_OP_READ_FIXED ||
2947 req->opcode == IORING_OP_WRITE_FIXED) {
2948 struct io_ring_ctx *ctx = req->ctx;
2951 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
2953 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
2954 req->imu = ctx->user_bufs[index];
2955 io_req_set_rsrc_node(req);
2958 req->rw.addr = READ_ONCE(sqe->addr);
2959 req->rw.len = READ_ONCE(sqe->len);
2963 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2969 case -ERESTARTNOINTR:
2970 case -ERESTARTNOHAND:
2971 case -ERESTART_RESTARTBLOCK:
2973 * We can't just restart the syscall, since previously
2974 * submitted sqes may already be in progress. Just fail this
2980 kiocb->ki_complete(kiocb, ret, 0);
2984 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2985 unsigned int issue_flags)
2987 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2988 struct io_async_rw *io = req->async_data;
2990 /* add previously done IO, if any */
2991 if (io && io->bytes_done > 0) {
2993 ret = io->bytes_done;
2995 ret += io->bytes_done;
2998 if (req->flags & REQ_F_CUR_POS)
2999 req->file->f_pos = kiocb->ki_pos;
3000 if (ret >= 0 && (kiocb->ki_complete == io_complete_rw))
3001 __io_complete_rw(req, ret, 0, issue_flags);
3003 io_rw_done(kiocb, ret);
3005 if (req->flags & REQ_F_REISSUE) {
3006 req->flags &= ~REQ_F_REISSUE;
3007 if (io_resubmit_prep(req)) {
3008 io_req_task_queue_reissue(req);
3010 unsigned int cflags = io_put_rw_kbuf(req);
3011 struct io_ring_ctx *ctx = req->ctx;
3014 if (!(issue_flags & IO_URING_F_NONBLOCK)) {
3015 mutex_lock(&ctx->uring_lock);
3016 __io_req_complete(req, issue_flags, ret, cflags);
3017 mutex_unlock(&ctx->uring_lock);
3019 __io_req_complete(req, issue_flags, ret, cflags);
3025 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3026 struct io_mapped_ubuf *imu)
3028 size_t len = req->rw.len;
3029 u64 buf_end, buf_addr = req->rw.addr;
3032 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3034 /* not inside the mapped region */
3035 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3039 * May not be a start of buffer, set size appropriately
3040 * and advance us to the beginning.
3042 offset = buf_addr - imu->ubuf;
3043 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3047 * Don't use iov_iter_advance() here, as it's really slow for
3048 * using the latter parts of a big fixed buffer - it iterates
3049 * over each segment manually. We can cheat a bit here, because
3052 * 1) it's a BVEC iter, we set it up
3053 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3054 * first and last bvec
3056 * So just find our index, and adjust the iterator afterwards.
3057 * If the offset is within the first bvec (or the whole first
3058 * bvec, just use iov_iter_advance(). This makes it easier
3059 * since we can just skip the first segment, which may not
3060 * be PAGE_SIZE aligned.
3062 const struct bio_vec *bvec = imu->bvec;
3064 if (offset <= bvec->bv_len) {
3065 iov_iter_advance(iter, offset);
3067 unsigned long seg_skip;
3069 /* skip first vec */
3070 offset -= bvec->bv_len;
3071 seg_skip = 1 + (offset >> PAGE_SHIFT);
3073 iter->bvec = bvec + seg_skip;
3074 iter->nr_segs -= seg_skip;
3075 iter->count -= bvec->bv_len + offset;
3076 iter->iov_offset = offset & ~PAGE_MASK;
3083 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3085 if (WARN_ON_ONCE(!req->imu))
3087 return __io_import_fixed(req, rw, iter, req->imu);
3090 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3093 mutex_unlock(&ctx->uring_lock);
3096 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3099 * "Normal" inline submissions always hold the uring_lock, since we
3100 * grab it from the system call. Same is true for the SQPOLL offload.
3101 * The only exception is when we've detached the request and issue it
3102 * from an async worker thread, grab the lock for that case.
3105 mutex_lock(&ctx->uring_lock);
3108 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
3109 int bgid, struct io_buffer *kbuf,
3112 struct io_buffer *head;
3114 if (req->flags & REQ_F_BUFFER_SELECTED)
3117 io_ring_submit_lock(req->ctx, needs_lock);
3119 lockdep_assert_held(&req->ctx->uring_lock);
3121 head = xa_load(&req->ctx->io_buffers, bgid);
3123 if (!list_empty(&head->list)) {
3124 kbuf = list_last_entry(&head->list, struct io_buffer,
3126 list_del(&kbuf->list);
3129 xa_erase(&req->ctx->io_buffers, bgid);
3131 if (*len > kbuf->len)
3134 kbuf = ERR_PTR(-ENOBUFS);
3137 io_ring_submit_unlock(req->ctx, needs_lock);
3142 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
3145 struct io_buffer *kbuf;
3148 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3149 bgid = req->buf_index;
3150 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
3153 req->rw.addr = (u64) (unsigned long) kbuf;
3154 req->flags |= REQ_F_BUFFER_SELECTED;
3155 return u64_to_user_ptr(kbuf->addr);
3158 #ifdef CONFIG_COMPAT
3159 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3162 struct compat_iovec __user *uiov;
3163 compat_ssize_t clen;
3167 uiov = u64_to_user_ptr(req->rw.addr);
3168 if (!access_ok(uiov, sizeof(*uiov)))
3170 if (__get_user(clen, &uiov->iov_len))
3176 buf = io_rw_buffer_select(req, &len, needs_lock);
3178 return PTR_ERR(buf);
3179 iov[0].iov_base = buf;
3180 iov[0].iov_len = (compat_size_t) len;
3185 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3188 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3192 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3195 len = iov[0].iov_len;
3198 buf = io_rw_buffer_select(req, &len, needs_lock);
3200 return PTR_ERR(buf);
3201 iov[0].iov_base = buf;
3202 iov[0].iov_len = len;
3206 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3209 if (req->flags & REQ_F_BUFFER_SELECTED) {
3210 struct io_buffer *kbuf;
3212 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3213 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3214 iov[0].iov_len = kbuf->len;
3217 if (req->rw.len != 1)
3220 #ifdef CONFIG_COMPAT
3221 if (req->ctx->compat)
3222 return io_compat_import(req, iov, needs_lock);
3225 return __io_iov_buffer_select(req, iov, needs_lock);
3228 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3229 struct iov_iter *iter, bool needs_lock)
3231 void __user *buf = u64_to_user_ptr(req->rw.addr);
3232 size_t sqe_len = req->rw.len;
3233 u8 opcode = req->opcode;
3236 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3238 return io_import_fixed(req, rw, iter);
3241 /* buffer index only valid with fixed read/write, or buffer select */
3242 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3245 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3246 if (req->flags & REQ_F_BUFFER_SELECT) {
3247 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3249 return PTR_ERR(buf);
3250 req->rw.len = sqe_len;
3253 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3258 if (req->flags & REQ_F_BUFFER_SELECT) {
3259 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3261 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3266 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3270 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3272 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3276 * For files that don't have ->read_iter() and ->write_iter(), handle them
3277 * by looping over ->read() or ->write() manually.
3279 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3281 struct kiocb *kiocb = &req->rw.kiocb;
3282 struct file *file = req->file;
3286 * Don't support polled IO through this interface, and we can't
3287 * support non-blocking either. For the latter, this just causes
3288 * the kiocb to be handled from an async context.
3290 if (kiocb->ki_flags & IOCB_HIPRI)
3292 if (kiocb->ki_flags & IOCB_NOWAIT)
3295 while (iov_iter_count(iter)) {
3299 if (!iov_iter_is_bvec(iter)) {
3300 iovec = iov_iter_iovec(iter);
3302 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3303 iovec.iov_len = req->rw.len;
3307 nr = file->f_op->read(file, iovec.iov_base,
3308 iovec.iov_len, io_kiocb_ppos(kiocb));
3310 nr = file->f_op->write(file, iovec.iov_base,
3311 iovec.iov_len, io_kiocb_ppos(kiocb));
3320 if (!iov_iter_is_bvec(iter)) {
3321 iov_iter_advance(iter, nr);
3328 if (nr != iovec.iov_len)
3335 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3336 const struct iovec *fast_iov, struct iov_iter *iter)
3338 struct io_async_rw *rw = req->async_data;
3340 memcpy(&rw->iter, iter, sizeof(*iter));
3341 rw->free_iovec = iovec;
3343 /* can only be fixed buffers, no need to do anything */
3344 if (iov_iter_is_bvec(iter))
3347 unsigned iov_off = 0;
3349 rw->iter.iov = rw->fast_iov;
3350 if (iter->iov != fast_iov) {
3351 iov_off = iter->iov - fast_iov;
3352 rw->iter.iov += iov_off;
3354 if (rw->fast_iov != fast_iov)
3355 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3356 sizeof(struct iovec) * iter->nr_segs);
3358 req->flags |= REQ_F_NEED_CLEANUP;
3362 static inline int io_alloc_async_data(struct io_kiocb *req)
3364 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3365 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3366 return req->async_data == NULL;
3369 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3370 const struct iovec *fast_iov,
3371 struct iov_iter *iter, bool force)
3373 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3375 if (!req->async_data) {
3376 struct io_async_rw *iorw;
3378 if (io_alloc_async_data(req)) {
3383 io_req_map_rw(req, iovec, fast_iov, iter);
3384 iorw = req->async_data;
3385 /* we've copied and mapped the iter, ensure state is saved */
3386 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3391 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3393 struct io_async_rw *iorw = req->async_data;
3394 struct iovec *iov = iorw->fast_iov;
3397 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3398 if (unlikely(ret < 0))
3401 iorw->bytes_done = 0;
3402 iorw->free_iovec = iov;
3404 req->flags |= REQ_F_NEED_CLEANUP;
3405 iov_iter_save_state(&iorw->iter, &iorw->iter_state);
3409 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3411 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3413 return io_prep_rw(req, sqe, READ);
3417 * This is our waitqueue callback handler, registered through lock_page_async()
3418 * when we initially tried to do the IO with the iocb armed our waitqueue.
3419 * This gets called when the page is unlocked, and we generally expect that to
3420 * happen when the page IO is completed and the page is now uptodate. This will
3421 * queue a task_work based retry of the operation, attempting to copy the data
3422 * again. If the latter fails because the page was NOT uptodate, then we will
3423 * do a thread based blocking retry of the operation. That's the unexpected
3426 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3427 int sync, void *arg)
3429 struct wait_page_queue *wpq;
3430 struct io_kiocb *req = wait->private;
3431 struct wait_page_key *key = arg;
3433 wpq = container_of(wait, struct wait_page_queue, wait);
3435 if (!wake_page_match(wpq, key))
3438 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3439 list_del_init(&wait->entry);
3440 io_req_task_queue(req);
3445 * This controls whether a given IO request should be armed for async page
3446 * based retry. If we return false here, the request is handed to the async
3447 * worker threads for retry. If we're doing buffered reads on a regular file,
3448 * we prepare a private wait_page_queue entry and retry the operation. This
3449 * will either succeed because the page is now uptodate and unlocked, or it
3450 * will register a callback when the page is unlocked at IO completion. Through
3451 * that callback, io_uring uses task_work to setup a retry of the operation.
3452 * That retry will attempt the buffered read again. The retry will generally
3453 * succeed, or in rare cases where it fails, we then fall back to using the
3454 * async worker threads for a blocking retry.
3456 static bool io_rw_should_retry(struct io_kiocb *req)
3458 struct io_async_rw *rw = req->async_data;
3459 struct wait_page_queue *wait = &rw->wpq;
3460 struct kiocb *kiocb = &req->rw.kiocb;
3462 /* never retry for NOWAIT, we just complete with -EAGAIN */
3463 if (req->flags & REQ_F_NOWAIT)
3466 /* Only for buffered IO */
3467 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3471 * just use poll if we can, and don't attempt if the fs doesn't
3472 * support callback based unlocks
3474 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3477 wait->wait.func = io_async_buf_func;
3478 wait->wait.private = req;
3479 wait->wait.flags = 0;
3480 INIT_LIST_HEAD(&wait->wait.entry);
3481 kiocb->ki_flags |= IOCB_WAITQ;
3482 kiocb->ki_flags &= ~IOCB_NOWAIT;
3483 kiocb->ki_waitq = wait;
3487 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3489 if (req->file->f_op->read_iter)
3490 return call_read_iter(req->file, &req->rw.kiocb, iter);
3491 else if (req->file->f_op->read)
3492 return loop_rw_iter(READ, req, iter);
3497 static bool need_read_all(struct io_kiocb *req)
3499 return req->flags & REQ_F_ISREG ||
3500 S_ISBLK(file_inode(req->file)->i_mode);
3503 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3505 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3506 struct kiocb *kiocb = &req->rw.kiocb;
3507 struct iov_iter __iter, *iter = &__iter;
3508 struct io_async_rw *rw = req->async_data;
3509 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3510 struct iov_iter_state __state, *state;
3515 state = &rw->iter_state;
3517 * We come here from an earlier attempt, restore our state to
3518 * match in case it doesn't. It's cheap enough that we don't
3519 * need to make this conditional.
3521 iov_iter_restore(iter, state);
3524 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3528 iov_iter_save_state(iter, state);
3530 req->result = iov_iter_count(iter);
3532 /* Ensure we clear previously set non-block flag */
3533 if (!force_nonblock)
3534 kiocb->ki_flags &= ~IOCB_NOWAIT;
3536 kiocb->ki_flags |= IOCB_NOWAIT;
3538 /* If the file doesn't support async, just async punt */
3539 if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3540 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3541 return ret ?: -EAGAIN;
3544 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), req->result);
3545 if (unlikely(ret)) {
3550 ret = io_iter_do_read(req, iter);
3552 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3553 req->flags &= ~REQ_F_REISSUE;
3554 /* IOPOLL retry should happen for io-wq threads */
3555 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3557 /* no retry on NONBLOCK nor RWF_NOWAIT */
3558 if (req->flags & REQ_F_NOWAIT)
3561 } else if (ret == -EIOCBQUEUED) {
3563 } else if (ret <= 0 || ret == req->result || !force_nonblock ||
3564 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
3565 /* read all, failed, already did sync or don't want to retry */
3570 * Don't depend on the iter state matching what was consumed, or being
3571 * untouched in case of error. Restore it and we'll advance it
3572 * manually if we need to.
3574 iov_iter_restore(iter, state);
3576 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3581 rw = req->async_data;
3583 * Now use our persistent iterator and state, if we aren't already.
3584 * We've restored and mapped the iter to match.
3586 if (iter != &rw->iter) {
3588 state = &rw->iter_state;
3593 * We end up here because of a partial read, either from
3594 * above or inside this loop. Advance the iter by the bytes
3595 * that were consumed.
3597 iov_iter_advance(iter, ret);
3598 if (!iov_iter_count(iter))
3600 rw->bytes_done += ret;
3601 iov_iter_save_state(iter, state);
3603 /* if we can retry, do so with the callbacks armed */
3604 if (!io_rw_should_retry(req)) {
3605 kiocb->ki_flags &= ~IOCB_WAITQ;
3610 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3611 * we get -EIOCBQUEUED, then we'll get a notification when the
3612 * desired page gets unlocked. We can also get a partial read
3613 * here, and if we do, then just retry at the new offset.
3615 ret = io_iter_do_read(req, iter);
3616 if (ret == -EIOCBQUEUED)
3618 /* we got some bytes, but not all. retry. */
3619 kiocb->ki_flags &= ~IOCB_WAITQ;
3620 iov_iter_restore(iter, state);
3623 kiocb_done(kiocb, ret, issue_flags);
3625 /* it's faster to check here then delegate to kfree */
3631 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3633 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3635 return io_prep_rw(req, sqe, WRITE);
3638 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3640 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3641 struct kiocb *kiocb = &req->rw.kiocb;
3642 struct iov_iter __iter, *iter = &__iter;
3643 struct io_async_rw *rw = req->async_data;
3644 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3645 struct iov_iter_state __state, *state;
3650 state = &rw->iter_state;
3651 iov_iter_restore(iter, state);
3654 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3658 iov_iter_save_state(iter, state);
3660 req->result = iov_iter_count(iter);
3662 /* Ensure we clear previously set non-block flag */
3663 if (!force_nonblock)
3664 kiocb->ki_flags &= ~IOCB_NOWAIT;
3666 kiocb->ki_flags |= IOCB_NOWAIT;
3668 /* If the file doesn't support async, just async punt */
3669 if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3672 /* file path doesn't support NOWAIT for non-direct_IO */
3673 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3674 (req->flags & REQ_F_ISREG))
3677 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), req->result);
3682 * Open-code file_start_write here to grab freeze protection,
3683 * which will be released by another thread in
3684 * io_complete_rw(). Fool lockdep by telling it the lock got
3685 * released so that it doesn't complain about the held lock when
3686 * we return to userspace.
3688 if (req->flags & REQ_F_ISREG) {
3689 sb_start_write(file_inode(req->file)->i_sb);
3690 __sb_writers_release(file_inode(req->file)->i_sb,
3693 kiocb->ki_flags |= IOCB_WRITE;
3695 if (req->file->f_op->write_iter)
3696 ret2 = call_write_iter(req->file, kiocb, iter);
3697 else if (req->file->f_op->write)
3698 ret2 = loop_rw_iter(WRITE, req, iter);
3702 if (req->flags & REQ_F_REISSUE) {
3703 req->flags &= ~REQ_F_REISSUE;
3708 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3709 * retry them without IOCB_NOWAIT.
3711 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3713 /* no retry on NONBLOCK nor RWF_NOWAIT */
3714 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3716 if (!force_nonblock || ret2 != -EAGAIN) {
3717 /* IOPOLL retry should happen for io-wq threads */
3718 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3721 kiocb_done(kiocb, ret2, issue_flags);
3724 iov_iter_restore(iter, state);
3725 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3727 if (kiocb->ki_flags & IOCB_WRITE)
3728 kiocb_end_write(req);
3734 /* it's reportedly faster than delegating the null check to kfree() */
3740 static int io_renameat_prep(struct io_kiocb *req,
3741 const struct io_uring_sqe *sqe)
3743 struct io_rename *ren = &req->rename;
3744 const char __user *oldf, *newf;
3746 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3748 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3750 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3753 ren->old_dfd = READ_ONCE(sqe->fd);
3754 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3755 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3756 ren->new_dfd = READ_ONCE(sqe->len);
3757 ren->flags = READ_ONCE(sqe->rename_flags);
3759 ren->oldpath = getname(oldf);
3760 if (IS_ERR(ren->oldpath))
3761 return PTR_ERR(ren->oldpath);
3763 ren->newpath = getname(newf);
3764 if (IS_ERR(ren->newpath)) {
3765 putname(ren->oldpath);
3766 return PTR_ERR(ren->newpath);
3769 req->flags |= REQ_F_NEED_CLEANUP;
3773 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3775 struct io_rename *ren = &req->rename;
3778 if (issue_flags & IO_URING_F_NONBLOCK)
3781 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3782 ren->newpath, ren->flags);
3784 req->flags &= ~REQ_F_NEED_CLEANUP;
3787 io_req_complete(req, ret);
3791 static int io_unlinkat_prep(struct io_kiocb *req,
3792 const struct io_uring_sqe *sqe)
3794 struct io_unlink *un = &req->unlink;
3795 const char __user *fname;
3797 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3799 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
3802 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3805 un->dfd = READ_ONCE(sqe->fd);
3807 un->flags = READ_ONCE(sqe->unlink_flags);
3808 if (un->flags & ~AT_REMOVEDIR)
3811 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3812 un->filename = getname(fname);
3813 if (IS_ERR(un->filename))
3814 return PTR_ERR(un->filename);
3816 req->flags |= REQ_F_NEED_CLEANUP;
3820 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3822 struct io_unlink *un = &req->unlink;
3825 if (issue_flags & IO_URING_F_NONBLOCK)
3828 if (un->flags & AT_REMOVEDIR)
3829 ret = do_rmdir(un->dfd, un->filename);
3831 ret = do_unlinkat(un->dfd, un->filename);
3833 req->flags &= ~REQ_F_NEED_CLEANUP;
3836 io_req_complete(req, ret);
3840 static int io_mkdirat_prep(struct io_kiocb *req,
3841 const struct io_uring_sqe *sqe)
3843 struct io_mkdir *mkd = &req->mkdir;
3844 const char __user *fname;
3846 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3848 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
3851 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3854 mkd->dfd = READ_ONCE(sqe->fd);
3855 mkd->mode = READ_ONCE(sqe->len);
3857 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3858 mkd->filename = getname(fname);
3859 if (IS_ERR(mkd->filename))
3860 return PTR_ERR(mkd->filename);
3862 req->flags |= REQ_F_NEED_CLEANUP;
3866 static int io_mkdirat(struct io_kiocb *req, int issue_flags)
3868 struct io_mkdir *mkd = &req->mkdir;
3871 if (issue_flags & IO_URING_F_NONBLOCK)
3874 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
3876 req->flags &= ~REQ_F_NEED_CLEANUP;
3879 io_req_complete(req, ret);
3883 static int io_symlinkat_prep(struct io_kiocb *req,
3884 const struct io_uring_sqe *sqe)
3886 struct io_symlink *sl = &req->symlink;
3887 const char __user *oldpath, *newpath;
3889 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3891 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
3894 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3897 sl->new_dfd = READ_ONCE(sqe->fd);
3898 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
3899 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3901 sl->oldpath = getname(oldpath);
3902 if (IS_ERR(sl->oldpath))
3903 return PTR_ERR(sl->oldpath);
3905 sl->newpath = getname(newpath);
3906 if (IS_ERR(sl->newpath)) {
3907 putname(sl->oldpath);
3908 return PTR_ERR(sl->newpath);
3911 req->flags |= REQ_F_NEED_CLEANUP;
3915 static int io_symlinkat(struct io_kiocb *req, int issue_flags)
3917 struct io_symlink *sl = &req->symlink;
3920 if (issue_flags & IO_URING_F_NONBLOCK)
3923 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
3925 req->flags &= ~REQ_F_NEED_CLEANUP;
3928 io_req_complete(req, ret);
3932 static int io_linkat_prep(struct io_kiocb *req,
3933 const struct io_uring_sqe *sqe)
3935 struct io_hardlink *lnk = &req->hardlink;
3936 const char __user *oldf, *newf;
3938 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3940 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
3942 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3945 lnk->old_dfd = READ_ONCE(sqe->fd);
3946 lnk->new_dfd = READ_ONCE(sqe->len);
3947 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3948 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3949 lnk->flags = READ_ONCE(sqe->hardlink_flags);
3951 lnk->oldpath = getname(oldf);
3952 if (IS_ERR(lnk->oldpath))
3953 return PTR_ERR(lnk->oldpath);
3955 lnk->newpath = getname(newf);
3956 if (IS_ERR(lnk->newpath)) {
3957 putname(lnk->oldpath);
3958 return PTR_ERR(lnk->newpath);
3961 req->flags |= REQ_F_NEED_CLEANUP;
3965 static int io_linkat(struct io_kiocb *req, int issue_flags)
3967 struct io_hardlink *lnk = &req->hardlink;
3970 if (issue_flags & IO_URING_F_NONBLOCK)
3973 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
3974 lnk->newpath, lnk->flags);
3976 req->flags &= ~REQ_F_NEED_CLEANUP;
3979 io_req_complete(req, ret);
3983 static int io_shutdown_prep(struct io_kiocb *req,
3984 const struct io_uring_sqe *sqe)
3986 #if defined(CONFIG_NET)
3987 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3989 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3990 sqe->buf_index || sqe->splice_fd_in))
3993 req->shutdown.how = READ_ONCE(sqe->len);
4000 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
4002 #if defined(CONFIG_NET)
4003 struct socket *sock;
4006 if (issue_flags & IO_URING_F_NONBLOCK)
4009 sock = sock_from_file(req->file);
4010 if (unlikely(!sock))
4013 ret = __sys_shutdown_sock(sock, req->shutdown.how);
4016 io_req_complete(req, ret);
4023 static int __io_splice_prep(struct io_kiocb *req,
4024 const struct io_uring_sqe *sqe)
4026 struct io_splice *sp = &req->splice;
4027 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4029 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4032 sp->len = READ_ONCE(sqe->len);
4033 sp->flags = READ_ONCE(sqe->splice_flags);
4034 if (unlikely(sp->flags & ~valid_flags))
4036 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4040 static int io_tee_prep(struct io_kiocb *req,
4041 const struct io_uring_sqe *sqe)
4043 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4045 return __io_splice_prep(req, sqe);
4048 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4050 struct io_splice *sp = &req->splice;
4051 struct file *out = sp->file_out;
4052 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4056 if (issue_flags & IO_URING_F_NONBLOCK)
4059 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4060 (sp->flags & SPLICE_F_FD_IN_FIXED));
4067 ret = do_tee(in, out, sp->len, flags);
4069 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4074 io_req_complete(req, ret);
4078 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4080 struct io_splice *sp = &req->splice;
4082 sp->off_in = READ_ONCE(sqe->splice_off_in);
4083 sp->off_out = READ_ONCE(sqe->off);
4084 return __io_splice_prep(req, sqe);
4087 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4089 struct io_splice *sp = &req->splice;
4090 struct file *out = sp->file_out;
4091 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4092 loff_t *poff_in, *poff_out;
4096 if (issue_flags & IO_URING_F_NONBLOCK)
4099 in = io_file_get(req->ctx, req, sp->splice_fd_in,
4100 (sp->flags & SPLICE_F_FD_IN_FIXED));
4106 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4107 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4110 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4112 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4117 io_req_complete(req, ret);
4122 * IORING_OP_NOP just posts a completion event, nothing else.
4124 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
4126 struct io_ring_ctx *ctx = req->ctx;
4128 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4131 __io_req_complete(req, issue_flags, 0, 0);
4135 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4137 struct io_ring_ctx *ctx = req->ctx;
4139 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4141 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4145 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4146 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4149 req->sync.off = READ_ONCE(sqe->off);
4150 req->sync.len = READ_ONCE(sqe->len);
4154 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
4156 loff_t end = req->sync.off + req->sync.len;
4159 /* fsync always requires a blocking context */
4160 if (issue_flags & IO_URING_F_NONBLOCK)
4163 ret = vfs_fsync_range(req->file, req->sync.off,
4164 end > 0 ? end : LLONG_MAX,
4165 req->sync.flags & IORING_FSYNC_DATASYNC);
4168 io_req_complete(req, ret);
4172 static int io_fallocate_prep(struct io_kiocb *req,
4173 const struct io_uring_sqe *sqe)
4175 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4178 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4181 req->sync.off = READ_ONCE(sqe->off);
4182 req->sync.len = READ_ONCE(sqe->addr);
4183 req->sync.mode = READ_ONCE(sqe->len);
4187 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
4191 /* fallocate always requiring blocking context */
4192 if (issue_flags & IO_URING_F_NONBLOCK)
4194 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4199 fsnotify_modify(req->file);
4200 io_req_complete(req, ret);
4204 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4206 const char __user *fname;
4209 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4211 if (unlikely(sqe->ioprio || sqe->buf_index))
4213 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4216 /* open.how should be already initialised */
4217 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
4218 req->open.how.flags |= O_LARGEFILE;
4220 req->open.dfd = READ_ONCE(sqe->fd);
4221 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4222 req->open.filename = getname(fname);
4223 if (IS_ERR(req->open.filename)) {
4224 ret = PTR_ERR(req->open.filename);
4225 req->open.filename = NULL;
4229 req->open.file_slot = READ_ONCE(sqe->file_index);
4230 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4233 req->open.nofile = rlimit(RLIMIT_NOFILE);
4234 req->flags |= REQ_F_NEED_CLEANUP;
4238 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4240 u64 mode = READ_ONCE(sqe->len);
4241 u64 flags = READ_ONCE(sqe->open_flags);
4243 req->open.how = build_open_how(flags, mode);
4244 return __io_openat_prep(req, sqe);
4247 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4249 struct open_how __user *how;
4253 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4254 len = READ_ONCE(sqe->len);
4255 if (len < OPEN_HOW_SIZE_VER0)
4258 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4263 return __io_openat_prep(req, sqe);
4266 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
4268 struct open_flags op;
4270 bool resolve_nonblock, nonblock_set;
4271 bool fixed = !!req->open.file_slot;
4274 ret = build_open_flags(&req->open.how, &op);
4277 nonblock_set = op.open_flag & O_NONBLOCK;
4278 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
4279 if (issue_flags & IO_URING_F_NONBLOCK) {
4281 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4282 * it'll always -EAGAIN
4284 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4286 op.lookup_flags |= LOOKUP_CACHED;
4287 op.open_flag |= O_NONBLOCK;
4291 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4296 file = do_filp_open(req->open.dfd, req->open.filename, &op);
4299 * We could hang on to this 'fd' on retrying, but seems like
4300 * marginal gain for something that is now known to be a slower
4301 * path. So just put it, and we'll get a new one when we retry.
4306 ret = PTR_ERR(file);
4307 /* only retry if RESOLVE_CACHED wasn't already set by application */
4308 if (ret == -EAGAIN &&
4309 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4314 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4315 file->f_flags &= ~O_NONBLOCK;
4316 fsnotify_open(file);
4319 fd_install(ret, file);
4321 ret = io_install_fixed_file(req, file, issue_flags,
4322 req->open.file_slot - 1);
4324 putname(req->open.filename);
4325 req->flags &= ~REQ_F_NEED_CLEANUP;
4328 __io_req_complete(req, issue_flags, ret, 0);
4332 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
4334 return io_openat2(req, issue_flags);
4337 static int io_remove_buffers_prep(struct io_kiocb *req,
4338 const struct io_uring_sqe *sqe)
4340 struct io_provide_buf *p = &req->pbuf;
4343 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4347 tmp = READ_ONCE(sqe->fd);
4348 if (!tmp || tmp > USHRT_MAX)
4351 memset(p, 0, sizeof(*p));
4353 p->bgid = READ_ONCE(sqe->buf_group);
4357 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
4358 int bgid, unsigned nbufs)
4362 /* shouldn't happen */
4366 /* the head kbuf is the list itself */
4367 while (!list_empty(&buf->list)) {
4368 struct io_buffer *nxt;
4370 nxt = list_first_entry(&buf->list, struct io_buffer, list);
4371 list_del(&nxt->list);
4379 xa_erase(&ctx->io_buffers, bgid);
4384 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
4386 struct io_provide_buf *p = &req->pbuf;
4387 struct io_ring_ctx *ctx = req->ctx;
4388 struct io_buffer *head;
4390 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4392 io_ring_submit_lock(ctx, !force_nonblock);
4394 lockdep_assert_held(&ctx->uring_lock);
4397 head = xa_load(&ctx->io_buffers, p->bgid);
4399 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
4403 /* complete before unlock, IOPOLL may need the lock */
4404 __io_req_complete(req, issue_flags, ret, 0);
4405 io_ring_submit_unlock(ctx, !force_nonblock);
4409 static int io_provide_buffers_prep(struct io_kiocb *req,
4410 const struct io_uring_sqe *sqe)
4412 unsigned long size, tmp_check;
4413 struct io_provide_buf *p = &req->pbuf;
4416 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
4419 tmp = READ_ONCE(sqe->fd);
4420 if (!tmp || tmp > USHRT_MAX)
4423 p->addr = READ_ONCE(sqe->addr);
4424 p->len = READ_ONCE(sqe->len);
4426 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4429 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4432 size = (unsigned long)p->len * p->nbufs;
4433 if (!access_ok(u64_to_user_ptr(p->addr), size))
4436 p->bgid = READ_ONCE(sqe->buf_group);
4437 tmp = READ_ONCE(sqe->off);
4438 if (tmp > USHRT_MAX)
4444 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4446 struct io_buffer *buf;
4447 u64 addr = pbuf->addr;
4448 int i, bid = pbuf->bid;
4450 for (i = 0; i < pbuf->nbufs; i++) {
4451 buf = kmalloc(sizeof(*buf), GFP_KERNEL_ACCOUNT);
4456 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
4461 INIT_LIST_HEAD(&buf->list);
4464 list_add_tail(&buf->list, &(*head)->list);
4469 return i ? i : -ENOMEM;
4472 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4474 struct io_provide_buf *p = &req->pbuf;
4475 struct io_ring_ctx *ctx = req->ctx;
4476 struct io_buffer *head, *list;
4478 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4480 io_ring_submit_lock(ctx, !force_nonblock);
4482 lockdep_assert_held(&ctx->uring_lock);
4484 list = head = xa_load(&ctx->io_buffers, p->bgid);
4486 ret = io_add_buffers(p, &head);
4487 if (ret >= 0 && !list) {
4488 ret = xa_insert(&ctx->io_buffers, p->bgid, head,
4489 GFP_KERNEL_ACCOUNT);
4491 __io_remove_buffers(ctx, head, p->bgid, -1U);
4495 /* complete before unlock, IOPOLL may need the lock */
4496 __io_req_complete(req, issue_flags, ret, 0);
4497 io_ring_submit_unlock(ctx, !force_nonblock);
4501 static int io_epoll_ctl_prep(struct io_kiocb *req,
4502 const struct io_uring_sqe *sqe)
4504 #if defined(CONFIG_EPOLL)
4505 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4507 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4510 req->epoll.epfd = READ_ONCE(sqe->fd);
4511 req->epoll.op = READ_ONCE(sqe->len);
4512 req->epoll.fd = READ_ONCE(sqe->off);
4514 if (ep_op_has_event(req->epoll.op)) {
4515 struct epoll_event __user *ev;
4517 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4518 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4528 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4530 #if defined(CONFIG_EPOLL)
4531 struct io_epoll *ie = &req->epoll;
4533 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4535 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4536 if (force_nonblock && ret == -EAGAIN)
4541 __io_req_complete(req, issue_flags, ret, 0);
4548 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4550 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4551 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
4553 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4556 req->madvise.addr = READ_ONCE(sqe->addr);
4557 req->madvise.len = READ_ONCE(sqe->len);
4558 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4565 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4567 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4568 struct io_madvise *ma = &req->madvise;
4571 if (issue_flags & IO_URING_F_NONBLOCK)
4574 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4577 io_req_complete(req, ret);
4584 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4586 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4588 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4591 req->fadvise.offset = READ_ONCE(sqe->off);
4592 req->fadvise.len = READ_ONCE(sqe->len);
4593 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4597 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4599 struct io_fadvise *fa = &req->fadvise;
4602 if (issue_flags & IO_URING_F_NONBLOCK) {
4603 switch (fa->advice) {
4604 case POSIX_FADV_NORMAL:
4605 case POSIX_FADV_RANDOM:
4606 case POSIX_FADV_SEQUENTIAL:
4613 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4616 __io_req_complete(req, issue_flags, ret, 0);
4620 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4622 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4624 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
4626 if (req->flags & REQ_F_FIXED_FILE)
4629 req->statx.dfd = READ_ONCE(sqe->fd);
4630 req->statx.mask = READ_ONCE(sqe->len);
4631 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4632 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4633 req->statx.flags = READ_ONCE(sqe->statx_flags);
4638 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4640 struct io_statx *ctx = &req->statx;
4643 if (issue_flags & IO_URING_F_NONBLOCK)
4646 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4651 io_req_complete(req, ret);
4655 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4657 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4659 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4660 sqe->rw_flags || sqe->buf_index)
4662 if (req->flags & REQ_F_FIXED_FILE)
4665 req->close.fd = READ_ONCE(sqe->fd);
4666 req->close.file_slot = READ_ONCE(sqe->file_index);
4667 if (req->close.file_slot && req->close.fd)
4673 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4675 struct files_struct *files = current->files;
4676 struct io_close *close = &req->close;
4677 struct fdtable *fdt;
4678 struct file *file = NULL;
4681 if (req->close.file_slot) {
4682 ret = io_close_fixed(req, issue_flags);
4686 spin_lock(&files->file_lock);
4687 fdt = files_fdtable(files);
4688 if (close->fd >= fdt->max_fds) {
4689 spin_unlock(&files->file_lock);
4692 file = fdt->fd[close->fd];
4693 if (!file || file->f_op == &io_uring_fops) {
4694 spin_unlock(&files->file_lock);
4699 /* if the file has a flush method, be safe and punt to async */
4700 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4701 spin_unlock(&files->file_lock);
4705 ret = __close_fd_get_file(close->fd, &file);
4706 spin_unlock(&files->file_lock);
4713 /* No ->flush() or already async, safely close from here */
4714 ret = filp_close(file, current->files);
4720 __io_req_complete(req, issue_flags, ret, 0);
4724 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4726 struct io_ring_ctx *ctx = req->ctx;
4728 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4730 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4734 req->sync.off = READ_ONCE(sqe->off);
4735 req->sync.len = READ_ONCE(sqe->len);
4736 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4740 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4744 /* sync_file_range always requires a blocking context */
4745 if (issue_flags & IO_URING_F_NONBLOCK)
4748 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4752 io_req_complete(req, ret);
4756 #if defined(CONFIG_NET)
4757 static int io_setup_async_msg(struct io_kiocb *req,
4758 struct io_async_msghdr *kmsg)
4760 struct io_async_msghdr *async_msg = req->async_data;
4764 if (io_alloc_async_data(req)) {
4765 kfree(kmsg->free_iov);
4768 async_msg = req->async_data;
4769 req->flags |= REQ_F_NEED_CLEANUP;
4770 memcpy(async_msg, kmsg, sizeof(*kmsg));
4771 async_msg->msg.msg_name = &async_msg->addr;
4772 /* if were using fast_iov, set it to the new one */
4773 if (!async_msg->free_iov)
4774 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4779 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4780 struct io_async_msghdr *iomsg)
4782 iomsg->msg.msg_name = &iomsg->addr;
4783 iomsg->free_iov = iomsg->fast_iov;
4784 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4785 req->sr_msg.msg_flags, &iomsg->free_iov);
4788 static int io_sendmsg_prep_async(struct io_kiocb *req)
4792 ret = io_sendmsg_copy_hdr(req, req->async_data);
4794 req->flags |= REQ_F_NEED_CLEANUP;
4798 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4800 struct io_sr_msg *sr = &req->sr_msg;
4802 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4804 if (unlikely(sqe->addr2 || sqe->file_index))
4806 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
4809 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4810 sr->len = READ_ONCE(sqe->len);
4811 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4812 if (sr->msg_flags & MSG_DONTWAIT)
4813 req->flags |= REQ_F_NOWAIT;
4815 #ifdef CONFIG_COMPAT
4816 if (req->ctx->compat)
4817 sr->msg_flags |= MSG_CMSG_COMPAT;
4822 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4824 struct io_async_msghdr iomsg, *kmsg;
4825 struct socket *sock;
4830 sock = sock_from_file(req->file);
4831 if (unlikely(!sock))
4834 kmsg = req->async_data;
4836 ret = io_sendmsg_copy_hdr(req, &iomsg);
4842 flags = req->sr_msg.msg_flags;
4843 if (issue_flags & IO_URING_F_NONBLOCK)
4844 flags |= MSG_DONTWAIT;
4845 if (flags & MSG_WAITALL)
4846 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4848 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4849 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4850 return io_setup_async_msg(req, kmsg);
4851 if (ret == -ERESTARTSYS)
4854 /* fast path, check for non-NULL to avoid function call */
4856 kfree(kmsg->free_iov);
4857 req->flags &= ~REQ_F_NEED_CLEANUP;
4860 __io_req_complete(req, issue_flags, ret, 0);
4864 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4866 struct io_sr_msg *sr = &req->sr_msg;
4869 struct socket *sock;
4874 sock = sock_from_file(req->file);
4875 if (unlikely(!sock))
4878 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4882 msg.msg_name = NULL;
4883 msg.msg_control = NULL;
4884 msg.msg_controllen = 0;
4885 msg.msg_namelen = 0;
4887 flags = req->sr_msg.msg_flags;
4888 if (issue_flags & IO_URING_F_NONBLOCK)
4889 flags |= MSG_DONTWAIT;
4890 if (flags & MSG_WAITALL)
4891 min_ret = iov_iter_count(&msg.msg_iter);
4893 msg.msg_flags = flags;
4894 ret = sock_sendmsg(sock, &msg);
4895 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4897 if (ret == -ERESTARTSYS)
4902 __io_req_complete(req, issue_flags, ret, 0);
4906 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4907 struct io_async_msghdr *iomsg)
4909 struct io_sr_msg *sr = &req->sr_msg;
4910 struct iovec __user *uiov;
4914 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4915 &iomsg->uaddr, &uiov, &iov_len);
4919 if (req->flags & REQ_F_BUFFER_SELECT) {
4922 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4924 sr->len = iomsg->fast_iov[0].iov_len;
4925 iomsg->free_iov = NULL;
4927 iomsg->free_iov = iomsg->fast_iov;
4928 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4929 &iomsg->free_iov, &iomsg->msg.msg_iter,
4938 #ifdef CONFIG_COMPAT
4939 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4940 struct io_async_msghdr *iomsg)
4942 struct io_sr_msg *sr = &req->sr_msg;
4943 struct compat_iovec __user *uiov;
4948 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4953 uiov = compat_ptr(ptr);
4954 if (req->flags & REQ_F_BUFFER_SELECT) {
4955 compat_ssize_t clen;
4959 if (!access_ok(uiov, sizeof(*uiov)))
4961 if (__get_user(clen, &uiov->iov_len))
4966 iomsg->free_iov = NULL;
4968 iomsg->free_iov = iomsg->fast_iov;
4969 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4970 UIO_FASTIOV, &iomsg->free_iov,
4971 &iomsg->msg.msg_iter, true);
4980 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4981 struct io_async_msghdr *iomsg)
4983 iomsg->msg.msg_name = &iomsg->addr;
4985 #ifdef CONFIG_COMPAT
4986 if (req->ctx->compat)
4987 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4990 return __io_recvmsg_copy_hdr(req, iomsg);
4993 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4996 struct io_sr_msg *sr = &req->sr_msg;
4997 struct io_buffer *kbuf;
4999 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
5004 req->flags |= REQ_F_BUFFER_SELECTED;
5008 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
5010 return io_put_kbuf(req, req->sr_msg.kbuf);
5013 static int io_recvmsg_prep_async(struct io_kiocb *req)
5017 ret = io_recvmsg_copy_hdr(req, req->async_data);
5019 req->flags |= REQ_F_NEED_CLEANUP;
5023 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5025 struct io_sr_msg *sr = &req->sr_msg;
5027 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5029 if (unlikely(sqe->addr2 || sqe->file_index))
5031 if (unlikely(sqe->addr2 || sqe->file_index || sqe->ioprio))
5034 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5035 sr->len = READ_ONCE(sqe->len);
5036 sr->bgid = READ_ONCE(sqe->buf_group);
5037 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5038 if (sr->msg_flags & MSG_DONTWAIT)
5039 req->flags |= REQ_F_NOWAIT;
5041 #ifdef CONFIG_COMPAT
5042 if (req->ctx->compat)
5043 sr->msg_flags |= MSG_CMSG_COMPAT;
5048 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
5050 struct io_async_msghdr iomsg, *kmsg;
5051 struct socket *sock;
5052 struct io_buffer *kbuf;
5055 int ret, cflags = 0;
5056 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5058 sock = sock_from_file(req->file);
5059 if (unlikely(!sock))
5062 kmsg = req->async_data;
5064 ret = io_recvmsg_copy_hdr(req, &iomsg);
5070 if (req->flags & REQ_F_BUFFER_SELECT) {
5071 kbuf = io_recv_buffer_select(req, !force_nonblock);
5073 return PTR_ERR(kbuf);
5074 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5075 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5076 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
5077 1, req->sr_msg.len);
5080 flags = req->sr_msg.msg_flags;
5082 flags |= MSG_DONTWAIT;
5083 if (flags & MSG_WAITALL)
5084 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5086 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5087 kmsg->uaddr, flags);
5088 if (force_nonblock && ret == -EAGAIN)
5089 return io_setup_async_msg(req, kmsg);
5090 if (ret == -ERESTARTSYS)
5093 if (req->flags & REQ_F_BUFFER_SELECTED)
5094 cflags = io_put_recv_kbuf(req);
5095 /* fast path, check for non-NULL to avoid function call */
5097 kfree(kmsg->free_iov);
5098 req->flags &= ~REQ_F_NEED_CLEANUP;
5099 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5101 __io_req_complete(req, issue_flags, ret, cflags);
5105 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
5107 struct io_buffer *kbuf;
5108 struct io_sr_msg *sr = &req->sr_msg;
5110 void __user *buf = sr->buf;
5111 struct socket *sock;
5115 int ret, cflags = 0;
5116 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5118 sock = sock_from_file(req->file);
5119 if (unlikely(!sock))
5122 if (req->flags & REQ_F_BUFFER_SELECT) {
5123 kbuf = io_recv_buffer_select(req, !force_nonblock);
5125 return PTR_ERR(kbuf);
5126 buf = u64_to_user_ptr(kbuf->addr);
5129 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
5133 msg.msg_name = NULL;
5134 msg.msg_control = NULL;
5135 msg.msg_controllen = 0;
5136 msg.msg_namelen = 0;
5137 msg.msg_iocb = NULL;
5140 flags = req->sr_msg.msg_flags;
5142 flags |= MSG_DONTWAIT;
5143 if (flags & MSG_WAITALL)
5144 min_ret = iov_iter_count(&msg.msg_iter);
5146 ret = sock_recvmsg(sock, &msg, flags);
5147 if (force_nonblock && ret == -EAGAIN)
5149 if (ret == -ERESTARTSYS)
5152 if (req->flags & REQ_F_BUFFER_SELECTED)
5153 cflags = io_put_recv_kbuf(req);
5154 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
5156 __io_req_complete(req, issue_flags, ret, cflags);
5160 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5162 struct io_accept *accept = &req->accept;
5164 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5166 if (sqe->ioprio || sqe->len || sqe->buf_index)
5169 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5170 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5171 accept->flags = READ_ONCE(sqe->accept_flags);
5172 accept->nofile = rlimit(RLIMIT_NOFILE);
5174 accept->file_slot = READ_ONCE(sqe->file_index);
5175 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
5177 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5179 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5180 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
5184 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
5186 struct io_accept *accept = &req->accept;
5187 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5188 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
5189 bool fixed = !!accept->file_slot;
5193 if (req->file->f_flags & O_NONBLOCK)
5194 req->flags |= REQ_F_NOWAIT;
5197 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5198 if (unlikely(fd < 0))
5201 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5206 ret = PTR_ERR(file);
5207 if (ret == -EAGAIN && force_nonblock)
5209 if (ret == -ERESTARTSYS)
5212 } else if (!fixed) {
5213 fd_install(fd, file);
5216 ret = io_install_fixed_file(req, file, issue_flags,
5217 accept->file_slot - 1);
5219 __io_req_complete(req, issue_flags, ret, 0);
5223 static int io_connect_prep_async(struct io_kiocb *req)
5225 struct io_async_connect *io = req->async_data;
5226 struct io_connect *conn = &req->connect;
5228 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5231 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5233 struct io_connect *conn = &req->connect;
5235 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5237 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5241 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5242 conn->addr_len = READ_ONCE(sqe->addr2);
5246 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
5248 struct io_async_connect __io, *io;
5249 unsigned file_flags;
5251 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5253 if (req->async_data) {
5254 io = req->async_data;
5256 ret = move_addr_to_kernel(req->connect.addr,
5257 req->connect.addr_len,
5264 file_flags = force_nonblock ? O_NONBLOCK : 0;
5266 ret = __sys_connect_file(req->file, &io->address,
5267 req->connect.addr_len, file_flags);
5268 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
5269 if (req->async_data)
5271 if (io_alloc_async_data(req)) {
5275 memcpy(req->async_data, &__io, sizeof(__io));
5278 if (ret == -ERESTARTSYS)
5283 __io_req_complete(req, issue_flags, ret, 0);
5286 #else /* !CONFIG_NET */
5287 #define IO_NETOP_FN(op) \
5288 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5290 return -EOPNOTSUPP; \
5293 #define IO_NETOP_PREP(op) \
5295 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5297 return -EOPNOTSUPP; \
5300 #define IO_NETOP_PREP_ASYNC(op) \
5302 static int io_##op##_prep_async(struct io_kiocb *req) \
5304 return -EOPNOTSUPP; \
5307 IO_NETOP_PREP_ASYNC(sendmsg);
5308 IO_NETOP_PREP_ASYNC(recvmsg);
5309 IO_NETOP_PREP_ASYNC(connect);
5310 IO_NETOP_PREP(accept);
5313 #endif /* CONFIG_NET */
5315 struct io_poll_table {
5316 struct poll_table_struct pt;
5317 struct io_kiocb *req;
5322 #define IO_POLL_CANCEL_FLAG BIT(31)
5323 #define IO_POLL_REF_MASK ((1u << 20)-1)
5326 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5327 * bump it and acquire ownership. It's disallowed to modify requests while not
5328 * owning it, that prevents from races for enqueueing task_work's and b/w
5329 * arming poll and wakeups.
5331 static inline bool io_poll_get_ownership(struct io_kiocb *req)
5333 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
5336 static void io_poll_mark_cancelled(struct io_kiocb *req)
5338 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
5341 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
5343 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
5344 if (req->opcode == IORING_OP_POLL_ADD)
5345 return req->async_data;
5346 return req->apoll->double_poll;
5349 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5351 if (req->opcode == IORING_OP_POLL_ADD)
5353 return &req->apoll->poll;
5356 static void io_poll_req_insert(struct io_kiocb *req)
5358 struct io_ring_ctx *ctx = req->ctx;
5359 struct hlist_head *list;
5361 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5362 hlist_add_head(&req->hash_node, list);
5365 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5366 wait_queue_func_t wake_func)
5369 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5370 /* mask in events that we always want/need */
5371 poll->events = events | IO_POLL_UNMASK;
5372 INIT_LIST_HEAD(&poll->wait.entry);
5373 init_waitqueue_func_entry(&poll->wait, wake_func);
5376 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
5378 struct wait_queue_head *head = poll->head;
5380 spin_lock_irq(&head->lock);
5381 list_del_init(&poll->wait.entry);
5383 spin_unlock_irq(&head->lock);
5386 static void io_poll_remove_entries(struct io_kiocb *req)
5388 struct io_poll_iocb *poll = io_poll_get_single(req);
5389 struct io_poll_iocb *poll_double = io_poll_get_double(req);
5392 io_poll_remove_entry(poll);
5393 if (poll_double && poll_double->head)
5394 io_poll_remove_entry(poll_double);
5398 * All poll tw should go through this. Checks for poll events, manages
5399 * references, does rewait, etc.
5401 * Returns a negative error on failure. >0 when no action require, which is
5402 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5403 * the request, then the mask is stored in req->result.
5405 static int io_poll_check_events(struct io_kiocb *req)
5407 struct io_ring_ctx *ctx = req->ctx;
5408 struct io_poll_iocb *poll = io_poll_get_single(req);
5411 /* req->task == current here, checking PF_EXITING is safe */
5412 if (unlikely(req->task->flags & PF_EXITING))
5413 io_poll_mark_cancelled(req);
5416 v = atomic_read(&req->poll_refs);
5418 /* tw handler should be the owner, and so have some references */
5419 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5421 if (v & IO_POLL_CANCEL_FLAG)
5425 struct poll_table_struct pt = { ._key = poll->events };
5427 req->result = vfs_poll(req->file, &pt) & poll->events;
5430 /* multishot, just fill an CQE and proceed */
5431 if (req->result && !(poll->events & EPOLLONESHOT)) {
5432 __poll_t mask = mangle_poll(req->result & poll->events);
5435 spin_lock(&ctx->completion_lock);
5436 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5438 io_commit_cqring(ctx);
5439 spin_unlock(&ctx->completion_lock);
5440 if (unlikely(!filled))
5442 io_cqring_ev_posted(ctx);
5443 } else if (req->result) {
5448 * Release all references, retry if someone tried to restart
5449 * task_work while we were executing it.
5451 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
5456 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
5458 struct io_ring_ctx *ctx = req->ctx;
5461 ret = io_poll_check_events(req);
5466 req->result = mangle_poll(req->result & req->poll.events);
5472 io_poll_remove_entries(req);
5473 spin_lock(&ctx->completion_lock);
5474 hash_del(&req->hash_node);
5475 spin_unlock(&ctx->completion_lock);
5476 io_req_complete_post(req, req->result, 0);
5479 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
5481 struct io_ring_ctx *ctx = req->ctx;
5484 ret = io_poll_check_events(req);
5488 io_poll_remove_entries(req);
5489 spin_lock(&ctx->completion_lock);
5490 hash_del(&req->hash_node);
5491 spin_unlock(&ctx->completion_lock);
5494 io_req_task_submit(req, locked);
5496 io_req_complete_failed(req, ret);
5499 static void __io_poll_execute(struct io_kiocb *req, int mask)
5502 if (req->opcode == IORING_OP_POLL_ADD)
5503 req->io_task_work.func = io_poll_task_func;
5505 req->io_task_work.func = io_apoll_task_func;
5507 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
5508 io_req_task_work_add(req);
5511 static inline void io_poll_execute(struct io_kiocb *req, int res)
5513 if (io_poll_get_ownership(req))
5514 __io_poll_execute(req, res);
5517 static void io_poll_cancel_req(struct io_kiocb *req)
5519 io_poll_mark_cancelled(req);
5520 /* kick tw, which should complete the request */
5521 io_poll_execute(req, 0);
5524 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5527 struct io_kiocb *req = wait->private;
5528 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
5530 __poll_t mask = key_to_poll(key);
5532 /* for instances that support it check for an event match first */
5533 if (mask && !(mask & poll->events))
5536 if (io_poll_get_ownership(req))
5537 __io_poll_execute(req, mask);
5541 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5542 struct wait_queue_head *head,
5543 struct io_poll_iocb **poll_ptr)
5545 struct io_kiocb *req = pt->req;
5548 * The file being polled uses multiple waitqueues for poll handling
5549 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
5552 if (unlikely(pt->nr_entries)) {
5553 struct io_poll_iocb *first = poll;
5555 /* double add on the same waitqueue head, ignore */
5556 if (first->head == head)
5558 /* already have a 2nd entry, fail a third attempt */
5560 if ((*poll_ptr)->head == head)
5562 pt->error = -EINVAL;
5566 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5568 pt->error = -ENOMEM;
5571 io_init_poll_iocb(poll, first->events, first->wait.func);
5577 poll->wait.private = req;
5579 if (poll->events & EPOLLEXCLUSIVE)
5580 add_wait_queue_exclusive(head, &poll->wait);
5582 add_wait_queue(head, &poll->wait);
5585 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5586 struct poll_table_struct *p)
5588 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5590 __io_queue_proc(&pt->req->poll, pt, head,
5591 (struct io_poll_iocb **) &pt->req->async_data);
5594 static int __io_arm_poll_handler(struct io_kiocb *req,
5595 struct io_poll_iocb *poll,
5596 struct io_poll_table *ipt, __poll_t mask)
5598 struct io_ring_ctx *ctx = req->ctx;
5601 INIT_HLIST_NODE(&req->hash_node);
5602 io_init_poll_iocb(poll, mask, io_poll_wake);
5603 poll->file = req->file;
5604 poll->wait.private = req;
5606 ipt->pt._key = mask;
5609 ipt->nr_entries = 0;
5612 * Take the ownership to delay any tw execution up until we're done
5613 * with poll arming. see io_poll_get_ownership().
5615 atomic_set(&req->poll_refs, 1);
5616 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5618 if (mask && (poll->events & EPOLLONESHOT)) {
5619 io_poll_remove_entries(req);
5620 /* no one else has access to the req, forget about the ref */
5623 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
5624 io_poll_remove_entries(req);
5626 ipt->error = -EINVAL;
5630 spin_lock(&ctx->completion_lock);
5631 io_poll_req_insert(req);
5632 spin_unlock(&ctx->completion_lock);
5635 /* can't multishot if failed, just queue the event we've got */
5636 if (unlikely(ipt->error || !ipt->nr_entries))
5637 poll->events |= EPOLLONESHOT;
5638 __io_poll_execute(req, mask);
5643 * Release ownership. If someone tried to queue a tw while it was
5644 * locked, kick it off for them.
5646 v = atomic_dec_return(&req->poll_refs);
5647 if (unlikely(v & IO_POLL_REF_MASK))
5648 __io_poll_execute(req, 0);
5652 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5653 struct poll_table_struct *p)
5655 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5656 struct async_poll *apoll = pt->req->apoll;
5658 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5667 static int io_arm_poll_handler(struct io_kiocb *req)
5669 const struct io_op_def *def = &io_op_defs[req->opcode];
5670 struct io_ring_ctx *ctx = req->ctx;
5671 struct async_poll *apoll;
5672 struct io_poll_table ipt;
5673 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
5676 if (!req->file || !file_can_poll(req->file))
5677 return IO_APOLL_ABORTED;
5678 if (req->flags & REQ_F_POLLED)
5679 return IO_APOLL_ABORTED;
5680 if (!def->pollin && !def->pollout)
5681 return IO_APOLL_ABORTED;
5684 mask |= POLLIN | POLLRDNORM;
5686 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5687 if ((req->opcode == IORING_OP_RECVMSG) &&
5688 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5691 mask |= POLLOUT | POLLWRNORM;
5694 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5695 if (unlikely(!apoll))
5696 return IO_APOLL_ABORTED;
5697 apoll->double_poll = NULL;
5699 req->flags |= REQ_F_POLLED;
5700 ipt.pt._qproc = io_async_queue_proc;
5702 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
5703 if (ret || ipt.error)
5704 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
5706 trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5707 mask, apoll->poll.events);
5712 * Returns true if we found and killed one or more poll requests
5714 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5717 struct hlist_node *tmp;
5718 struct io_kiocb *req;
5722 spin_lock(&ctx->completion_lock);
5723 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5724 struct hlist_head *list;
5726 list = &ctx->cancel_hash[i];
5727 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5728 if (io_match_task_safe(req, tsk, cancel_all)) {
5729 io_poll_cancel_req(req);
5734 spin_unlock(&ctx->completion_lock);
5738 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5740 __must_hold(&ctx->completion_lock)
5742 struct hlist_head *list;
5743 struct io_kiocb *req;
5745 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5746 hlist_for_each_entry(req, list, hash_node) {
5747 if (sqe_addr != req->user_data)
5749 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5756 static bool io_poll_disarm(struct io_kiocb *req)
5757 __must_hold(&ctx->completion_lock)
5759 if (!io_poll_get_ownership(req))
5761 io_poll_remove_entries(req);
5762 hash_del(&req->hash_node);
5766 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5768 __must_hold(&ctx->completion_lock)
5770 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
5774 io_poll_cancel_req(req);
5778 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5783 events = READ_ONCE(sqe->poll32_events);
5785 events = swahw32(events);
5787 if (!(flags & IORING_POLL_ADD_MULTI))
5788 events |= EPOLLONESHOT;
5789 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5792 static int io_poll_update_prep(struct io_kiocb *req,
5793 const struct io_uring_sqe *sqe)
5795 struct io_poll_update *upd = &req->poll_update;
5798 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5800 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
5802 flags = READ_ONCE(sqe->len);
5803 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5804 IORING_POLL_ADD_MULTI))
5806 /* meaningless without update */
5807 if (flags == IORING_POLL_ADD_MULTI)
5810 upd->old_user_data = READ_ONCE(sqe->addr);
5811 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5812 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5814 upd->new_user_data = READ_ONCE(sqe->off);
5815 if (!upd->update_user_data && upd->new_user_data)
5817 if (upd->update_events)
5818 upd->events = io_poll_parse_events(sqe, flags);
5819 else if (sqe->poll32_events)
5825 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5827 struct io_poll_iocb *poll = &req->poll;
5830 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5832 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5834 flags = READ_ONCE(sqe->len);
5835 if (flags & ~IORING_POLL_ADD_MULTI)
5838 io_req_set_refcount(req);
5839 poll->events = io_poll_parse_events(sqe, flags);
5843 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5845 struct io_poll_iocb *poll = &req->poll;
5846 struct io_poll_table ipt;
5849 ipt.pt._qproc = io_poll_queue_proc;
5851 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
5852 ret = ret ?: ipt.error;
5854 __io_req_complete(req, issue_flags, ret, 0);
5858 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5860 struct io_ring_ctx *ctx = req->ctx;
5861 struct io_kiocb *preq;
5864 spin_lock(&ctx->completion_lock);
5865 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5866 if (!preq || !io_poll_disarm(preq)) {
5867 spin_unlock(&ctx->completion_lock);
5868 ret = preq ? -EALREADY : -ENOENT;
5871 spin_unlock(&ctx->completion_lock);
5873 if (req->poll_update.update_events || req->poll_update.update_user_data) {
5874 /* only mask one event flags, keep behavior flags */
5875 if (req->poll_update.update_events) {
5876 preq->poll.events &= ~0xffff;
5877 preq->poll.events |= req->poll_update.events & 0xffff;
5878 preq->poll.events |= IO_POLL_UNMASK;
5880 if (req->poll_update.update_user_data)
5881 preq->user_data = req->poll_update.new_user_data;
5883 ret2 = io_poll_add(preq, issue_flags);
5884 /* successfully updated, don't complete poll request */
5889 io_req_complete(preq, -ECANCELED);
5893 /* complete update request, we're done with it */
5894 io_req_complete(req, ret);
5898 static void io_req_task_timeout(struct io_kiocb *req, bool *locked)
5901 io_req_complete_post(req, -ETIME, 0);
5904 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5906 struct io_timeout_data *data = container_of(timer,
5907 struct io_timeout_data, timer);
5908 struct io_kiocb *req = data->req;
5909 struct io_ring_ctx *ctx = req->ctx;
5910 unsigned long flags;
5912 spin_lock_irqsave(&ctx->timeout_lock, flags);
5913 list_del_init(&req->timeout.list);
5914 atomic_set(&req->ctx->cq_timeouts,
5915 atomic_read(&req->ctx->cq_timeouts) + 1);
5916 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5918 req->io_task_work.func = io_req_task_timeout;
5919 io_req_task_work_add(req);
5920 return HRTIMER_NORESTART;
5923 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5925 __must_hold(&ctx->timeout_lock)
5927 struct io_timeout_data *io;
5928 struct io_kiocb *req;
5931 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5932 found = user_data == req->user_data;
5937 return ERR_PTR(-ENOENT);
5939 io = req->async_data;
5940 if (hrtimer_try_to_cancel(&io->timer) == -1)
5941 return ERR_PTR(-EALREADY);
5942 list_del_init(&req->timeout.list);
5946 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5947 __must_hold(&ctx->completion_lock)
5948 __must_hold(&ctx->timeout_lock)
5950 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5953 return PTR_ERR(req);
5956 io_fill_cqe_req(req, -ECANCELED, 0);
5957 io_put_req_deferred(req);
5961 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
5963 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
5964 case IORING_TIMEOUT_BOOTTIME:
5965 return CLOCK_BOOTTIME;
5966 case IORING_TIMEOUT_REALTIME:
5967 return CLOCK_REALTIME;
5969 /* can't happen, vetted at prep time */
5973 return CLOCK_MONOTONIC;
5977 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5978 struct timespec64 *ts, enum hrtimer_mode mode)
5979 __must_hold(&ctx->timeout_lock)
5981 struct io_timeout_data *io;
5982 struct io_kiocb *req;
5985 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
5986 found = user_data == req->user_data;
5993 io = req->async_data;
5994 if (hrtimer_try_to_cancel(&io->timer) == -1)
5996 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
5997 io->timer.function = io_link_timeout_fn;
5998 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6002 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6003 struct timespec64 *ts, enum hrtimer_mode mode)
6004 __must_hold(&ctx->timeout_lock)
6006 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6007 struct io_timeout_data *data;
6010 return PTR_ERR(req);
6012 req->timeout.off = 0; /* noseq */
6013 data = req->async_data;
6014 list_add_tail(&req->timeout.list, &ctx->timeout_list);
6015 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
6016 data->timer.function = io_timeout_fn;
6017 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6021 static int io_timeout_remove_prep(struct io_kiocb *req,
6022 const struct io_uring_sqe *sqe)
6024 struct io_timeout_rem *tr = &req->timeout_rem;
6026 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6028 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6030 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
6033 tr->ltimeout = false;
6034 tr->addr = READ_ONCE(sqe->addr);
6035 tr->flags = READ_ONCE(sqe->timeout_flags);
6036 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6037 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6039 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6040 tr->ltimeout = true;
6041 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
6043 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6045 } else if (tr->flags) {
6046 /* timeout removal doesn't support flags */
6053 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6055 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6060 * Remove or update an existing timeout command
6062 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
6064 struct io_timeout_rem *tr = &req->timeout_rem;
6065 struct io_ring_ctx *ctx = req->ctx;
6068 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6069 spin_lock(&ctx->completion_lock);
6070 spin_lock_irq(&ctx->timeout_lock);
6071 ret = io_timeout_cancel(ctx, tr->addr);
6072 spin_unlock_irq(&ctx->timeout_lock);
6073 spin_unlock(&ctx->completion_lock);
6075 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6077 spin_lock_irq(&ctx->timeout_lock);
6079 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6081 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
6082 spin_unlock_irq(&ctx->timeout_lock);
6087 io_req_complete_post(req, ret, 0);
6091 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
6092 bool is_timeout_link)
6094 struct io_timeout_data *data;
6096 u32 off = READ_ONCE(sqe->off);
6098 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6100 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6103 if (off && is_timeout_link)
6105 flags = READ_ONCE(sqe->timeout_flags);
6106 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK))
6108 /* more than one clock specified is invalid, obviously */
6109 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6112 INIT_LIST_HEAD(&req->timeout.list);
6113 req->timeout.off = off;
6114 if (unlikely(off && !req->ctx->off_timeout_used))
6115 req->ctx->off_timeout_used = true;
6117 if (!req->async_data && io_alloc_async_data(req))
6120 data = req->async_data;
6122 data->flags = flags;
6124 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
6127 INIT_LIST_HEAD(&req->timeout.list);
6128 data->mode = io_translate_timeout_mode(flags);
6129 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
6131 if (is_timeout_link) {
6132 struct io_submit_link *link = &req->ctx->submit_state.link;
6136 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6138 req->timeout.head = link->last;
6139 link->last->flags |= REQ_F_ARM_LTIMEOUT;
6144 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
6146 struct io_ring_ctx *ctx = req->ctx;
6147 struct io_timeout_data *data = req->async_data;
6148 struct list_head *entry;
6149 u32 tail, off = req->timeout.off;
6151 spin_lock_irq(&ctx->timeout_lock);
6154 * sqe->off holds how many events that need to occur for this
6155 * timeout event to be satisfied. If it isn't set, then this is
6156 * a pure timeout request, sequence isn't used.
6158 if (io_is_timeout_noseq(req)) {
6159 entry = ctx->timeout_list.prev;
6163 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6164 req->timeout.target_seq = tail + off;
6166 /* Update the last seq here in case io_flush_timeouts() hasn't.
6167 * This is safe because ->completion_lock is held, and submissions
6168 * and completions are never mixed in the same ->completion_lock section.
6170 ctx->cq_last_tm_flush = tail;
6173 * Insertion sort, ensuring the first entry in the list is always
6174 * the one we need first.
6176 list_for_each_prev(entry, &ctx->timeout_list) {
6177 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6180 if (io_is_timeout_noseq(nxt))
6182 /* nxt.seq is behind @tail, otherwise would've been completed */
6183 if (off >= nxt->timeout.target_seq - tail)
6187 list_add(&req->timeout.list, entry);
6188 data->timer.function = io_timeout_fn;
6189 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
6190 spin_unlock_irq(&ctx->timeout_lock);
6194 struct io_cancel_data {
6195 struct io_ring_ctx *ctx;
6199 static bool io_cancel_cb(struct io_wq_work *work, void *data)
6201 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6202 struct io_cancel_data *cd = data;
6204 return req->ctx == cd->ctx && req->user_data == cd->user_data;
6207 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6208 struct io_ring_ctx *ctx)
6210 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
6211 enum io_wq_cancel cancel_ret;
6214 if (!tctx || !tctx->io_wq)
6217 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
6218 switch (cancel_ret) {
6219 case IO_WQ_CANCEL_OK:
6222 case IO_WQ_CANCEL_RUNNING:
6225 case IO_WQ_CANCEL_NOTFOUND:
6233 static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
6235 struct io_ring_ctx *ctx = req->ctx;
6238 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
6240 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
6244 spin_lock(&ctx->completion_lock);
6245 spin_lock_irq(&ctx->timeout_lock);
6246 ret = io_timeout_cancel(ctx, sqe_addr);
6247 spin_unlock_irq(&ctx->timeout_lock);
6250 ret = io_poll_cancel(ctx, sqe_addr, false);
6252 spin_unlock(&ctx->completion_lock);
6256 static int io_async_cancel_prep(struct io_kiocb *req,
6257 const struct io_uring_sqe *sqe)
6259 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6261 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6263 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6267 req->cancel.addr = READ_ONCE(sqe->addr);
6271 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
6273 struct io_ring_ctx *ctx = req->ctx;
6274 u64 sqe_addr = req->cancel.addr;
6275 struct io_tctx_node *node;
6278 ret = io_try_cancel_userdata(req, sqe_addr);
6282 /* slow path, try all io-wq's */
6283 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6285 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6286 struct io_uring_task *tctx = node->task->io_uring;
6288 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6292 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6296 io_req_complete_post(req, ret, 0);
6300 static int io_rsrc_update_prep(struct io_kiocb *req,
6301 const struct io_uring_sqe *sqe)
6303 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6305 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
6308 req->rsrc_update.offset = READ_ONCE(sqe->off);
6309 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6310 if (!req->rsrc_update.nr_args)
6312 req->rsrc_update.arg = READ_ONCE(sqe->addr);
6316 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
6318 struct io_ring_ctx *ctx = req->ctx;
6319 struct io_uring_rsrc_update2 up;
6322 up.offset = req->rsrc_update.offset;
6323 up.data = req->rsrc_update.arg;
6329 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6330 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
6331 &up, req->rsrc_update.nr_args);
6332 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
6336 __io_req_complete(req, issue_flags, ret, 0);
6340 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6342 switch (req->opcode) {
6345 case IORING_OP_READV:
6346 case IORING_OP_READ_FIXED:
6347 case IORING_OP_READ:
6348 return io_read_prep(req, sqe);
6349 case IORING_OP_WRITEV:
6350 case IORING_OP_WRITE_FIXED:
6351 case IORING_OP_WRITE:
6352 return io_write_prep(req, sqe);
6353 case IORING_OP_POLL_ADD:
6354 return io_poll_add_prep(req, sqe);
6355 case IORING_OP_POLL_REMOVE:
6356 return io_poll_update_prep(req, sqe);
6357 case IORING_OP_FSYNC:
6358 return io_fsync_prep(req, sqe);
6359 case IORING_OP_SYNC_FILE_RANGE:
6360 return io_sfr_prep(req, sqe);
6361 case IORING_OP_SENDMSG:
6362 case IORING_OP_SEND:
6363 return io_sendmsg_prep(req, sqe);
6364 case IORING_OP_RECVMSG:
6365 case IORING_OP_RECV:
6366 return io_recvmsg_prep(req, sqe);
6367 case IORING_OP_CONNECT:
6368 return io_connect_prep(req, sqe);
6369 case IORING_OP_TIMEOUT:
6370 return io_timeout_prep(req, sqe, false);
6371 case IORING_OP_TIMEOUT_REMOVE:
6372 return io_timeout_remove_prep(req, sqe);
6373 case IORING_OP_ASYNC_CANCEL:
6374 return io_async_cancel_prep(req, sqe);
6375 case IORING_OP_LINK_TIMEOUT:
6376 return io_timeout_prep(req, sqe, true);
6377 case IORING_OP_ACCEPT:
6378 return io_accept_prep(req, sqe);
6379 case IORING_OP_FALLOCATE:
6380 return io_fallocate_prep(req, sqe);
6381 case IORING_OP_OPENAT:
6382 return io_openat_prep(req, sqe);
6383 case IORING_OP_CLOSE:
6384 return io_close_prep(req, sqe);
6385 case IORING_OP_FILES_UPDATE:
6386 return io_rsrc_update_prep(req, sqe);
6387 case IORING_OP_STATX:
6388 return io_statx_prep(req, sqe);
6389 case IORING_OP_FADVISE:
6390 return io_fadvise_prep(req, sqe);
6391 case IORING_OP_MADVISE:
6392 return io_madvise_prep(req, sqe);
6393 case IORING_OP_OPENAT2:
6394 return io_openat2_prep(req, sqe);
6395 case IORING_OP_EPOLL_CTL:
6396 return io_epoll_ctl_prep(req, sqe);
6397 case IORING_OP_SPLICE:
6398 return io_splice_prep(req, sqe);
6399 case IORING_OP_PROVIDE_BUFFERS:
6400 return io_provide_buffers_prep(req, sqe);
6401 case IORING_OP_REMOVE_BUFFERS:
6402 return io_remove_buffers_prep(req, sqe);
6404 return io_tee_prep(req, sqe);
6405 case IORING_OP_SHUTDOWN:
6406 return io_shutdown_prep(req, sqe);
6407 case IORING_OP_RENAMEAT:
6408 return io_renameat_prep(req, sqe);
6409 case IORING_OP_UNLINKAT:
6410 return io_unlinkat_prep(req, sqe);
6411 case IORING_OP_MKDIRAT:
6412 return io_mkdirat_prep(req, sqe);
6413 case IORING_OP_SYMLINKAT:
6414 return io_symlinkat_prep(req, sqe);
6415 case IORING_OP_LINKAT:
6416 return io_linkat_prep(req, sqe);
6419 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6424 static int io_req_prep_async(struct io_kiocb *req)
6426 if (!io_op_defs[req->opcode].needs_async_setup)
6428 if (WARN_ON_ONCE(req->async_data))
6430 if (io_alloc_async_data(req))
6433 switch (req->opcode) {
6434 case IORING_OP_READV:
6435 return io_rw_prep_async(req, READ);
6436 case IORING_OP_WRITEV:
6437 return io_rw_prep_async(req, WRITE);
6438 case IORING_OP_SENDMSG:
6439 return io_sendmsg_prep_async(req);
6440 case IORING_OP_RECVMSG:
6441 return io_recvmsg_prep_async(req);
6442 case IORING_OP_CONNECT:
6443 return io_connect_prep_async(req);
6445 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
6450 static u32 io_get_sequence(struct io_kiocb *req)
6452 u32 seq = req->ctx->cached_sq_head;
6454 /* need original cached_sq_head, but it was increased for each req */
6455 io_for_each_link(req, req)
6460 static bool io_drain_req(struct io_kiocb *req)
6462 struct io_kiocb *pos;
6463 struct io_ring_ctx *ctx = req->ctx;
6464 struct io_defer_entry *de;
6468 if (req->flags & REQ_F_FAIL) {
6469 io_req_complete_fail_submit(req);
6474 * If we need to drain a request in the middle of a link, drain the
6475 * head request and the next request/link after the current link.
6476 * Considering sequential execution of links, IOSQE_IO_DRAIN will be
6477 * maintained for every request of our link.
6479 if (ctx->drain_next) {
6480 req->flags |= REQ_F_IO_DRAIN;
6481 ctx->drain_next = false;
6483 /* not interested in head, start from the first linked */
6484 io_for_each_link(pos, req->link) {
6485 if (pos->flags & REQ_F_IO_DRAIN) {
6486 ctx->drain_next = true;
6487 req->flags |= REQ_F_IO_DRAIN;
6492 /* Still need defer if there is pending req in defer list. */
6493 spin_lock(&ctx->completion_lock);
6494 if (likely(list_empty_careful(&ctx->defer_list) &&
6495 !(req->flags & REQ_F_IO_DRAIN))) {
6496 spin_unlock(&ctx->completion_lock);
6497 ctx->drain_active = false;
6500 spin_unlock(&ctx->completion_lock);
6502 seq = io_get_sequence(req);
6503 /* Still a chance to pass the sequence check */
6504 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6507 ret = io_req_prep_async(req);
6510 io_prep_async_link(req);
6511 de = kmalloc(sizeof(*de), GFP_KERNEL);
6515 io_req_complete_failed(req, ret);
6519 spin_lock(&ctx->completion_lock);
6520 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6521 spin_unlock(&ctx->completion_lock);
6523 io_queue_async_work(req, NULL);
6527 trace_io_uring_defer(ctx, req, req->user_data);
6530 list_add_tail(&de->list, &ctx->defer_list);
6531 spin_unlock(&ctx->completion_lock);
6535 static void io_clean_op(struct io_kiocb *req)
6537 if (req->flags & REQ_F_BUFFER_SELECTED) {
6538 switch (req->opcode) {
6539 case IORING_OP_READV:
6540 case IORING_OP_READ_FIXED:
6541 case IORING_OP_READ:
6542 kfree((void *)(unsigned long)req->rw.addr);
6544 case IORING_OP_RECVMSG:
6545 case IORING_OP_RECV:
6546 kfree(req->sr_msg.kbuf);
6551 if (req->flags & REQ_F_NEED_CLEANUP) {
6552 switch (req->opcode) {
6553 case IORING_OP_READV:
6554 case IORING_OP_READ_FIXED:
6555 case IORING_OP_READ:
6556 case IORING_OP_WRITEV:
6557 case IORING_OP_WRITE_FIXED:
6558 case IORING_OP_WRITE: {
6559 struct io_async_rw *io = req->async_data;
6561 kfree(io->free_iovec);
6564 case IORING_OP_RECVMSG:
6565 case IORING_OP_SENDMSG: {
6566 struct io_async_msghdr *io = req->async_data;
6568 kfree(io->free_iov);
6571 case IORING_OP_OPENAT:
6572 case IORING_OP_OPENAT2:
6573 if (req->open.filename)
6574 putname(req->open.filename);
6576 case IORING_OP_RENAMEAT:
6577 putname(req->rename.oldpath);
6578 putname(req->rename.newpath);
6580 case IORING_OP_UNLINKAT:
6581 putname(req->unlink.filename);
6583 case IORING_OP_MKDIRAT:
6584 putname(req->mkdir.filename);
6586 case IORING_OP_SYMLINKAT:
6587 putname(req->symlink.oldpath);
6588 putname(req->symlink.newpath);
6590 case IORING_OP_LINKAT:
6591 putname(req->hardlink.oldpath);
6592 putname(req->hardlink.newpath);
6596 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6597 kfree(req->apoll->double_poll);
6601 if (req->flags & REQ_F_INFLIGHT) {
6602 struct io_uring_task *tctx = req->task->io_uring;
6604 atomic_dec(&tctx->inflight_tracked);
6606 if (req->flags & REQ_F_CREDS)
6607 put_cred(req->creds);
6609 req->flags &= ~IO_REQ_CLEAN_FLAGS;
6612 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6614 struct io_ring_ctx *ctx = req->ctx;
6615 const struct cred *creds = NULL;
6618 if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
6619 creds = override_creds(req->creds);
6621 switch (req->opcode) {
6623 ret = io_nop(req, issue_flags);
6625 case IORING_OP_READV:
6626 case IORING_OP_READ_FIXED:
6627 case IORING_OP_READ:
6628 ret = io_read(req, issue_flags);
6630 case IORING_OP_WRITEV:
6631 case IORING_OP_WRITE_FIXED:
6632 case IORING_OP_WRITE:
6633 ret = io_write(req, issue_flags);
6635 case IORING_OP_FSYNC:
6636 ret = io_fsync(req, issue_flags);
6638 case IORING_OP_POLL_ADD:
6639 ret = io_poll_add(req, issue_flags);
6641 case IORING_OP_POLL_REMOVE:
6642 ret = io_poll_update(req, issue_flags);
6644 case IORING_OP_SYNC_FILE_RANGE:
6645 ret = io_sync_file_range(req, issue_flags);
6647 case IORING_OP_SENDMSG:
6648 ret = io_sendmsg(req, issue_flags);
6650 case IORING_OP_SEND:
6651 ret = io_send(req, issue_flags);
6653 case IORING_OP_RECVMSG:
6654 ret = io_recvmsg(req, issue_flags);
6656 case IORING_OP_RECV:
6657 ret = io_recv(req, issue_flags);
6659 case IORING_OP_TIMEOUT:
6660 ret = io_timeout(req, issue_flags);
6662 case IORING_OP_TIMEOUT_REMOVE:
6663 ret = io_timeout_remove(req, issue_flags);
6665 case IORING_OP_ACCEPT:
6666 ret = io_accept(req, issue_flags);
6668 case IORING_OP_CONNECT:
6669 ret = io_connect(req, issue_flags);
6671 case IORING_OP_ASYNC_CANCEL:
6672 ret = io_async_cancel(req, issue_flags);
6674 case IORING_OP_FALLOCATE:
6675 ret = io_fallocate(req, issue_flags);
6677 case IORING_OP_OPENAT:
6678 ret = io_openat(req, issue_flags);
6680 case IORING_OP_CLOSE:
6681 ret = io_close(req, issue_flags);
6683 case IORING_OP_FILES_UPDATE:
6684 ret = io_files_update(req, issue_flags);
6686 case IORING_OP_STATX:
6687 ret = io_statx(req, issue_flags);
6689 case IORING_OP_FADVISE:
6690 ret = io_fadvise(req, issue_flags);
6692 case IORING_OP_MADVISE:
6693 ret = io_madvise(req, issue_flags);
6695 case IORING_OP_OPENAT2:
6696 ret = io_openat2(req, issue_flags);
6698 case IORING_OP_EPOLL_CTL:
6699 ret = io_epoll_ctl(req, issue_flags);
6701 case IORING_OP_SPLICE:
6702 ret = io_splice(req, issue_flags);
6704 case IORING_OP_PROVIDE_BUFFERS:
6705 ret = io_provide_buffers(req, issue_flags);
6707 case IORING_OP_REMOVE_BUFFERS:
6708 ret = io_remove_buffers(req, issue_flags);
6711 ret = io_tee(req, issue_flags);
6713 case IORING_OP_SHUTDOWN:
6714 ret = io_shutdown(req, issue_flags);
6716 case IORING_OP_RENAMEAT:
6717 ret = io_renameat(req, issue_flags);
6719 case IORING_OP_UNLINKAT:
6720 ret = io_unlinkat(req, issue_flags);
6722 case IORING_OP_MKDIRAT:
6723 ret = io_mkdirat(req, issue_flags);
6725 case IORING_OP_SYMLINKAT:
6726 ret = io_symlinkat(req, issue_flags);
6728 case IORING_OP_LINKAT:
6729 ret = io_linkat(req, issue_flags);
6737 revert_creds(creds);
6740 /* If the op doesn't have a file, we're not polling for it */
6741 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file)
6742 io_iopoll_req_issued(req);
6747 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
6749 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6751 req = io_put_req_find_next(req);
6752 return req ? &req->work : NULL;
6755 static void io_wq_submit_work(struct io_wq_work *work)
6757 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6758 struct io_kiocb *timeout;
6761 /* one will be dropped by ->io_free_work() after returning to io-wq */
6762 if (!(req->flags & REQ_F_REFCOUNT))
6763 __io_req_set_refcount(req, 2);
6767 timeout = io_prep_linked_timeout(req);
6769 io_queue_linked_timeout(timeout);
6771 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
6772 if (work->flags & IO_WQ_WORK_CANCEL)
6777 ret = io_issue_sqe(req, 0);
6779 * We can get EAGAIN for polled IO even though we're
6780 * forcing a sync submission from here, since we can't
6781 * wait for request slots on the block side.
6783 if (ret != -EAGAIN || !(req->ctx->flags & IORING_SETUP_IOPOLL))
6789 /* avoid locking problems by failing it from a clean context */
6791 io_req_task_queue_fail(req, ret);
6794 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6797 return &table->files[i];
6800 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6803 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6805 return (struct file *) (slot->file_ptr & FFS_MASK);
6808 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6810 unsigned long file_ptr = (unsigned long) file;
6812 if (__io_file_supports_nowait(file, READ))
6813 file_ptr |= FFS_ASYNC_READ;
6814 if (__io_file_supports_nowait(file, WRITE))
6815 file_ptr |= FFS_ASYNC_WRITE;
6816 if (S_ISREG(file_inode(file)->i_mode))
6817 file_ptr |= FFS_ISREG;
6818 file_slot->file_ptr = file_ptr;
6821 static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
6822 struct io_kiocb *req, int fd)
6825 unsigned long file_ptr;
6827 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6829 fd = array_index_nospec(fd, ctx->nr_user_files);
6830 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6831 file = (struct file *) (file_ptr & FFS_MASK);
6832 file_ptr &= ~FFS_MASK;
6833 /* mask in overlapping REQ_F and FFS bits */
6834 req->flags |= (file_ptr << REQ_F_NOWAIT_READ_BIT);
6835 io_req_set_rsrc_node(req);
6839 static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
6840 struct io_kiocb *req, int fd)
6842 struct file *file = fget(fd);
6844 trace_io_uring_file_get(ctx, fd);
6846 /* we don't allow fixed io_uring files */
6847 if (file && unlikely(file->f_op == &io_uring_fops))
6848 io_req_track_inflight(req);
6852 static inline struct file *io_file_get(struct io_ring_ctx *ctx,
6853 struct io_kiocb *req, int fd, bool fixed)
6856 return io_file_get_fixed(ctx, req, fd);
6858 return io_file_get_normal(ctx, req, fd);
6861 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
6863 struct io_kiocb *prev = req->timeout.prev;
6867 if (!(req->task->flags & PF_EXITING))
6868 ret = io_try_cancel_userdata(req, prev->user_data);
6869 io_req_complete_post(req, ret ?: -ETIME, 0);
6872 io_req_complete_post(req, -ETIME, 0);
6876 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6878 struct io_timeout_data *data = container_of(timer,
6879 struct io_timeout_data, timer);
6880 struct io_kiocb *prev, *req = data->req;
6881 struct io_ring_ctx *ctx = req->ctx;
6882 unsigned long flags;
6884 spin_lock_irqsave(&ctx->timeout_lock, flags);
6885 prev = req->timeout.head;
6886 req->timeout.head = NULL;
6889 * We don't expect the list to be empty, that will only happen if we
6890 * race with the completion of the linked work.
6893 io_remove_next_linked(prev);
6894 if (!req_ref_inc_not_zero(prev))
6897 list_del(&req->timeout.list);
6898 req->timeout.prev = prev;
6899 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
6901 req->io_task_work.func = io_req_task_link_timeout;
6902 io_req_task_work_add(req);
6903 return HRTIMER_NORESTART;
6906 static void io_queue_linked_timeout(struct io_kiocb *req)
6908 struct io_ring_ctx *ctx = req->ctx;
6910 spin_lock_irq(&ctx->timeout_lock);
6912 * If the back reference is NULL, then our linked request finished
6913 * before we got a chance to setup the timer
6915 if (req->timeout.head) {
6916 struct io_timeout_data *data = req->async_data;
6918 data->timer.function = io_link_timeout_fn;
6919 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6921 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
6923 spin_unlock_irq(&ctx->timeout_lock);
6924 /* drop submission reference */
6928 static void __io_queue_sqe(struct io_kiocb *req)
6929 __must_hold(&req->ctx->uring_lock)
6931 struct io_kiocb *linked_timeout;
6935 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6938 * We async punt it if the file wasn't marked NOWAIT, or if the file
6939 * doesn't support non-blocking read/write attempts
6942 if (req->flags & REQ_F_COMPLETE_INLINE) {
6943 struct io_ring_ctx *ctx = req->ctx;
6944 struct io_submit_state *state = &ctx->submit_state;
6946 state->compl_reqs[state->compl_nr++] = req;
6947 if (state->compl_nr == ARRAY_SIZE(state->compl_reqs))
6948 io_submit_flush_completions(ctx);
6952 linked_timeout = io_prep_linked_timeout(req);
6954 io_queue_linked_timeout(linked_timeout);
6955 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6956 linked_timeout = io_prep_linked_timeout(req);
6958 switch (io_arm_poll_handler(req)) {
6959 case IO_APOLL_READY:
6961 io_queue_linked_timeout(linked_timeout);
6963 case IO_APOLL_ABORTED:
6965 * Queued up for async execution, worker will release
6966 * submit reference when the iocb is actually submitted.
6968 io_queue_async_work(req, NULL);
6973 io_queue_linked_timeout(linked_timeout);
6975 io_req_complete_failed(req, ret);
6979 static inline void io_queue_sqe(struct io_kiocb *req)
6980 __must_hold(&req->ctx->uring_lock)
6982 if (unlikely(req->ctx->drain_active) && io_drain_req(req))
6985 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
6986 __io_queue_sqe(req);
6987 } else if (req->flags & REQ_F_FAIL) {
6988 io_req_complete_fail_submit(req);
6990 int ret = io_req_prep_async(req);
6993 io_req_complete_failed(req, ret);
6995 io_queue_async_work(req, NULL);
7000 * Check SQE restrictions (opcode and flags).
7002 * Returns 'true' if SQE is allowed, 'false' otherwise.
7004 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7005 struct io_kiocb *req,
7006 unsigned int sqe_flags)
7008 if (likely(!ctx->restricted))
7011 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7014 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7015 ctx->restrictions.sqe_flags_required)
7018 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7019 ctx->restrictions.sqe_flags_required))
7025 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7026 const struct io_uring_sqe *sqe)
7027 __must_hold(&ctx->uring_lock)
7029 struct io_submit_state *state;
7030 unsigned int sqe_flags;
7031 int personality, ret = 0;
7033 /* req is partially pre-initialised, see io_preinit_req() */
7034 req->opcode = READ_ONCE(sqe->opcode);
7035 /* same numerical values with corresponding REQ_F_*, safe to copy */
7036 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7037 req->user_data = READ_ONCE(sqe->user_data);
7039 req->fixed_rsrc_refs = NULL;
7040 req->task = current;
7042 /* enforce forwards compatibility on users */
7043 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
7045 if (unlikely(req->opcode >= IORING_OP_LAST))
7047 if (!io_check_restriction(ctx, req, sqe_flags))
7050 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
7051 !io_op_defs[req->opcode].buffer_select)
7053 if (unlikely(sqe_flags & IOSQE_IO_DRAIN))
7054 ctx->drain_active = true;
7056 personality = READ_ONCE(sqe->personality);
7058 req->creds = xa_load(&ctx->personalities, personality);
7061 get_cred(req->creds);
7062 req->flags |= REQ_F_CREDS;
7064 state = &ctx->submit_state;
7067 * Plug now if we have more than 1 IO left after this, and the target
7068 * is potentially a read/write to block based storage.
7070 if (!state->plug_started && state->ios_left > 1 &&
7071 io_op_defs[req->opcode].plug) {
7072 blk_start_plug(&state->plug);
7073 state->plug_started = true;
7076 if (io_op_defs[req->opcode].needs_file) {
7077 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
7078 (sqe_flags & IOSQE_FIXED_FILE));
7079 if (unlikely(!req->file))
7087 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
7088 const struct io_uring_sqe *sqe)
7089 __must_hold(&ctx->uring_lock)
7091 struct io_submit_link *link = &ctx->submit_state.link;
7094 ret = io_init_req(ctx, req, sqe);
7095 if (unlikely(ret)) {
7097 /* fail even hard links since we don't submit */
7100 * we can judge a link req is failed or cancelled by if
7101 * REQ_F_FAIL is set, but the head is an exception since
7102 * it may be set REQ_F_FAIL because of other req's failure
7103 * so let's leverage req->result to distinguish if a head
7104 * is set REQ_F_FAIL because of its failure or other req's
7105 * failure so that we can set the correct ret code for it.
7106 * init result here to avoid affecting the normal path.
7108 if (!(link->head->flags & REQ_F_FAIL))
7109 req_fail_link_node(link->head, -ECANCELED);
7110 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7112 * the current req is a normal req, we should return
7113 * error and thus break the submittion loop.
7115 io_req_complete_failed(req, ret);
7118 req_fail_link_node(req, ret);
7120 ret = io_req_prep(req, sqe);
7125 /* don't need @sqe from now on */
7126 trace_io_uring_submit_sqe(ctx, req, req->opcode, req->user_data,
7128 ctx->flags & IORING_SETUP_SQPOLL);
7131 * If we already have a head request, queue this one for async
7132 * submittal once the head completes. If we don't have a head but
7133 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7134 * submitted sync once the chain is complete. If none of those
7135 * conditions are true (normal request), then just queue it.
7138 struct io_kiocb *head = link->head;
7140 if (!(req->flags & REQ_F_FAIL)) {
7141 ret = io_req_prep_async(req);
7142 if (unlikely(ret)) {
7143 req_fail_link_node(req, ret);
7144 if (!(head->flags & REQ_F_FAIL))
7145 req_fail_link_node(head, -ECANCELED);
7148 trace_io_uring_link(ctx, req, head);
7149 link->last->link = req;
7152 /* last request of a link, enqueue the link */
7153 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7158 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7170 * Batched submission is done, ensure local IO is flushed out.
7172 static void io_submit_state_end(struct io_submit_state *state,
7173 struct io_ring_ctx *ctx)
7175 if (state->link.head)
7176 io_queue_sqe(state->link.head);
7177 if (state->compl_nr)
7178 io_submit_flush_completions(ctx);
7179 if (state->plug_started)
7180 blk_finish_plug(&state->plug);
7184 * Start submission side cache.
7186 static void io_submit_state_start(struct io_submit_state *state,
7187 unsigned int max_ios)
7189 state->plug_started = false;
7190 state->ios_left = max_ios;
7191 /* set only head, no need to init link_last in advance */
7192 state->link.head = NULL;
7195 static void io_commit_sqring(struct io_ring_ctx *ctx)
7197 struct io_rings *rings = ctx->rings;
7200 * Ensure any loads from the SQEs are done at this point,
7201 * since once we write the new head, the application could
7202 * write new data to them.
7204 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
7208 * Fetch an sqe, if one is available. Note this returns a pointer to memory
7209 * that is mapped by userspace. This means that care needs to be taken to
7210 * ensure that reads are stable, as we cannot rely on userspace always
7211 * being a good citizen. If members of the sqe are validated and then later
7212 * used, it's important that those reads are done through READ_ONCE() to
7213 * prevent a re-load down the line.
7215 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
7217 unsigned head, mask = ctx->sq_entries - 1;
7218 unsigned sq_idx = ctx->cached_sq_head++ & mask;
7221 * The cached sq head (or cq tail) serves two purposes:
7223 * 1) allows us to batch the cost of updating the user visible
7225 * 2) allows the kernel side to track the head on its own, even
7226 * though the application is the one updating it.
7228 head = READ_ONCE(ctx->sq_array[sq_idx]);
7229 if (likely(head < ctx->sq_entries))
7230 return &ctx->sq_sqes[head];
7232 /* drop invalid entries */
7234 WRITE_ONCE(ctx->rings->sq_dropped,
7235 READ_ONCE(ctx->rings->sq_dropped) + 1);
7239 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
7240 __must_hold(&ctx->uring_lock)
7244 /* make sure SQ entry isn't read before tail */
7245 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
7246 if (!percpu_ref_tryget_many(&ctx->refs, nr))
7248 io_get_task_refs(nr);
7250 io_submit_state_start(&ctx->submit_state, nr);
7251 while (submitted < nr) {
7252 const struct io_uring_sqe *sqe;
7253 struct io_kiocb *req;
7255 req = io_alloc_req(ctx);
7256 if (unlikely(!req)) {
7258 submitted = -EAGAIN;
7261 sqe = io_get_sqe(ctx);
7262 if (unlikely(!sqe)) {
7263 list_add(&req->inflight_entry, &ctx->submit_state.free_list);
7266 /* will complete beyond this point, count as submitted */
7268 if (io_submit_sqe(ctx, req, sqe))
7272 if (unlikely(submitted != nr)) {
7273 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
7274 int unused = nr - ref_used;
7276 current->io_uring->cached_refs += unused;
7277 percpu_ref_put_many(&ctx->refs, unused);
7280 io_submit_state_end(&ctx->submit_state, ctx);
7281 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7282 io_commit_sqring(ctx);
7287 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7289 return READ_ONCE(sqd->state);
7292 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7294 /* Tell userspace we may need a wakeup call */
7295 spin_lock(&ctx->completion_lock);
7296 WRITE_ONCE(ctx->rings->sq_flags,
7297 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
7298 spin_unlock(&ctx->completion_lock);
7301 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7303 spin_lock(&ctx->completion_lock);
7304 WRITE_ONCE(ctx->rings->sq_flags,
7305 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
7306 spin_unlock(&ctx->completion_lock);
7309 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
7311 unsigned int to_submit;
7314 to_submit = io_sqring_entries(ctx);
7315 /* if we're handling multiple rings, cap submit size for fairness */
7316 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7317 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
7319 if (!list_empty(&ctx->iopoll_list) || to_submit) {
7320 unsigned nr_events = 0;
7321 const struct cred *creds = NULL;
7323 if (ctx->sq_creds != current_cred())
7324 creds = override_creds(ctx->sq_creds);
7326 mutex_lock(&ctx->uring_lock);
7327 if (!list_empty(&ctx->iopoll_list))
7328 io_do_iopoll(ctx, &nr_events, 0);
7331 * Don't submit if refs are dying, good for io_uring_register(),
7332 * but also it is relied upon by io_ring_exit_work()
7334 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7335 !(ctx->flags & IORING_SETUP_R_DISABLED))
7336 ret = io_submit_sqes(ctx, to_submit);
7337 mutex_unlock(&ctx->uring_lock);
7339 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7340 wake_up(&ctx->sqo_sq_wait);
7342 revert_creds(creds);
7348 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
7350 struct io_ring_ctx *ctx;
7351 unsigned sq_thread_idle = 0;
7353 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7354 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
7355 sqd->sq_thread_idle = sq_thread_idle;
7358 static bool io_sqd_handle_event(struct io_sq_data *sqd)
7360 bool did_sig = false;
7361 struct ksignal ksig;
7363 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7364 signal_pending(current)) {
7365 mutex_unlock(&sqd->lock);
7366 if (signal_pending(current))
7367 did_sig = get_signal(&ksig);
7369 mutex_lock(&sqd->lock);
7371 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7374 static int io_sq_thread(void *data)
7376 struct io_sq_data *sqd = data;
7377 struct io_ring_ctx *ctx;
7378 unsigned long timeout = 0;
7379 char buf[TASK_COMM_LEN];
7382 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
7383 set_task_comm(current, buf);
7385 if (sqd->sq_cpu != -1)
7386 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
7388 set_cpus_allowed_ptr(current, cpu_online_mask);
7389 current->flags |= PF_NO_SETAFFINITY;
7391 mutex_lock(&sqd->lock);
7393 bool cap_entries, sqt_spin = false;
7395 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
7396 if (io_sqd_handle_event(sqd))
7398 timeout = jiffies + sqd->sq_thread_idle;
7401 cap_entries = !list_is_singular(&sqd->ctx_list);
7402 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7403 int ret = __io_sq_thread(ctx, cap_entries);
7405 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
7408 if (io_run_task_work())
7411 if (sqt_spin || !time_after(jiffies, timeout)) {
7414 timeout = jiffies + sqd->sq_thread_idle;
7418 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
7419 if (!io_sqd_events_pending(sqd) && !current->task_works) {
7420 bool needs_sched = true;
7422 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
7423 io_ring_set_wakeup_flag(ctx);
7425 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
7426 !list_empty_careful(&ctx->iopoll_list)) {
7427 needs_sched = false;
7430 if (io_sqring_entries(ctx)) {
7431 needs_sched = false;
7437 mutex_unlock(&sqd->lock);
7439 mutex_lock(&sqd->lock);
7441 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7442 io_ring_clear_wakeup_flag(ctx);
7445 finish_wait(&sqd->wait, &wait);
7446 timeout = jiffies + sqd->sq_thread_idle;
7449 io_uring_cancel_generic(true, sqd);
7451 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7452 io_ring_set_wakeup_flag(ctx);
7454 mutex_unlock(&sqd->lock);
7456 complete(&sqd->exited);
7460 struct io_wait_queue {
7461 struct wait_queue_entry wq;
7462 struct io_ring_ctx *ctx;
7464 unsigned nr_timeouts;
7467 static inline bool io_should_wake(struct io_wait_queue *iowq)
7469 struct io_ring_ctx *ctx = iowq->ctx;
7470 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
7473 * Wake up if we have enough events, or if a timeout occurred since we
7474 * started waiting. For timeouts, we always want to return to userspace,
7475 * regardless of event count.
7477 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
7480 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
7481 int wake_flags, void *key)
7483 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
7487 * Cannot safely flush overflowed CQEs from here, ensure we wake up
7488 * the task, and the next invocation will do it.
7490 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
7491 return autoremove_wake_function(curr, mode, wake_flags, key);
7495 static int io_run_task_work_sig(void)
7497 if (io_run_task_work())
7499 if (!signal_pending(current))
7501 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
7502 return -ERESTARTSYS;
7506 /* when returns >0, the caller should retry */
7507 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
7508 struct io_wait_queue *iowq,
7513 /* make sure we run task_work before checking for signals */
7514 ret = io_run_task_work_sig();
7515 if (ret || io_should_wake(iowq))
7517 /* let the caller flush overflows, retry */
7518 if (test_bit(0, &ctx->check_cq_overflow))
7521 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
7527 * Wait until events become available, if we don't already have some. The
7528 * application must reap them itself, as they reside on the shared cq ring.
7530 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
7531 const sigset_t __user *sig, size_t sigsz,
7532 struct __kernel_timespec __user *uts)
7534 struct io_wait_queue iowq;
7535 struct io_rings *rings = ctx->rings;
7536 ktime_t timeout = KTIME_MAX;
7540 io_cqring_overflow_flush(ctx);
7541 if (io_cqring_events(ctx) >= min_events)
7543 if (!io_run_task_work())
7548 struct timespec64 ts;
7550 if (get_timespec64(&ts, uts))
7552 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
7556 #ifdef CONFIG_COMPAT
7557 if (in_compat_syscall())
7558 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7562 ret = set_user_sigmask(sig, sigsz);
7568 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
7569 iowq.wq.private = current;
7570 INIT_LIST_HEAD(&iowq.wq.entry);
7572 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7573 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
7575 trace_io_uring_cqring_wait(ctx, min_events);
7577 /* if we can't even flush overflow, don't wait for more */
7578 if (!io_cqring_overflow_flush(ctx)) {
7582 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
7583 TASK_INTERRUPTIBLE);
7584 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
7585 finish_wait(&ctx->cq_wait, &iowq.wq);
7589 restore_saved_sigmask_unless(ret == -EINTR);
7591 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7594 static void io_free_page_table(void **table, size_t size)
7596 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7598 for (i = 0; i < nr_tables; i++)
7603 static void **io_alloc_page_table(size_t size)
7605 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
7606 size_t init_size = size;
7609 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
7613 for (i = 0; i < nr_tables; i++) {
7614 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
7616 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
7618 io_free_page_table(table, init_size);
7626 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7628 percpu_ref_exit(&ref_node->refs);
7632 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7634 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7635 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7636 unsigned long flags;
7637 bool first_add = false;
7638 unsigned long delay = HZ;
7640 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
7643 /* if we are mid-quiesce then do not delay */
7644 if (node->rsrc_data->quiesce)
7647 while (!list_empty(&ctx->rsrc_ref_list)) {
7648 node = list_first_entry(&ctx->rsrc_ref_list,
7649 struct io_rsrc_node, node);
7650 /* recycle ref nodes in order */
7653 list_del(&node->node);
7654 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7656 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
7659 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7662 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7664 struct io_rsrc_node *ref_node;
7666 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7670 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7675 INIT_LIST_HEAD(&ref_node->node);
7676 INIT_LIST_HEAD(&ref_node->rsrc_list);
7677 ref_node->done = false;
7681 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7682 struct io_rsrc_data *data_to_kill)
7684 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7685 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7688 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7690 rsrc_node->rsrc_data = data_to_kill;
7691 spin_lock_irq(&ctx->rsrc_ref_lock);
7692 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7693 spin_unlock_irq(&ctx->rsrc_ref_lock);
7695 atomic_inc(&data_to_kill->refs);
7696 percpu_ref_kill(&rsrc_node->refs);
7697 ctx->rsrc_node = NULL;
7700 if (!ctx->rsrc_node) {
7701 ctx->rsrc_node = ctx->rsrc_backup_node;
7702 ctx->rsrc_backup_node = NULL;
7706 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7708 if (ctx->rsrc_backup_node)
7710 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7711 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7714 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7718 /* As we may drop ->uring_lock, other task may have started quiesce */
7722 data->quiesce = true;
7724 ret = io_rsrc_node_switch_start(ctx);
7727 io_rsrc_node_switch(ctx, data);
7729 /* kill initial ref, already quiesced if zero */
7730 if (atomic_dec_and_test(&data->refs))
7732 mutex_unlock(&ctx->uring_lock);
7733 flush_delayed_work(&ctx->rsrc_put_work);
7734 ret = wait_for_completion_interruptible(&data->done);
7736 mutex_lock(&ctx->uring_lock);
7737 if (atomic_read(&data->refs) > 0) {
7739 * it has been revived by another thread while
7742 mutex_unlock(&ctx->uring_lock);
7748 atomic_inc(&data->refs);
7749 /* wait for all works potentially completing data->done */
7750 flush_delayed_work(&ctx->rsrc_put_work);
7751 reinit_completion(&data->done);
7753 ret = io_run_task_work_sig();
7754 mutex_lock(&ctx->uring_lock);
7756 data->quiesce = false;
7761 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
7763 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
7764 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
7766 return &data->tags[table_idx][off];
7769 static void io_rsrc_data_free(struct io_rsrc_data *data)
7771 size_t size = data->nr * sizeof(data->tags[0][0]);
7774 io_free_page_table((void **)data->tags, size);
7778 static int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
7779 u64 __user *utags, unsigned nr,
7780 struct io_rsrc_data **pdata)
7782 struct io_rsrc_data *data;
7786 data = kzalloc(sizeof(*data), GFP_KERNEL);
7789 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
7797 data->do_put = do_put;
7800 for (i = 0; i < nr; i++) {
7801 u64 *tag_slot = io_get_tag_slot(data, i);
7803 if (copy_from_user(tag_slot, &utags[i],
7809 atomic_set(&data->refs, 1);
7810 init_completion(&data->done);
7814 io_rsrc_data_free(data);
7818 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7820 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
7821 GFP_KERNEL_ACCOUNT);
7822 return !!table->files;
7825 static void io_free_file_tables(struct io_file_table *table)
7827 kvfree(table->files);
7828 table->files = NULL;
7831 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7833 #if defined(CONFIG_UNIX)
7834 if (ctx->ring_sock) {
7835 struct sock *sock = ctx->ring_sock->sk;
7836 struct sk_buff *skb;
7838 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7844 for (i = 0; i < ctx->nr_user_files; i++) {
7847 file = io_file_from_index(ctx, i);
7852 io_free_file_tables(&ctx->file_table);
7853 io_rsrc_data_free(ctx->file_data);
7854 ctx->file_data = NULL;
7855 ctx->nr_user_files = 0;
7858 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7860 unsigned nr = ctx->nr_user_files;
7863 if (!ctx->file_data)
7867 * Quiesce may unlock ->uring_lock, and while it's not held
7868 * prevent new requests using the table.
7870 ctx->nr_user_files = 0;
7871 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7872 ctx->nr_user_files = nr;
7874 __io_sqe_files_unregister(ctx);
7878 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7879 __releases(&sqd->lock)
7881 WARN_ON_ONCE(sqd->thread == current);
7884 * Do the dance but not conditional clear_bit() because it'd race with
7885 * other threads incrementing park_pending and setting the bit.
7887 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7888 if (atomic_dec_return(&sqd->park_pending))
7889 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7890 mutex_unlock(&sqd->lock);
7893 static void io_sq_thread_park(struct io_sq_data *sqd)
7894 __acquires(&sqd->lock)
7896 WARN_ON_ONCE(sqd->thread == current);
7898 atomic_inc(&sqd->park_pending);
7899 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7900 mutex_lock(&sqd->lock);
7902 wake_up_process(sqd->thread);
7905 static void io_sq_thread_stop(struct io_sq_data *sqd)
7907 WARN_ON_ONCE(sqd->thread == current);
7908 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7910 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7911 mutex_lock(&sqd->lock);
7913 wake_up_process(sqd->thread);
7914 mutex_unlock(&sqd->lock);
7915 wait_for_completion(&sqd->exited);
7918 static void io_put_sq_data(struct io_sq_data *sqd)
7920 if (refcount_dec_and_test(&sqd->refs)) {
7921 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7923 io_sq_thread_stop(sqd);
7928 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7930 struct io_sq_data *sqd = ctx->sq_data;
7933 io_sq_thread_park(sqd);
7934 list_del_init(&ctx->sqd_list);
7935 io_sqd_update_thread_idle(sqd);
7936 io_sq_thread_unpark(sqd);
7938 io_put_sq_data(sqd);
7939 ctx->sq_data = NULL;
7943 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7945 struct io_ring_ctx *ctx_attach;
7946 struct io_sq_data *sqd;
7949 f = fdget(p->wq_fd);
7951 return ERR_PTR(-ENXIO);
7952 if (f.file->f_op != &io_uring_fops) {
7954 return ERR_PTR(-EINVAL);
7957 ctx_attach = f.file->private_data;
7958 sqd = ctx_attach->sq_data;
7961 return ERR_PTR(-EINVAL);
7963 if (sqd->task_tgid != current->tgid) {
7965 return ERR_PTR(-EPERM);
7968 refcount_inc(&sqd->refs);
7973 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7976 struct io_sq_data *sqd;
7979 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7980 sqd = io_attach_sq_data(p);
7985 /* fall through for EPERM case, setup new sqd/task */
7986 if (PTR_ERR(sqd) != -EPERM)
7990 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7992 return ERR_PTR(-ENOMEM);
7994 atomic_set(&sqd->park_pending, 0);
7995 refcount_set(&sqd->refs, 1);
7996 INIT_LIST_HEAD(&sqd->ctx_list);
7997 mutex_init(&sqd->lock);
7998 init_waitqueue_head(&sqd->wait);
7999 init_completion(&sqd->exited);
8003 #if defined(CONFIG_UNIX)
8005 * Ensure the UNIX gc is aware of our file set, so we are certain that
8006 * the io_uring can be safely unregistered on process exit, even if we have
8007 * loops in the file referencing.
8009 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8011 struct sock *sk = ctx->ring_sock->sk;
8012 struct scm_fp_list *fpl;
8013 struct sk_buff *skb;
8016 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8020 skb = alloc_skb(0, GFP_KERNEL);
8029 fpl->user = get_uid(current_user());
8030 for (i = 0; i < nr; i++) {
8031 struct file *file = io_file_from_index(ctx, i + offset);
8035 fpl->fp[nr_files] = get_file(file);
8036 unix_inflight(fpl->user, fpl->fp[nr_files]);
8041 fpl->max = SCM_MAX_FD;
8042 fpl->count = nr_files;
8043 UNIXCB(skb).fp = fpl;
8044 skb->destructor = unix_destruct_scm;
8045 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8046 skb_queue_head(&sk->sk_receive_queue, skb);
8048 for (i = 0; i < nr; i++) {
8049 struct file *file = io_file_from_index(ctx, i + offset);
8056 free_uid(fpl->user);
8064 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8065 * causes regular reference counting to break down. We rely on the UNIX
8066 * garbage collection to take care of this problem for us.
8068 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8070 unsigned left, total;
8074 left = ctx->nr_user_files;
8076 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
8078 ret = __io_sqe_files_scm(ctx, this_files, total);
8082 total += this_files;
8088 while (total < ctx->nr_user_files) {
8089 struct file *file = io_file_from_index(ctx, total);
8099 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8105 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8107 struct file *file = prsrc->file;
8108 #if defined(CONFIG_UNIX)
8109 struct sock *sock = ctx->ring_sock->sk;
8110 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8111 struct sk_buff *skb;
8114 __skb_queue_head_init(&list);
8117 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8118 * remove this entry and rearrange the file array.
8120 skb = skb_dequeue(head);
8122 struct scm_fp_list *fp;
8124 fp = UNIXCB(skb).fp;
8125 for (i = 0; i < fp->count; i++) {
8128 if (fp->fp[i] != file)
8131 unix_notinflight(fp->user, fp->fp[i]);
8132 left = fp->count - 1 - i;
8134 memmove(&fp->fp[i], &fp->fp[i + 1],
8135 left * sizeof(struct file *));
8142 __skb_queue_tail(&list, skb);
8152 __skb_queue_tail(&list, skb);
8154 skb = skb_dequeue(head);
8157 if (skb_peek(&list)) {
8158 spin_lock_irq(&head->lock);
8159 while ((skb = __skb_dequeue(&list)) != NULL)
8160 __skb_queue_tail(head, skb);
8161 spin_unlock_irq(&head->lock);
8168 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
8170 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
8171 struct io_ring_ctx *ctx = rsrc_data->ctx;
8172 struct io_rsrc_put *prsrc, *tmp;
8174 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8175 list_del(&prsrc->list);
8178 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
8180 io_ring_submit_lock(ctx, lock_ring);
8181 spin_lock(&ctx->completion_lock);
8182 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
8183 io_commit_cqring(ctx);
8184 spin_unlock(&ctx->completion_lock);
8185 io_cqring_ev_posted(ctx);
8186 io_ring_submit_unlock(ctx, lock_ring);
8189 rsrc_data->do_put(ctx, prsrc);
8193 io_rsrc_node_destroy(ref_node);
8194 if (atomic_dec_and_test(&rsrc_data->refs))
8195 complete(&rsrc_data->done);
8198 static void io_rsrc_put_work(struct work_struct *work)
8200 struct io_ring_ctx *ctx;
8201 struct llist_node *node;
8203 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8204 node = llist_del_all(&ctx->rsrc_put_llist);
8207 struct io_rsrc_node *ref_node;
8208 struct llist_node *next = node->next;
8210 ref_node = llist_entry(node, struct io_rsrc_node, llist);
8211 __io_rsrc_put_work(ref_node);
8216 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
8217 unsigned nr_args, u64 __user *tags)
8219 __s32 __user *fds = (__s32 __user *) arg;
8228 if (nr_args > IORING_MAX_FIXED_FILES)
8230 if (nr_args > rlimit(RLIMIT_NOFILE))
8232 ret = io_rsrc_node_switch_start(ctx);
8235 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8241 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
8244 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
8245 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
8249 /* allow sparse sets */
8252 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
8259 if (unlikely(!file))
8263 * Don't allow io_uring instances to be registered. If UNIX
8264 * isn't enabled, then this causes a reference cycle and this
8265 * instance can never get freed. If UNIX is enabled we'll
8266 * handle it just fine, but there's still no point in allowing
8267 * a ring fd as it doesn't support regular read/write anyway.
8269 if (file->f_op == &io_uring_fops) {
8273 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
8276 ret = io_sqe_files_scm(ctx);
8278 __io_sqe_files_unregister(ctx);
8282 io_rsrc_node_switch(ctx, NULL);
8285 for (i = 0; i < ctx->nr_user_files; i++) {
8286 file = io_file_from_index(ctx, i);
8290 io_free_file_tables(&ctx->file_table);
8291 ctx->nr_user_files = 0;
8293 io_rsrc_data_free(ctx->file_data);
8294 ctx->file_data = NULL;
8298 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
8301 #if defined(CONFIG_UNIX)
8302 struct sock *sock = ctx->ring_sock->sk;
8303 struct sk_buff_head *head = &sock->sk_receive_queue;
8304 struct sk_buff *skb;
8307 * See if we can merge this file into an existing skb SCM_RIGHTS
8308 * file set. If there's no room, fall back to allocating a new skb
8309 * and filling it in.
8311 spin_lock_irq(&head->lock);
8312 skb = skb_peek(head);
8314 struct scm_fp_list *fpl = UNIXCB(skb).fp;
8316 if (fpl->count < SCM_MAX_FD) {
8317 __skb_unlink(skb, head);
8318 spin_unlock_irq(&head->lock);
8319 fpl->fp[fpl->count] = get_file(file);
8320 unix_inflight(fpl->user, fpl->fp[fpl->count]);
8322 spin_lock_irq(&head->lock);
8323 __skb_queue_head(head, skb);
8328 spin_unlock_irq(&head->lock);
8335 return __io_sqe_files_scm(ctx, 1, index);
8341 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
8342 struct io_rsrc_node *node, void *rsrc)
8344 u64 *tag_slot = io_get_tag_slot(data, idx);
8345 struct io_rsrc_put *prsrc;
8347 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
8351 prsrc->tag = *tag_slot;
8354 list_add(&prsrc->list, &node->rsrc_list);
8358 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
8359 unsigned int issue_flags, u32 slot_index)
8361 struct io_ring_ctx *ctx = req->ctx;
8362 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
8363 bool needs_switch = false;
8364 struct io_fixed_file *file_slot;
8367 io_ring_submit_lock(ctx, !force_nonblock);
8368 if (file->f_op == &io_uring_fops)
8371 if (!ctx->file_data)
8374 if (slot_index >= ctx->nr_user_files)
8377 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
8378 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
8380 if (file_slot->file_ptr) {
8381 struct file *old_file;
8383 ret = io_rsrc_node_switch_start(ctx);
8387 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8388 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
8389 ctx->rsrc_node, old_file);
8392 file_slot->file_ptr = 0;
8393 needs_switch = true;
8396 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
8397 io_fixed_file_set(file_slot, file);
8398 ret = io_sqe_file_register(ctx, file, slot_index);
8400 file_slot->file_ptr = 0;
8407 io_rsrc_node_switch(ctx, ctx->file_data);
8408 io_ring_submit_unlock(ctx, !force_nonblock);
8414 static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
8416 unsigned int offset = req->close.file_slot - 1;
8417 struct io_ring_ctx *ctx = req->ctx;
8418 struct io_fixed_file *file_slot;
8422 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8424 if (unlikely(!ctx->file_data))
8427 if (offset >= ctx->nr_user_files)
8429 ret = io_rsrc_node_switch_start(ctx);
8433 offset = array_index_nospec(offset, ctx->nr_user_files);
8434 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
8436 if (!file_slot->file_ptr)
8439 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8440 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
8444 file_slot->file_ptr = 0;
8445 io_rsrc_node_switch(ctx, ctx->file_data);
8448 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
8452 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
8453 struct io_uring_rsrc_update2 *up,
8456 u64 __user *tags = u64_to_user_ptr(up->tags);
8457 __s32 __user *fds = u64_to_user_ptr(up->data);
8458 struct io_rsrc_data *data = ctx->file_data;
8459 struct io_fixed_file *file_slot;
8463 bool needs_switch = false;
8465 if (!ctx->file_data)
8467 if (up->offset + nr_args > ctx->nr_user_files)
8470 for (done = 0; done < nr_args; done++) {
8473 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
8474 copy_from_user(&fd, &fds[done], sizeof(fd))) {
8478 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
8482 if (fd == IORING_REGISTER_FILES_SKIP)
8485 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
8486 file_slot = io_fixed_file_slot(&ctx->file_table, i);
8488 if (file_slot->file_ptr) {
8489 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
8490 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
8493 file_slot->file_ptr = 0;
8494 needs_switch = true;
8503 * Don't allow io_uring instances to be registered. If
8504 * UNIX isn't enabled, then this causes a reference
8505 * cycle and this instance can never get freed. If UNIX
8506 * is enabled we'll handle it just fine, but there's
8507 * still no point in allowing a ring fd as it doesn't
8508 * support regular read/write anyway.
8510 if (file->f_op == &io_uring_fops) {
8515 *io_get_tag_slot(data, i) = tag;
8516 io_fixed_file_set(file_slot, file);
8517 err = io_sqe_file_register(ctx, file, i);
8519 file_slot->file_ptr = 0;
8527 io_rsrc_node_switch(ctx, data);
8528 return done ? done : err;
8531 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
8532 struct task_struct *task)
8534 struct io_wq_hash *hash;
8535 struct io_wq_data data;
8536 unsigned int concurrency;
8538 mutex_lock(&ctx->uring_lock);
8539 hash = ctx->hash_map;
8541 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
8543 mutex_unlock(&ctx->uring_lock);
8544 return ERR_PTR(-ENOMEM);
8546 refcount_set(&hash->refs, 1);
8547 init_waitqueue_head(&hash->wait);
8548 ctx->hash_map = hash;
8550 mutex_unlock(&ctx->uring_lock);
8554 data.free_work = io_wq_free_work;
8555 data.do_work = io_wq_submit_work;
8557 /* Do QD, or 4 * CPUS, whatever is smallest */
8558 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
8560 return io_wq_create(concurrency, &data);
8563 static int io_uring_alloc_task_context(struct task_struct *task,
8564 struct io_ring_ctx *ctx)
8566 struct io_uring_task *tctx;
8569 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
8570 if (unlikely(!tctx))
8573 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
8574 if (unlikely(ret)) {
8579 tctx->io_wq = io_init_wq_offload(ctx, task);
8580 if (IS_ERR(tctx->io_wq)) {
8581 ret = PTR_ERR(tctx->io_wq);
8582 percpu_counter_destroy(&tctx->inflight);
8588 init_waitqueue_head(&tctx->wait);
8589 atomic_set(&tctx->in_idle, 0);
8590 atomic_set(&tctx->inflight_tracked, 0);
8591 task->io_uring = tctx;
8592 spin_lock_init(&tctx->task_lock);
8593 INIT_WQ_LIST(&tctx->task_list);
8594 init_task_work(&tctx->task_work, tctx_task_work);
8598 void __io_uring_free(struct task_struct *tsk)
8600 struct io_uring_task *tctx = tsk->io_uring;
8602 WARN_ON_ONCE(!xa_empty(&tctx->xa));
8603 WARN_ON_ONCE(tctx->io_wq);
8604 WARN_ON_ONCE(tctx->cached_refs);
8606 percpu_counter_destroy(&tctx->inflight);
8608 tsk->io_uring = NULL;
8611 static int io_sq_offload_create(struct io_ring_ctx *ctx,
8612 struct io_uring_params *p)
8616 /* Retain compatibility with failing for an invalid attach attempt */
8617 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
8618 IORING_SETUP_ATTACH_WQ) {
8621 f = fdget(p->wq_fd);
8624 if (f.file->f_op != &io_uring_fops) {
8630 if (ctx->flags & IORING_SETUP_SQPOLL) {
8631 struct task_struct *tsk;
8632 struct io_sq_data *sqd;
8635 sqd = io_get_sq_data(p, &attached);
8641 ctx->sq_creds = get_current_cred();
8643 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
8644 if (!ctx->sq_thread_idle)
8645 ctx->sq_thread_idle = HZ;
8647 io_sq_thread_park(sqd);
8648 list_add(&ctx->sqd_list, &sqd->ctx_list);
8649 io_sqd_update_thread_idle(sqd);
8650 /* don't attach to a dying SQPOLL thread, would be racy */
8651 ret = (attached && !sqd->thread) ? -ENXIO : 0;
8652 io_sq_thread_unpark(sqd);
8659 if (p->flags & IORING_SETUP_SQ_AFF) {
8660 int cpu = p->sq_thread_cpu;
8663 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
8670 sqd->task_pid = current->pid;
8671 sqd->task_tgid = current->tgid;
8672 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8679 ret = io_uring_alloc_task_context(tsk, ctx);
8680 wake_up_new_task(tsk);
8683 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8684 /* Can't have SQ_AFF without SQPOLL */
8691 complete(&ctx->sq_data->exited);
8693 io_sq_thread_finish(ctx);
8697 static inline void __io_unaccount_mem(struct user_struct *user,
8698 unsigned long nr_pages)
8700 atomic_long_sub(nr_pages, &user->locked_vm);
8703 static inline int __io_account_mem(struct user_struct *user,
8704 unsigned long nr_pages)
8706 unsigned long page_limit, cur_pages, new_pages;
8708 /* Don't allow more pages than we can safely lock */
8709 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8712 cur_pages = atomic_long_read(&user->locked_vm);
8713 new_pages = cur_pages + nr_pages;
8714 if (new_pages > page_limit)
8716 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8717 new_pages) != cur_pages);
8722 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8725 __io_unaccount_mem(ctx->user, nr_pages);
8727 if (ctx->mm_account)
8728 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8731 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8736 ret = __io_account_mem(ctx->user, nr_pages);
8741 if (ctx->mm_account)
8742 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8747 static void io_mem_free(void *ptr)
8754 page = virt_to_head_page(ptr);
8755 if (put_page_testzero(page))
8756 free_compound_page(page);
8759 static void *io_mem_alloc(size_t size)
8761 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
8763 return (void *) __get_free_pages(gfp, get_order(size));
8766 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8769 struct io_rings *rings;
8770 size_t off, sq_array_size;
8772 off = struct_size(rings, cqes, cq_entries);
8773 if (off == SIZE_MAX)
8777 off = ALIGN(off, SMP_CACHE_BYTES);
8785 sq_array_size = array_size(sizeof(u32), sq_entries);
8786 if (sq_array_size == SIZE_MAX)
8789 if (check_add_overflow(off, sq_array_size, &off))
8795 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8797 struct io_mapped_ubuf *imu = *slot;
8800 if (imu != ctx->dummy_ubuf) {
8801 for (i = 0; i < imu->nr_bvecs; i++)
8802 unpin_user_page(imu->bvec[i].bv_page);
8803 if (imu->acct_pages)
8804 io_unaccount_mem(ctx, imu->acct_pages);
8810 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8812 io_buffer_unmap(ctx, &prsrc->buf);
8816 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8820 for (i = 0; i < ctx->nr_user_bufs; i++)
8821 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8822 kfree(ctx->user_bufs);
8823 io_rsrc_data_free(ctx->buf_data);
8824 ctx->user_bufs = NULL;
8825 ctx->buf_data = NULL;
8826 ctx->nr_user_bufs = 0;
8829 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8831 unsigned nr = ctx->nr_user_bufs;
8838 * Quiesce may unlock ->uring_lock, and while it's not held
8839 * prevent new requests using the table.
8841 ctx->nr_user_bufs = 0;
8842 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8843 ctx->nr_user_bufs = nr;
8845 __io_sqe_buffers_unregister(ctx);
8849 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8850 void __user *arg, unsigned index)
8852 struct iovec __user *src;
8854 #ifdef CONFIG_COMPAT
8856 struct compat_iovec __user *ciovs;
8857 struct compat_iovec ciov;
8859 ciovs = (struct compat_iovec __user *) arg;
8860 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8863 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8864 dst->iov_len = ciov.iov_len;
8868 src = (struct iovec __user *) arg;
8869 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8875 * Not super efficient, but this is just a registration time. And we do cache
8876 * the last compound head, so generally we'll only do a full search if we don't
8879 * We check if the given compound head page has already been accounted, to
8880 * avoid double accounting it. This allows us to account the full size of the
8881 * page, not just the constituent pages of a huge page.
8883 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8884 int nr_pages, struct page *hpage)
8888 /* check current page array */
8889 for (i = 0; i < nr_pages; i++) {
8890 if (!PageCompound(pages[i]))
8892 if (compound_head(pages[i]) == hpage)
8896 /* check previously registered pages */
8897 for (i = 0; i < ctx->nr_user_bufs; i++) {
8898 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8900 for (j = 0; j < imu->nr_bvecs; j++) {
8901 if (!PageCompound(imu->bvec[j].bv_page))
8903 if (compound_head(imu->bvec[j].bv_page) == hpage)
8911 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8912 int nr_pages, struct io_mapped_ubuf *imu,
8913 struct page **last_hpage)
8917 imu->acct_pages = 0;
8918 for (i = 0; i < nr_pages; i++) {
8919 if (!PageCompound(pages[i])) {
8924 hpage = compound_head(pages[i]);
8925 if (hpage == *last_hpage)
8927 *last_hpage = hpage;
8928 if (headpage_already_acct(ctx, pages, i, hpage))
8930 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8934 if (!imu->acct_pages)
8937 ret = io_account_mem(ctx, imu->acct_pages);
8939 imu->acct_pages = 0;
8943 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8944 struct io_mapped_ubuf **pimu,
8945 struct page **last_hpage)
8947 struct io_mapped_ubuf *imu = NULL;
8948 struct vm_area_struct **vmas = NULL;
8949 struct page **pages = NULL;
8950 unsigned long off, start, end, ubuf;
8952 int ret, pret, nr_pages, i;
8954 if (!iov->iov_base) {
8955 *pimu = ctx->dummy_ubuf;
8959 ubuf = (unsigned long) iov->iov_base;
8960 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8961 start = ubuf >> PAGE_SHIFT;
8962 nr_pages = end - start;
8967 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8971 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8976 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8981 mmap_read_lock(current->mm);
8982 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8984 if (pret == nr_pages) {
8985 /* don't support file backed memory */
8986 for (i = 0; i < nr_pages; i++) {
8987 struct vm_area_struct *vma = vmas[i];
8989 if (vma_is_shmem(vma))
8992 !is_file_hugepages(vma->vm_file)) {
8998 ret = pret < 0 ? pret : -EFAULT;
9000 mmap_read_unlock(current->mm);
9003 * if we did partial map, or found file backed vmas,
9004 * release any pages we did get
9007 unpin_user_pages(pages, pret);
9011 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9013 unpin_user_pages(pages, pret);
9017 off = ubuf & ~PAGE_MASK;
9018 size = iov->iov_len;
9019 for (i = 0; i < nr_pages; i++) {
9022 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9023 imu->bvec[i].bv_page = pages[i];
9024 imu->bvec[i].bv_len = vec_len;
9025 imu->bvec[i].bv_offset = off;
9029 /* store original address for later verification */
9031 imu->ubuf_end = ubuf + iov->iov_len;
9032 imu->nr_bvecs = nr_pages;
9043 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
9045 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9046 return ctx->user_bufs ? 0 : -ENOMEM;
9049 static int io_buffer_validate(struct iovec *iov)
9051 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9054 * Don't impose further limits on the size and buffer
9055 * constraints here, we'll -EINVAL later when IO is
9056 * submitted if they are wrong.
9059 return iov->iov_len ? -EFAULT : 0;
9063 /* arbitrary limit, but we need something */
9064 if (iov->iov_len > SZ_1G)
9067 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9073 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
9074 unsigned int nr_args, u64 __user *tags)
9076 struct page *last_hpage = NULL;
9077 struct io_rsrc_data *data;
9083 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
9085 ret = io_rsrc_node_switch_start(ctx);
9088 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9091 ret = io_buffers_map_alloc(ctx, nr_args);
9093 io_rsrc_data_free(data);
9097 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
9098 ret = io_copy_iov(ctx, &iov, arg, i);
9101 ret = io_buffer_validate(&iov);
9104 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
9109 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9115 WARN_ON_ONCE(ctx->buf_data);
9117 ctx->buf_data = data;
9119 __io_sqe_buffers_unregister(ctx);
9121 io_rsrc_node_switch(ctx, NULL);
9125 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9126 struct io_uring_rsrc_update2 *up,
9127 unsigned int nr_args)
9129 u64 __user *tags = u64_to_user_ptr(up->tags);
9130 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
9131 struct page *last_hpage = NULL;
9132 bool needs_switch = false;
9138 if (up->offset + nr_args > ctx->nr_user_bufs)
9141 for (done = 0; done < nr_args; done++) {
9142 struct io_mapped_ubuf *imu;
9143 int offset = up->offset + done;
9146 err = io_copy_iov(ctx, &iov, iovs, done);
9149 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9153 err = io_buffer_validate(&iov);
9156 if (!iov.iov_base && tag) {
9160 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9164 i = array_index_nospec(offset, ctx->nr_user_bufs);
9165 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
9166 err = io_queue_rsrc_removal(ctx->buf_data, i,
9167 ctx->rsrc_node, ctx->user_bufs[i]);
9168 if (unlikely(err)) {
9169 io_buffer_unmap(ctx, &imu);
9172 ctx->user_bufs[i] = NULL;
9173 needs_switch = true;
9176 ctx->user_bufs[i] = imu;
9177 *io_get_tag_slot(ctx->buf_data, offset) = tag;
9181 io_rsrc_node_switch(ctx, ctx->buf_data);
9182 return done ? done : err;
9185 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
9187 __s32 __user *fds = arg;
9193 if (copy_from_user(&fd, fds, sizeof(*fds)))
9196 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
9197 if (IS_ERR(ctx->cq_ev_fd)) {
9198 int ret = PTR_ERR(ctx->cq_ev_fd);
9200 ctx->cq_ev_fd = NULL;
9207 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9209 if (ctx->cq_ev_fd) {
9210 eventfd_ctx_put(ctx->cq_ev_fd);
9211 ctx->cq_ev_fd = NULL;
9218 static void io_destroy_buffers(struct io_ring_ctx *ctx)
9220 struct io_buffer *buf;
9221 unsigned long index;
9223 xa_for_each(&ctx->io_buffers, index, buf)
9224 __io_remove_buffers(ctx, buf, index, -1U);
9227 static void io_req_cache_free(struct list_head *list)
9229 struct io_kiocb *req, *nxt;
9231 list_for_each_entry_safe(req, nxt, list, inflight_entry) {
9232 list_del(&req->inflight_entry);
9233 kmem_cache_free(req_cachep, req);
9237 static void io_req_caches_free(struct io_ring_ctx *ctx)
9239 struct io_submit_state *state = &ctx->submit_state;
9241 mutex_lock(&ctx->uring_lock);
9243 if (state->free_reqs) {
9244 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
9245 state->free_reqs = 0;
9248 io_flush_cached_locked_reqs(ctx, state);
9249 io_req_cache_free(&state->free_list);
9250 mutex_unlock(&ctx->uring_lock);
9253 static void io_wait_rsrc_data(struct io_rsrc_data *data)
9255 if (data && !atomic_dec_and_test(&data->refs))
9256 wait_for_completion(&data->done);
9259 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
9261 io_sq_thread_finish(ctx);
9263 if (ctx->mm_account) {
9264 mmdrop(ctx->mm_account);
9265 ctx->mm_account = NULL;
9268 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
9269 io_wait_rsrc_data(ctx->buf_data);
9270 io_wait_rsrc_data(ctx->file_data);
9272 mutex_lock(&ctx->uring_lock);
9274 __io_sqe_buffers_unregister(ctx);
9276 __io_sqe_files_unregister(ctx);
9278 __io_cqring_overflow_flush(ctx, true);
9279 mutex_unlock(&ctx->uring_lock);
9280 io_eventfd_unregister(ctx);
9281 io_destroy_buffers(ctx);
9283 put_cred(ctx->sq_creds);
9285 /* there are no registered resources left, nobody uses it */
9287 io_rsrc_node_destroy(ctx->rsrc_node);
9288 if (ctx->rsrc_backup_node)
9289 io_rsrc_node_destroy(ctx->rsrc_backup_node);
9290 flush_delayed_work(&ctx->rsrc_put_work);
9292 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
9293 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
9295 #if defined(CONFIG_UNIX)
9296 if (ctx->ring_sock) {
9297 ctx->ring_sock->file = NULL; /* so that iput() is called */
9298 sock_release(ctx->ring_sock);
9301 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
9303 io_mem_free(ctx->rings);
9304 io_mem_free(ctx->sq_sqes);
9306 percpu_ref_exit(&ctx->refs);
9307 free_uid(ctx->user);
9308 io_req_caches_free(ctx);
9310 io_wq_put_hash(ctx->hash_map);
9311 kfree(ctx->cancel_hash);
9312 kfree(ctx->dummy_ubuf);
9316 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
9318 struct io_ring_ctx *ctx = file->private_data;
9321 poll_wait(file, &ctx->poll_wait, wait);
9323 * synchronizes with barrier from wq_has_sleeper call in
9327 if (!io_sqring_full(ctx))
9328 mask |= EPOLLOUT | EPOLLWRNORM;
9331 * Don't flush cqring overflow list here, just do a simple check.
9332 * Otherwise there could possible be ABBA deadlock:
9335 * lock(&ctx->uring_lock);
9337 * lock(&ctx->uring_lock);
9340 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
9341 * pushs them to do the flush.
9343 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
9344 mask |= EPOLLIN | EPOLLRDNORM;
9349 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
9351 const struct cred *creds;
9353 creds = xa_erase(&ctx->personalities, id);
9362 struct io_tctx_exit {
9363 struct callback_head task_work;
9364 struct completion completion;
9365 struct io_ring_ctx *ctx;
9368 static void io_tctx_exit_cb(struct callback_head *cb)
9370 struct io_uring_task *tctx = current->io_uring;
9371 struct io_tctx_exit *work;
9373 work = container_of(cb, struct io_tctx_exit, task_work);
9375 * When @in_idle, we're in cancellation and it's racy to remove the
9376 * node. It'll be removed by the end of cancellation, just ignore it.
9378 if (!atomic_read(&tctx->in_idle))
9379 io_uring_del_tctx_node((unsigned long)work->ctx);
9380 complete(&work->completion);
9383 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
9385 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9387 return req->ctx == data;
9390 static void io_ring_exit_work(struct work_struct *work)
9392 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
9393 unsigned long timeout = jiffies + HZ * 60 * 5;
9394 unsigned long interval = HZ / 20;
9395 struct io_tctx_exit exit;
9396 struct io_tctx_node *node;
9400 * If we're doing polled IO and end up having requests being
9401 * submitted async (out-of-line), then completions can come in while
9402 * we're waiting for refs to drop. We need to reap these manually,
9403 * as nobody else will be looking for them.
9406 io_uring_try_cancel_requests(ctx, NULL, true);
9408 struct io_sq_data *sqd = ctx->sq_data;
9409 struct task_struct *tsk;
9411 io_sq_thread_park(sqd);
9413 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
9414 io_wq_cancel_cb(tsk->io_uring->io_wq,
9415 io_cancel_ctx_cb, ctx, true);
9416 io_sq_thread_unpark(sqd);
9419 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
9420 /* there is little hope left, don't run it too often */
9423 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
9425 init_completion(&exit.completion);
9426 init_task_work(&exit.task_work, io_tctx_exit_cb);
9429 * Some may use context even when all refs and requests have been put,
9430 * and they are free to do so while still holding uring_lock or
9431 * completion_lock, see io_req_task_submit(). Apart from other work,
9432 * this lock/unlock section also waits them to finish.
9434 mutex_lock(&ctx->uring_lock);
9435 while (!list_empty(&ctx->tctx_list)) {
9436 WARN_ON_ONCE(time_after(jiffies, timeout));
9438 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
9440 /* don't spin on a single task if cancellation failed */
9441 list_rotate_left(&ctx->tctx_list);
9442 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
9443 if (WARN_ON_ONCE(ret))
9445 wake_up_process(node->task);
9447 mutex_unlock(&ctx->uring_lock);
9448 wait_for_completion(&exit.completion);
9449 mutex_lock(&ctx->uring_lock);
9451 mutex_unlock(&ctx->uring_lock);
9452 spin_lock(&ctx->completion_lock);
9453 spin_unlock(&ctx->completion_lock);
9455 io_ring_ctx_free(ctx);
9458 /* Returns true if we found and killed one or more timeouts */
9459 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
9462 struct io_kiocb *req, *tmp;
9465 spin_lock(&ctx->completion_lock);
9466 spin_lock_irq(&ctx->timeout_lock);
9467 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
9468 if (io_match_task(req, tsk, cancel_all)) {
9469 io_kill_timeout(req, -ECANCELED);
9473 spin_unlock_irq(&ctx->timeout_lock);
9475 io_commit_cqring(ctx);
9476 spin_unlock(&ctx->completion_lock);
9478 io_cqring_ev_posted(ctx);
9479 return canceled != 0;
9482 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
9484 unsigned long index;
9485 struct creds *creds;
9487 mutex_lock(&ctx->uring_lock);
9488 percpu_ref_kill(&ctx->refs);
9490 __io_cqring_overflow_flush(ctx, true);
9491 xa_for_each(&ctx->personalities, index, creds)
9492 io_unregister_personality(ctx, index);
9493 mutex_unlock(&ctx->uring_lock);
9495 io_kill_timeouts(ctx, NULL, true);
9496 io_poll_remove_all(ctx, NULL, true);
9498 /* if we failed setting up the ctx, we might not have any rings */
9499 io_iopoll_try_reap_events(ctx);
9501 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
9503 * Use system_unbound_wq to avoid spawning tons of event kworkers
9504 * if we're exiting a ton of rings at the same time. It just adds
9505 * noise and overhead, there's no discernable change in runtime
9506 * over using system_wq.
9508 queue_work(system_unbound_wq, &ctx->exit_work);
9511 static int io_uring_release(struct inode *inode, struct file *file)
9513 struct io_ring_ctx *ctx = file->private_data;
9515 file->private_data = NULL;
9516 io_ring_ctx_wait_and_kill(ctx);
9520 struct io_task_cancel {
9521 struct task_struct *task;
9525 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
9527 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
9528 struct io_task_cancel *cancel = data;
9530 return io_match_task_safe(req, cancel->task, cancel->all);
9533 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
9534 struct task_struct *task, bool cancel_all)
9536 struct io_defer_entry *de;
9539 spin_lock(&ctx->completion_lock);
9540 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
9541 if (io_match_task_safe(de->req, task, cancel_all)) {
9542 list_cut_position(&list, &ctx->defer_list, &de->list);
9546 spin_unlock(&ctx->completion_lock);
9547 if (list_empty(&list))
9550 while (!list_empty(&list)) {
9551 de = list_first_entry(&list, struct io_defer_entry, list);
9552 list_del_init(&de->list);
9553 io_req_complete_failed(de->req, -ECANCELED);
9559 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
9561 struct io_tctx_node *node;
9562 enum io_wq_cancel cret;
9565 mutex_lock(&ctx->uring_lock);
9566 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
9567 struct io_uring_task *tctx = node->task->io_uring;
9570 * io_wq will stay alive while we hold uring_lock, because it's
9571 * killed after ctx nodes, which requires to take the lock.
9573 if (!tctx || !tctx->io_wq)
9575 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
9576 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9578 mutex_unlock(&ctx->uring_lock);
9583 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
9584 struct task_struct *task,
9587 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
9588 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9591 enum io_wq_cancel cret;
9595 ret |= io_uring_try_cancel_iowq(ctx);
9596 } else if (tctx && tctx->io_wq) {
9598 * Cancels requests of all rings, not only @ctx, but
9599 * it's fine as the task is in exit/exec.
9601 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9603 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
9606 /* SQPOLL thread does its own polling */
9607 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
9608 (ctx->sq_data && ctx->sq_data->thread == current)) {
9609 while (!list_empty_careful(&ctx->iopoll_list)) {
9610 io_iopoll_try_reap_events(ctx);
9615 ret |= io_cancel_defer_files(ctx, task, cancel_all);
9616 ret |= io_poll_remove_all(ctx, task, cancel_all);
9617 ret |= io_kill_timeouts(ctx, task, cancel_all);
9619 ret |= io_run_task_work();
9626 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9628 struct io_uring_task *tctx = current->io_uring;
9629 struct io_tctx_node *node;
9632 if (unlikely(!tctx)) {
9633 ret = io_uring_alloc_task_context(current, ctx);
9637 tctx = current->io_uring;
9638 if (ctx->iowq_limits_set) {
9639 unsigned int limits[2] = { ctx->iowq_limits[0],
9640 ctx->iowq_limits[1], };
9642 ret = io_wq_max_workers(tctx->io_wq, limits);
9647 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
9648 node = kmalloc(sizeof(*node), GFP_KERNEL);
9652 node->task = current;
9654 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
9661 mutex_lock(&ctx->uring_lock);
9662 list_add(&node->ctx_node, &ctx->tctx_list);
9663 mutex_unlock(&ctx->uring_lock);
9670 * Note that this task has used io_uring. We use it for cancelation purposes.
9672 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
9674 struct io_uring_task *tctx = current->io_uring;
9676 if (likely(tctx && tctx->last == ctx))
9678 return __io_uring_add_tctx_node(ctx);
9682 * Remove this io_uring_file -> task mapping.
9684 static void io_uring_del_tctx_node(unsigned long index)
9686 struct io_uring_task *tctx = current->io_uring;
9687 struct io_tctx_node *node;
9691 node = xa_erase(&tctx->xa, index);
9695 WARN_ON_ONCE(current != node->task);
9696 WARN_ON_ONCE(list_empty(&node->ctx_node));
9698 mutex_lock(&node->ctx->uring_lock);
9699 list_del(&node->ctx_node);
9700 mutex_unlock(&node->ctx->uring_lock);
9702 if (tctx->last == node->ctx)
9707 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9709 struct io_wq *wq = tctx->io_wq;
9710 struct io_tctx_node *node;
9711 unsigned long index;
9713 xa_for_each(&tctx->xa, index, node) {
9714 io_uring_del_tctx_node(index);
9719 * Must be after io_uring_del_task_file() (removes nodes under
9720 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
9722 io_wq_put_and_exit(wq);
9727 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9730 return atomic_read(&tctx->inflight_tracked);
9731 return percpu_counter_sum(&tctx->inflight);
9735 * Find any io_uring ctx that this task has registered or done IO on, and cancel
9736 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
9738 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
9740 struct io_uring_task *tctx = current->io_uring;
9741 struct io_ring_ctx *ctx;
9745 WARN_ON_ONCE(sqd && sqd->thread != current);
9747 if (!current->io_uring)
9750 io_wq_exit_start(tctx->io_wq);
9752 atomic_inc(&tctx->in_idle);
9754 io_uring_drop_tctx_refs(current);
9755 /* read completions before cancelations */
9756 inflight = tctx_inflight(tctx, !cancel_all);
9761 struct io_tctx_node *node;
9762 unsigned long index;
9764 xa_for_each(&tctx->xa, index, node) {
9765 /* sqpoll task will cancel all its requests */
9766 if (node->ctx->sq_data)
9768 io_uring_try_cancel_requests(node->ctx, current,
9772 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9773 io_uring_try_cancel_requests(ctx, current,
9777 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
9779 io_uring_drop_tctx_refs(current);
9782 * If we've seen completions, retry without waiting. This
9783 * avoids a race where a completion comes in before we did
9784 * prepare_to_wait().
9786 if (inflight == tctx_inflight(tctx, !cancel_all))
9788 finish_wait(&tctx->wait, &wait);
9791 io_uring_clean_tctx(tctx);
9794 * We shouldn't run task_works after cancel, so just leave
9795 * ->in_idle set for normal exit.
9797 atomic_dec(&tctx->in_idle);
9798 /* for exec all current's requests should be gone, kill tctx */
9799 __io_uring_free(current);
9803 void __io_uring_cancel(bool cancel_all)
9805 io_uring_cancel_generic(cancel_all, NULL);
9808 static void *io_uring_validate_mmap_request(struct file *file,
9809 loff_t pgoff, size_t sz)
9811 struct io_ring_ctx *ctx = file->private_data;
9812 loff_t offset = pgoff << PAGE_SHIFT;
9817 case IORING_OFF_SQ_RING:
9818 case IORING_OFF_CQ_RING:
9821 case IORING_OFF_SQES:
9825 return ERR_PTR(-EINVAL);
9828 page = virt_to_head_page(ptr);
9829 if (sz > page_size(page))
9830 return ERR_PTR(-EINVAL);
9837 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9839 size_t sz = vma->vm_end - vma->vm_start;
9843 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9845 return PTR_ERR(ptr);
9847 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9848 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9851 #else /* !CONFIG_MMU */
9853 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9855 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9858 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9860 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9863 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9864 unsigned long addr, unsigned long len,
9865 unsigned long pgoff, unsigned long flags)
9869 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9871 return PTR_ERR(ptr);
9873 return (unsigned long) ptr;
9876 #endif /* !CONFIG_MMU */
9878 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9883 if (!io_sqring_full(ctx))
9885 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9887 if (!io_sqring_full(ctx))
9890 } while (!signal_pending(current));
9892 finish_wait(&ctx->sqo_sq_wait, &wait);
9896 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9897 struct __kernel_timespec __user **ts,
9898 const sigset_t __user **sig)
9900 struct io_uring_getevents_arg arg;
9903 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9904 * is just a pointer to the sigset_t.
9906 if (!(flags & IORING_ENTER_EXT_ARG)) {
9907 *sig = (const sigset_t __user *) argp;
9913 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9914 * timespec and sigset_t pointers if good.
9916 if (*argsz != sizeof(arg))
9918 if (copy_from_user(&arg, argp, sizeof(arg)))
9922 *sig = u64_to_user_ptr(arg.sigmask);
9923 *argsz = arg.sigmask_sz;
9924 *ts = u64_to_user_ptr(arg.ts);
9928 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9929 u32, min_complete, u32, flags, const void __user *, argp,
9932 struct io_ring_ctx *ctx;
9939 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9940 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9944 if (unlikely(!f.file))
9948 if (unlikely(f.file->f_op != &io_uring_fops))
9952 ctx = f.file->private_data;
9953 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9957 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9961 * For SQ polling, the thread will do all submissions and completions.
9962 * Just return the requested submit count, and wake the thread if
9966 if (ctx->flags & IORING_SETUP_SQPOLL) {
9967 io_cqring_overflow_flush(ctx);
9969 if (unlikely(ctx->sq_data->thread == NULL)) {
9973 if (flags & IORING_ENTER_SQ_WAKEUP)
9974 wake_up(&ctx->sq_data->wait);
9975 if (flags & IORING_ENTER_SQ_WAIT) {
9976 ret = io_sqpoll_wait_sq(ctx);
9980 submitted = to_submit;
9981 } else if (to_submit) {
9982 ret = io_uring_add_tctx_node(ctx);
9985 mutex_lock(&ctx->uring_lock);
9986 submitted = io_submit_sqes(ctx, to_submit);
9987 mutex_unlock(&ctx->uring_lock);
9989 if (submitted != to_submit)
9992 if (flags & IORING_ENTER_GETEVENTS) {
9993 const sigset_t __user *sig;
9994 struct __kernel_timespec __user *ts;
9996 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10000 min_complete = min(min_complete, ctx->cq_entries);
10003 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10004 * space applications don't need to do io completion events
10005 * polling again, they can rely on io_sq_thread to do polling
10006 * work, which can reduce cpu usage and uring_lock contention.
10008 if (ctx->flags & IORING_SETUP_IOPOLL &&
10009 !(ctx->flags & IORING_SETUP_SQPOLL)) {
10010 ret = io_iopoll_check(ctx, min_complete);
10012 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
10017 percpu_ref_put(&ctx->refs);
10020 return submitted ? submitted : ret;
10023 #ifdef CONFIG_PROC_FS
10024 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
10025 const struct cred *cred)
10027 struct user_namespace *uns = seq_user_ns(m);
10028 struct group_info *gi;
10033 seq_printf(m, "%5d\n", id);
10034 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10035 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10036 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10037 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10038 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10039 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10040 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10041 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10042 seq_puts(m, "\n\tGroups:\t");
10043 gi = cred->group_info;
10044 for (g = 0; g < gi->ngroups; g++) {
10045 seq_put_decimal_ull(m, g ? " " : "",
10046 from_kgid_munged(uns, gi->gid[g]));
10048 seq_puts(m, "\n\tCapEff:\t");
10049 cap = cred->cap_effective;
10050 CAP_FOR_EACH_U32(__capi)
10051 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10056 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
10058 struct io_sq_data *sq = NULL;
10063 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
10064 * since fdinfo case grabs it in the opposite direction of normal use
10065 * cases. If we fail to get the lock, we just don't iterate any
10066 * structures that could be going away outside the io_uring mutex.
10068 has_lock = mutex_trylock(&ctx->uring_lock);
10070 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
10076 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
10077 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
10078 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
10079 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
10080 struct file *f = io_file_from_index(ctx, i);
10083 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
10085 seq_printf(m, "%5u: <none>\n", i);
10087 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
10088 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
10089 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
10090 unsigned int len = buf->ubuf_end - buf->ubuf;
10092 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
10094 if (has_lock && !xa_empty(&ctx->personalities)) {
10095 unsigned long index;
10096 const struct cred *cred;
10098 seq_printf(m, "Personalities:\n");
10099 xa_for_each(&ctx->personalities, index, cred)
10100 io_uring_show_cred(m, index, cred);
10102 seq_printf(m, "PollList:\n");
10103 spin_lock(&ctx->completion_lock);
10104 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
10105 struct hlist_head *list = &ctx->cancel_hash[i];
10106 struct io_kiocb *req;
10108 hlist_for_each_entry(req, list, hash_node)
10109 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
10110 req->task->task_works != NULL);
10112 spin_unlock(&ctx->completion_lock);
10114 mutex_unlock(&ctx->uring_lock);
10117 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
10119 struct io_ring_ctx *ctx = f->private_data;
10121 if (percpu_ref_tryget(&ctx->refs)) {
10122 __io_uring_show_fdinfo(ctx, m);
10123 percpu_ref_put(&ctx->refs);
10128 static const struct file_operations io_uring_fops = {
10129 .release = io_uring_release,
10130 .mmap = io_uring_mmap,
10132 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
10133 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
10135 .poll = io_uring_poll,
10136 #ifdef CONFIG_PROC_FS
10137 .show_fdinfo = io_uring_show_fdinfo,
10141 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
10142 struct io_uring_params *p)
10144 struct io_rings *rings;
10145 size_t size, sq_array_offset;
10147 /* make sure these are sane, as we already accounted them */
10148 ctx->sq_entries = p->sq_entries;
10149 ctx->cq_entries = p->cq_entries;
10151 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
10152 if (size == SIZE_MAX)
10155 rings = io_mem_alloc(size);
10159 ctx->rings = rings;
10160 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
10161 rings->sq_ring_mask = p->sq_entries - 1;
10162 rings->cq_ring_mask = p->cq_entries - 1;
10163 rings->sq_ring_entries = p->sq_entries;
10164 rings->cq_ring_entries = p->cq_entries;
10166 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
10167 if (size == SIZE_MAX) {
10168 io_mem_free(ctx->rings);
10173 ctx->sq_sqes = io_mem_alloc(size);
10174 if (!ctx->sq_sqes) {
10175 io_mem_free(ctx->rings);
10183 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
10187 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
10191 ret = io_uring_add_tctx_node(ctx);
10196 fd_install(fd, file);
10201 * Allocate an anonymous fd, this is what constitutes the application
10202 * visible backing of an io_uring instance. The application mmaps this
10203 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
10204 * we have to tie this fd to a socket for file garbage collection purposes.
10206 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
10209 #if defined(CONFIG_UNIX)
10212 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
10215 return ERR_PTR(ret);
10218 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
10219 O_RDWR | O_CLOEXEC);
10220 #if defined(CONFIG_UNIX)
10221 if (IS_ERR(file)) {
10222 sock_release(ctx->ring_sock);
10223 ctx->ring_sock = NULL;
10225 ctx->ring_sock->file = file;
10231 static int io_uring_create(unsigned entries, struct io_uring_params *p,
10232 struct io_uring_params __user *params)
10234 struct io_ring_ctx *ctx;
10240 if (entries > IORING_MAX_ENTRIES) {
10241 if (!(p->flags & IORING_SETUP_CLAMP))
10243 entries = IORING_MAX_ENTRIES;
10247 * Use twice as many entries for the CQ ring. It's possible for the
10248 * application to drive a higher depth than the size of the SQ ring,
10249 * since the sqes are only used at submission time. This allows for
10250 * some flexibility in overcommitting a bit. If the application has
10251 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
10252 * of CQ ring entries manually.
10254 p->sq_entries = roundup_pow_of_two(entries);
10255 if (p->flags & IORING_SETUP_CQSIZE) {
10257 * If IORING_SETUP_CQSIZE is set, we do the same roundup
10258 * to a power-of-two, if it isn't already. We do NOT impose
10259 * any cq vs sq ring sizing.
10261 if (!p->cq_entries)
10263 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
10264 if (!(p->flags & IORING_SETUP_CLAMP))
10266 p->cq_entries = IORING_MAX_CQ_ENTRIES;
10268 p->cq_entries = roundup_pow_of_two(p->cq_entries);
10269 if (p->cq_entries < p->sq_entries)
10272 p->cq_entries = 2 * p->sq_entries;
10275 ctx = io_ring_ctx_alloc(p);
10278 ctx->compat = in_compat_syscall();
10279 if (!capable(CAP_IPC_LOCK))
10280 ctx->user = get_uid(current_user());
10283 * This is just grabbed for accounting purposes. When a process exits,
10284 * the mm is exited and dropped before the files, hence we need to hang
10285 * on to this mm purely for the purposes of being able to unaccount
10286 * memory (locked/pinned vm). It's not used for anything else.
10288 mmgrab(current->mm);
10289 ctx->mm_account = current->mm;
10291 ret = io_allocate_scq_urings(ctx, p);
10295 ret = io_sq_offload_create(ctx, p);
10298 /* always set a rsrc node */
10299 ret = io_rsrc_node_switch_start(ctx);
10302 io_rsrc_node_switch(ctx, NULL);
10304 memset(&p->sq_off, 0, sizeof(p->sq_off));
10305 p->sq_off.head = offsetof(struct io_rings, sq.head);
10306 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
10307 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
10308 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
10309 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
10310 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
10311 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
10313 memset(&p->cq_off, 0, sizeof(p->cq_off));
10314 p->cq_off.head = offsetof(struct io_rings, cq.head);
10315 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
10316 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
10317 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
10318 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
10319 p->cq_off.cqes = offsetof(struct io_rings, cqes);
10320 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
10322 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
10323 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
10324 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
10325 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
10326 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
10327 IORING_FEAT_RSRC_TAGS;
10329 if (copy_to_user(params, p, sizeof(*p))) {
10334 file = io_uring_get_file(ctx);
10335 if (IS_ERR(file)) {
10336 ret = PTR_ERR(file);
10341 * Install ring fd as the very last thing, so we don't risk someone
10342 * having closed it before we finish setup
10344 ret = io_uring_install_fd(ctx, file);
10346 /* fput will clean it up */
10351 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
10354 io_ring_ctx_wait_and_kill(ctx);
10359 * Sets up an aio uring context, and returns the fd. Applications asks for a
10360 * ring size, we return the actual sq/cq ring sizes (among other things) in the
10361 * params structure passed in.
10363 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
10365 struct io_uring_params p;
10368 if (copy_from_user(&p, params, sizeof(p)))
10370 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
10375 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
10376 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
10377 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
10378 IORING_SETUP_R_DISABLED))
10381 return io_uring_create(entries, &p, params);
10384 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
10385 struct io_uring_params __user *, params)
10387 return io_uring_setup(entries, params);
10390 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
10392 struct io_uring_probe *p;
10396 size = struct_size(p, ops, nr_args);
10397 if (size == SIZE_MAX)
10399 p = kzalloc(size, GFP_KERNEL);
10404 if (copy_from_user(p, arg, size))
10407 if (memchr_inv(p, 0, size))
10410 p->last_op = IORING_OP_LAST - 1;
10411 if (nr_args > IORING_OP_LAST)
10412 nr_args = IORING_OP_LAST;
10414 for (i = 0; i < nr_args; i++) {
10416 if (!io_op_defs[i].not_supported)
10417 p->ops[i].flags = IO_URING_OP_SUPPORTED;
10422 if (copy_to_user(arg, p, size))
10429 static int io_register_personality(struct io_ring_ctx *ctx)
10431 const struct cred *creds;
10435 creds = get_current_cred();
10437 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
10438 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
10446 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
10447 unsigned int nr_args)
10449 struct io_uring_restriction *res;
10453 /* Restrictions allowed only if rings started disabled */
10454 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10457 /* We allow only a single restrictions registration */
10458 if (ctx->restrictions.registered)
10461 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
10464 size = array_size(nr_args, sizeof(*res));
10465 if (size == SIZE_MAX)
10468 res = memdup_user(arg, size);
10470 return PTR_ERR(res);
10474 for (i = 0; i < nr_args; i++) {
10475 switch (res[i].opcode) {
10476 case IORING_RESTRICTION_REGISTER_OP:
10477 if (res[i].register_op >= IORING_REGISTER_LAST) {
10482 __set_bit(res[i].register_op,
10483 ctx->restrictions.register_op);
10485 case IORING_RESTRICTION_SQE_OP:
10486 if (res[i].sqe_op >= IORING_OP_LAST) {
10491 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
10493 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
10494 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
10496 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
10497 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
10506 /* Reset all restrictions if an error happened */
10508 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
10510 ctx->restrictions.registered = true;
10516 static int io_register_enable_rings(struct io_ring_ctx *ctx)
10518 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
10521 if (ctx->restrictions.registered)
10522 ctx->restricted = 1;
10524 ctx->flags &= ~IORING_SETUP_R_DISABLED;
10525 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
10526 wake_up(&ctx->sq_data->wait);
10530 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
10531 struct io_uring_rsrc_update2 *up,
10537 if (check_add_overflow(up->offset, nr_args, &tmp))
10539 err = io_rsrc_node_switch_start(ctx);
10544 case IORING_RSRC_FILE:
10545 return __io_sqe_files_update(ctx, up, nr_args);
10546 case IORING_RSRC_BUFFER:
10547 return __io_sqe_buffers_update(ctx, up, nr_args);
10552 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
10555 struct io_uring_rsrc_update2 up;
10559 memset(&up, 0, sizeof(up));
10560 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
10562 if (up.resv || up.resv2)
10564 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
10567 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
10568 unsigned size, unsigned type)
10570 struct io_uring_rsrc_update2 up;
10572 if (size != sizeof(up))
10574 if (copy_from_user(&up, arg, sizeof(up)))
10576 if (!up.nr || up.resv || up.resv2)
10578 return __io_register_rsrc_update(ctx, type, &up, up.nr);
10581 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
10582 unsigned int size, unsigned int type)
10584 struct io_uring_rsrc_register rr;
10586 /* keep it extendible */
10587 if (size != sizeof(rr))
10590 memset(&rr, 0, sizeof(rr));
10591 if (copy_from_user(&rr, arg, size))
10593 if (!rr.nr || rr.resv || rr.resv2)
10597 case IORING_RSRC_FILE:
10598 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
10599 rr.nr, u64_to_user_ptr(rr.tags));
10600 case IORING_RSRC_BUFFER:
10601 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
10602 rr.nr, u64_to_user_ptr(rr.tags));
10607 static int io_register_iowq_aff(struct io_ring_ctx *ctx, void __user *arg,
10610 struct io_uring_task *tctx = current->io_uring;
10611 cpumask_var_t new_mask;
10614 if (!tctx || !tctx->io_wq)
10617 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
10620 cpumask_clear(new_mask);
10621 if (len > cpumask_size())
10622 len = cpumask_size();
10624 if (in_compat_syscall()) {
10625 ret = compat_get_bitmap(cpumask_bits(new_mask),
10626 (const compat_ulong_t __user *)arg,
10627 len * 8 /* CHAR_BIT */);
10629 ret = copy_from_user(new_mask, arg, len);
10633 free_cpumask_var(new_mask);
10637 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
10638 free_cpumask_var(new_mask);
10642 static int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
10644 struct io_uring_task *tctx = current->io_uring;
10646 if (!tctx || !tctx->io_wq)
10649 return io_wq_cpu_affinity(tctx->io_wq, NULL);
10652 static int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
10654 __must_hold(&ctx->uring_lock)
10656 struct io_tctx_node *node;
10657 struct io_uring_task *tctx = NULL;
10658 struct io_sq_data *sqd = NULL;
10659 __u32 new_count[2];
10662 if (copy_from_user(new_count, arg, sizeof(new_count)))
10664 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10665 if (new_count[i] > INT_MAX)
10668 if (ctx->flags & IORING_SETUP_SQPOLL) {
10669 sqd = ctx->sq_data;
10672 * Observe the correct sqd->lock -> ctx->uring_lock
10673 * ordering. Fine to drop uring_lock here, we hold
10674 * a ref to the ctx.
10676 refcount_inc(&sqd->refs);
10677 mutex_unlock(&ctx->uring_lock);
10678 mutex_lock(&sqd->lock);
10679 mutex_lock(&ctx->uring_lock);
10681 tctx = sqd->thread->io_uring;
10684 tctx = current->io_uring;
10687 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
10689 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10691 ctx->iowq_limits[i] = new_count[i];
10692 ctx->iowq_limits_set = true;
10695 if (tctx && tctx->io_wq) {
10696 ret = io_wq_max_workers(tctx->io_wq, new_count);
10700 memset(new_count, 0, sizeof(new_count));
10704 mutex_unlock(&sqd->lock);
10705 io_put_sq_data(sqd);
10708 if (copy_to_user(arg, new_count, sizeof(new_count)))
10711 /* that's it for SQPOLL, only the SQPOLL task creates requests */
10715 /* now propagate the restriction to all registered users */
10716 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10717 struct io_uring_task *tctx = node->task->io_uring;
10719 if (WARN_ON_ONCE(!tctx->io_wq))
10722 for (i = 0; i < ARRAY_SIZE(new_count); i++)
10723 new_count[i] = ctx->iowq_limits[i];
10724 /* ignore errors, it always returns zero anyway */
10725 (void)io_wq_max_workers(tctx->io_wq, new_count);
10730 mutex_unlock(&sqd->lock);
10731 io_put_sq_data(sqd);
10736 static bool io_register_op_must_quiesce(int op)
10739 case IORING_REGISTER_BUFFERS:
10740 case IORING_UNREGISTER_BUFFERS:
10741 case IORING_REGISTER_FILES:
10742 case IORING_UNREGISTER_FILES:
10743 case IORING_REGISTER_FILES_UPDATE:
10744 case IORING_REGISTER_PROBE:
10745 case IORING_REGISTER_PERSONALITY:
10746 case IORING_UNREGISTER_PERSONALITY:
10747 case IORING_REGISTER_FILES2:
10748 case IORING_REGISTER_FILES_UPDATE2:
10749 case IORING_REGISTER_BUFFERS2:
10750 case IORING_REGISTER_BUFFERS_UPDATE:
10751 case IORING_REGISTER_IOWQ_AFF:
10752 case IORING_UNREGISTER_IOWQ_AFF:
10753 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10760 static int io_ctx_quiesce(struct io_ring_ctx *ctx)
10764 percpu_ref_kill(&ctx->refs);
10767 * Drop uring mutex before waiting for references to exit. If another
10768 * thread is currently inside io_uring_enter() it might need to grab the
10769 * uring_lock to make progress. If we hold it here across the drain
10770 * wait, then we can deadlock. It's safe to drop the mutex here, since
10771 * no new references will come in after we've killed the percpu ref.
10773 mutex_unlock(&ctx->uring_lock);
10775 ret = wait_for_completion_interruptible(&ctx->ref_comp);
10778 ret = io_run_task_work_sig();
10779 } while (ret >= 0);
10780 mutex_lock(&ctx->uring_lock);
10783 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
10787 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
10788 void __user *arg, unsigned nr_args)
10789 __releases(ctx->uring_lock)
10790 __acquires(ctx->uring_lock)
10795 * We're inside the ring mutex, if the ref is already dying, then
10796 * someone else killed the ctx or is already going through
10797 * io_uring_register().
10799 if (percpu_ref_is_dying(&ctx->refs))
10802 if (ctx->restricted) {
10803 if (opcode >= IORING_REGISTER_LAST)
10805 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
10806 if (!test_bit(opcode, ctx->restrictions.register_op))
10810 if (io_register_op_must_quiesce(opcode)) {
10811 ret = io_ctx_quiesce(ctx);
10817 case IORING_REGISTER_BUFFERS:
10818 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
10820 case IORING_UNREGISTER_BUFFERS:
10822 if (arg || nr_args)
10824 ret = io_sqe_buffers_unregister(ctx);
10826 case IORING_REGISTER_FILES:
10827 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
10829 case IORING_UNREGISTER_FILES:
10831 if (arg || nr_args)
10833 ret = io_sqe_files_unregister(ctx);
10835 case IORING_REGISTER_FILES_UPDATE:
10836 ret = io_register_files_update(ctx, arg, nr_args);
10838 case IORING_REGISTER_EVENTFD:
10839 case IORING_REGISTER_EVENTFD_ASYNC:
10843 ret = io_eventfd_register(ctx, arg);
10846 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10847 ctx->eventfd_async = 1;
10849 ctx->eventfd_async = 0;
10851 case IORING_UNREGISTER_EVENTFD:
10853 if (arg || nr_args)
10855 ret = io_eventfd_unregister(ctx);
10857 case IORING_REGISTER_PROBE:
10859 if (!arg || nr_args > 256)
10861 ret = io_probe(ctx, arg, nr_args);
10863 case IORING_REGISTER_PERSONALITY:
10865 if (arg || nr_args)
10867 ret = io_register_personality(ctx);
10869 case IORING_UNREGISTER_PERSONALITY:
10873 ret = io_unregister_personality(ctx, nr_args);
10875 case IORING_REGISTER_ENABLE_RINGS:
10877 if (arg || nr_args)
10879 ret = io_register_enable_rings(ctx);
10881 case IORING_REGISTER_RESTRICTIONS:
10882 ret = io_register_restrictions(ctx, arg, nr_args);
10884 case IORING_REGISTER_FILES2:
10885 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
10887 case IORING_REGISTER_FILES_UPDATE2:
10888 ret = io_register_rsrc_update(ctx, arg, nr_args,
10891 case IORING_REGISTER_BUFFERS2:
10892 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
10894 case IORING_REGISTER_BUFFERS_UPDATE:
10895 ret = io_register_rsrc_update(ctx, arg, nr_args,
10896 IORING_RSRC_BUFFER);
10898 case IORING_REGISTER_IOWQ_AFF:
10900 if (!arg || !nr_args)
10902 ret = io_register_iowq_aff(ctx, arg, nr_args);
10904 case IORING_UNREGISTER_IOWQ_AFF:
10906 if (arg || nr_args)
10908 ret = io_unregister_iowq_aff(ctx);
10910 case IORING_REGISTER_IOWQ_MAX_WORKERS:
10912 if (!arg || nr_args != 2)
10914 ret = io_register_iowq_max_workers(ctx, arg);
10921 if (io_register_op_must_quiesce(opcode)) {
10922 /* bring the ctx back to life */
10923 percpu_ref_reinit(&ctx->refs);
10924 reinit_completion(&ctx->ref_comp);
10929 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10930 void __user *, arg, unsigned int, nr_args)
10932 struct io_ring_ctx *ctx;
10941 if (f.file->f_op != &io_uring_fops)
10944 ctx = f.file->private_data;
10946 io_run_task_work();
10948 mutex_lock(&ctx->uring_lock);
10949 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10950 mutex_unlock(&ctx->uring_lock);
10951 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10952 ctx->cq_ev_fd != NULL, ret);
10958 static int __init io_uring_init(void)
10960 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10961 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10962 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10965 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10966 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10967 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10968 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10969 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10970 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10971 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10972 BUILD_BUG_SQE_ELEM(8, __u64, off);
10973 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10974 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10975 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10976 BUILD_BUG_SQE_ELEM(24, __u32, len);
10977 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10978 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10979 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10980 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10981 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10982 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10983 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10984 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10985 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10986 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10987 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10988 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10989 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10990 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10991 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10992 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10993 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10994 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
10995 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10996 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10997 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
10999 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11000 sizeof(struct io_uring_rsrc_update));
11001 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11002 sizeof(struct io_uring_rsrc_update2));
11004 /* ->buf_index is u16 */
11005 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11007 /* should fit into one byte */
11008 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
11010 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
11011 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
11013 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11017 __initcall(io_uring_init);