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_cqring (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>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 #define IORING_FILE_TABLE_SHIFT 9
97 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
104 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 enum io_uring_cmd_flags {
191 IO_URING_F_NONBLOCK = 1,
192 IO_URING_F_COMPLETE_DEFER = 2,
195 struct io_mapped_ubuf {
198 struct bio_vec *bvec;
199 unsigned int nr_bvecs;
200 unsigned long acct_pages;
205 struct io_overflow_cqe {
206 struct io_uring_cqe cqe;
207 struct list_head list;
211 struct list_head list;
218 struct fixed_rsrc_table {
222 struct io_rsrc_node {
223 struct percpu_ref refs;
224 struct list_head node;
225 struct list_head rsrc_list;
226 struct io_rsrc_data *rsrc_data;
227 struct llist_node llist;
231 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
233 struct io_rsrc_data {
234 struct fixed_rsrc_table *table;
235 struct io_ring_ctx *ctx;
238 struct percpu_ref refs;
239 struct completion done;
244 struct list_head list;
250 struct io_restriction {
251 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
252 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
253 u8 sqe_flags_allowed;
254 u8 sqe_flags_required;
259 IO_SQ_THREAD_SHOULD_STOP = 0,
260 IO_SQ_THREAD_SHOULD_PARK,
265 atomic_t park_pending;
268 /* ctx's that are using this sqd */
269 struct list_head ctx_list;
271 struct task_struct *thread;
272 struct wait_queue_head wait;
274 unsigned sq_thread_idle;
280 struct completion exited;
281 struct callback_head *park_task_work;
284 #define IO_IOPOLL_BATCH 8
285 #define IO_COMPL_BATCH 32
286 #define IO_REQ_CACHE_SIZE 32
287 #define IO_REQ_ALLOC_BATCH 8
289 struct io_comp_state {
290 struct io_kiocb *reqs[IO_COMPL_BATCH];
292 unsigned int locked_free_nr;
293 /* inline/task_work completion list, under ->uring_lock */
294 struct list_head free_list;
295 /* IRQ completion list, under ->completion_lock */
296 struct list_head locked_free_list;
299 struct io_submit_link {
300 struct io_kiocb *head;
301 struct io_kiocb *last;
304 struct io_submit_state {
305 struct blk_plug plug;
306 struct io_submit_link link;
309 * io_kiocb alloc cache
311 void *reqs[IO_REQ_CACHE_SIZE];
312 unsigned int free_reqs;
317 * Batch completion logic
319 struct io_comp_state comp;
322 * File reference cache
326 unsigned int file_refs;
327 unsigned int ios_left;
332 struct percpu_ref refs;
333 } ____cacheline_aligned_in_smp;
337 unsigned int compat: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
343 * Ring buffer of indices into array of io_uring_sqe, which is
344 * mmapped by the application using the IORING_OFF_SQES offset.
346 * This indirection could e.g. be used to assign fixed
347 * io_uring_sqe entries to operations and only submit them to
348 * the queue when needed.
350 * The kernel modifies neither the indices array nor the entries
354 unsigned cached_sq_head;
357 unsigned sq_thread_idle;
358 unsigned cached_sq_dropped;
359 unsigned cached_cq_overflow;
360 unsigned long sq_check_overflow;
362 /* hashed buffered write serialization */
363 struct io_wq_hash *hash_map;
365 struct list_head defer_list;
366 struct list_head timeout_list;
367 struct list_head cq_overflow_list;
369 struct io_uring_sqe *sq_sqes;
370 } ____cacheline_aligned_in_smp;
373 struct mutex uring_lock;
374 wait_queue_head_t wait;
375 } ____cacheline_aligned_in_smp;
377 struct io_submit_state submit_state;
379 struct io_rings *rings;
381 /* Only used for accounting purposes */
382 struct mm_struct *mm_account;
384 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
385 struct io_sq_data *sq_data; /* if using sq thread polling */
387 struct wait_queue_head sqo_sq_wait;
388 struct list_head sqd_list;
391 * If used, fixed file set. Writers must ensure that ->refs is dead,
392 * readers must ensure that ->refs is alive as long as the file* is
393 * used. Only updated through io_uring_register(2).
395 struct io_rsrc_data *file_data;
396 unsigned nr_user_files;
398 /* if used, fixed mapped user buffers */
399 unsigned nr_user_bufs;
400 struct io_mapped_ubuf *user_bufs;
402 struct user_struct *user;
404 struct completion ref_comp;
406 #if defined(CONFIG_UNIX)
407 struct socket *ring_sock;
410 struct xarray io_buffers;
412 struct xarray personalities;
416 unsigned cached_cq_tail;
419 atomic_t cq_timeouts;
420 unsigned cq_last_tm_flush;
421 unsigned long cq_check_overflow;
422 struct wait_queue_head cq_wait;
423 struct fasync_struct *cq_fasync;
424 struct eventfd_ctx *cq_ev_fd;
425 } ____cacheline_aligned_in_smp;
428 spinlock_t completion_lock;
431 * ->iopoll_list is protected by the ctx->uring_lock for
432 * io_uring instances that don't use IORING_SETUP_SQPOLL.
433 * For SQPOLL, only the single threaded io_sq_thread() will
434 * manipulate the list, hence no extra locking is needed there.
436 struct list_head iopoll_list;
437 struct hlist_head *cancel_hash;
438 unsigned cancel_hash_bits;
439 bool poll_multi_file;
441 spinlock_t inflight_lock;
442 struct list_head inflight_list;
443 } ____cacheline_aligned_in_smp;
445 struct delayed_work rsrc_put_work;
446 struct llist_head rsrc_put_llist;
447 struct list_head rsrc_ref_list;
448 spinlock_t rsrc_ref_lock;
449 struct io_rsrc_node *rsrc_node;
450 struct io_rsrc_node *rsrc_backup_node;
452 struct io_restriction restrictions;
455 struct callback_head *exit_task_work;
457 /* Keep this last, we don't need it for the fast path */
458 struct work_struct exit_work;
459 struct list_head tctx_list;
462 struct io_uring_task {
463 /* submission side */
465 struct wait_queue_head wait;
466 const struct io_ring_ctx *last;
468 struct percpu_counter inflight;
471 spinlock_t task_lock;
472 struct io_wq_work_list task_list;
473 unsigned long task_state;
474 struct callback_head task_work;
478 * First field must be the file pointer in all the
479 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
481 struct io_poll_iocb {
483 struct wait_queue_head *head;
488 bool update_user_data;
490 struct wait_queue_entry wait;
498 struct io_poll_remove {
508 struct io_timeout_data {
509 struct io_kiocb *req;
510 struct hrtimer timer;
511 struct timespec64 ts;
512 enum hrtimer_mode mode;
517 struct sockaddr __user *addr;
518 int __user *addr_len;
520 unsigned long nofile;
540 struct list_head list;
541 /* head of the link, used by linked timeouts only */
542 struct io_kiocb *head;
545 struct io_timeout_rem {
550 struct timespec64 ts;
555 /* NOTE: kiocb has the file as the first member, so don't do it here */
563 struct sockaddr __user *addr;
570 struct user_msghdr __user *umsg;
576 struct io_buffer *kbuf;
582 struct filename *filename;
584 unsigned long nofile;
587 struct io_rsrc_update {
613 struct epoll_event event;
617 struct file *file_out;
618 struct file *file_in;
625 struct io_provide_buf {
639 const char __user *filename;
640 struct statx __user *buffer;
652 struct filename *oldpath;
653 struct filename *newpath;
661 struct filename *filename;
664 struct io_completion {
666 struct list_head list;
670 struct io_async_connect {
671 struct sockaddr_storage address;
674 struct io_async_msghdr {
675 struct iovec fast_iov[UIO_FASTIOV];
676 /* points to an allocated iov, if NULL we use fast_iov instead */
677 struct iovec *free_iov;
678 struct sockaddr __user *uaddr;
680 struct sockaddr_storage addr;
684 struct iovec fast_iov[UIO_FASTIOV];
685 const struct iovec *free_iovec;
686 struct iov_iter iter;
688 struct wait_page_queue wpq;
692 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
693 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
694 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
695 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
696 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
697 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
703 REQ_F_LINK_TIMEOUT_BIT,
704 REQ_F_NEED_CLEANUP_BIT,
706 REQ_F_BUFFER_SELECTED_BIT,
707 REQ_F_LTIMEOUT_ACTIVE_BIT,
708 REQ_F_COMPLETE_INLINE_BIT,
710 REQ_F_DONT_REISSUE_BIT,
711 /* keep async read/write and isreg together and in order */
712 REQ_F_ASYNC_READ_BIT,
713 REQ_F_ASYNC_WRITE_BIT,
716 /* not a real bit, just to check we're not overflowing the space */
722 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
723 /* drain existing IO first */
724 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
726 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
727 /* doesn't sever on completion < 0 */
728 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
730 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
731 /* IOSQE_BUFFER_SELECT */
732 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
734 /* fail rest of links */
735 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
736 /* on inflight list, should be cancelled and waited on exit reliably */
737 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
738 /* read/write uses file position */
739 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
740 /* must not punt to workers */
741 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
742 /* has or had linked timeout */
743 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
745 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
746 /* already went through poll handler */
747 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
748 /* buffer already selected */
749 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
750 /* linked timeout is active, i.e. prepared by link's head */
751 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
752 /* completion is deferred through io_comp_state */
753 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
754 /* caller should reissue async */
755 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
756 /* don't attempt request reissue, see io_rw_reissue() */
757 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
758 /* supports async reads */
759 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
760 /* supports async writes */
761 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
763 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
767 struct io_poll_iocb poll;
768 struct io_poll_iocb *double_poll;
771 struct io_task_work {
772 struct io_wq_work_node node;
773 task_work_func_t func;
777 * NOTE! Each of the iocb union members has the file pointer
778 * as the first entry in their struct definition. So you can
779 * access the file pointer through any of the sub-structs,
780 * or directly as just 'ki_filp' in this struct.
786 struct io_poll_iocb poll;
787 struct io_poll_remove poll_remove;
788 struct io_accept accept;
790 struct io_cancel cancel;
791 struct io_timeout timeout;
792 struct io_timeout_rem timeout_rem;
793 struct io_connect connect;
794 struct io_sr_msg sr_msg;
796 struct io_close close;
797 struct io_rsrc_update rsrc_update;
798 struct io_fadvise fadvise;
799 struct io_madvise madvise;
800 struct io_epoll epoll;
801 struct io_splice splice;
802 struct io_provide_buf pbuf;
803 struct io_statx statx;
804 struct io_shutdown shutdown;
805 struct io_rename rename;
806 struct io_unlink unlink;
807 /* use only after cleaning per-op data, see io_clean_op() */
808 struct io_completion compl;
811 /* opcode allocated if it needs to store data for async defer */
814 /* polled IO has completed */
820 struct io_ring_ctx *ctx;
823 struct task_struct *task;
826 struct io_kiocb *link;
827 struct percpu_ref *fixed_rsrc_refs;
830 * 1. used with ctx->iopoll_list with reads/writes
831 * 2. to track reqs with ->files (see io_op_def::file_table)
833 struct list_head inflight_entry;
835 struct io_task_work io_task_work;
836 struct callback_head task_work;
838 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
839 struct hlist_node hash_node;
840 struct async_poll *apoll;
841 struct io_wq_work work;
844 struct io_tctx_node {
845 struct list_head ctx_node;
846 struct task_struct *task;
847 struct io_ring_ctx *ctx;
850 struct io_defer_entry {
851 struct list_head list;
852 struct io_kiocb *req;
857 /* needs req->file assigned */
858 unsigned needs_file : 1;
859 /* hash wq insertion if file is a regular file */
860 unsigned hash_reg_file : 1;
861 /* unbound wq insertion if file is a non-regular file */
862 unsigned unbound_nonreg_file : 1;
863 /* opcode is not supported by this kernel */
864 unsigned not_supported : 1;
865 /* set if opcode supports polled "wait" */
867 unsigned pollout : 1;
868 /* op supports buffer selection */
869 unsigned buffer_select : 1;
870 /* do prep async if is going to be punted */
871 unsigned needs_async_setup : 1;
872 /* should block plug */
874 /* size of async data needed, if any */
875 unsigned short async_size;
878 static const struct io_op_def io_op_defs[] = {
879 [IORING_OP_NOP] = {},
880 [IORING_OP_READV] = {
882 .unbound_nonreg_file = 1,
885 .needs_async_setup = 1,
887 .async_size = sizeof(struct io_async_rw),
889 [IORING_OP_WRITEV] = {
892 .unbound_nonreg_file = 1,
894 .needs_async_setup = 1,
896 .async_size = sizeof(struct io_async_rw),
898 [IORING_OP_FSYNC] = {
901 [IORING_OP_READ_FIXED] = {
903 .unbound_nonreg_file = 1,
906 .async_size = sizeof(struct io_async_rw),
908 [IORING_OP_WRITE_FIXED] = {
911 .unbound_nonreg_file = 1,
914 .async_size = sizeof(struct io_async_rw),
916 [IORING_OP_POLL_ADD] = {
918 .unbound_nonreg_file = 1,
920 [IORING_OP_POLL_REMOVE] = {},
921 [IORING_OP_SYNC_FILE_RANGE] = {
924 [IORING_OP_SENDMSG] = {
926 .unbound_nonreg_file = 1,
928 .needs_async_setup = 1,
929 .async_size = sizeof(struct io_async_msghdr),
931 [IORING_OP_RECVMSG] = {
933 .unbound_nonreg_file = 1,
936 .needs_async_setup = 1,
937 .async_size = sizeof(struct io_async_msghdr),
939 [IORING_OP_TIMEOUT] = {
940 .async_size = sizeof(struct io_timeout_data),
942 [IORING_OP_TIMEOUT_REMOVE] = {
943 /* used by timeout updates' prep() */
945 [IORING_OP_ACCEPT] = {
947 .unbound_nonreg_file = 1,
950 [IORING_OP_ASYNC_CANCEL] = {},
951 [IORING_OP_LINK_TIMEOUT] = {
952 .async_size = sizeof(struct io_timeout_data),
954 [IORING_OP_CONNECT] = {
956 .unbound_nonreg_file = 1,
958 .needs_async_setup = 1,
959 .async_size = sizeof(struct io_async_connect),
961 [IORING_OP_FALLOCATE] = {
964 [IORING_OP_OPENAT] = {},
965 [IORING_OP_CLOSE] = {},
966 [IORING_OP_FILES_UPDATE] = {},
967 [IORING_OP_STATX] = {},
970 .unbound_nonreg_file = 1,
974 .async_size = sizeof(struct io_async_rw),
976 [IORING_OP_WRITE] = {
978 .unbound_nonreg_file = 1,
981 .async_size = sizeof(struct io_async_rw),
983 [IORING_OP_FADVISE] = {
986 [IORING_OP_MADVISE] = {},
989 .unbound_nonreg_file = 1,
994 .unbound_nonreg_file = 1,
998 [IORING_OP_OPENAT2] = {
1000 [IORING_OP_EPOLL_CTL] = {
1001 .unbound_nonreg_file = 1,
1003 [IORING_OP_SPLICE] = {
1006 .unbound_nonreg_file = 1,
1008 [IORING_OP_PROVIDE_BUFFERS] = {},
1009 [IORING_OP_REMOVE_BUFFERS] = {},
1013 .unbound_nonreg_file = 1,
1015 [IORING_OP_SHUTDOWN] = {
1018 [IORING_OP_RENAMEAT] = {},
1019 [IORING_OP_UNLINKAT] = {},
1022 static bool io_disarm_next(struct io_kiocb *req);
1023 static void io_uring_del_task_file(unsigned long index);
1024 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1025 struct task_struct *task,
1026 struct files_struct *files);
1027 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
1028 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1030 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1031 static void io_put_req(struct io_kiocb *req);
1032 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1033 static void io_dismantle_req(struct io_kiocb *req);
1034 static void io_put_task(struct task_struct *task, int nr);
1035 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1036 static void io_queue_linked_timeout(struct io_kiocb *req);
1037 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1038 struct io_uring_rsrc_update *ip,
1040 static void io_clean_op(struct io_kiocb *req);
1041 static struct file *io_file_get(struct io_submit_state *state,
1042 struct io_kiocb *req, int fd, bool fixed);
1043 static void __io_queue_sqe(struct io_kiocb *req);
1044 static void io_rsrc_put_work(struct work_struct *work);
1046 static void io_req_task_queue(struct io_kiocb *req);
1047 static void io_submit_flush_completions(struct io_comp_state *cs,
1048 struct io_ring_ctx *ctx);
1049 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1050 static int io_req_prep_async(struct io_kiocb *req);
1052 static struct kmem_cache *req_cachep;
1054 static const struct file_operations io_uring_fops;
1056 struct sock *io_uring_get_socket(struct file *file)
1058 #if defined(CONFIG_UNIX)
1059 if (file->f_op == &io_uring_fops) {
1060 struct io_ring_ctx *ctx = file->private_data;
1062 return ctx->ring_sock->sk;
1067 EXPORT_SYMBOL(io_uring_get_socket);
1069 #define io_for_each_link(pos, head) \
1070 for (pos = (head); pos; pos = pos->link)
1072 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1074 struct io_ring_ctx *ctx = req->ctx;
1076 if (!req->fixed_rsrc_refs) {
1077 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1078 percpu_ref_get(req->fixed_rsrc_refs);
1082 static bool io_match_task(struct io_kiocb *head,
1083 struct task_struct *task,
1084 struct files_struct *files)
1086 struct io_kiocb *req;
1088 if (task && head->task != task)
1093 io_for_each_link(req, head) {
1094 if (req->flags & REQ_F_INFLIGHT)
1100 static inline void req_set_fail_links(struct io_kiocb *req)
1102 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1103 req->flags |= REQ_F_FAIL_LINK;
1106 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1108 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1110 complete(&ctx->ref_comp);
1113 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1115 return !req->timeout.off;
1118 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1120 struct io_ring_ctx *ctx;
1123 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1128 * Use 5 bits less than the max cq entries, that should give us around
1129 * 32 entries per hash list if totally full and uniformly spread.
1131 hash_bits = ilog2(p->cq_entries);
1135 ctx->cancel_hash_bits = hash_bits;
1136 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1138 if (!ctx->cancel_hash)
1140 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1142 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1143 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1146 ctx->flags = p->flags;
1147 init_waitqueue_head(&ctx->sqo_sq_wait);
1148 INIT_LIST_HEAD(&ctx->sqd_list);
1149 init_waitqueue_head(&ctx->cq_wait);
1150 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1151 init_completion(&ctx->ref_comp);
1152 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1153 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1154 mutex_init(&ctx->uring_lock);
1155 init_waitqueue_head(&ctx->wait);
1156 spin_lock_init(&ctx->completion_lock);
1157 INIT_LIST_HEAD(&ctx->iopoll_list);
1158 INIT_LIST_HEAD(&ctx->defer_list);
1159 INIT_LIST_HEAD(&ctx->timeout_list);
1160 spin_lock_init(&ctx->inflight_lock);
1161 INIT_LIST_HEAD(&ctx->inflight_list);
1162 spin_lock_init(&ctx->rsrc_ref_lock);
1163 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1164 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1165 init_llist_head(&ctx->rsrc_put_llist);
1166 INIT_LIST_HEAD(&ctx->tctx_list);
1167 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1168 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1171 kfree(ctx->cancel_hash);
1176 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1178 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1179 struct io_ring_ctx *ctx = req->ctx;
1181 return seq != ctx->cached_cq_tail
1182 + READ_ONCE(ctx->cached_cq_overflow);
1188 static void io_req_track_inflight(struct io_kiocb *req)
1190 struct io_ring_ctx *ctx = req->ctx;
1192 if (!(req->flags & REQ_F_INFLIGHT)) {
1193 req->flags |= REQ_F_INFLIGHT;
1195 spin_lock_irq(&ctx->inflight_lock);
1196 list_add(&req->inflight_entry, &ctx->inflight_list);
1197 spin_unlock_irq(&ctx->inflight_lock);
1201 static void io_prep_async_work(struct io_kiocb *req)
1203 const struct io_op_def *def = &io_op_defs[req->opcode];
1204 struct io_ring_ctx *ctx = req->ctx;
1206 if (!req->work.creds)
1207 req->work.creds = get_current_cred();
1209 req->work.list.next = NULL;
1210 req->work.flags = 0;
1211 if (req->flags & REQ_F_FORCE_ASYNC)
1212 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1214 if (req->flags & REQ_F_ISREG) {
1215 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1216 io_wq_hash_work(&req->work, file_inode(req->file));
1217 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1218 if (def->unbound_nonreg_file)
1219 req->work.flags |= IO_WQ_WORK_UNBOUND;
1222 switch (req->opcode) {
1223 case IORING_OP_SPLICE:
1226 * Splice operation will be punted aync, and here need to
1227 * modify io_wq_work.flags, so initialize io_wq_work firstly.
1229 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1230 req->work.flags |= IO_WQ_WORK_UNBOUND;
1235 static void io_prep_async_link(struct io_kiocb *req)
1237 struct io_kiocb *cur;
1239 io_for_each_link(cur, req)
1240 io_prep_async_work(cur);
1243 static void io_queue_async_work(struct io_kiocb *req)
1245 struct io_ring_ctx *ctx = req->ctx;
1246 struct io_kiocb *link = io_prep_linked_timeout(req);
1247 struct io_uring_task *tctx = req->task->io_uring;
1250 BUG_ON(!tctx->io_wq);
1252 /* init ->work of the whole link before punting */
1253 io_prep_async_link(req);
1254 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1255 &req->work, req->flags);
1256 io_wq_enqueue(tctx->io_wq, &req->work);
1258 io_queue_linked_timeout(link);
1261 static void io_kill_timeout(struct io_kiocb *req, int status)
1263 struct io_timeout_data *io = req->async_data;
1266 ret = hrtimer_try_to_cancel(&io->timer);
1268 atomic_set(&req->ctx->cq_timeouts,
1269 atomic_read(&req->ctx->cq_timeouts) + 1);
1270 list_del_init(&req->timeout.list);
1271 io_cqring_fill_event(req, status);
1272 io_put_req_deferred(req, 1);
1276 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1279 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1280 struct io_defer_entry, list);
1282 if (req_need_defer(de->req, de->seq))
1284 list_del_init(&de->list);
1285 io_req_task_queue(de->req);
1287 } while (!list_empty(&ctx->defer_list));
1290 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1294 if (list_empty(&ctx->timeout_list))
1297 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1300 u32 events_needed, events_got;
1301 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1302 struct io_kiocb, timeout.list);
1304 if (io_is_timeout_noseq(req))
1308 * Since seq can easily wrap around over time, subtract
1309 * the last seq at which timeouts were flushed before comparing.
1310 * Assuming not more than 2^31-1 events have happened since,
1311 * these subtractions won't have wrapped, so we can check if
1312 * target is in [last_seq, current_seq] by comparing the two.
1314 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1315 events_got = seq - ctx->cq_last_tm_flush;
1316 if (events_got < events_needed)
1319 list_del_init(&req->timeout.list);
1320 io_kill_timeout(req, 0);
1321 } while (!list_empty(&ctx->timeout_list));
1323 ctx->cq_last_tm_flush = seq;
1326 static void io_commit_cqring(struct io_ring_ctx *ctx)
1328 io_flush_timeouts(ctx);
1330 /* order cqe stores with ring update */
1331 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1333 if (unlikely(!list_empty(&ctx->defer_list)))
1334 __io_queue_deferred(ctx);
1337 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1339 struct io_rings *r = ctx->rings;
1341 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1344 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1346 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1349 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1351 struct io_rings *rings = ctx->rings;
1355 * writes to the cq entry need to come after reading head; the
1356 * control dependency is enough as we're using WRITE_ONCE to
1359 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1362 tail = ctx->cached_cq_tail++;
1363 return &rings->cqes[tail & ctx->cq_mask];
1366 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1370 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1372 if (!ctx->eventfd_async)
1374 return io_wq_current_is_worker();
1377 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1379 /* see waitqueue_active() comment */
1382 if (waitqueue_active(&ctx->wait))
1383 wake_up(&ctx->wait);
1384 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1385 wake_up(&ctx->sq_data->wait);
1386 if (io_should_trigger_evfd(ctx))
1387 eventfd_signal(ctx->cq_ev_fd, 1);
1388 if (waitqueue_active(&ctx->cq_wait)) {
1389 wake_up_interruptible(&ctx->cq_wait);
1390 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1394 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1396 /* see waitqueue_active() comment */
1399 if (ctx->flags & IORING_SETUP_SQPOLL) {
1400 if (waitqueue_active(&ctx->wait))
1401 wake_up(&ctx->wait);
1403 if (io_should_trigger_evfd(ctx))
1404 eventfd_signal(ctx->cq_ev_fd, 1);
1405 if (waitqueue_active(&ctx->cq_wait)) {
1406 wake_up_interruptible(&ctx->cq_wait);
1407 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1411 /* Returns true if there are no backlogged entries after the flush */
1412 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1414 struct io_rings *rings = ctx->rings;
1415 unsigned long flags;
1416 bool all_flushed, posted;
1418 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1422 spin_lock_irqsave(&ctx->completion_lock, flags);
1423 while (!list_empty(&ctx->cq_overflow_list)) {
1424 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1425 struct io_overflow_cqe *ocqe;
1429 ocqe = list_first_entry(&ctx->cq_overflow_list,
1430 struct io_overflow_cqe, list);
1432 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1434 WRITE_ONCE(ctx->rings->cq_overflow,
1435 ++ctx->cached_cq_overflow);
1437 list_del(&ocqe->list);
1441 all_flushed = list_empty(&ctx->cq_overflow_list);
1443 clear_bit(0, &ctx->sq_check_overflow);
1444 clear_bit(0, &ctx->cq_check_overflow);
1445 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1449 io_commit_cqring(ctx);
1450 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1452 io_cqring_ev_posted(ctx);
1456 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1460 if (test_bit(0, &ctx->cq_check_overflow)) {
1461 /* iopoll syncs against uring_lock, not completion_lock */
1462 if (ctx->flags & IORING_SETUP_IOPOLL)
1463 mutex_lock(&ctx->uring_lock);
1464 ret = __io_cqring_overflow_flush(ctx, force);
1465 if (ctx->flags & IORING_SETUP_IOPOLL)
1466 mutex_unlock(&ctx->uring_lock);
1473 * Shamelessly stolen from the mm implementation of page reference checking,
1474 * see commit f958d7b528b1 for details.
1476 #define req_ref_zero_or_close_to_overflow(req) \
1477 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1479 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1481 return atomic_inc_not_zero(&req->refs);
1484 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1486 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1487 return atomic_sub_and_test(refs, &req->refs);
1490 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1492 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1493 return atomic_dec_and_test(&req->refs);
1496 static inline void req_ref_put(struct io_kiocb *req)
1498 WARN_ON_ONCE(req_ref_put_and_test(req));
1501 static inline void req_ref_get(struct io_kiocb *req)
1503 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1504 atomic_inc(&req->refs);
1507 static bool __io_cqring_fill_event(struct io_kiocb *req, long res,
1508 unsigned int cflags)
1510 struct io_ring_ctx *ctx = req->ctx;
1511 struct io_uring_cqe *cqe;
1513 trace_io_uring_complete(ctx, req->user_data, res, cflags);
1516 * If we can't get a cq entry, userspace overflowed the
1517 * submission (by quite a lot). Increment the overflow count in
1520 cqe = io_get_cqring(ctx);
1522 WRITE_ONCE(cqe->user_data, req->user_data);
1523 WRITE_ONCE(cqe->res, res);
1524 WRITE_ONCE(cqe->flags, cflags);
1527 if (!atomic_read(&req->task->io_uring->in_idle)) {
1528 struct io_overflow_cqe *ocqe;
1530 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1533 if (list_empty(&ctx->cq_overflow_list)) {
1534 set_bit(0, &ctx->sq_check_overflow);
1535 set_bit(0, &ctx->cq_check_overflow);
1536 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1538 ocqe->cqe.user_data = req->user_data;
1539 ocqe->cqe.res = res;
1540 ocqe->cqe.flags = cflags;
1541 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1546 * If we're in ring overflow flush mode, or in task cancel mode,
1547 * or cannot allocate an overflow entry, then we need to drop it
1550 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1554 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1556 __io_cqring_fill_event(req, res, 0);
1559 static void io_req_complete_post(struct io_kiocb *req, long res,
1560 unsigned int cflags)
1562 struct io_ring_ctx *ctx = req->ctx;
1563 unsigned long flags;
1565 spin_lock_irqsave(&ctx->completion_lock, flags);
1566 __io_cqring_fill_event(req, res, cflags);
1568 * If we're the last reference to this request, add to our locked
1571 if (req_ref_put_and_test(req)) {
1572 struct io_comp_state *cs = &ctx->submit_state.comp;
1574 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1575 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1576 io_disarm_next(req);
1578 io_req_task_queue(req->link);
1582 io_dismantle_req(req);
1583 io_put_task(req->task, 1);
1584 list_add(&req->compl.list, &cs->locked_free_list);
1585 cs->locked_free_nr++;
1587 if (!percpu_ref_tryget(&ctx->refs))
1590 io_commit_cqring(ctx);
1591 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1594 io_cqring_ev_posted(ctx);
1595 percpu_ref_put(&ctx->refs);
1599 static void io_req_complete_state(struct io_kiocb *req, long res,
1600 unsigned int cflags)
1602 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1605 req->compl.cflags = cflags;
1606 req->flags |= REQ_F_COMPLETE_INLINE;
1609 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1610 long res, unsigned cflags)
1612 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1613 io_req_complete_state(req, res, cflags);
1615 io_req_complete_post(req, res, cflags);
1618 static inline void io_req_complete(struct io_kiocb *req, long res)
1620 __io_req_complete(req, 0, res, 0);
1623 static void io_req_complete_failed(struct io_kiocb *req, long res)
1625 req_set_fail_links(req);
1627 io_req_complete_post(req, res, 0);
1630 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1631 struct io_comp_state *cs)
1633 spin_lock_irq(&ctx->completion_lock);
1634 list_splice_init(&cs->locked_free_list, &cs->free_list);
1635 cs->locked_free_nr = 0;
1636 spin_unlock_irq(&ctx->completion_lock);
1639 /* Returns true IFF there are requests in the cache */
1640 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1642 struct io_submit_state *state = &ctx->submit_state;
1643 struct io_comp_state *cs = &state->comp;
1647 * If we have more than a batch's worth of requests in our IRQ side
1648 * locked cache, grab the lock and move them over to our submission
1651 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
1652 io_flush_cached_locked_reqs(ctx, cs);
1654 nr = state->free_reqs;
1655 while (!list_empty(&cs->free_list)) {
1656 struct io_kiocb *req = list_first_entry(&cs->free_list,
1657 struct io_kiocb, compl.list);
1659 list_del(&req->compl.list);
1660 state->reqs[nr++] = req;
1661 if (nr == ARRAY_SIZE(state->reqs))
1665 state->free_reqs = nr;
1669 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1671 struct io_submit_state *state = &ctx->submit_state;
1673 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1675 if (!state->free_reqs) {
1676 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1679 if (io_flush_cached_reqs(ctx))
1682 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1686 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1687 * retry single alloc to be on the safe side.
1689 if (unlikely(ret <= 0)) {
1690 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1691 if (!state->reqs[0])
1695 state->free_reqs = ret;
1699 return state->reqs[state->free_reqs];
1702 static inline void io_put_file(struct file *file)
1708 static void io_dismantle_req(struct io_kiocb *req)
1710 unsigned int flags = req->flags;
1712 if (!(flags & REQ_F_FIXED_FILE))
1713 io_put_file(req->file);
1714 if (flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1718 if (req->flags & REQ_F_INFLIGHT) {
1719 struct io_ring_ctx *ctx = req->ctx;
1720 unsigned long flags;
1722 spin_lock_irqsave(&ctx->inflight_lock, flags);
1723 list_del(&req->inflight_entry);
1724 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1725 req->flags &= ~REQ_F_INFLIGHT;
1728 if (req->fixed_rsrc_refs)
1729 percpu_ref_put(req->fixed_rsrc_refs);
1730 if (req->async_data)
1731 kfree(req->async_data);
1732 if (req->work.creds) {
1733 put_cred(req->work.creds);
1734 req->work.creds = NULL;
1738 /* must to be called somewhat shortly after putting a request */
1739 static inline void io_put_task(struct task_struct *task, int nr)
1741 struct io_uring_task *tctx = task->io_uring;
1743 percpu_counter_sub(&tctx->inflight, nr);
1744 if (unlikely(atomic_read(&tctx->in_idle)))
1745 wake_up(&tctx->wait);
1746 put_task_struct_many(task, nr);
1749 static void __io_free_req(struct io_kiocb *req)
1751 struct io_ring_ctx *ctx = req->ctx;
1753 io_dismantle_req(req);
1754 io_put_task(req->task, 1);
1756 kmem_cache_free(req_cachep, req);
1757 percpu_ref_put(&ctx->refs);
1760 static inline void io_remove_next_linked(struct io_kiocb *req)
1762 struct io_kiocb *nxt = req->link;
1764 req->link = nxt->link;
1768 static bool io_kill_linked_timeout(struct io_kiocb *req)
1769 __must_hold(&req->ctx->completion_lock)
1771 struct io_kiocb *link = req->link;
1774 * Can happen if a linked timeout fired and link had been like
1775 * req -> link t-out -> link t-out [-> ...]
1777 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1778 struct io_timeout_data *io = link->async_data;
1781 io_remove_next_linked(req);
1782 link->timeout.head = NULL;
1783 ret = hrtimer_try_to_cancel(&io->timer);
1785 io_cqring_fill_event(link, -ECANCELED);
1786 io_put_req_deferred(link, 1);
1793 static void io_fail_links(struct io_kiocb *req)
1794 __must_hold(&req->ctx->completion_lock)
1796 struct io_kiocb *nxt, *link = req->link;
1803 trace_io_uring_fail_link(req, link);
1804 io_cqring_fill_event(link, -ECANCELED);
1805 io_put_req_deferred(link, 2);
1810 static bool io_disarm_next(struct io_kiocb *req)
1811 __must_hold(&req->ctx->completion_lock)
1813 bool posted = false;
1815 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1816 posted = io_kill_linked_timeout(req);
1817 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1818 posted |= (req->link != NULL);
1824 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1826 struct io_kiocb *nxt;
1829 * If LINK is set, we have dependent requests in this chain. If we
1830 * didn't fail this request, queue the first one up, moving any other
1831 * dependencies to the next request. In case of failure, fail the rest
1834 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1835 struct io_ring_ctx *ctx = req->ctx;
1836 unsigned long flags;
1839 spin_lock_irqsave(&ctx->completion_lock, flags);
1840 posted = io_disarm_next(req);
1842 io_commit_cqring(req->ctx);
1843 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1845 io_cqring_ev_posted(ctx);
1852 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1854 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1856 return __io_req_find_next(req);
1859 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1863 if (ctx->submit_state.comp.nr) {
1864 mutex_lock(&ctx->uring_lock);
1865 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1866 mutex_unlock(&ctx->uring_lock);
1868 percpu_ref_put(&ctx->refs);
1871 static bool __tctx_task_work(struct io_uring_task *tctx)
1873 struct io_ring_ctx *ctx = NULL;
1874 struct io_wq_work_list list;
1875 struct io_wq_work_node *node;
1877 if (wq_list_empty(&tctx->task_list))
1880 spin_lock_irq(&tctx->task_lock);
1881 list = tctx->task_list;
1882 INIT_WQ_LIST(&tctx->task_list);
1883 spin_unlock_irq(&tctx->task_lock);
1887 struct io_wq_work_node *next = node->next;
1888 struct io_kiocb *req;
1890 req = container_of(node, struct io_kiocb, io_task_work.node);
1891 if (req->ctx != ctx) {
1892 ctx_flush_and_put(ctx);
1894 percpu_ref_get(&ctx->refs);
1897 req->task_work.func(&req->task_work);
1901 ctx_flush_and_put(ctx);
1902 return list.first != NULL;
1905 static void tctx_task_work(struct callback_head *cb)
1907 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1909 clear_bit(0, &tctx->task_state);
1911 while (__tctx_task_work(tctx))
1915 static int io_req_task_work_add(struct io_kiocb *req)
1917 struct task_struct *tsk = req->task;
1918 struct io_uring_task *tctx = tsk->io_uring;
1919 enum task_work_notify_mode notify;
1920 struct io_wq_work_node *node, *prev;
1921 unsigned long flags;
1924 if (unlikely(tsk->flags & PF_EXITING))
1927 WARN_ON_ONCE(!tctx);
1929 spin_lock_irqsave(&tctx->task_lock, flags);
1930 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1931 spin_unlock_irqrestore(&tctx->task_lock, flags);
1933 /* task_work already pending, we're done */
1934 if (test_bit(0, &tctx->task_state) ||
1935 test_and_set_bit(0, &tctx->task_state))
1939 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1940 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1941 * processing task_work. There's no reliable way to tell if TWA_RESUME
1944 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1946 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1947 wake_up_process(tsk);
1952 * Slow path - we failed, find and delete work. if the work is not
1953 * in the list, it got run and we're fine.
1955 spin_lock_irqsave(&tctx->task_lock, flags);
1956 wq_list_for_each(node, prev, &tctx->task_list) {
1957 if (&req->io_task_work.node == node) {
1958 wq_list_del(&tctx->task_list, node, prev);
1963 spin_unlock_irqrestore(&tctx->task_lock, flags);
1964 clear_bit(0, &tctx->task_state);
1968 static bool io_run_task_work_head(struct callback_head **work_head)
1970 struct callback_head *work, *next;
1971 bool executed = false;
1974 work = xchg(work_head, NULL);
1990 static void io_task_work_add_head(struct callback_head **work_head,
1991 struct callback_head *task_work)
1993 struct callback_head *head;
1996 head = READ_ONCE(*work_head);
1997 task_work->next = head;
1998 } while (cmpxchg(work_head, head, task_work) != head);
2001 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2002 task_work_func_t cb)
2004 init_task_work(&req->task_work, cb);
2005 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2008 static void io_req_task_cancel(struct callback_head *cb)
2010 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2011 struct io_ring_ctx *ctx = req->ctx;
2013 /* ctx is guaranteed to stay alive while we hold uring_lock */
2014 mutex_lock(&ctx->uring_lock);
2015 io_req_complete_failed(req, req->result);
2016 mutex_unlock(&ctx->uring_lock);
2019 static void __io_req_task_submit(struct io_kiocb *req)
2021 struct io_ring_ctx *ctx = req->ctx;
2023 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2024 mutex_lock(&ctx->uring_lock);
2025 if (!(current->flags & PF_EXITING) && !current->in_execve)
2026 __io_queue_sqe(req);
2028 io_req_complete_failed(req, -EFAULT);
2029 mutex_unlock(&ctx->uring_lock);
2032 static void io_req_task_submit(struct callback_head *cb)
2034 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2036 __io_req_task_submit(req);
2039 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2042 req->task_work.func = io_req_task_cancel;
2044 if (unlikely(io_req_task_work_add(req)))
2045 io_req_task_work_add_fallback(req, io_req_task_cancel);
2048 static void io_req_task_queue(struct io_kiocb *req)
2050 req->task_work.func = io_req_task_submit;
2052 if (unlikely(io_req_task_work_add(req)))
2053 io_req_task_queue_fail(req, -ECANCELED);
2056 static inline void io_queue_next(struct io_kiocb *req)
2058 struct io_kiocb *nxt = io_req_find_next(req);
2061 io_req_task_queue(nxt);
2064 static void io_free_req(struct io_kiocb *req)
2071 struct task_struct *task;
2076 static inline void io_init_req_batch(struct req_batch *rb)
2083 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2084 struct req_batch *rb)
2087 io_put_task(rb->task, rb->task_refs);
2089 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2092 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2093 struct io_submit_state *state)
2096 io_dismantle_req(req);
2098 if (req->task != rb->task) {
2100 io_put_task(rb->task, rb->task_refs);
2101 rb->task = req->task;
2107 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2108 state->reqs[state->free_reqs++] = req;
2110 list_add(&req->compl.list, &state->comp.free_list);
2113 static void io_submit_flush_completions(struct io_comp_state *cs,
2114 struct io_ring_ctx *ctx)
2117 struct io_kiocb *req;
2118 struct req_batch rb;
2120 io_init_req_batch(&rb);
2121 spin_lock_irq(&ctx->completion_lock);
2122 for (i = 0; i < nr; i++) {
2124 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2126 io_commit_cqring(ctx);
2127 spin_unlock_irq(&ctx->completion_lock);
2129 io_cqring_ev_posted(ctx);
2130 for (i = 0; i < nr; i++) {
2133 /* submission and completion refs */
2134 if (req_ref_sub_and_test(req, 2))
2135 io_req_free_batch(&rb, req, &ctx->submit_state);
2138 io_req_free_batch_finish(ctx, &rb);
2143 * Drop reference to request, return next in chain (if there is one) if this
2144 * was the last reference to this request.
2146 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2148 struct io_kiocb *nxt = NULL;
2150 if (req_ref_put_and_test(req)) {
2151 nxt = io_req_find_next(req);
2157 static inline void io_put_req(struct io_kiocb *req)
2159 if (req_ref_put_and_test(req))
2163 static void io_put_req_deferred_cb(struct callback_head *cb)
2165 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2170 static void io_free_req_deferred(struct io_kiocb *req)
2172 req->task_work.func = io_put_req_deferred_cb;
2173 if (unlikely(io_req_task_work_add(req)))
2174 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2177 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2179 if (req_ref_sub_and_test(req, refs))
2180 io_free_req_deferred(req);
2183 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2185 /* See comment at the top of this file */
2187 return __io_cqring_events(ctx);
2190 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2192 struct io_rings *rings = ctx->rings;
2194 /* make sure SQ entry isn't read before tail */
2195 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2198 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2200 unsigned int cflags;
2202 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2203 cflags |= IORING_CQE_F_BUFFER;
2204 req->flags &= ~REQ_F_BUFFER_SELECTED;
2209 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2211 struct io_buffer *kbuf;
2213 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2214 return io_put_kbuf(req, kbuf);
2217 static inline bool io_run_task_work(void)
2220 * Not safe to run on exiting task, and the task_work handling will
2221 * not add work to such a task.
2223 if (unlikely(current->flags & PF_EXITING))
2225 if (current->task_works) {
2226 __set_current_state(TASK_RUNNING);
2235 * Find and free completed poll iocbs
2237 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2238 struct list_head *done)
2240 struct req_batch rb;
2241 struct io_kiocb *req;
2243 /* order with ->result store in io_complete_rw_iopoll() */
2246 io_init_req_batch(&rb);
2247 while (!list_empty(done)) {
2250 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2251 list_del(&req->inflight_entry);
2253 if (READ_ONCE(req->result) == -EAGAIN &&
2254 !(req->flags & REQ_F_DONT_REISSUE)) {
2255 req->iopoll_completed = 0;
2257 io_queue_async_work(req);
2261 if (req->flags & REQ_F_BUFFER_SELECTED)
2262 cflags = io_put_rw_kbuf(req);
2264 __io_cqring_fill_event(req, req->result, cflags);
2267 if (req_ref_put_and_test(req))
2268 io_req_free_batch(&rb, req, &ctx->submit_state);
2271 io_commit_cqring(ctx);
2272 io_cqring_ev_posted_iopoll(ctx);
2273 io_req_free_batch_finish(ctx, &rb);
2276 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2279 struct io_kiocb *req, *tmp;
2285 * Only spin for completions if we don't have multiple devices hanging
2286 * off our complete list, and we're under the requested amount.
2288 spin = !ctx->poll_multi_file && *nr_events < min;
2291 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2292 struct kiocb *kiocb = &req->rw.kiocb;
2295 * Move completed and retryable entries to our local lists.
2296 * If we find a request that requires polling, break out
2297 * and complete those lists first, if we have entries there.
2299 if (READ_ONCE(req->iopoll_completed)) {
2300 list_move_tail(&req->inflight_entry, &done);
2303 if (!list_empty(&done))
2306 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2310 /* iopoll may have completed current req */
2311 if (READ_ONCE(req->iopoll_completed))
2312 list_move_tail(&req->inflight_entry, &done);
2319 if (!list_empty(&done))
2320 io_iopoll_complete(ctx, nr_events, &done);
2326 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2327 * non-spinning poll check - we'll still enter the driver poll loop, but only
2328 * as a non-spinning completion check.
2330 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2333 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2336 ret = io_do_iopoll(ctx, nr_events, min);
2339 if (*nr_events >= min)
2347 * We can't just wait for polled events to come to us, we have to actively
2348 * find and complete them.
2350 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2352 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2355 mutex_lock(&ctx->uring_lock);
2356 while (!list_empty(&ctx->iopoll_list)) {
2357 unsigned int nr_events = 0;
2359 io_do_iopoll(ctx, &nr_events, 0);
2361 /* let it sleep and repeat later if can't complete a request */
2365 * Ensure we allow local-to-the-cpu processing to take place,
2366 * in this case we need to ensure that we reap all events.
2367 * Also let task_work, etc. to progress by releasing the mutex
2369 if (need_resched()) {
2370 mutex_unlock(&ctx->uring_lock);
2372 mutex_lock(&ctx->uring_lock);
2375 mutex_unlock(&ctx->uring_lock);
2378 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2380 unsigned int nr_events = 0;
2381 int iters = 0, ret = 0;
2384 * We disallow the app entering submit/complete with polling, but we
2385 * still need to lock the ring to prevent racing with polled issue
2386 * that got punted to a workqueue.
2388 mutex_lock(&ctx->uring_lock);
2391 * Don't enter poll loop if we already have events pending.
2392 * If we do, we can potentially be spinning for commands that
2393 * already triggered a CQE (eg in error).
2395 if (test_bit(0, &ctx->cq_check_overflow))
2396 __io_cqring_overflow_flush(ctx, false);
2397 if (io_cqring_events(ctx))
2401 * If a submit got punted to a workqueue, we can have the
2402 * application entering polling for a command before it gets
2403 * issued. That app will hold the uring_lock for the duration
2404 * of the poll right here, so we need to take a breather every
2405 * now and then to ensure that the issue has a chance to add
2406 * the poll to the issued list. Otherwise we can spin here
2407 * forever, while the workqueue is stuck trying to acquire the
2410 if (!(++iters & 7)) {
2411 mutex_unlock(&ctx->uring_lock);
2413 mutex_lock(&ctx->uring_lock);
2416 ret = io_iopoll_getevents(ctx, &nr_events, min);
2420 } while (min && !nr_events && !need_resched());
2422 mutex_unlock(&ctx->uring_lock);
2426 static void kiocb_end_write(struct io_kiocb *req)
2429 * Tell lockdep we inherited freeze protection from submission
2432 if (req->flags & REQ_F_ISREG) {
2433 struct super_block *sb = file_inode(req->file)->i_sb;
2435 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2441 static bool io_resubmit_prep(struct io_kiocb *req)
2443 struct io_async_rw *rw = req->async_data;
2446 return !io_req_prep_async(req);
2447 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2448 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2452 static bool io_rw_should_reissue(struct io_kiocb *req)
2454 umode_t mode = file_inode(req->file)->i_mode;
2455 struct io_ring_ctx *ctx = req->ctx;
2457 if (!S_ISBLK(mode) && !S_ISREG(mode))
2459 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2460 !(ctx->flags & IORING_SETUP_IOPOLL)))
2463 * If ref is dying, we might be running poll reap from the exit work.
2464 * Don't attempt to reissue from that path, just let it fail with
2467 if (percpu_ref_is_dying(&ctx->refs))
2472 static bool io_rw_should_reissue(struct io_kiocb *req)
2478 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2479 unsigned int issue_flags)
2483 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2484 kiocb_end_write(req);
2485 if (res != req->result) {
2486 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2487 io_rw_should_reissue(req)) {
2488 req->flags |= REQ_F_REISSUE;
2491 req_set_fail_links(req);
2493 if (req->flags & REQ_F_BUFFER_SELECTED)
2494 cflags = io_put_rw_kbuf(req);
2495 __io_req_complete(req, issue_flags, res, cflags);
2498 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2500 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2502 __io_complete_rw(req, res, res2, 0);
2505 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2507 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2509 if (kiocb->ki_flags & IOCB_WRITE)
2510 kiocb_end_write(req);
2511 if (unlikely(res != req->result)) {
2515 if (res == -EAGAIN && io_rw_should_reissue(req) &&
2516 io_resubmit_prep(req))
2520 req_set_fail_links(req);
2521 req->flags |= REQ_F_DONT_REISSUE;
2525 WRITE_ONCE(req->result, res);
2526 /* order with io_iopoll_complete() checking ->result */
2528 WRITE_ONCE(req->iopoll_completed, 1);
2532 * After the iocb has been issued, it's safe to be found on the poll list.
2533 * Adding the kiocb to the list AFTER submission ensures that we don't
2534 * find it from a io_iopoll_getevents() thread before the issuer is done
2535 * accessing the kiocb cookie.
2537 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2539 struct io_ring_ctx *ctx = req->ctx;
2542 * Track whether we have multiple files in our lists. This will impact
2543 * how we do polling eventually, not spinning if we're on potentially
2544 * different devices.
2546 if (list_empty(&ctx->iopoll_list)) {
2547 ctx->poll_multi_file = false;
2548 } else if (!ctx->poll_multi_file) {
2549 struct io_kiocb *list_req;
2551 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2553 if (list_req->file != req->file)
2554 ctx->poll_multi_file = true;
2558 * For fast devices, IO may have already completed. If it has, add
2559 * it to the front so we find it first.
2561 if (READ_ONCE(req->iopoll_completed))
2562 list_add(&req->inflight_entry, &ctx->iopoll_list);
2564 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2567 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2568 * task context or in io worker task context. If current task context is
2569 * sq thread, we don't need to check whether should wake up sq thread.
2571 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2572 wq_has_sleeper(&ctx->sq_data->wait))
2573 wake_up(&ctx->sq_data->wait);
2576 static inline void io_state_file_put(struct io_submit_state *state)
2578 if (state->file_refs) {
2579 fput_many(state->file, state->file_refs);
2580 state->file_refs = 0;
2585 * Get as many references to a file as we have IOs left in this submission,
2586 * assuming most submissions are for one file, or at least that each file
2587 * has more than one submission.
2589 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2594 if (state->file_refs) {
2595 if (state->fd == fd) {
2599 io_state_file_put(state);
2601 state->file = fget_many(fd, state->ios_left);
2602 if (unlikely(!state->file))
2606 state->file_refs = state->ios_left - 1;
2610 static bool io_bdev_nowait(struct block_device *bdev)
2612 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2616 * If we tracked the file through the SCM inflight mechanism, we could support
2617 * any file. For now, just ensure that anything potentially problematic is done
2620 static bool __io_file_supports_async(struct file *file, int rw)
2622 umode_t mode = file_inode(file)->i_mode;
2624 if (S_ISBLK(mode)) {
2625 if (IS_ENABLED(CONFIG_BLOCK) &&
2626 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2630 if (S_ISCHR(mode) || S_ISSOCK(mode))
2632 if (S_ISREG(mode)) {
2633 if (IS_ENABLED(CONFIG_BLOCK) &&
2634 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2635 file->f_op != &io_uring_fops)
2640 /* any ->read/write should understand O_NONBLOCK */
2641 if (file->f_flags & O_NONBLOCK)
2644 if (!(file->f_mode & FMODE_NOWAIT))
2648 return file->f_op->read_iter != NULL;
2650 return file->f_op->write_iter != NULL;
2653 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2655 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2657 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2660 return __io_file_supports_async(req->file, rw);
2663 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2665 struct io_ring_ctx *ctx = req->ctx;
2666 struct kiocb *kiocb = &req->rw.kiocb;
2667 struct file *file = req->file;
2671 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2672 req->flags |= REQ_F_ISREG;
2674 kiocb->ki_pos = READ_ONCE(sqe->off);
2675 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2676 req->flags |= REQ_F_CUR_POS;
2677 kiocb->ki_pos = file->f_pos;
2679 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2680 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2681 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2685 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2686 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2687 req->flags |= REQ_F_NOWAIT;
2689 ioprio = READ_ONCE(sqe->ioprio);
2691 ret = ioprio_check_cap(ioprio);
2695 kiocb->ki_ioprio = ioprio;
2697 kiocb->ki_ioprio = get_current_ioprio();
2699 if (ctx->flags & IORING_SETUP_IOPOLL) {
2700 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2701 !kiocb->ki_filp->f_op->iopoll)
2704 kiocb->ki_flags |= IOCB_HIPRI;
2705 kiocb->ki_complete = io_complete_rw_iopoll;
2706 req->iopoll_completed = 0;
2708 if (kiocb->ki_flags & IOCB_HIPRI)
2710 kiocb->ki_complete = io_complete_rw;
2713 req->rw.addr = READ_ONCE(sqe->addr);
2714 req->rw.len = READ_ONCE(sqe->len);
2715 req->buf_index = READ_ONCE(sqe->buf_index);
2719 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2725 case -ERESTARTNOINTR:
2726 case -ERESTARTNOHAND:
2727 case -ERESTART_RESTARTBLOCK:
2729 * We can't just restart the syscall, since previously
2730 * submitted sqes may already be in progress. Just fail this
2736 kiocb->ki_complete(kiocb, ret, 0);
2740 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2741 unsigned int issue_flags)
2743 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2744 struct io_async_rw *io = req->async_data;
2745 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2747 /* add previously done IO, if any */
2748 if (io && io->bytes_done > 0) {
2750 ret = io->bytes_done;
2752 ret += io->bytes_done;
2755 if (req->flags & REQ_F_CUR_POS)
2756 req->file->f_pos = kiocb->ki_pos;
2757 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2758 __io_complete_rw(req, ret, 0, issue_flags);
2760 io_rw_done(kiocb, ret);
2762 if (check_reissue && req->flags & REQ_F_REISSUE) {
2763 req->flags &= ~REQ_F_REISSUE;
2764 if (!io_resubmit_prep(req)) {
2766 io_queue_async_work(req);
2770 req_set_fail_links(req);
2771 if (req->flags & REQ_F_BUFFER_SELECTED)
2772 cflags = io_put_rw_kbuf(req);
2773 __io_req_complete(req, issue_flags, ret, cflags);
2778 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2780 struct io_ring_ctx *ctx = req->ctx;
2781 size_t len = req->rw.len;
2782 struct io_mapped_ubuf *imu;
2783 u16 index, buf_index = req->buf_index;
2784 u64 buf_end, buf_addr = req->rw.addr;
2787 if (unlikely(buf_index >= ctx->nr_user_bufs))
2789 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2790 imu = &ctx->user_bufs[index];
2791 buf_addr = req->rw.addr;
2793 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2795 /* not inside the mapped region */
2796 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2800 * May not be a start of buffer, set size appropriately
2801 * and advance us to the beginning.
2803 offset = buf_addr - imu->ubuf;
2804 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2808 * Don't use iov_iter_advance() here, as it's really slow for
2809 * using the latter parts of a big fixed buffer - it iterates
2810 * over each segment manually. We can cheat a bit here, because
2813 * 1) it's a BVEC iter, we set it up
2814 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2815 * first and last bvec
2817 * So just find our index, and adjust the iterator afterwards.
2818 * If the offset is within the first bvec (or the whole first
2819 * bvec, just use iov_iter_advance(). This makes it easier
2820 * since we can just skip the first segment, which may not
2821 * be PAGE_SIZE aligned.
2823 const struct bio_vec *bvec = imu->bvec;
2825 if (offset <= bvec->bv_len) {
2826 iov_iter_advance(iter, offset);
2828 unsigned long seg_skip;
2830 /* skip first vec */
2831 offset -= bvec->bv_len;
2832 seg_skip = 1 + (offset >> PAGE_SHIFT);
2834 iter->bvec = bvec + seg_skip;
2835 iter->nr_segs -= seg_skip;
2836 iter->count -= bvec->bv_len + offset;
2837 iter->iov_offset = offset & ~PAGE_MASK;
2844 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2847 mutex_unlock(&ctx->uring_lock);
2850 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2853 * "Normal" inline submissions always hold the uring_lock, since we
2854 * grab it from the system call. Same is true for the SQPOLL offload.
2855 * The only exception is when we've detached the request and issue it
2856 * from an async worker thread, grab the lock for that case.
2859 mutex_lock(&ctx->uring_lock);
2862 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2863 int bgid, struct io_buffer *kbuf,
2866 struct io_buffer *head;
2868 if (req->flags & REQ_F_BUFFER_SELECTED)
2871 io_ring_submit_lock(req->ctx, needs_lock);
2873 lockdep_assert_held(&req->ctx->uring_lock);
2875 head = xa_load(&req->ctx->io_buffers, bgid);
2877 if (!list_empty(&head->list)) {
2878 kbuf = list_last_entry(&head->list, struct io_buffer,
2880 list_del(&kbuf->list);
2883 xa_erase(&req->ctx->io_buffers, bgid);
2885 if (*len > kbuf->len)
2888 kbuf = ERR_PTR(-ENOBUFS);
2891 io_ring_submit_unlock(req->ctx, needs_lock);
2896 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2899 struct io_buffer *kbuf;
2902 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2903 bgid = req->buf_index;
2904 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2907 req->rw.addr = (u64) (unsigned long) kbuf;
2908 req->flags |= REQ_F_BUFFER_SELECTED;
2909 return u64_to_user_ptr(kbuf->addr);
2912 #ifdef CONFIG_COMPAT
2913 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2916 struct compat_iovec __user *uiov;
2917 compat_ssize_t clen;
2921 uiov = u64_to_user_ptr(req->rw.addr);
2922 if (!access_ok(uiov, sizeof(*uiov)))
2924 if (__get_user(clen, &uiov->iov_len))
2930 buf = io_rw_buffer_select(req, &len, needs_lock);
2932 return PTR_ERR(buf);
2933 iov[0].iov_base = buf;
2934 iov[0].iov_len = (compat_size_t) len;
2939 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2942 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2946 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2949 len = iov[0].iov_len;
2952 buf = io_rw_buffer_select(req, &len, needs_lock);
2954 return PTR_ERR(buf);
2955 iov[0].iov_base = buf;
2956 iov[0].iov_len = len;
2960 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2963 if (req->flags & REQ_F_BUFFER_SELECTED) {
2964 struct io_buffer *kbuf;
2966 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2967 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2968 iov[0].iov_len = kbuf->len;
2971 if (req->rw.len != 1)
2974 #ifdef CONFIG_COMPAT
2975 if (req->ctx->compat)
2976 return io_compat_import(req, iov, needs_lock);
2979 return __io_iov_buffer_select(req, iov, needs_lock);
2982 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2983 struct iov_iter *iter, bool needs_lock)
2985 void __user *buf = u64_to_user_ptr(req->rw.addr);
2986 size_t sqe_len = req->rw.len;
2987 u8 opcode = req->opcode;
2990 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2992 return io_import_fixed(req, rw, iter);
2995 /* buffer index only valid with fixed read/write, or buffer select */
2996 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2999 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3000 if (req->flags & REQ_F_BUFFER_SELECT) {
3001 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3003 return PTR_ERR(buf);
3004 req->rw.len = sqe_len;
3007 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3012 if (req->flags & REQ_F_BUFFER_SELECT) {
3013 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3015 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3020 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3024 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3026 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3030 * For files that don't have ->read_iter() and ->write_iter(), handle them
3031 * by looping over ->read() or ->write() manually.
3033 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3035 struct kiocb *kiocb = &req->rw.kiocb;
3036 struct file *file = req->file;
3040 * Don't support polled IO through this interface, and we can't
3041 * support non-blocking either. For the latter, this just causes
3042 * the kiocb to be handled from an async context.
3044 if (kiocb->ki_flags & IOCB_HIPRI)
3046 if (kiocb->ki_flags & IOCB_NOWAIT)
3049 while (iov_iter_count(iter)) {
3053 if (!iov_iter_is_bvec(iter)) {
3054 iovec = iov_iter_iovec(iter);
3056 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3057 iovec.iov_len = req->rw.len;
3061 nr = file->f_op->read(file, iovec.iov_base,
3062 iovec.iov_len, io_kiocb_ppos(kiocb));
3064 nr = file->f_op->write(file, iovec.iov_base,
3065 iovec.iov_len, io_kiocb_ppos(kiocb));
3074 if (nr != iovec.iov_len)
3078 iov_iter_advance(iter, nr);
3084 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3085 const struct iovec *fast_iov, struct iov_iter *iter)
3087 struct io_async_rw *rw = req->async_data;
3089 memcpy(&rw->iter, iter, sizeof(*iter));
3090 rw->free_iovec = iovec;
3092 /* can only be fixed buffers, no need to do anything */
3093 if (iov_iter_is_bvec(iter))
3096 unsigned iov_off = 0;
3098 rw->iter.iov = rw->fast_iov;
3099 if (iter->iov != fast_iov) {
3100 iov_off = iter->iov - fast_iov;
3101 rw->iter.iov += iov_off;
3103 if (rw->fast_iov != fast_iov)
3104 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3105 sizeof(struct iovec) * iter->nr_segs);
3107 req->flags |= REQ_F_NEED_CLEANUP;
3111 static inline int io_alloc_async_data(struct io_kiocb *req)
3113 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3114 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3115 return req->async_data == NULL;
3118 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3119 const struct iovec *fast_iov,
3120 struct iov_iter *iter, bool force)
3122 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3124 if (!req->async_data) {
3125 if (io_alloc_async_data(req)) {
3130 io_req_map_rw(req, iovec, fast_iov, iter);
3135 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3137 struct io_async_rw *iorw = req->async_data;
3138 struct iovec *iov = iorw->fast_iov;
3141 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3142 if (unlikely(ret < 0))
3145 iorw->bytes_done = 0;
3146 iorw->free_iovec = iov;
3148 req->flags |= REQ_F_NEED_CLEANUP;
3152 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3154 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3156 return io_prep_rw(req, sqe);
3160 * This is our waitqueue callback handler, registered through lock_page_async()
3161 * when we initially tried to do the IO with the iocb armed our waitqueue.
3162 * This gets called when the page is unlocked, and we generally expect that to
3163 * happen when the page IO is completed and the page is now uptodate. This will
3164 * queue a task_work based retry of the operation, attempting to copy the data
3165 * again. If the latter fails because the page was NOT uptodate, then we will
3166 * do a thread based blocking retry of the operation. That's the unexpected
3169 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3170 int sync, void *arg)
3172 struct wait_page_queue *wpq;
3173 struct io_kiocb *req = wait->private;
3174 struct wait_page_key *key = arg;
3176 wpq = container_of(wait, struct wait_page_queue, wait);
3178 if (!wake_page_match(wpq, key))
3181 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3182 list_del_init(&wait->entry);
3184 /* submit ref gets dropped, acquire a new one */
3186 io_req_task_queue(req);
3191 * This controls whether a given IO request should be armed for async page
3192 * based retry. If we return false here, the request is handed to the async
3193 * worker threads for retry. If we're doing buffered reads on a regular file,
3194 * we prepare a private wait_page_queue entry and retry the operation. This
3195 * will either succeed because the page is now uptodate and unlocked, or it
3196 * will register a callback when the page is unlocked at IO completion. Through
3197 * that callback, io_uring uses task_work to setup a retry of the operation.
3198 * That retry will attempt the buffered read again. The retry will generally
3199 * succeed, or in rare cases where it fails, we then fall back to using the
3200 * async worker threads for a blocking retry.
3202 static bool io_rw_should_retry(struct io_kiocb *req)
3204 struct io_async_rw *rw = req->async_data;
3205 struct wait_page_queue *wait = &rw->wpq;
3206 struct kiocb *kiocb = &req->rw.kiocb;
3208 /* never retry for NOWAIT, we just complete with -EAGAIN */
3209 if (req->flags & REQ_F_NOWAIT)
3212 /* Only for buffered IO */
3213 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3217 * just use poll if we can, and don't attempt if the fs doesn't
3218 * support callback based unlocks
3220 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3223 wait->wait.func = io_async_buf_func;
3224 wait->wait.private = req;
3225 wait->wait.flags = 0;
3226 INIT_LIST_HEAD(&wait->wait.entry);
3227 kiocb->ki_flags |= IOCB_WAITQ;
3228 kiocb->ki_flags &= ~IOCB_NOWAIT;
3229 kiocb->ki_waitq = wait;
3233 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3235 if (req->file->f_op->read_iter)
3236 return call_read_iter(req->file, &req->rw.kiocb, iter);
3237 else if (req->file->f_op->read)
3238 return loop_rw_iter(READ, req, iter);
3243 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3245 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3246 struct kiocb *kiocb = &req->rw.kiocb;
3247 struct iov_iter __iter, *iter = &__iter;
3248 struct io_async_rw *rw = req->async_data;
3249 ssize_t io_size, ret, ret2;
3250 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3256 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3260 io_size = iov_iter_count(iter);
3261 req->result = io_size;
3263 /* Ensure we clear previously set non-block flag */
3264 if (!force_nonblock)
3265 kiocb->ki_flags &= ~IOCB_NOWAIT;
3267 kiocb->ki_flags |= IOCB_NOWAIT;
3269 /* If the file doesn't support async, just async punt */
3270 if (force_nonblock && !io_file_supports_async(req, READ)) {
3271 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3272 return ret ?: -EAGAIN;
3275 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3276 if (unlikely(ret)) {
3281 ret = io_iter_do_read(req, iter);
3283 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3284 req->flags &= ~REQ_F_REISSUE;
3285 /* IOPOLL retry should happen for io-wq threads */
3286 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3288 /* no retry on NONBLOCK nor RWF_NOWAIT */
3289 if (req->flags & REQ_F_NOWAIT)
3291 /* some cases will consume bytes even on error returns */
3292 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3294 } else if (ret == -EIOCBQUEUED) {
3296 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3297 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3298 /* read all, failed, already did sync or don't want to retry */
3302 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3307 rw = req->async_data;
3308 /* now use our persistent iterator, if we aren't already */
3313 rw->bytes_done += ret;
3314 /* if we can retry, do so with the callbacks armed */
3315 if (!io_rw_should_retry(req)) {
3316 kiocb->ki_flags &= ~IOCB_WAITQ;
3321 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3322 * we get -EIOCBQUEUED, then we'll get a notification when the
3323 * desired page gets unlocked. We can also get a partial read
3324 * here, and if we do, then just retry at the new offset.
3326 ret = io_iter_do_read(req, iter);
3327 if (ret == -EIOCBQUEUED)
3329 /* we got some bytes, but not all. retry. */
3330 kiocb->ki_flags &= ~IOCB_WAITQ;
3331 } while (ret > 0 && ret < io_size);
3333 kiocb_done(kiocb, ret, issue_flags);
3335 /* it's faster to check here then delegate to kfree */
3341 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3343 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3345 return io_prep_rw(req, sqe);
3348 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3350 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3351 struct kiocb *kiocb = &req->rw.kiocb;
3352 struct iov_iter __iter, *iter = &__iter;
3353 struct io_async_rw *rw = req->async_data;
3354 ssize_t ret, ret2, io_size;
3355 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3361 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3365 io_size = iov_iter_count(iter);
3366 req->result = io_size;
3368 /* Ensure we clear previously set non-block flag */
3369 if (!force_nonblock)
3370 kiocb->ki_flags &= ~IOCB_NOWAIT;
3372 kiocb->ki_flags |= IOCB_NOWAIT;
3374 /* If the file doesn't support async, just async punt */
3375 if (force_nonblock && !io_file_supports_async(req, WRITE))
3378 /* file path doesn't support NOWAIT for non-direct_IO */
3379 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3380 (req->flags & REQ_F_ISREG))
3383 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3388 * Open-code file_start_write here to grab freeze protection,
3389 * which will be released by another thread in
3390 * io_complete_rw(). Fool lockdep by telling it the lock got
3391 * released so that it doesn't complain about the held lock when
3392 * we return to userspace.
3394 if (req->flags & REQ_F_ISREG) {
3395 sb_start_write(file_inode(req->file)->i_sb);
3396 __sb_writers_release(file_inode(req->file)->i_sb,
3399 kiocb->ki_flags |= IOCB_WRITE;
3401 if (req->file->f_op->write_iter)
3402 ret2 = call_write_iter(req->file, kiocb, iter);
3403 else if (req->file->f_op->write)
3404 ret2 = loop_rw_iter(WRITE, req, iter);
3408 if (req->flags & REQ_F_REISSUE) {
3409 req->flags &= ~REQ_F_REISSUE;
3414 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3415 * retry them without IOCB_NOWAIT.
3417 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3419 /* no retry on NONBLOCK nor RWF_NOWAIT */
3420 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3422 if (!force_nonblock || ret2 != -EAGAIN) {
3423 /* IOPOLL retry should happen for io-wq threads */
3424 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3427 kiocb_done(kiocb, ret2, issue_flags);
3430 /* some cases will consume bytes even on error returns */
3431 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3432 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3433 return ret ?: -EAGAIN;
3436 /* it's reportedly faster than delegating the null check to kfree() */
3442 static int io_renameat_prep(struct io_kiocb *req,
3443 const struct io_uring_sqe *sqe)
3445 struct io_rename *ren = &req->rename;
3446 const char __user *oldf, *newf;
3448 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3451 ren->old_dfd = READ_ONCE(sqe->fd);
3452 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3453 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3454 ren->new_dfd = READ_ONCE(sqe->len);
3455 ren->flags = READ_ONCE(sqe->rename_flags);
3457 ren->oldpath = getname(oldf);
3458 if (IS_ERR(ren->oldpath))
3459 return PTR_ERR(ren->oldpath);
3461 ren->newpath = getname(newf);
3462 if (IS_ERR(ren->newpath)) {
3463 putname(ren->oldpath);
3464 return PTR_ERR(ren->newpath);
3467 req->flags |= REQ_F_NEED_CLEANUP;
3471 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3473 struct io_rename *ren = &req->rename;
3476 if (issue_flags & IO_URING_F_NONBLOCK)
3479 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3480 ren->newpath, ren->flags);
3482 req->flags &= ~REQ_F_NEED_CLEANUP;
3484 req_set_fail_links(req);
3485 io_req_complete(req, ret);
3489 static int io_unlinkat_prep(struct io_kiocb *req,
3490 const struct io_uring_sqe *sqe)
3492 struct io_unlink *un = &req->unlink;
3493 const char __user *fname;
3495 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3498 un->dfd = READ_ONCE(sqe->fd);
3500 un->flags = READ_ONCE(sqe->unlink_flags);
3501 if (un->flags & ~AT_REMOVEDIR)
3504 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3505 un->filename = getname(fname);
3506 if (IS_ERR(un->filename))
3507 return PTR_ERR(un->filename);
3509 req->flags |= REQ_F_NEED_CLEANUP;
3513 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3515 struct io_unlink *un = &req->unlink;
3518 if (issue_flags & IO_URING_F_NONBLOCK)
3521 if (un->flags & AT_REMOVEDIR)
3522 ret = do_rmdir(un->dfd, un->filename);
3524 ret = do_unlinkat(un->dfd, un->filename);
3526 req->flags &= ~REQ_F_NEED_CLEANUP;
3528 req_set_fail_links(req);
3529 io_req_complete(req, ret);
3533 static int io_shutdown_prep(struct io_kiocb *req,
3534 const struct io_uring_sqe *sqe)
3536 #if defined(CONFIG_NET)
3537 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3539 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3543 req->shutdown.how = READ_ONCE(sqe->len);
3550 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3552 #if defined(CONFIG_NET)
3553 struct socket *sock;
3556 if (issue_flags & IO_URING_F_NONBLOCK)
3559 sock = sock_from_file(req->file);
3560 if (unlikely(!sock))
3563 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3565 req_set_fail_links(req);
3566 io_req_complete(req, ret);
3573 static int __io_splice_prep(struct io_kiocb *req,
3574 const struct io_uring_sqe *sqe)
3576 struct io_splice* sp = &req->splice;
3577 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3579 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3583 sp->len = READ_ONCE(sqe->len);
3584 sp->flags = READ_ONCE(sqe->splice_flags);
3586 if (unlikely(sp->flags & ~valid_flags))
3589 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3590 (sp->flags & SPLICE_F_FD_IN_FIXED));
3593 req->flags |= REQ_F_NEED_CLEANUP;
3597 static int io_tee_prep(struct io_kiocb *req,
3598 const struct io_uring_sqe *sqe)
3600 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3602 return __io_splice_prep(req, sqe);
3605 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3607 struct io_splice *sp = &req->splice;
3608 struct file *in = sp->file_in;
3609 struct file *out = sp->file_out;
3610 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3613 if (issue_flags & IO_URING_F_NONBLOCK)
3616 ret = do_tee(in, out, sp->len, flags);
3618 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3620 req->flags &= ~REQ_F_NEED_CLEANUP;
3623 req_set_fail_links(req);
3624 io_req_complete(req, ret);
3628 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3630 struct io_splice* sp = &req->splice;
3632 sp->off_in = READ_ONCE(sqe->splice_off_in);
3633 sp->off_out = READ_ONCE(sqe->off);
3634 return __io_splice_prep(req, sqe);
3637 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3639 struct io_splice *sp = &req->splice;
3640 struct file *in = sp->file_in;
3641 struct file *out = sp->file_out;
3642 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3643 loff_t *poff_in, *poff_out;
3646 if (issue_flags & IO_URING_F_NONBLOCK)
3649 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3650 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3653 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3655 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3657 req->flags &= ~REQ_F_NEED_CLEANUP;
3660 req_set_fail_links(req);
3661 io_req_complete(req, ret);
3666 * IORING_OP_NOP just posts a completion event, nothing else.
3668 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3670 struct io_ring_ctx *ctx = req->ctx;
3672 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3675 __io_req_complete(req, issue_flags, 0, 0);
3679 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3681 struct io_ring_ctx *ctx = req->ctx;
3686 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3688 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3691 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3692 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3695 req->sync.off = READ_ONCE(sqe->off);
3696 req->sync.len = READ_ONCE(sqe->len);
3700 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3702 loff_t end = req->sync.off + req->sync.len;
3705 /* fsync always requires a blocking context */
3706 if (issue_flags & IO_URING_F_NONBLOCK)
3709 ret = vfs_fsync_range(req->file, req->sync.off,
3710 end > 0 ? end : LLONG_MAX,
3711 req->sync.flags & IORING_FSYNC_DATASYNC);
3713 req_set_fail_links(req);
3714 io_req_complete(req, ret);
3718 static int io_fallocate_prep(struct io_kiocb *req,
3719 const struct io_uring_sqe *sqe)
3721 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3723 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3726 req->sync.off = READ_ONCE(sqe->off);
3727 req->sync.len = READ_ONCE(sqe->addr);
3728 req->sync.mode = READ_ONCE(sqe->len);
3732 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3736 /* fallocate always requiring blocking context */
3737 if (issue_flags & IO_URING_F_NONBLOCK)
3739 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3742 req_set_fail_links(req);
3743 io_req_complete(req, ret);
3747 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3749 const char __user *fname;
3752 if (unlikely(sqe->ioprio || sqe->buf_index))
3754 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3757 /* open.how should be already initialised */
3758 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3759 req->open.how.flags |= O_LARGEFILE;
3761 req->open.dfd = READ_ONCE(sqe->fd);
3762 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3763 req->open.filename = getname(fname);
3764 if (IS_ERR(req->open.filename)) {
3765 ret = PTR_ERR(req->open.filename);
3766 req->open.filename = NULL;
3769 req->open.nofile = rlimit(RLIMIT_NOFILE);
3770 req->flags |= REQ_F_NEED_CLEANUP;
3774 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3778 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3780 mode = READ_ONCE(sqe->len);
3781 flags = READ_ONCE(sqe->open_flags);
3782 req->open.how = build_open_how(flags, mode);
3783 return __io_openat_prep(req, sqe);
3786 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3788 struct open_how __user *how;
3792 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3794 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3795 len = READ_ONCE(sqe->len);
3796 if (len < OPEN_HOW_SIZE_VER0)
3799 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3804 return __io_openat_prep(req, sqe);
3807 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3809 struct open_flags op;
3812 bool resolve_nonblock;
3815 ret = build_open_flags(&req->open.how, &op);
3818 nonblock_set = op.open_flag & O_NONBLOCK;
3819 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3820 if (issue_flags & IO_URING_F_NONBLOCK) {
3822 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3823 * it'll always -EAGAIN
3825 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3827 op.lookup_flags |= LOOKUP_CACHED;
3828 op.open_flag |= O_NONBLOCK;
3831 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3835 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3836 /* only retry if RESOLVE_CACHED wasn't already set by application */
3837 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3838 file == ERR_PTR(-EAGAIN)) {
3840 * We could hang on to this 'fd', but seems like marginal
3841 * gain for something that is now known to be a slower path.
3842 * So just put it, and we'll get a new one when we retry.
3850 ret = PTR_ERR(file);
3852 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3853 file->f_flags &= ~O_NONBLOCK;
3854 fsnotify_open(file);
3855 fd_install(ret, file);
3858 putname(req->open.filename);
3859 req->flags &= ~REQ_F_NEED_CLEANUP;
3861 req_set_fail_links(req);
3862 io_req_complete(req, ret);
3866 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3868 return io_openat2(req, issue_flags);
3871 static int io_remove_buffers_prep(struct io_kiocb *req,
3872 const struct io_uring_sqe *sqe)
3874 struct io_provide_buf *p = &req->pbuf;
3877 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3880 tmp = READ_ONCE(sqe->fd);
3881 if (!tmp || tmp > USHRT_MAX)
3884 memset(p, 0, sizeof(*p));
3886 p->bgid = READ_ONCE(sqe->buf_group);
3890 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3891 int bgid, unsigned nbufs)
3895 /* shouldn't happen */
3899 /* the head kbuf is the list itself */
3900 while (!list_empty(&buf->list)) {
3901 struct io_buffer *nxt;
3903 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3904 list_del(&nxt->list);
3911 xa_erase(&ctx->io_buffers, bgid);
3916 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3918 struct io_provide_buf *p = &req->pbuf;
3919 struct io_ring_ctx *ctx = req->ctx;
3920 struct io_buffer *head;
3922 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3924 io_ring_submit_lock(ctx, !force_nonblock);
3926 lockdep_assert_held(&ctx->uring_lock);
3929 head = xa_load(&ctx->io_buffers, p->bgid);
3931 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3933 req_set_fail_links(req);
3935 /* complete before unlock, IOPOLL may need the lock */
3936 __io_req_complete(req, issue_flags, ret, 0);
3937 io_ring_submit_unlock(ctx, !force_nonblock);
3941 static int io_provide_buffers_prep(struct io_kiocb *req,
3942 const struct io_uring_sqe *sqe)
3945 struct io_provide_buf *p = &req->pbuf;
3948 if (sqe->ioprio || sqe->rw_flags)
3951 tmp = READ_ONCE(sqe->fd);
3952 if (!tmp || tmp > USHRT_MAX)
3955 p->addr = READ_ONCE(sqe->addr);
3956 p->len = READ_ONCE(sqe->len);
3958 size = (unsigned long)p->len * p->nbufs;
3959 if (!access_ok(u64_to_user_ptr(p->addr), size))
3962 p->bgid = READ_ONCE(sqe->buf_group);
3963 tmp = READ_ONCE(sqe->off);
3964 if (tmp > USHRT_MAX)
3970 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3972 struct io_buffer *buf;
3973 u64 addr = pbuf->addr;
3974 int i, bid = pbuf->bid;
3976 for (i = 0; i < pbuf->nbufs; i++) {
3977 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3982 buf->len = pbuf->len;
3987 INIT_LIST_HEAD(&buf->list);
3990 list_add_tail(&buf->list, &(*head)->list);
3994 return i ? i : -ENOMEM;
3997 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3999 struct io_provide_buf *p = &req->pbuf;
4000 struct io_ring_ctx *ctx = req->ctx;
4001 struct io_buffer *head, *list;
4003 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4005 io_ring_submit_lock(ctx, !force_nonblock);
4007 lockdep_assert_held(&ctx->uring_lock);
4009 list = head = xa_load(&ctx->io_buffers, p->bgid);
4011 ret = io_add_buffers(p, &head);
4012 if (ret >= 0 && !list) {
4013 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4015 __io_remove_buffers(ctx, head, p->bgid, -1U);
4018 req_set_fail_links(req);
4019 /* complete before unlock, IOPOLL may need the lock */
4020 __io_req_complete(req, issue_flags, ret, 0);
4021 io_ring_submit_unlock(ctx, !force_nonblock);
4025 static int io_epoll_ctl_prep(struct io_kiocb *req,
4026 const struct io_uring_sqe *sqe)
4028 #if defined(CONFIG_EPOLL)
4029 if (sqe->ioprio || sqe->buf_index)
4031 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4034 req->epoll.epfd = READ_ONCE(sqe->fd);
4035 req->epoll.op = READ_ONCE(sqe->len);
4036 req->epoll.fd = READ_ONCE(sqe->off);
4038 if (ep_op_has_event(req->epoll.op)) {
4039 struct epoll_event __user *ev;
4041 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4042 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4052 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4054 #if defined(CONFIG_EPOLL)
4055 struct io_epoll *ie = &req->epoll;
4057 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4059 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4060 if (force_nonblock && ret == -EAGAIN)
4064 req_set_fail_links(req);
4065 __io_req_complete(req, issue_flags, ret, 0);
4072 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4074 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4075 if (sqe->ioprio || sqe->buf_index || sqe->off)
4077 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4080 req->madvise.addr = READ_ONCE(sqe->addr);
4081 req->madvise.len = READ_ONCE(sqe->len);
4082 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4089 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4091 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4092 struct io_madvise *ma = &req->madvise;
4095 if (issue_flags & IO_URING_F_NONBLOCK)
4098 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4100 req_set_fail_links(req);
4101 io_req_complete(req, ret);
4108 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4110 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4112 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4115 req->fadvise.offset = READ_ONCE(sqe->off);
4116 req->fadvise.len = READ_ONCE(sqe->len);
4117 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4121 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4123 struct io_fadvise *fa = &req->fadvise;
4126 if (issue_flags & IO_URING_F_NONBLOCK) {
4127 switch (fa->advice) {
4128 case POSIX_FADV_NORMAL:
4129 case POSIX_FADV_RANDOM:
4130 case POSIX_FADV_SEQUENTIAL:
4137 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4139 req_set_fail_links(req);
4140 io_req_complete(req, ret);
4144 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4146 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4148 if (sqe->ioprio || sqe->buf_index)
4150 if (req->flags & REQ_F_FIXED_FILE)
4153 req->statx.dfd = READ_ONCE(sqe->fd);
4154 req->statx.mask = READ_ONCE(sqe->len);
4155 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4156 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4157 req->statx.flags = READ_ONCE(sqe->statx_flags);
4162 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4164 struct io_statx *ctx = &req->statx;
4167 if (issue_flags & IO_URING_F_NONBLOCK)
4170 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4174 req_set_fail_links(req);
4175 io_req_complete(req, ret);
4179 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4181 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4183 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4184 sqe->rw_flags || sqe->buf_index)
4186 if (req->flags & REQ_F_FIXED_FILE)
4189 req->close.fd = READ_ONCE(sqe->fd);
4193 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4195 struct files_struct *files = current->files;
4196 struct io_close *close = &req->close;
4197 struct fdtable *fdt;
4203 spin_lock(&files->file_lock);
4204 fdt = files_fdtable(files);
4205 if (close->fd >= fdt->max_fds) {
4206 spin_unlock(&files->file_lock);
4209 file = fdt->fd[close->fd];
4211 spin_unlock(&files->file_lock);
4215 if (file->f_op == &io_uring_fops) {
4216 spin_unlock(&files->file_lock);
4221 /* if the file has a flush method, be safe and punt to async */
4222 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4223 spin_unlock(&files->file_lock);
4227 ret = __close_fd_get_file(close->fd, &file);
4228 spin_unlock(&files->file_lock);
4235 /* No ->flush() or already async, safely close from here */
4236 ret = filp_close(file, current->files);
4239 req_set_fail_links(req);
4242 __io_req_complete(req, issue_flags, ret, 0);
4246 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4248 struct io_ring_ctx *ctx = req->ctx;
4250 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4252 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4255 req->sync.off = READ_ONCE(sqe->off);
4256 req->sync.len = READ_ONCE(sqe->len);
4257 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4261 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4265 /* sync_file_range always requires a blocking context */
4266 if (issue_flags & IO_URING_F_NONBLOCK)
4269 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4272 req_set_fail_links(req);
4273 io_req_complete(req, ret);
4277 #if defined(CONFIG_NET)
4278 static int io_setup_async_msg(struct io_kiocb *req,
4279 struct io_async_msghdr *kmsg)
4281 struct io_async_msghdr *async_msg = req->async_data;
4285 if (io_alloc_async_data(req)) {
4286 kfree(kmsg->free_iov);
4289 async_msg = req->async_data;
4290 req->flags |= REQ_F_NEED_CLEANUP;
4291 memcpy(async_msg, kmsg, sizeof(*kmsg));
4292 async_msg->msg.msg_name = &async_msg->addr;
4293 /* if were using fast_iov, set it to the new one */
4294 if (!async_msg->free_iov)
4295 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4300 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4301 struct io_async_msghdr *iomsg)
4303 iomsg->msg.msg_name = &iomsg->addr;
4304 iomsg->free_iov = iomsg->fast_iov;
4305 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4306 req->sr_msg.msg_flags, &iomsg->free_iov);
4309 static int io_sendmsg_prep_async(struct io_kiocb *req)
4313 ret = io_sendmsg_copy_hdr(req, req->async_data);
4315 req->flags |= REQ_F_NEED_CLEANUP;
4319 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4321 struct io_sr_msg *sr = &req->sr_msg;
4323 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4326 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4327 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4328 sr->len = READ_ONCE(sqe->len);
4330 #ifdef CONFIG_COMPAT
4331 if (req->ctx->compat)
4332 sr->msg_flags |= MSG_CMSG_COMPAT;
4337 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4339 struct io_async_msghdr iomsg, *kmsg;
4340 struct socket *sock;
4345 sock = sock_from_file(req->file);
4346 if (unlikely(!sock))
4349 kmsg = req->async_data;
4351 ret = io_sendmsg_copy_hdr(req, &iomsg);
4357 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4358 if (flags & MSG_DONTWAIT)
4359 req->flags |= REQ_F_NOWAIT;
4360 else if (issue_flags & IO_URING_F_NONBLOCK)
4361 flags |= MSG_DONTWAIT;
4363 if (flags & MSG_WAITALL)
4364 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4366 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4367 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4368 return io_setup_async_msg(req, kmsg);
4369 if (ret == -ERESTARTSYS)
4372 /* fast path, check for non-NULL to avoid function call */
4374 kfree(kmsg->free_iov);
4375 req->flags &= ~REQ_F_NEED_CLEANUP;
4377 req_set_fail_links(req);
4378 __io_req_complete(req, issue_flags, ret, 0);
4382 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4384 struct io_sr_msg *sr = &req->sr_msg;
4387 struct socket *sock;
4392 sock = sock_from_file(req->file);
4393 if (unlikely(!sock))
4396 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4400 msg.msg_name = NULL;
4401 msg.msg_control = NULL;
4402 msg.msg_controllen = 0;
4403 msg.msg_namelen = 0;
4405 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4406 if (flags & MSG_DONTWAIT)
4407 req->flags |= REQ_F_NOWAIT;
4408 else if (issue_flags & IO_URING_F_NONBLOCK)
4409 flags |= MSG_DONTWAIT;
4411 if (flags & MSG_WAITALL)
4412 min_ret = iov_iter_count(&msg.msg_iter);
4414 msg.msg_flags = flags;
4415 ret = sock_sendmsg(sock, &msg);
4416 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4418 if (ret == -ERESTARTSYS)
4422 req_set_fail_links(req);
4423 __io_req_complete(req, issue_flags, ret, 0);
4427 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4428 struct io_async_msghdr *iomsg)
4430 struct io_sr_msg *sr = &req->sr_msg;
4431 struct iovec __user *uiov;
4435 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4436 &iomsg->uaddr, &uiov, &iov_len);
4440 if (req->flags & REQ_F_BUFFER_SELECT) {
4443 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4445 sr->len = iomsg->fast_iov[0].iov_len;
4446 iomsg->free_iov = NULL;
4448 iomsg->free_iov = iomsg->fast_iov;
4449 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4450 &iomsg->free_iov, &iomsg->msg.msg_iter,
4459 #ifdef CONFIG_COMPAT
4460 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4461 struct io_async_msghdr *iomsg)
4463 struct compat_msghdr __user *msg_compat;
4464 struct io_sr_msg *sr = &req->sr_msg;
4465 struct compat_iovec __user *uiov;
4470 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4471 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4476 uiov = compat_ptr(ptr);
4477 if (req->flags & REQ_F_BUFFER_SELECT) {
4478 compat_ssize_t clen;
4482 if (!access_ok(uiov, sizeof(*uiov)))
4484 if (__get_user(clen, &uiov->iov_len))
4489 iomsg->free_iov = NULL;
4491 iomsg->free_iov = iomsg->fast_iov;
4492 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4493 UIO_FASTIOV, &iomsg->free_iov,
4494 &iomsg->msg.msg_iter, true);
4503 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4504 struct io_async_msghdr *iomsg)
4506 iomsg->msg.msg_name = &iomsg->addr;
4508 #ifdef CONFIG_COMPAT
4509 if (req->ctx->compat)
4510 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4513 return __io_recvmsg_copy_hdr(req, iomsg);
4516 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4519 struct io_sr_msg *sr = &req->sr_msg;
4520 struct io_buffer *kbuf;
4522 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4527 req->flags |= REQ_F_BUFFER_SELECTED;
4531 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4533 return io_put_kbuf(req, req->sr_msg.kbuf);
4536 static int io_recvmsg_prep_async(struct io_kiocb *req)
4540 ret = io_recvmsg_copy_hdr(req, req->async_data);
4542 req->flags |= REQ_F_NEED_CLEANUP;
4546 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4548 struct io_sr_msg *sr = &req->sr_msg;
4550 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4553 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4554 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4555 sr->len = READ_ONCE(sqe->len);
4556 sr->bgid = READ_ONCE(sqe->buf_group);
4558 #ifdef CONFIG_COMPAT
4559 if (req->ctx->compat)
4560 sr->msg_flags |= MSG_CMSG_COMPAT;
4565 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4567 struct io_async_msghdr iomsg, *kmsg;
4568 struct socket *sock;
4569 struct io_buffer *kbuf;
4572 int ret, cflags = 0;
4573 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4575 sock = sock_from_file(req->file);
4576 if (unlikely(!sock))
4579 kmsg = req->async_data;
4581 ret = io_recvmsg_copy_hdr(req, &iomsg);
4587 if (req->flags & REQ_F_BUFFER_SELECT) {
4588 kbuf = io_recv_buffer_select(req, !force_nonblock);
4590 return PTR_ERR(kbuf);
4591 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4592 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4593 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4594 1, req->sr_msg.len);
4597 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4598 if (flags & MSG_DONTWAIT)
4599 req->flags |= REQ_F_NOWAIT;
4600 else if (force_nonblock)
4601 flags |= MSG_DONTWAIT;
4603 if (flags & MSG_WAITALL)
4604 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4606 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4607 kmsg->uaddr, flags);
4608 if (force_nonblock && ret == -EAGAIN)
4609 return io_setup_async_msg(req, kmsg);
4610 if (ret == -ERESTARTSYS)
4613 if (req->flags & REQ_F_BUFFER_SELECTED)
4614 cflags = io_put_recv_kbuf(req);
4615 /* fast path, check for non-NULL to avoid function call */
4617 kfree(kmsg->free_iov);
4618 req->flags &= ~REQ_F_NEED_CLEANUP;
4619 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4620 req_set_fail_links(req);
4621 __io_req_complete(req, issue_flags, ret, cflags);
4625 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4627 struct io_buffer *kbuf;
4628 struct io_sr_msg *sr = &req->sr_msg;
4630 void __user *buf = sr->buf;
4631 struct socket *sock;
4635 int ret, cflags = 0;
4636 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4638 sock = sock_from_file(req->file);
4639 if (unlikely(!sock))
4642 if (req->flags & REQ_F_BUFFER_SELECT) {
4643 kbuf = io_recv_buffer_select(req, !force_nonblock);
4645 return PTR_ERR(kbuf);
4646 buf = u64_to_user_ptr(kbuf->addr);
4649 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4653 msg.msg_name = NULL;
4654 msg.msg_control = NULL;
4655 msg.msg_controllen = 0;
4656 msg.msg_namelen = 0;
4657 msg.msg_iocb = NULL;
4660 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4661 if (flags & MSG_DONTWAIT)
4662 req->flags |= REQ_F_NOWAIT;
4663 else if (force_nonblock)
4664 flags |= MSG_DONTWAIT;
4666 if (flags & MSG_WAITALL)
4667 min_ret = iov_iter_count(&msg.msg_iter);
4669 ret = sock_recvmsg(sock, &msg, flags);
4670 if (force_nonblock && ret == -EAGAIN)
4672 if (ret == -ERESTARTSYS)
4675 if (req->flags & REQ_F_BUFFER_SELECTED)
4676 cflags = io_put_recv_kbuf(req);
4677 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4678 req_set_fail_links(req);
4679 __io_req_complete(req, issue_flags, ret, cflags);
4683 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4685 struct io_accept *accept = &req->accept;
4687 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4689 if (sqe->ioprio || sqe->len || sqe->buf_index)
4692 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4693 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4694 accept->flags = READ_ONCE(sqe->accept_flags);
4695 accept->nofile = rlimit(RLIMIT_NOFILE);
4699 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4701 struct io_accept *accept = &req->accept;
4702 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4703 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4706 if (req->file->f_flags & O_NONBLOCK)
4707 req->flags |= REQ_F_NOWAIT;
4709 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4710 accept->addr_len, accept->flags,
4712 if (ret == -EAGAIN && force_nonblock)
4715 if (ret == -ERESTARTSYS)
4717 req_set_fail_links(req);
4719 __io_req_complete(req, issue_flags, ret, 0);
4723 static int io_connect_prep_async(struct io_kiocb *req)
4725 struct io_async_connect *io = req->async_data;
4726 struct io_connect *conn = &req->connect;
4728 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4731 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4733 struct io_connect *conn = &req->connect;
4735 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4737 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4740 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4741 conn->addr_len = READ_ONCE(sqe->addr2);
4745 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4747 struct io_async_connect __io, *io;
4748 unsigned file_flags;
4750 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4752 if (req->async_data) {
4753 io = req->async_data;
4755 ret = move_addr_to_kernel(req->connect.addr,
4756 req->connect.addr_len,
4763 file_flags = force_nonblock ? O_NONBLOCK : 0;
4765 ret = __sys_connect_file(req->file, &io->address,
4766 req->connect.addr_len, file_flags);
4767 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4768 if (req->async_data)
4770 if (io_alloc_async_data(req)) {
4774 memcpy(req->async_data, &__io, sizeof(__io));
4777 if (ret == -ERESTARTSYS)
4781 req_set_fail_links(req);
4782 __io_req_complete(req, issue_flags, ret, 0);
4785 #else /* !CONFIG_NET */
4786 #define IO_NETOP_FN(op) \
4787 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4789 return -EOPNOTSUPP; \
4792 #define IO_NETOP_PREP(op) \
4794 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4796 return -EOPNOTSUPP; \
4799 #define IO_NETOP_PREP_ASYNC(op) \
4801 static int io_##op##_prep_async(struct io_kiocb *req) \
4803 return -EOPNOTSUPP; \
4806 IO_NETOP_PREP_ASYNC(sendmsg);
4807 IO_NETOP_PREP_ASYNC(recvmsg);
4808 IO_NETOP_PREP_ASYNC(connect);
4809 IO_NETOP_PREP(accept);
4812 #endif /* CONFIG_NET */
4814 struct io_poll_table {
4815 struct poll_table_struct pt;
4816 struct io_kiocb *req;
4820 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4821 __poll_t mask, task_work_func_t func)
4825 /* for instances that support it check for an event match first: */
4826 if (mask && !(mask & poll->events))
4829 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4831 list_del_init(&poll->wait.entry);
4834 req->task_work.func = func;
4837 * If this fails, then the task is exiting. When a task exits, the
4838 * work gets canceled, so just cancel this request as well instead
4839 * of executing it. We can't safely execute it anyway, as we may not
4840 * have the needed state needed for it anyway.
4842 ret = io_req_task_work_add(req);
4843 if (unlikely(ret)) {
4844 WRITE_ONCE(poll->canceled, true);
4845 io_req_task_work_add_fallback(req, func);
4850 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4851 __acquires(&req->ctx->completion_lock)
4853 struct io_ring_ctx *ctx = req->ctx;
4855 if (!req->result && !READ_ONCE(poll->canceled)) {
4856 struct poll_table_struct pt = { ._key = poll->events };
4858 req->result = vfs_poll(req->file, &pt) & poll->events;
4861 spin_lock_irq(&ctx->completion_lock);
4862 if (!req->result && !READ_ONCE(poll->canceled)) {
4863 add_wait_queue(poll->head, &poll->wait);
4870 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4872 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4873 if (req->opcode == IORING_OP_POLL_ADD)
4874 return req->async_data;
4875 return req->apoll->double_poll;
4878 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4880 if (req->opcode == IORING_OP_POLL_ADD)
4882 return &req->apoll->poll;
4885 static void io_poll_remove_double(struct io_kiocb *req)
4886 __must_hold(&req->ctx->completion_lock)
4888 struct io_poll_iocb *poll = io_poll_get_double(req);
4890 lockdep_assert_held(&req->ctx->completion_lock);
4892 if (poll && poll->head) {
4893 struct wait_queue_head *head = poll->head;
4895 spin_lock(&head->lock);
4896 list_del_init(&poll->wait.entry);
4897 if (poll->wait.private)
4900 spin_unlock(&head->lock);
4904 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4905 __must_hold(&req->ctx->completion_lock)
4907 struct io_ring_ctx *ctx = req->ctx;
4908 unsigned flags = IORING_CQE_F_MORE;
4910 if (!error && req->poll.canceled) {
4912 req->poll.events |= EPOLLONESHOT;
4915 error = mangle_poll(mask);
4916 if (req->poll.events & EPOLLONESHOT)
4918 if (!__io_cqring_fill_event(req, error, flags)) {
4919 io_poll_remove_waitqs(req);
4920 req->poll.done = true;
4923 io_commit_cqring(ctx);
4924 return !(flags & IORING_CQE_F_MORE);
4927 static void io_poll_task_func(struct callback_head *cb)
4929 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4930 struct io_ring_ctx *ctx = req->ctx;
4931 struct io_kiocb *nxt;
4933 if (io_poll_rewait(req, &req->poll)) {
4934 spin_unlock_irq(&ctx->completion_lock);
4938 post_ev = done = io_poll_complete(req, req->result, 0);
4940 hash_del(&req->hash_node);
4941 } else if (!(req->poll.events & EPOLLONESHOT)) {
4944 add_wait_queue(req->poll.head, &req->poll.wait);
4946 spin_unlock_irq(&ctx->completion_lock);
4949 io_cqring_ev_posted(ctx);
4951 nxt = io_put_req_find_next(req);
4953 __io_req_task_submit(nxt);
4958 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4959 int sync, void *key)
4961 struct io_kiocb *req = wait->private;
4962 struct io_poll_iocb *poll = io_poll_get_single(req);
4963 __poll_t mask = key_to_poll(key);
4965 /* for instances that support it check for an event match first: */
4966 if (mask && !(mask & poll->events))
4968 if (!(poll->events & EPOLLONESHOT))
4969 return poll->wait.func(&poll->wait, mode, sync, key);
4971 list_del_init(&wait->entry);
4973 if (poll && poll->head) {
4976 spin_lock(&poll->head->lock);
4977 done = list_empty(&poll->wait.entry);
4979 list_del_init(&poll->wait.entry);
4980 /* make sure double remove sees this as being gone */
4981 wait->private = NULL;
4982 spin_unlock(&poll->head->lock);
4984 /* use wait func handler, so it matches the rq type */
4985 poll->wait.func(&poll->wait, mode, sync, key);
4992 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4993 wait_queue_func_t wake_func)
4997 poll->canceled = false;
4998 poll->update_events = poll->update_user_data = false;
4999 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5000 /* mask in events that we always want/need */
5001 poll->events = events | IO_POLL_UNMASK;
5002 INIT_LIST_HEAD(&poll->wait.entry);
5003 init_waitqueue_func_entry(&poll->wait, wake_func);
5006 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5007 struct wait_queue_head *head,
5008 struct io_poll_iocb **poll_ptr)
5010 struct io_kiocb *req = pt->req;
5013 * If poll->head is already set, it's because the file being polled
5014 * uses multiple waitqueues for poll handling (eg one for read, one
5015 * for write). Setup a separate io_poll_iocb if this happens.
5017 if (unlikely(poll->head)) {
5018 struct io_poll_iocb *poll_one = poll;
5020 /* already have a 2nd entry, fail a third attempt */
5022 pt->error = -EINVAL;
5025 /* double add on the same waitqueue head, ignore */
5026 if (poll->head == head)
5028 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5030 pt->error = -ENOMEM;
5033 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5035 poll->wait.private = req;
5042 if (poll->events & EPOLLEXCLUSIVE)
5043 add_wait_queue_exclusive(head, &poll->wait);
5045 add_wait_queue(head, &poll->wait);
5048 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5049 struct poll_table_struct *p)
5051 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5052 struct async_poll *apoll = pt->req->apoll;
5054 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5057 static void io_async_task_func(struct callback_head *cb)
5059 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5060 struct async_poll *apoll = req->apoll;
5061 struct io_ring_ctx *ctx = req->ctx;
5063 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5065 if (io_poll_rewait(req, &apoll->poll)) {
5066 spin_unlock_irq(&ctx->completion_lock);
5070 /* If req is still hashed, it cannot have been canceled. Don't check. */
5071 if (hash_hashed(&req->hash_node))
5072 hash_del(&req->hash_node);
5074 io_poll_remove_double(req);
5075 spin_unlock_irq(&ctx->completion_lock);
5077 if (!READ_ONCE(apoll->poll.canceled))
5078 __io_req_task_submit(req);
5080 io_req_complete_failed(req, -ECANCELED);
5082 kfree(apoll->double_poll);
5086 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5089 struct io_kiocb *req = wait->private;
5090 struct io_poll_iocb *poll = &req->apoll->poll;
5092 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5095 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5098 static void io_poll_req_insert(struct io_kiocb *req)
5100 struct io_ring_ctx *ctx = req->ctx;
5101 struct hlist_head *list;
5103 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5104 hlist_add_head(&req->hash_node, list);
5107 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5108 struct io_poll_iocb *poll,
5109 struct io_poll_table *ipt, __poll_t mask,
5110 wait_queue_func_t wake_func)
5111 __acquires(&ctx->completion_lock)
5113 struct io_ring_ctx *ctx = req->ctx;
5114 bool cancel = false;
5116 INIT_HLIST_NODE(&req->hash_node);
5117 io_init_poll_iocb(poll, mask, wake_func);
5118 poll->file = req->file;
5119 poll->wait.private = req;
5121 ipt->pt._key = mask;
5123 ipt->error = -EINVAL;
5125 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5127 spin_lock_irq(&ctx->completion_lock);
5128 if (likely(poll->head)) {
5129 spin_lock(&poll->head->lock);
5130 if (unlikely(list_empty(&poll->wait.entry))) {
5136 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5137 list_del_init(&poll->wait.entry);
5139 WRITE_ONCE(poll->canceled, true);
5140 else if (!poll->done) /* actually waiting for an event */
5141 io_poll_req_insert(req);
5142 spin_unlock(&poll->head->lock);
5148 static bool io_arm_poll_handler(struct io_kiocb *req)
5150 const struct io_op_def *def = &io_op_defs[req->opcode];
5151 struct io_ring_ctx *ctx = req->ctx;
5152 struct async_poll *apoll;
5153 struct io_poll_table ipt;
5157 if (!req->file || !file_can_poll(req->file))
5159 if (req->flags & REQ_F_POLLED)
5163 else if (def->pollout)
5167 /* if we can't nonblock try, then no point in arming a poll handler */
5168 if (!io_file_supports_async(req, rw))
5171 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5172 if (unlikely(!apoll))
5174 apoll->double_poll = NULL;
5176 req->flags |= REQ_F_POLLED;
5179 mask = EPOLLONESHOT;
5181 mask |= POLLIN | POLLRDNORM;
5183 mask |= POLLOUT | POLLWRNORM;
5185 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5186 if ((req->opcode == IORING_OP_RECVMSG) &&
5187 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5190 mask |= POLLERR | POLLPRI;
5192 ipt.pt._qproc = io_async_queue_proc;
5194 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5196 if (ret || ipt.error) {
5197 io_poll_remove_double(req);
5198 spin_unlock_irq(&ctx->completion_lock);
5199 kfree(apoll->double_poll);
5203 spin_unlock_irq(&ctx->completion_lock);
5204 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5205 apoll->poll.events);
5209 static bool __io_poll_remove_one(struct io_kiocb *req,
5210 struct io_poll_iocb *poll, bool do_cancel)
5211 __must_hold(&req->ctx->completion_lock)
5213 bool do_complete = false;
5217 spin_lock(&poll->head->lock);
5219 WRITE_ONCE(poll->canceled, true);
5220 if (!list_empty(&poll->wait.entry)) {
5221 list_del_init(&poll->wait.entry);
5224 spin_unlock(&poll->head->lock);
5225 hash_del(&req->hash_node);
5229 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5230 __must_hold(&req->ctx->completion_lock)
5234 io_poll_remove_double(req);
5236 if (req->opcode == IORING_OP_POLL_ADD) {
5237 do_complete = __io_poll_remove_one(req, &req->poll, true);
5239 struct async_poll *apoll = req->apoll;
5241 /* non-poll requests have submit ref still */
5242 do_complete = __io_poll_remove_one(req, &apoll->poll, true);
5245 kfree(apoll->double_poll);
5253 static bool io_poll_remove_one(struct io_kiocb *req)
5254 __must_hold(&req->ctx->completion_lock)
5258 do_complete = io_poll_remove_waitqs(req);
5260 io_cqring_fill_event(req, -ECANCELED);
5261 io_commit_cqring(req->ctx);
5262 req_set_fail_links(req);
5263 io_put_req_deferred(req, 1);
5270 * Returns true if we found and killed one or more poll requests
5272 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5273 struct files_struct *files)
5275 struct hlist_node *tmp;
5276 struct io_kiocb *req;
5279 spin_lock_irq(&ctx->completion_lock);
5280 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5281 struct hlist_head *list;
5283 list = &ctx->cancel_hash[i];
5284 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5285 if (io_match_task(req, tsk, files))
5286 posted += io_poll_remove_one(req);
5289 spin_unlock_irq(&ctx->completion_lock);
5292 io_cqring_ev_posted(ctx);
5297 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr)
5298 __must_hold(&ctx->completion_lock)
5300 struct hlist_head *list;
5301 struct io_kiocb *req;
5303 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5304 hlist_for_each_entry(req, list, hash_node) {
5305 if (sqe_addr != req->user_data)
5313 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5314 __must_hold(&ctx->completion_lock)
5316 struct io_kiocb *req;
5318 req = io_poll_find(ctx, sqe_addr);
5321 if (io_poll_remove_one(req))
5327 static int io_poll_remove_prep(struct io_kiocb *req,
5328 const struct io_uring_sqe *sqe)
5330 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5332 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5336 req->poll_remove.addr = READ_ONCE(sqe->addr);
5341 * Find a running poll command that matches one specified in sqe->addr,
5342 * and remove it if found.
5344 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5346 struct io_ring_ctx *ctx = req->ctx;
5349 spin_lock_irq(&ctx->completion_lock);
5350 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5351 spin_unlock_irq(&ctx->completion_lock);
5354 req_set_fail_links(req);
5355 io_req_complete(req, ret);
5359 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5362 struct io_kiocb *req = wait->private;
5363 struct io_poll_iocb *poll = &req->poll;
5365 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5368 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5369 struct poll_table_struct *p)
5371 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5373 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5376 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5378 struct io_poll_iocb *poll = &req->poll;
5381 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5383 if (sqe->ioprio || sqe->buf_index)
5385 flags = READ_ONCE(sqe->len);
5386 if (flags & ~(IORING_POLL_ADD_MULTI | IORING_POLL_UPDATE_EVENTS |
5387 IORING_POLL_UPDATE_USER_DATA))
5389 events = READ_ONCE(sqe->poll32_events);
5391 events = swahw32(events);
5393 if (!(flags & IORING_POLL_ADD_MULTI))
5394 events |= EPOLLONESHOT;
5395 poll->update_events = poll->update_user_data = false;
5396 if (flags & IORING_POLL_UPDATE_EVENTS) {
5397 poll->update_events = true;
5398 poll->old_user_data = READ_ONCE(sqe->addr);
5400 if (flags & IORING_POLL_UPDATE_USER_DATA) {
5401 poll->update_user_data = true;
5402 poll->new_user_data = READ_ONCE(sqe->off);
5404 if (!(poll->update_events || poll->update_user_data) &&
5405 (sqe->off || sqe->addr))
5407 poll->events = demangle_poll(events) |
5408 (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5412 static int __io_poll_add(struct io_kiocb *req)
5414 struct io_poll_iocb *poll = &req->poll;
5415 struct io_ring_ctx *ctx = req->ctx;
5416 struct io_poll_table ipt;
5419 ipt.pt._qproc = io_poll_queue_proc;
5421 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5424 if (mask) { /* no async, we'd stolen it */
5426 io_poll_complete(req, mask, 0);
5428 spin_unlock_irq(&ctx->completion_lock);
5431 io_cqring_ev_posted(ctx);
5432 if (poll->events & EPOLLONESHOT)
5438 static int io_poll_update(struct io_kiocb *req)
5440 struct io_ring_ctx *ctx = req->ctx;
5441 struct io_kiocb *preq;
5444 spin_lock_irq(&ctx->completion_lock);
5445 preq = io_poll_find(ctx, req->poll.old_user_data);
5449 } else if (preq->opcode != IORING_OP_POLL_ADD) {
5450 /* don't allow internal poll updates */
5454 if (!__io_poll_remove_one(preq, &preq->poll, false)) {
5455 if (preq->poll.events & EPOLLONESHOT) {
5460 /* we now have a detached poll request. reissue. */
5463 spin_unlock_irq(&ctx->completion_lock);
5465 req_set_fail_links(req);
5466 io_req_complete(req, ret);
5469 /* only mask one event flags, keep behavior flags */
5470 if (req->poll.update_events) {
5471 preq->poll.events &= ~0xffff;
5472 preq->poll.events |= req->poll.events & 0xffff;
5473 preq->poll.events |= IO_POLL_UNMASK;
5475 if (req->poll.update_user_data)
5476 preq->user_data = req->poll.new_user_data;
5478 /* complete update request, we're done with it */
5479 io_req_complete(req, ret);
5481 ret = __io_poll_add(preq);
5483 req_set_fail_links(preq);
5484 io_req_complete(preq, ret);
5489 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5491 if (!req->poll.update_events && !req->poll.update_user_data)
5492 return __io_poll_add(req);
5493 return io_poll_update(req);
5496 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5498 struct io_timeout_data *data = container_of(timer,
5499 struct io_timeout_data, timer);
5500 struct io_kiocb *req = data->req;
5501 struct io_ring_ctx *ctx = req->ctx;
5502 unsigned long flags;
5504 spin_lock_irqsave(&ctx->completion_lock, flags);
5505 list_del_init(&req->timeout.list);
5506 atomic_set(&req->ctx->cq_timeouts,
5507 atomic_read(&req->ctx->cq_timeouts) + 1);
5509 io_cqring_fill_event(req, -ETIME);
5510 io_commit_cqring(ctx);
5511 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5513 io_cqring_ev_posted(ctx);
5514 req_set_fail_links(req);
5516 return HRTIMER_NORESTART;
5519 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5521 __must_hold(&ctx->completion_lock)
5523 struct io_timeout_data *io;
5524 struct io_kiocb *req;
5527 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5528 if (user_data == req->user_data) {
5535 return ERR_PTR(ret);
5537 io = req->async_data;
5538 ret = hrtimer_try_to_cancel(&io->timer);
5540 return ERR_PTR(-EALREADY);
5541 list_del_init(&req->timeout.list);
5545 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5546 __must_hold(&ctx->completion_lock)
5548 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5551 return PTR_ERR(req);
5553 req_set_fail_links(req);
5554 io_cqring_fill_event(req, -ECANCELED);
5555 io_put_req_deferred(req, 1);
5559 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5560 struct timespec64 *ts, enum hrtimer_mode mode)
5561 __must_hold(&ctx->completion_lock)
5563 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5564 struct io_timeout_data *data;
5567 return PTR_ERR(req);
5569 req->timeout.off = 0; /* noseq */
5570 data = req->async_data;
5571 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5572 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5573 data->timer.function = io_timeout_fn;
5574 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5578 static int io_timeout_remove_prep(struct io_kiocb *req,
5579 const struct io_uring_sqe *sqe)
5581 struct io_timeout_rem *tr = &req->timeout_rem;
5583 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5585 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5587 if (sqe->ioprio || sqe->buf_index || sqe->len)
5590 tr->addr = READ_ONCE(sqe->addr);
5591 tr->flags = READ_ONCE(sqe->timeout_flags);
5592 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5593 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5595 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5597 } else if (tr->flags) {
5598 /* timeout removal doesn't support flags */
5605 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5607 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5612 * Remove or update an existing timeout command
5614 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5616 struct io_timeout_rem *tr = &req->timeout_rem;
5617 struct io_ring_ctx *ctx = req->ctx;
5620 spin_lock_irq(&ctx->completion_lock);
5621 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5622 ret = io_timeout_cancel(ctx, tr->addr);
5624 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5625 io_translate_timeout_mode(tr->flags));
5627 io_cqring_fill_event(req, ret);
5628 io_commit_cqring(ctx);
5629 spin_unlock_irq(&ctx->completion_lock);
5630 io_cqring_ev_posted(ctx);
5632 req_set_fail_links(req);
5637 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5638 bool is_timeout_link)
5640 struct io_timeout_data *data;
5642 u32 off = READ_ONCE(sqe->off);
5644 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5646 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5648 if (off && is_timeout_link)
5650 flags = READ_ONCE(sqe->timeout_flags);
5651 if (flags & ~IORING_TIMEOUT_ABS)
5654 req->timeout.off = off;
5656 if (!req->async_data && io_alloc_async_data(req))
5659 data = req->async_data;
5662 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5665 data->mode = io_translate_timeout_mode(flags);
5666 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5667 if (is_timeout_link)
5668 io_req_track_inflight(req);
5672 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5674 struct io_ring_ctx *ctx = req->ctx;
5675 struct io_timeout_data *data = req->async_data;
5676 struct list_head *entry;
5677 u32 tail, off = req->timeout.off;
5679 spin_lock_irq(&ctx->completion_lock);
5682 * sqe->off holds how many events that need to occur for this
5683 * timeout event to be satisfied. If it isn't set, then this is
5684 * a pure timeout request, sequence isn't used.
5686 if (io_is_timeout_noseq(req)) {
5687 entry = ctx->timeout_list.prev;
5691 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5692 req->timeout.target_seq = tail + off;
5694 /* Update the last seq here in case io_flush_timeouts() hasn't.
5695 * This is safe because ->completion_lock is held, and submissions
5696 * and completions are never mixed in the same ->completion_lock section.
5698 ctx->cq_last_tm_flush = tail;
5701 * Insertion sort, ensuring the first entry in the list is always
5702 * the one we need first.
5704 list_for_each_prev(entry, &ctx->timeout_list) {
5705 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5708 if (io_is_timeout_noseq(nxt))
5710 /* nxt.seq is behind @tail, otherwise would've been completed */
5711 if (off >= nxt->timeout.target_seq - tail)
5715 list_add(&req->timeout.list, entry);
5716 data->timer.function = io_timeout_fn;
5717 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5718 spin_unlock_irq(&ctx->completion_lock);
5722 struct io_cancel_data {
5723 struct io_ring_ctx *ctx;
5727 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5729 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5730 struct io_cancel_data *cd = data;
5732 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5735 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5736 struct io_ring_ctx *ctx)
5738 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5739 enum io_wq_cancel cancel_ret;
5742 if (!tctx || !tctx->io_wq)
5745 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5746 switch (cancel_ret) {
5747 case IO_WQ_CANCEL_OK:
5750 case IO_WQ_CANCEL_RUNNING:
5753 case IO_WQ_CANCEL_NOTFOUND:
5761 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5762 struct io_kiocb *req, __u64 sqe_addr,
5765 unsigned long flags;
5768 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5769 if (ret != -ENOENT) {
5770 spin_lock_irqsave(&ctx->completion_lock, flags);
5774 spin_lock_irqsave(&ctx->completion_lock, flags);
5775 ret = io_timeout_cancel(ctx, sqe_addr);
5778 ret = io_poll_cancel(ctx, sqe_addr);
5782 io_cqring_fill_event(req, ret);
5783 io_commit_cqring(ctx);
5784 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5785 io_cqring_ev_posted(ctx);
5788 req_set_fail_links(req);
5792 static int io_async_cancel_prep(struct io_kiocb *req,
5793 const struct io_uring_sqe *sqe)
5795 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5797 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5799 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5802 req->cancel.addr = READ_ONCE(sqe->addr);
5806 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5808 struct io_ring_ctx *ctx = req->ctx;
5809 u64 sqe_addr = req->cancel.addr;
5810 struct io_tctx_node *node;
5813 /* tasks should wait for their io-wq threads, so safe w/o sync */
5814 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5815 spin_lock_irq(&ctx->completion_lock);
5818 ret = io_timeout_cancel(ctx, sqe_addr);
5821 ret = io_poll_cancel(ctx, sqe_addr);
5824 spin_unlock_irq(&ctx->completion_lock);
5826 /* slow path, try all io-wq's */
5827 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5829 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5830 struct io_uring_task *tctx = node->task->io_uring;
5832 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5836 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5838 spin_lock_irq(&ctx->completion_lock);
5840 io_cqring_fill_event(req, ret);
5841 io_commit_cqring(ctx);
5842 spin_unlock_irq(&ctx->completion_lock);
5843 io_cqring_ev_posted(ctx);
5846 req_set_fail_links(req);
5851 static int io_rsrc_update_prep(struct io_kiocb *req,
5852 const struct io_uring_sqe *sqe)
5854 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5856 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5858 if (sqe->ioprio || sqe->rw_flags)
5861 req->rsrc_update.offset = READ_ONCE(sqe->off);
5862 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5863 if (!req->rsrc_update.nr_args)
5865 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5869 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5871 struct io_ring_ctx *ctx = req->ctx;
5872 struct io_uring_rsrc_update up;
5875 if (issue_flags & IO_URING_F_NONBLOCK)
5878 up.offset = req->rsrc_update.offset;
5879 up.data = req->rsrc_update.arg;
5881 mutex_lock(&ctx->uring_lock);
5882 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5883 mutex_unlock(&ctx->uring_lock);
5886 req_set_fail_links(req);
5887 __io_req_complete(req, issue_flags, ret, 0);
5891 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5893 switch (req->opcode) {
5896 case IORING_OP_READV:
5897 case IORING_OP_READ_FIXED:
5898 case IORING_OP_READ:
5899 return io_read_prep(req, sqe);
5900 case IORING_OP_WRITEV:
5901 case IORING_OP_WRITE_FIXED:
5902 case IORING_OP_WRITE:
5903 return io_write_prep(req, sqe);
5904 case IORING_OP_POLL_ADD:
5905 return io_poll_add_prep(req, sqe);
5906 case IORING_OP_POLL_REMOVE:
5907 return io_poll_remove_prep(req, sqe);
5908 case IORING_OP_FSYNC:
5909 return io_fsync_prep(req, sqe);
5910 case IORING_OP_SYNC_FILE_RANGE:
5911 return io_sfr_prep(req, sqe);
5912 case IORING_OP_SENDMSG:
5913 case IORING_OP_SEND:
5914 return io_sendmsg_prep(req, sqe);
5915 case IORING_OP_RECVMSG:
5916 case IORING_OP_RECV:
5917 return io_recvmsg_prep(req, sqe);
5918 case IORING_OP_CONNECT:
5919 return io_connect_prep(req, sqe);
5920 case IORING_OP_TIMEOUT:
5921 return io_timeout_prep(req, sqe, false);
5922 case IORING_OP_TIMEOUT_REMOVE:
5923 return io_timeout_remove_prep(req, sqe);
5924 case IORING_OP_ASYNC_CANCEL:
5925 return io_async_cancel_prep(req, sqe);
5926 case IORING_OP_LINK_TIMEOUT:
5927 return io_timeout_prep(req, sqe, true);
5928 case IORING_OP_ACCEPT:
5929 return io_accept_prep(req, sqe);
5930 case IORING_OP_FALLOCATE:
5931 return io_fallocate_prep(req, sqe);
5932 case IORING_OP_OPENAT:
5933 return io_openat_prep(req, sqe);
5934 case IORING_OP_CLOSE:
5935 return io_close_prep(req, sqe);
5936 case IORING_OP_FILES_UPDATE:
5937 return io_rsrc_update_prep(req, sqe);
5938 case IORING_OP_STATX:
5939 return io_statx_prep(req, sqe);
5940 case IORING_OP_FADVISE:
5941 return io_fadvise_prep(req, sqe);
5942 case IORING_OP_MADVISE:
5943 return io_madvise_prep(req, sqe);
5944 case IORING_OP_OPENAT2:
5945 return io_openat2_prep(req, sqe);
5946 case IORING_OP_EPOLL_CTL:
5947 return io_epoll_ctl_prep(req, sqe);
5948 case IORING_OP_SPLICE:
5949 return io_splice_prep(req, sqe);
5950 case IORING_OP_PROVIDE_BUFFERS:
5951 return io_provide_buffers_prep(req, sqe);
5952 case IORING_OP_REMOVE_BUFFERS:
5953 return io_remove_buffers_prep(req, sqe);
5955 return io_tee_prep(req, sqe);
5956 case IORING_OP_SHUTDOWN:
5957 return io_shutdown_prep(req, sqe);
5958 case IORING_OP_RENAMEAT:
5959 return io_renameat_prep(req, sqe);
5960 case IORING_OP_UNLINKAT:
5961 return io_unlinkat_prep(req, sqe);
5964 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5969 static int io_req_prep_async(struct io_kiocb *req)
5971 if (!io_op_defs[req->opcode].needs_async_setup)
5973 if (WARN_ON_ONCE(req->async_data))
5975 if (io_alloc_async_data(req))
5978 switch (req->opcode) {
5979 case IORING_OP_READV:
5980 return io_rw_prep_async(req, READ);
5981 case IORING_OP_WRITEV:
5982 return io_rw_prep_async(req, WRITE);
5983 case IORING_OP_SENDMSG:
5984 return io_sendmsg_prep_async(req);
5985 case IORING_OP_RECVMSG:
5986 return io_recvmsg_prep_async(req);
5987 case IORING_OP_CONNECT:
5988 return io_connect_prep_async(req);
5990 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5995 static u32 io_get_sequence(struct io_kiocb *req)
5997 struct io_kiocb *pos;
5998 struct io_ring_ctx *ctx = req->ctx;
5999 u32 total_submitted, nr_reqs = 0;
6001 io_for_each_link(pos, req)
6004 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
6005 return total_submitted - nr_reqs;
6008 static int io_req_defer(struct io_kiocb *req)
6010 struct io_ring_ctx *ctx = req->ctx;
6011 struct io_defer_entry *de;
6015 /* Still need defer if there is pending req in defer list. */
6016 if (likely(list_empty_careful(&ctx->defer_list) &&
6017 !(req->flags & REQ_F_IO_DRAIN)))
6020 seq = io_get_sequence(req);
6021 /* Still a chance to pass the sequence check */
6022 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6025 ret = io_req_prep_async(req);
6028 io_prep_async_link(req);
6029 de = kmalloc(sizeof(*de), GFP_KERNEL);
6033 spin_lock_irq(&ctx->completion_lock);
6034 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6035 spin_unlock_irq(&ctx->completion_lock);
6037 io_queue_async_work(req);
6038 return -EIOCBQUEUED;
6041 trace_io_uring_defer(ctx, req, req->user_data);
6044 list_add_tail(&de->list, &ctx->defer_list);
6045 spin_unlock_irq(&ctx->completion_lock);
6046 return -EIOCBQUEUED;
6049 static void io_clean_op(struct io_kiocb *req)
6051 if (req->flags & REQ_F_BUFFER_SELECTED) {
6052 switch (req->opcode) {
6053 case IORING_OP_READV:
6054 case IORING_OP_READ_FIXED:
6055 case IORING_OP_READ:
6056 kfree((void *)(unsigned long)req->rw.addr);
6058 case IORING_OP_RECVMSG:
6059 case IORING_OP_RECV:
6060 kfree(req->sr_msg.kbuf);
6063 req->flags &= ~REQ_F_BUFFER_SELECTED;
6066 if (req->flags & REQ_F_NEED_CLEANUP) {
6067 switch (req->opcode) {
6068 case IORING_OP_READV:
6069 case IORING_OP_READ_FIXED:
6070 case IORING_OP_READ:
6071 case IORING_OP_WRITEV:
6072 case IORING_OP_WRITE_FIXED:
6073 case IORING_OP_WRITE: {
6074 struct io_async_rw *io = req->async_data;
6076 kfree(io->free_iovec);
6079 case IORING_OP_RECVMSG:
6080 case IORING_OP_SENDMSG: {
6081 struct io_async_msghdr *io = req->async_data;
6083 kfree(io->free_iov);
6086 case IORING_OP_SPLICE:
6088 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6089 io_put_file(req->splice.file_in);
6091 case IORING_OP_OPENAT:
6092 case IORING_OP_OPENAT2:
6093 if (req->open.filename)
6094 putname(req->open.filename);
6096 case IORING_OP_RENAMEAT:
6097 putname(req->rename.oldpath);
6098 putname(req->rename.newpath);
6100 case IORING_OP_UNLINKAT:
6101 putname(req->unlink.filename);
6104 req->flags &= ~REQ_F_NEED_CLEANUP;
6108 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6110 struct io_ring_ctx *ctx = req->ctx;
6111 const struct cred *creds = NULL;
6114 if (req->work.creds && req->work.creds != current_cred())
6115 creds = override_creds(req->work.creds);
6117 switch (req->opcode) {
6119 ret = io_nop(req, issue_flags);
6121 case IORING_OP_READV:
6122 case IORING_OP_READ_FIXED:
6123 case IORING_OP_READ:
6124 ret = io_read(req, issue_flags);
6126 case IORING_OP_WRITEV:
6127 case IORING_OP_WRITE_FIXED:
6128 case IORING_OP_WRITE:
6129 ret = io_write(req, issue_flags);
6131 case IORING_OP_FSYNC:
6132 ret = io_fsync(req, issue_flags);
6134 case IORING_OP_POLL_ADD:
6135 ret = io_poll_add(req, issue_flags);
6137 case IORING_OP_POLL_REMOVE:
6138 ret = io_poll_remove(req, issue_flags);
6140 case IORING_OP_SYNC_FILE_RANGE:
6141 ret = io_sync_file_range(req, issue_flags);
6143 case IORING_OP_SENDMSG:
6144 ret = io_sendmsg(req, issue_flags);
6146 case IORING_OP_SEND:
6147 ret = io_send(req, issue_flags);
6149 case IORING_OP_RECVMSG:
6150 ret = io_recvmsg(req, issue_flags);
6152 case IORING_OP_RECV:
6153 ret = io_recv(req, issue_flags);
6155 case IORING_OP_TIMEOUT:
6156 ret = io_timeout(req, issue_flags);
6158 case IORING_OP_TIMEOUT_REMOVE:
6159 ret = io_timeout_remove(req, issue_flags);
6161 case IORING_OP_ACCEPT:
6162 ret = io_accept(req, issue_flags);
6164 case IORING_OP_CONNECT:
6165 ret = io_connect(req, issue_flags);
6167 case IORING_OP_ASYNC_CANCEL:
6168 ret = io_async_cancel(req, issue_flags);
6170 case IORING_OP_FALLOCATE:
6171 ret = io_fallocate(req, issue_flags);
6173 case IORING_OP_OPENAT:
6174 ret = io_openat(req, issue_flags);
6176 case IORING_OP_CLOSE:
6177 ret = io_close(req, issue_flags);
6179 case IORING_OP_FILES_UPDATE:
6180 ret = io_files_update(req, issue_flags);
6182 case IORING_OP_STATX:
6183 ret = io_statx(req, issue_flags);
6185 case IORING_OP_FADVISE:
6186 ret = io_fadvise(req, issue_flags);
6188 case IORING_OP_MADVISE:
6189 ret = io_madvise(req, issue_flags);
6191 case IORING_OP_OPENAT2:
6192 ret = io_openat2(req, issue_flags);
6194 case IORING_OP_EPOLL_CTL:
6195 ret = io_epoll_ctl(req, issue_flags);
6197 case IORING_OP_SPLICE:
6198 ret = io_splice(req, issue_flags);
6200 case IORING_OP_PROVIDE_BUFFERS:
6201 ret = io_provide_buffers(req, issue_flags);
6203 case IORING_OP_REMOVE_BUFFERS:
6204 ret = io_remove_buffers(req, issue_flags);
6207 ret = io_tee(req, issue_flags);
6209 case IORING_OP_SHUTDOWN:
6210 ret = io_shutdown(req, issue_flags);
6212 case IORING_OP_RENAMEAT:
6213 ret = io_renameat(req, issue_flags);
6215 case IORING_OP_UNLINKAT:
6216 ret = io_unlinkat(req, issue_flags);
6224 revert_creds(creds);
6229 /* If the op doesn't have a file, we're not polling for it */
6230 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6231 const bool in_async = io_wq_current_is_worker();
6233 /* workqueue context doesn't hold uring_lock, grab it now */
6235 mutex_lock(&ctx->uring_lock);
6237 io_iopoll_req_issued(req, in_async);
6240 mutex_unlock(&ctx->uring_lock);
6246 static void io_wq_submit_work(struct io_wq_work *work)
6248 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6249 struct io_kiocb *timeout;
6252 timeout = io_prep_linked_timeout(req);
6254 io_queue_linked_timeout(timeout);
6256 if (work->flags & IO_WQ_WORK_CANCEL)
6261 ret = io_issue_sqe(req, 0);
6263 * We can get EAGAIN for polled IO even though we're
6264 * forcing a sync submission from here, since we can't
6265 * wait for request slots on the block side.
6273 /* avoid locking problems by failing it from a clean context */
6275 /* io-wq is going to take one down */
6277 io_req_task_queue_fail(req, ret);
6281 #define FFS_ASYNC_READ 0x1UL
6282 #define FFS_ASYNC_WRITE 0x2UL
6284 #define FFS_ISREG 0x4UL
6286 #define FFS_ISREG 0x0UL
6288 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6290 static inline struct file **io_fixed_file_slot(struct io_rsrc_data *file_data,
6293 struct fixed_rsrc_table *table;
6295 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6296 return &table->files[i & IORING_FILE_TABLE_MASK];
6299 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6302 struct file **file_slot = io_fixed_file_slot(ctx->file_data, index);
6304 return (struct file *) ((unsigned long) *file_slot & FFS_MASK);
6307 static struct file *io_file_get(struct io_submit_state *state,
6308 struct io_kiocb *req, int fd, bool fixed)
6310 struct io_ring_ctx *ctx = req->ctx;
6314 unsigned long file_ptr;
6316 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6318 fd = array_index_nospec(fd, ctx->nr_user_files);
6319 file_ptr = (unsigned long) *io_fixed_file_slot(ctx->file_data, fd);
6320 file = (struct file *) (file_ptr & FFS_MASK);
6321 file_ptr &= ~FFS_MASK;
6322 /* mask in overlapping REQ_F and FFS bits */
6323 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6324 io_req_set_rsrc_node(req);
6326 trace_io_uring_file_get(ctx, fd);
6327 file = __io_file_get(state, fd);
6329 /* we don't allow fixed io_uring files */
6330 if (file && unlikely(file->f_op == &io_uring_fops))
6331 io_req_track_inflight(req);
6337 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6339 struct io_timeout_data *data = container_of(timer,
6340 struct io_timeout_data, timer);
6341 struct io_kiocb *prev, *req = data->req;
6342 struct io_ring_ctx *ctx = req->ctx;
6343 unsigned long flags;
6345 spin_lock_irqsave(&ctx->completion_lock, flags);
6346 prev = req->timeout.head;
6347 req->timeout.head = NULL;
6350 * We don't expect the list to be empty, that will only happen if we
6351 * race with the completion of the linked work.
6353 if (prev && req_ref_inc_not_zero(prev))
6354 io_remove_next_linked(prev);
6357 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6360 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6361 io_put_req_deferred(prev, 1);
6363 io_req_complete_post(req, -ETIME, 0);
6364 io_put_req_deferred(req, 1);
6366 return HRTIMER_NORESTART;
6369 static void io_queue_linked_timeout(struct io_kiocb *req)
6371 struct io_ring_ctx *ctx = req->ctx;
6373 spin_lock_irq(&ctx->completion_lock);
6375 * If the back reference is NULL, then our linked request finished
6376 * before we got a chance to setup the timer
6378 if (req->timeout.head) {
6379 struct io_timeout_data *data = req->async_data;
6381 data->timer.function = io_link_timeout_fn;
6382 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6385 spin_unlock_irq(&ctx->completion_lock);
6386 /* drop submission reference */
6390 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6392 struct io_kiocb *nxt = req->link;
6394 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6395 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6398 nxt->timeout.head = req;
6399 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6400 req->flags |= REQ_F_LINK_TIMEOUT;
6404 static void __io_queue_sqe(struct io_kiocb *req)
6406 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6409 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6412 * We async punt it if the file wasn't marked NOWAIT, or if the file
6413 * doesn't support non-blocking read/write attempts
6416 /* drop submission reference */
6417 if (req->flags & REQ_F_COMPLETE_INLINE) {
6418 struct io_ring_ctx *ctx = req->ctx;
6419 struct io_comp_state *cs = &ctx->submit_state.comp;
6421 cs->reqs[cs->nr++] = req;
6422 if (cs->nr == ARRAY_SIZE(cs->reqs))
6423 io_submit_flush_completions(cs, ctx);
6427 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6428 if (!io_arm_poll_handler(req)) {
6430 * Queued up for async execution, worker will release
6431 * submit reference when the iocb is actually submitted.
6433 io_queue_async_work(req);
6436 io_req_complete_failed(req, ret);
6439 io_queue_linked_timeout(linked_timeout);
6442 static void io_queue_sqe(struct io_kiocb *req)
6446 ret = io_req_defer(req);
6448 if (ret != -EIOCBQUEUED) {
6450 io_req_complete_failed(req, ret);
6452 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6453 ret = io_req_prep_async(req);
6456 io_queue_async_work(req);
6458 __io_queue_sqe(req);
6463 * Check SQE restrictions (opcode and flags).
6465 * Returns 'true' if SQE is allowed, 'false' otherwise.
6467 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6468 struct io_kiocb *req,
6469 unsigned int sqe_flags)
6471 if (!ctx->restricted)
6474 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6477 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6478 ctx->restrictions.sqe_flags_required)
6481 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6482 ctx->restrictions.sqe_flags_required))
6488 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6489 const struct io_uring_sqe *sqe)
6491 struct io_submit_state *state;
6492 unsigned int sqe_flags;
6493 int personality, ret = 0;
6495 req->opcode = READ_ONCE(sqe->opcode);
6496 /* same numerical values with corresponding REQ_F_*, safe to copy */
6497 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6498 req->user_data = READ_ONCE(sqe->user_data);
6499 req->async_data = NULL;
6503 req->fixed_rsrc_refs = NULL;
6504 /* one is dropped after submission, the other at completion */
6505 atomic_set(&req->refs, 2);
6506 req->task = current;
6508 req->work.creds = NULL;
6510 /* enforce forwards compatibility on users */
6511 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6516 if (unlikely(req->opcode >= IORING_OP_LAST))
6519 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6522 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6523 !io_op_defs[req->opcode].buffer_select)
6526 personality = READ_ONCE(sqe->personality);
6528 req->work.creds = xa_load(&ctx->personalities, personality);
6529 if (!req->work.creds)
6531 get_cred(req->work.creds);
6533 state = &ctx->submit_state;
6536 * Plug now if we have more than 1 IO left after this, and the target
6537 * is potentially a read/write to block based storage.
6539 if (!state->plug_started && state->ios_left > 1 &&
6540 io_op_defs[req->opcode].plug) {
6541 blk_start_plug(&state->plug);
6542 state->plug_started = true;
6545 if (io_op_defs[req->opcode].needs_file) {
6546 bool fixed = req->flags & REQ_F_FIXED_FILE;
6548 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6549 if (unlikely(!req->file))
6557 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6558 const struct io_uring_sqe *sqe)
6560 struct io_submit_link *link = &ctx->submit_state.link;
6563 ret = io_init_req(ctx, req, sqe);
6564 if (unlikely(ret)) {
6567 /* fail even hard links since we don't submit */
6568 link->head->flags |= REQ_F_FAIL_LINK;
6569 io_req_complete_failed(link->head, -ECANCELED);
6572 io_req_complete_failed(req, ret);
6575 ret = io_req_prep(req, sqe);
6579 /* don't need @sqe from now on */
6580 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6581 true, ctx->flags & IORING_SETUP_SQPOLL);
6584 * If we already have a head request, queue this one for async
6585 * submittal once the head completes. If we don't have a head but
6586 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6587 * submitted sync once the chain is complete. If none of those
6588 * conditions are true (normal request), then just queue it.
6591 struct io_kiocb *head = link->head;
6594 * Taking sequential execution of a link, draining both sides
6595 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6596 * requests in the link. So, it drains the head and the
6597 * next after the link request. The last one is done via
6598 * drain_next flag to persist the effect across calls.
6600 if (req->flags & REQ_F_IO_DRAIN) {
6601 head->flags |= REQ_F_IO_DRAIN;
6602 ctx->drain_next = 1;
6604 ret = io_req_prep_async(req);
6607 trace_io_uring_link(ctx, req, head);
6608 link->last->link = req;
6611 /* last request of a link, enqueue the link */
6612 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6617 if (unlikely(ctx->drain_next)) {
6618 req->flags |= REQ_F_IO_DRAIN;
6619 ctx->drain_next = 0;
6621 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6633 * Batched submission is done, ensure local IO is flushed out.
6635 static void io_submit_state_end(struct io_submit_state *state,
6636 struct io_ring_ctx *ctx)
6638 if (state->link.head)
6639 io_queue_sqe(state->link.head);
6641 io_submit_flush_completions(&state->comp, ctx);
6642 if (state->plug_started)
6643 blk_finish_plug(&state->plug);
6644 io_state_file_put(state);
6648 * Start submission side cache.
6650 static void io_submit_state_start(struct io_submit_state *state,
6651 unsigned int max_ios)
6653 state->plug_started = false;
6654 state->ios_left = max_ios;
6655 /* set only head, no need to init link_last in advance */
6656 state->link.head = NULL;
6659 static void io_commit_sqring(struct io_ring_ctx *ctx)
6661 struct io_rings *rings = ctx->rings;
6664 * Ensure any loads from the SQEs are done at this point,
6665 * since once we write the new head, the application could
6666 * write new data to them.
6668 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6672 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6673 * that is mapped by userspace. This means that care needs to be taken to
6674 * ensure that reads are stable, as we cannot rely on userspace always
6675 * being a good citizen. If members of the sqe are validated and then later
6676 * used, it's important that those reads are done through READ_ONCE() to
6677 * prevent a re-load down the line.
6679 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6681 u32 *sq_array = ctx->sq_array;
6685 * The cached sq head (or cq tail) serves two purposes:
6687 * 1) allows us to batch the cost of updating the user visible
6689 * 2) allows the kernel side to track the head on its own, even
6690 * though the application is the one updating it.
6692 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6693 if (likely(head < ctx->sq_entries))
6694 return &ctx->sq_sqes[head];
6696 /* drop invalid entries */
6697 ctx->cached_sq_dropped++;
6698 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6702 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6706 /* if we have a backlog and couldn't flush it all, return BUSY */
6707 if (test_bit(0, &ctx->sq_check_overflow)) {
6708 if (!__io_cqring_overflow_flush(ctx, false))
6712 /* make sure SQ entry isn't read before tail */
6713 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6715 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6718 percpu_counter_add(¤t->io_uring->inflight, nr);
6719 refcount_add(nr, ¤t->usage);
6720 io_submit_state_start(&ctx->submit_state, nr);
6722 while (submitted < nr) {
6723 const struct io_uring_sqe *sqe;
6724 struct io_kiocb *req;
6726 req = io_alloc_req(ctx);
6727 if (unlikely(!req)) {
6729 submitted = -EAGAIN;
6732 sqe = io_get_sqe(ctx);
6733 if (unlikely(!sqe)) {
6734 kmem_cache_free(req_cachep, req);
6737 /* will complete beyond this point, count as submitted */
6739 if (io_submit_sqe(ctx, req, sqe))
6743 if (unlikely(submitted != nr)) {
6744 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6745 struct io_uring_task *tctx = current->io_uring;
6746 int unused = nr - ref_used;
6748 percpu_ref_put_many(&ctx->refs, unused);
6749 percpu_counter_sub(&tctx->inflight, unused);
6750 put_task_struct_many(current, unused);
6753 io_submit_state_end(&ctx->submit_state, ctx);
6754 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6755 io_commit_sqring(ctx);
6760 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6762 /* Tell userspace we may need a wakeup call */
6763 spin_lock_irq(&ctx->completion_lock);
6764 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6765 spin_unlock_irq(&ctx->completion_lock);
6768 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6770 spin_lock_irq(&ctx->completion_lock);
6771 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6772 spin_unlock_irq(&ctx->completion_lock);
6775 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6777 unsigned int to_submit;
6780 to_submit = io_sqring_entries(ctx);
6781 /* if we're handling multiple rings, cap submit size for fairness */
6782 if (cap_entries && to_submit > 8)
6785 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6786 unsigned nr_events = 0;
6788 mutex_lock(&ctx->uring_lock);
6789 if (!list_empty(&ctx->iopoll_list))
6790 io_do_iopoll(ctx, &nr_events, 0);
6792 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6793 !(ctx->flags & IORING_SETUP_R_DISABLED))
6794 ret = io_submit_sqes(ctx, to_submit);
6795 mutex_unlock(&ctx->uring_lock);
6798 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6799 wake_up(&ctx->sqo_sq_wait);
6804 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6806 struct io_ring_ctx *ctx;
6807 unsigned sq_thread_idle = 0;
6809 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6810 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6811 sqd->sq_thread_idle = sq_thread_idle;
6814 static int io_sq_thread(void *data)
6816 struct io_sq_data *sqd = data;
6817 struct io_ring_ctx *ctx;
6818 unsigned long timeout = 0;
6819 char buf[TASK_COMM_LEN];
6822 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6823 set_task_comm(current, buf);
6824 current->pf_io_worker = NULL;
6826 if (sqd->sq_cpu != -1)
6827 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6829 set_cpus_allowed_ptr(current, cpu_online_mask);
6830 current->flags |= PF_NO_SETAFFINITY;
6832 mutex_lock(&sqd->lock);
6833 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6835 bool cap_entries, sqt_spin, needs_sched;
6837 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6838 signal_pending(current)) {
6839 bool did_sig = false;
6841 mutex_unlock(&sqd->lock);
6842 if (signal_pending(current)) {
6843 struct ksignal ksig;
6845 did_sig = get_signal(&ksig);
6848 mutex_lock(&sqd->lock);
6852 io_run_task_work_head(&sqd->park_task_work);
6853 timeout = jiffies + sqd->sq_thread_idle;
6857 cap_entries = !list_is_singular(&sqd->ctx_list);
6858 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6859 const struct cred *creds = NULL;
6861 if (ctx->sq_creds != current_cred())
6862 creds = override_creds(ctx->sq_creds);
6863 ret = __io_sq_thread(ctx, cap_entries);
6865 revert_creds(creds);
6866 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6870 if (sqt_spin || !time_after(jiffies, timeout)) {
6874 timeout = jiffies + sqd->sq_thread_idle;
6879 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6880 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6881 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6882 !list_empty_careful(&ctx->iopoll_list)) {
6883 needs_sched = false;
6886 if (io_sqring_entries(ctx)) {
6887 needs_sched = false;
6892 if (needs_sched && !test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6893 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6894 io_ring_set_wakeup_flag(ctx);
6896 mutex_unlock(&sqd->lock);
6898 mutex_lock(&sqd->lock);
6899 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6900 io_ring_clear_wakeup_flag(ctx);
6903 finish_wait(&sqd->wait, &wait);
6904 io_run_task_work_head(&sqd->park_task_work);
6905 timeout = jiffies + sqd->sq_thread_idle;
6908 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6909 io_uring_cancel_sqpoll(ctx);
6911 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6912 io_ring_set_wakeup_flag(ctx);
6913 mutex_unlock(&sqd->lock);
6916 io_run_task_work_head(&sqd->park_task_work);
6917 complete(&sqd->exited);
6921 struct io_wait_queue {
6922 struct wait_queue_entry wq;
6923 struct io_ring_ctx *ctx;
6925 unsigned nr_timeouts;
6928 static inline bool io_should_wake(struct io_wait_queue *iowq)
6930 struct io_ring_ctx *ctx = iowq->ctx;
6933 * Wake up if we have enough events, or if a timeout occurred since we
6934 * started waiting. For timeouts, we always want to return to userspace,
6935 * regardless of event count.
6937 return io_cqring_events(ctx) >= iowq->to_wait ||
6938 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6941 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6942 int wake_flags, void *key)
6944 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6948 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6949 * the task, and the next invocation will do it.
6951 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6952 return autoremove_wake_function(curr, mode, wake_flags, key);
6956 static int io_run_task_work_sig(void)
6958 if (io_run_task_work())
6960 if (!signal_pending(current))
6962 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6963 return -ERESTARTSYS;
6967 /* when returns >0, the caller should retry */
6968 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6969 struct io_wait_queue *iowq,
6970 signed long *timeout)
6974 /* make sure we run task_work before checking for signals */
6975 ret = io_run_task_work_sig();
6976 if (ret || io_should_wake(iowq))
6978 /* let the caller flush overflows, retry */
6979 if (test_bit(0, &ctx->cq_check_overflow))
6982 *timeout = schedule_timeout(*timeout);
6983 return !*timeout ? -ETIME : 1;
6987 * Wait until events become available, if we don't already have some. The
6988 * application must reap them itself, as they reside on the shared cq ring.
6990 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6991 const sigset_t __user *sig, size_t sigsz,
6992 struct __kernel_timespec __user *uts)
6994 struct io_wait_queue iowq = {
6997 .func = io_wake_function,
6998 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7001 .to_wait = min_events,
7003 struct io_rings *rings = ctx->rings;
7004 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7008 io_cqring_overflow_flush(ctx, false);
7009 if (io_cqring_events(ctx) >= min_events)
7011 if (!io_run_task_work())
7016 #ifdef CONFIG_COMPAT
7017 if (in_compat_syscall())
7018 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7022 ret = set_user_sigmask(sig, sigsz);
7029 struct timespec64 ts;
7031 if (get_timespec64(&ts, uts))
7033 timeout = timespec64_to_jiffies(&ts);
7036 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7037 trace_io_uring_cqring_wait(ctx, min_events);
7039 /* if we can't even flush overflow, don't wait for more */
7040 if (!io_cqring_overflow_flush(ctx, false)) {
7044 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7045 TASK_INTERRUPTIBLE);
7046 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7047 finish_wait(&ctx->wait, &iowq.wq);
7051 restore_saved_sigmask_unless(ret == -EINTR);
7053 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7056 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7058 #if defined(CONFIG_UNIX)
7059 if (ctx->ring_sock) {
7060 struct sock *sock = ctx->ring_sock->sk;
7061 struct sk_buff *skb;
7063 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7069 for (i = 0; i < ctx->nr_user_files; i++) {
7072 file = io_file_from_index(ctx, i);
7079 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7081 struct io_rsrc_data *data = container_of(ref, struct io_rsrc_data, refs);
7083 complete(&data->done);
7086 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7088 spin_lock_bh(&ctx->rsrc_ref_lock);
7091 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7093 spin_unlock_bh(&ctx->rsrc_ref_lock);
7096 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7098 percpu_ref_exit(&ref_node->refs);
7102 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7103 struct io_rsrc_data *data_to_kill)
7105 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7106 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7109 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7111 rsrc_node->rsrc_data = data_to_kill;
7112 io_rsrc_ref_lock(ctx);
7113 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7114 io_rsrc_ref_unlock(ctx);
7116 percpu_ref_get(&data_to_kill->refs);
7117 percpu_ref_kill(&rsrc_node->refs);
7118 ctx->rsrc_node = NULL;
7121 if (!ctx->rsrc_node) {
7122 ctx->rsrc_node = ctx->rsrc_backup_node;
7123 ctx->rsrc_backup_node = NULL;
7127 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7129 if (ctx->rsrc_backup_node)
7131 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7132 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7135 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7139 /* As we may drop ->uring_lock, other task may have started quiesce */
7143 data->quiesce = true;
7145 ret = io_rsrc_node_switch_start(ctx);
7148 io_rsrc_node_switch(ctx, data);
7150 percpu_ref_kill(&data->refs);
7151 flush_delayed_work(&ctx->rsrc_put_work);
7153 ret = wait_for_completion_interruptible(&data->done);
7157 percpu_ref_resurrect(&data->refs);
7158 reinit_completion(&data->done);
7160 mutex_unlock(&ctx->uring_lock);
7161 ret = io_run_task_work_sig();
7162 mutex_lock(&ctx->uring_lock);
7164 data->quiesce = false;
7169 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7170 rsrc_put_fn *do_put)
7172 struct io_rsrc_data *data;
7174 data = kzalloc(sizeof(*data), GFP_KERNEL);
7178 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7179 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7184 data->do_put = do_put;
7185 init_completion(&data->done);
7189 static void io_rsrc_data_free(struct io_rsrc_data *data)
7191 percpu_ref_exit(&data->refs);
7196 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7198 struct io_rsrc_data *data = ctx->file_data;
7199 unsigned nr_tables, i;
7204 ret = io_rsrc_ref_quiesce(data, ctx);
7208 __io_sqe_files_unregister(ctx);
7209 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7210 for (i = 0; i < nr_tables; i++)
7211 kfree(data->table[i].files);
7212 io_rsrc_data_free(data);
7213 ctx->file_data = NULL;
7214 ctx->nr_user_files = 0;
7218 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7219 __releases(&sqd->lock)
7221 WARN_ON_ONCE(sqd->thread == current);
7224 * Do the dance but not conditional clear_bit() because it'd race with
7225 * other threads incrementing park_pending and setting the bit.
7227 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7228 if (atomic_dec_return(&sqd->park_pending))
7229 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7230 mutex_unlock(&sqd->lock);
7233 static void io_sq_thread_park(struct io_sq_data *sqd)
7234 __acquires(&sqd->lock)
7236 WARN_ON_ONCE(sqd->thread == current);
7238 atomic_inc(&sqd->park_pending);
7239 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7240 mutex_lock(&sqd->lock);
7242 wake_up_process(sqd->thread);
7245 static void io_sq_thread_stop(struct io_sq_data *sqd)
7247 WARN_ON_ONCE(sqd->thread == current);
7249 mutex_lock(&sqd->lock);
7250 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7252 wake_up_process(sqd->thread);
7253 mutex_unlock(&sqd->lock);
7254 wait_for_completion(&sqd->exited);
7257 static void io_put_sq_data(struct io_sq_data *sqd)
7259 if (refcount_dec_and_test(&sqd->refs)) {
7260 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7262 io_sq_thread_stop(sqd);
7267 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7269 struct io_sq_data *sqd = ctx->sq_data;
7272 io_sq_thread_park(sqd);
7273 list_del_init(&ctx->sqd_list);
7274 io_sqd_update_thread_idle(sqd);
7275 io_sq_thread_unpark(sqd);
7277 io_put_sq_data(sqd);
7278 ctx->sq_data = NULL;
7280 put_cred(ctx->sq_creds);
7284 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7286 struct io_ring_ctx *ctx_attach;
7287 struct io_sq_data *sqd;
7290 f = fdget(p->wq_fd);
7292 return ERR_PTR(-ENXIO);
7293 if (f.file->f_op != &io_uring_fops) {
7295 return ERR_PTR(-EINVAL);
7298 ctx_attach = f.file->private_data;
7299 sqd = ctx_attach->sq_data;
7302 return ERR_PTR(-EINVAL);
7304 if (sqd->task_tgid != current->tgid) {
7306 return ERR_PTR(-EPERM);
7309 refcount_inc(&sqd->refs);
7314 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7317 struct io_sq_data *sqd;
7320 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7321 sqd = io_attach_sq_data(p);
7326 /* fall through for EPERM case, setup new sqd/task */
7327 if (PTR_ERR(sqd) != -EPERM)
7331 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7333 return ERR_PTR(-ENOMEM);
7335 atomic_set(&sqd->park_pending, 0);
7336 refcount_set(&sqd->refs, 1);
7337 INIT_LIST_HEAD(&sqd->ctx_list);
7338 mutex_init(&sqd->lock);
7339 init_waitqueue_head(&sqd->wait);
7340 init_completion(&sqd->exited);
7344 #if defined(CONFIG_UNIX)
7346 * Ensure the UNIX gc is aware of our file set, so we are certain that
7347 * the io_uring can be safely unregistered on process exit, even if we have
7348 * loops in the file referencing.
7350 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7352 struct sock *sk = ctx->ring_sock->sk;
7353 struct scm_fp_list *fpl;
7354 struct sk_buff *skb;
7357 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7361 skb = alloc_skb(0, GFP_KERNEL);
7370 fpl->user = get_uid(current_user());
7371 for (i = 0; i < nr; i++) {
7372 struct file *file = io_file_from_index(ctx, i + offset);
7376 fpl->fp[nr_files] = get_file(file);
7377 unix_inflight(fpl->user, fpl->fp[nr_files]);
7382 fpl->max = SCM_MAX_FD;
7383 fpl->count = nr_files;
7384 UNIXCB(skb).fp = fpl;
7385 skb->destructor = unix_destruct_scm;
7386 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7387 skb_queue_head(&sk->sk_receive_queue, skb);
7389 for (i = 0; i < nr_files; i++)
7400 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7401 * causes regular reference counting to break down. We rely on the UNIX
7402 * garbage collection to take care of this problem for us.
7404 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7406 unsigned left, total;
7410 left = ctx->nr_user_files;
7412 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7414 ret = __io_sqe_files_scm(ctx, this_files, total);
7418 total += this_files;
7424 while (total < ctx->nr_user_files) {
7425 struct file *file = io_file_from_index(ctx, total);
7435 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7441 static int io_sqe_alloc_file_tables(struct io_rsrc_data *file_data,
7442 unsigned nr_tables, unsigned nr_files)
7446 for (i = 0; i < nr_tables; i++) {
7447 struct fixed_rsrc_table *table = &file_data->table[i];
7448 unsigned this_files;
7450 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7451 table->files = kcalloc(this_files, sizeof(struct file *),
7455 nr_files -= this_files;
7461 for (i = 0; i < nr_tables; i++) {
7462 struct fixed_rsrc_table *table = &file_data->table[i];
7463 kfree(table->files);
7468 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7470 struct file *file = prsrc->file;
7471 #if defined(CONFIG_UNIX)
7472 struct sock *sock = ctx->ring_sock->sk;
7473 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7474 struct sk_buff *skb;
7477 __skb_queue_head_init(&list);
7480 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7481 * remove this entry and rearrange the file array.
7483 skb = skb_dequeue(head);
7485 struct scm_fp_list *fp;
7487 fp = UNIXCB(skb).fp;
7488 for (i = 0; i < fp->count; i++) {
7491 if (fp->fp[i] != file)
7494 unix_notinflight(fp->user, fp->fp[i]);
7495 left = fp->count - 1 - i;
7497 memmove(&fp->fp[i], &fp->fp[i + 1],
7498 left * sizeof(struct file *));
7505 __skb_queue_tail(&list, skb);
7515 __skb_queue_tail(&list, skb);
7517 skb = skb_dequeue(head);
7520 if (skb_peek(&list)) {
7521 spin_lock_irq(&head->lock);
7522 while ((skb = __skb_dequeue(&list)) != NULL)
7523 __skb_queue_tail(head, skb);
7524 spin_unlock_irq(&head->lock);
7531 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7533 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7534 struct io_ring_ctx *ctx = rsrc_data->ctx;
7535 struct io_rsrc_put *prsrc, *tmp;
7537 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7538 list_del(&prsrc->list);
7539 rsrc_data->do_put(ctx, prsrc);
7543 io_rsrc_node_destroy(ref_node);
7544 percpu_ref_put(&rsrc_data->refs);
7547 static void io_rsrc_put_work(struct work_struct *work)
7549 struct io_ring_ctx *ctx;
7550 struct llist_node *node;
7552 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7553 node = llist_del_all(&ctx->rsrc_put_llist);
7556 struct io_rsrc_node *ref_node;
7557 struct llist_node *next = node->next;
7559 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7560 __io_rsrc_put_work(ref_node);
7565 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7567 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7568 struct io_rsrc_data *data = node->rsrc_data;
7569 struct io_ring_ctx *ctx = data->ctx;
7570 bool first_add = false;
7573 io_rsrc_ref_lock(ctx);
7576 while (!list_empty(&ctx->rsrc_ref_list)) {
7577 node = list_first_entry(&ctx->rsrc_ref_list,
7578 struct io_rsrc_node, node);
7579 /* recycle ref nodes in order */
7582 list_del(&node->node);
7583 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7585 io_rsrc_ref_unlock(ctx);
7587 delay = percpu_ref_is_dying(&data->refs) ? 0 : HZ;
7588 if (first_add || !delay)
7589 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7592 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7594 struct io_rsrc_node *ref_node;
7596 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7600 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7605 INIT_LIST_HEAD(&ref_node->node);
7606 INIT_LIST_HEAD(&ref_node->rsrc_list);
7607 ref_node->done = false;
7611 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7614 __s32 __user *fds = (__s32 __user *) arg;
7615 unsigned nr_tables, i;
7618 struct io_rsrc_data *file_data;
7624 if (nr_args > IORING_MAX_FIXED_FILES)
7626 ret = io_rsrc_node_switch_start(ctx);
7630 file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put);
7633 ctx->file_data = file_data;
7636 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7637 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7639 if (!file_data->table)
7642 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7645 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7646 unsigned long file_ptr;
7648 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7652 /* allow sparse sets */
7662 * Don't allow io_uring instances to be registered. If UNIX
7663 * isn't enabled, then this causes a reference cycle and this
7664 * instance can never get freed. If UNIX is enabled we'll
7665 * handle it just fine, but there's still no point in allowing
7666 * a ring fd as it doesn't support regular read/write anyway.
7668 if (file->f_op == &io_uring_fops) {
7672 file_ptr = (unsigned long) file;
7673 if (__io_file_supports_async(file, READ))
7674 file_ptr |= FFS_ASYNC_READ;
7675 if (__io_file_supports_async(file, WRITE))
7676 file_ptr |= FFS_ASYNC_WRITE;
7677 if (S_ISREG(file_inode(file)->i_mode))
7678 file_ptr |= FFS_ISREG;
7679 *io_fixed_file_slot(file_data, i) = (struct file *) file_ptr;
7682 ret = io_sqe_files_scm(ctx);
7684 io_sqe_files_unregister(ctx);
7688 io_rsrc_node_switch(ctx, NULL);
7691 for (i = 0; i < ctx->nr_user_files; i++) {
7692 file = io_file_from_index(ctx, i);
7696 for (i = 0; i < nr_tables; i++)
7697 kfree(file_data->table[i].files);
7698 ctx->nr_user_files = 0;
7700 io_rsrc_data_free(ctx->file_data);
7701 ctx->file_data = NULL;
7705 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7708 #if defined(CONFIG_UNIX)
7709 struct sock *sock = ctx->ring_sock->sk;
7710 struct sk_buff_head *head = &sock->sk_receive_queue;
7711 struct sk_buff *skb;
7714 * See if we can merge this file into an existing skb SCM_RIGHTS
7715 * file set. If there's no room, fall back to allocating a new skb
7716 * and filling it in.
7718 spin_lock_irq(&head->lock);
7719 skb = skb_peek(head);
7721 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7723 if (fpl->count < SCM_MAX_FD) {
7724 __skb_unlink(skb, head);
7725 spin_unlock_irq(&head->lock);
7726 fpl->fp[fpl->count] = get_file(file);
7727 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7729 spin_lock_irq(&head->lock);
7730 __skb_queue_head(head, skb);
7735 spin_unlock_irq(&head->lock);
7742 return __io_sqe_files_scm(ctx, 1, index);
7748 static int io_queue_rsrc_removal(struct io_rsrc_data *data,
7749 struct io_rsrc_node *node, void *rsrc)
7751 struct io_rsrc_put *prsrc;
7753 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7758 list_add(&prsrc->list, &node->rsrc_list);
7762 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7763 struct io_uring_rsrc_update *up,
7766 struct io_rsrc_data *data = ctx->file_data;
7767 struct file *file, **file_slot;
7771 bool needs_switch = false;
7773 if (check_add_overflow(up->offset, nr_args, &done))
7775 if (done > ctx->nr_user_files)
7777 err = io_rsrc_node_switch_start(ctx);
7781 fds = u64_to_user_ptr(up->data);
7782 for (done = 0; done < nr_args; done++) {
7784 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7788 if (fd == IORING_REGISTER_FILES_SKIP)
7791 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7792 file_slot = io_fixed_file_slot(ctx->file_data, i);
7795 file = (struct file *) ((unsigned long) *file_slot & FFS_MASK);
7796 err = io_queue_rsrc_removal(data, ctx->rsrc_node, file);
7800 needs_switch = true;
7809 * Don't allow io_uring instances to be registered. If
7810 * UNIX isn't enabled, then this causes a reference
7811 * cycle and this instance can never get freed. If UNIX
7812 * is enabled we'll handle it just fine, but there's
7813 * still no point in allowing a ring fd as it doesn't
7814 * support regular read/write anyway.
7816 if (file->f_op == &io_uring_fops) {
7822 err = io_sqe_file_register(ctx, file, i);
7832 io_rsrc_node_switch(ctx, data);
7833 return done ? done : err;
7836 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7839 struct io_uring_rsrc_update up;
7841 if (!ctx->file_data)
7845 if (copy_from_user(&up, arg, sizeof(up)))
7850 return __io_sqe_files_update(ctx, &up, nr_args);
7853 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7855 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7857 req = io_put_req_find_next(req);
7858 return req ? &req->work : NULL;
7861 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7862 struct task_struct *task)
7864 struct io_wq_hash *hash;
7865 struct io_wq_data data;
7866 unsigned int concurrency;
7868 hash = ctx->hash_map;
7870 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7872 return ERR_PTR(-ENOMEM);
7873 refcount_set(&hash->refs, 1);
7874 init_waitqueue_head(&hash->wait);
7875 ctx->hash_map = hash;
7880 data.free_work = io_free_work;
7881 data.do_work = io_wq_submit_work;
7883 /* Do QD, or 4 * CPUS, whatever is smallest */
7884 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7886 return io_wq_create(concurrency, &data);
7889 static int io_uring_alloc_task_context(struct task_struct *task,
7890 struct io_ring_ctx *ctx)
7892 struct io_uring_task *tctx;
7895 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7896 if (unlikely(!tctx))
7899 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7900 if (unlikely(ret)) {
7905 tctx->io_wq = io_init_wq_offload(ctx, task);
7906 if (IS_ERR(tctx->io_wq)) {
7907 ret = PTR_ERR(tctx->io_wq);
7908 percpu_counter_destroy(&tctx->inflight);
7914 init_waitqueue_head(&tctx->wait);
7916 atomic_set(&tctx->in_idle, 0);
7917 task->io_uring = tctx;
7918 spin_lock_init(&tctx->task_lock);
7919 INIT_WQ_LIST(&tctx->task_list);
7920 tctx->task_state = 0;
7921 init_task_work(&tctx->task_work, tctx_task_work);
7925 void __io_uring_free(struct task_struct *tsk)
7927 struct io_uring_task *tctx = tsk->io_uring;
7929 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7930 WARN_ON_ONCE(tctx->io_wq);
7932 percpu_counter_destroy(&tctx->inflight);
7934 tsk->io_uring = NULL;
7937 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7938 struct io_uring_params *p)
7942 /* Retain compatibility with failing for an invalid attach attempt */
7943 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7944 IORING_SETUP_ATTACH_WQ) {
7947 f = fdget(p->wq_fd);
7950 if (f.file->f_op != &io_uring_fops) {
7956 if (ctx->flags & IORING_SETUP_SQPOLL) {
7957 struct task_struct *tsk;
7958 struct io_sq_data *sqd;
7961 sqd = io_get_sq_data(p, &attached);
7967 ctx->sq_creds = get_current_cred();
7969 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7970 if (!ctx->sq_thread_idle)
7971 ctx->sq_thread_idle = HZ;
7974 io_sq_thread_park(sqd);
7975 list_add(&ctx->sqd_list, &sqd->ctx_list);
7976 io_sqd_update_thread_idle(sqd);
7977 /* don't attach to a dying SQPOLL thread, would be racy */
7978 if (attached && !sqd->thread)
7980 io_sq_thread_unpark(sqd);
7987 if (p->flags & IORING_SETUP_SQ_AFF) {
7988 int cpu = p->sq_thread_cpu;
7991 if (cpu >= nr_cpu_ids)
7993 if (!cpu_online(cpu))
8001 sqd->task_pid = current->pid;
8002 sqd->task_tgid = current->tgid;
8003 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
8010 ret = io_uring_alloc_task_context(tsk, ctx);
8011 wake_up_new_task(tsk);
8014 } else if (p->flags & IORING_SETUP_SQ_AFF) {
8015 /* Can't have SQ_AFF without SQPOLL */
8022 io_sq_thread_finish(ctx);
8025 complete(&ctx->sq_data->exited);
8029 static inline void __io_unaccount_mem(struct user_struct *user,
8030 unsigned long nr_pages)
8032 atomic_long_sub(nr_pages, &user->locked_vm);
8035 static inline int __io_account_mem(struct user_struct *user,
8036 unsigned long nr_pages)
8038 unsigned long page_limit, cur_pages, new_pages;
8040 /* Don't allow more pages than we can safely lock */
8041 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8044 cur_pages = atomic_long_read(&user->locked_vm);
8045 new_pages = cur_pages + nr_pages;
8046 if (new_pages > page_limit)
8048 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8049 new_pages) != cur_pages);
8054 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8057 __io_unaccount_mem(ctx->user, nr_pages);
8059 if (ctx->mm_account)
8060 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8063 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8068 ret = __io_account_mem(ctx->user, nr_pages);
8073 if (ctx->mm_account)
8074 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8079 static void io_mem_free(void *ptr)
8086 page = virt_to_head_page(ptr);
8087 if (put_page_testzero(page))
8088 free_compound_page(page);
8091 static void *io_mem_alloc(size_t size)
8093 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8094 __GFP_NORETRY | __GFP_ACCOUNT;
8096 return (void *) __get_free_pages(gfp_flags, get_order(size));
8099 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8102 struct io_rings *rings;
8103 size_t off, sq_array_size;
8105 off = struct_size(rings, cqes, cq_entries);
8106 if (off == SIZE_MAX)
8110 off = ALIGN(off, SMP_CACHE_BYTES);
8118 sq_array_size = array_size(sizeof(u32), sq_entries);
8119 if (sq_array_size == SIZE_MAX)
8122 if (check_add_overflow(off, sq_array_size, &off))
8128 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8132 if (!ctx->user_bufs)
8135 for (i = 0; i < ctx->nr_user_bufs; i++) {
8136 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8138 for (j = 0; j < imu->nr_bvecs; j++)
8139 unpin_user_page(imu->bvec[j].bv_page);
8141 if (imu->acct_pages)
8142 io_unaccount_mem(ctx, imu->acct_pages);
8147 kfree(ctx->user_bufs);
8148 ctx->user_bufs = NULL;
8149 ctx->nr_user_bufs = 0;
8153 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8154 void __user *arg, unsigned index)
8156 struct iovec __user *src;
8158 #ifdef CONFIG_COMPAT
8160 struct compat_iovec __user *ciovs;
8161 struct compat_iovec ciov;
8163 ciovs = (struct compat_iovec __user *) arg;
8164 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8167 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8168 dst->iov_len = ciov.iov_len;
8172 src = (struct iovec __user *) arg;
8173 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8179 * Not super efficient, but this is just a registration time. And we do cache
8180 * the last compound head, so generally we'll only do a full search if we don't
8183 * We check if the given compound head page has already been accounted, to
8184 * avoid double accounting it. This allows us to account the full size of the
8185 * page, not just the constituent pages of a huge page.
8187 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8188 int nr_pages, struct page *hpage)
8192 /* check current page array */
8193 for (i = 0; i < nr_pages; i++) {
8194 if (!PageCompound(pages[i]))
8196 if (compound_head(pages[i]) == hpage)
8200 /* check previously registered pages */
8201 for (i = 0; i < ctx->nr_user_bufs; i++) {
8202 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8204 for (j = 0; j < imu->nr_bvecs; j++) {
8205 if (!PageCompound(imu->bvec[j].bv_page))
8207 if (compound_head(imu->bvec[j].bv_page) == hpage)
8215 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8216 int nr_pages, struct io_mapped_ubuf *imu,
8217 struct page **last_hpage)
8221 for (i = 0; i < nr_pages; i++) {
8222 if (!PageCompound(pages[i])) {
8227 hpage = compound_head(pages[i]);
8228 if (hpage == *last_hpage)
8230 *last_hpage = hpage;
8231 if (headpage_already_acct(ctx, pages, i, hpage))
8233 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8237 if (!imu->acct_pages)
8240 ret = io_account_mem(ctx, imu->acct_pages);
8242 imu->acct_pages = 0;
8246 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8247 struct io_mapped_ubuf *imu,
8248 struct page **last_hpage)
8250 struct vm_area_struct **vmas = NULL;
8251 struct page **pages = NULL;
8252 unsigned long off, start, end, ubuf;
8254 int ret, pret, nr_pages, i;
8256 ubuf = (unsigned long) iov->iov_base;
8257 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8258 start = ubuf >> PAGE_SHIFT;
8259 nr_pages = end - start;
8263 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8267 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8272 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8278 mmap_read_lock(current->mm);
8279 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8281 if (pret == nr_pages) {
8282 /* don't support file backed memory */
8283 for (i = 0; i < nr_pages; i++) {
8284 struct vm_area_struct *vma = vmas[i];
8287 !is_file_hugepages(vma->vm_file)) {
8293 ret = pret < 0 ? pret : -EFAULT;
8295 mmap_read_unlock(current->mm);
8298 * if we did partial map, or found file backed vmas,
8299 * release any pages we did get
8302 unpin_user_pages(pages, pret);
8307 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8309 unpin_user_pages(pages, pret);
8314 off = ubuf & ~PAGE_MASK;
8315 size = iov->iov_len;
8316 for (i = 0; i < nr_pages; i++) {
8319 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8320 imu->bvec[i].bv_page = pages[i];
8321 imu->bvec[i].bv_len = vec_len;
8322 imu->bvec[i].bv_offset = off;
8326 /* store original address for later verification */
8328 imu->ubuf_end = ubuf + iov->iov_len;
8329 imu->nr_bvecs = nr_pages;
8337 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8341 if (!nr_args || nr_args > UIO_MAXIOV)
8344 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8346 if (!ctx->user_bufs)
8352 static int io_buffer_validate(struct iovec *iov)
8354 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8357 * Don't impose further limits on the size and buffer
8358 * constraints here, we'll -EINVAL later when IO is
8359 * submitted if they are wrong.
8361 if (!iov->iov_base || !iov->iov_len)
8364 /* arbitrary limit, but we need something */
8365 if (iov->iov_len > SZ_1G)
8368 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8374 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8375 unsigned int nr_args)
8379 struct page *last_hpage = NULL;
8381 ret = io_buffers_map_alloc(ctx, nr_args);
8385 for (i = 0; i < nr_args; i++) {
8386 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8388 ret = io_copy_iov(ctx, &iov, arg, i);
8392 ret = io_buffer_validate(&iov);
8396 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8400 ctx->nr_user_bufs++;
8404 io_sqe_buffers_unregister(ctx);
8409 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8411 __s32 __user *fds = arg;
8417 if (copy_from_user(&fd, fds, sizeof(*fds)))
8420 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8421 if (IS_ERR(ctx->cq_ev_fd)) {
8422 int ret = PTR_ERR(ctx->cq_ev_fd);
8423 ctx->cq_ev_fd = NULL;
8430 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8432 if (ctx->cq_ev_fd) {
8433 eventfd_ctx_put(ctx->cq_ev_fd);
8434 ctx->cq_ev_fd = NULL;
8441 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8443 struct io_buffer *buf;
8444 unsigned long index;
8446 xa_for_each(&ctx->io_buffers, index, buf)
8447 __io_remove_buffers(ctx, buf, index, -1U);
8450 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8452 struct io_kiocb *req, *nxt;
8454 list_for_each_entry_safe(req, nxt, list, compl.list) {
8455 if (tsk && req->task != tsk)
8457 list_del(&req->compl.list);
8458 kmem_cache_free(req_cachep, req);
8462 static void io_req_caches_free(struct io_ring_ctx *ctx)
8464 struct io_submit_state *submit_state = &ctx->submit_state;
8465 struct io_comp_state *cs = &ctx->submit_state.comp;
8467 mutex_lock(&ctx->uring_lock);
8469 if (submit_state->free_reqs) {
8470 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8471 submit_state->reqs);
8472 submit_state->free_reqs = 0;
8475 io_flush_cached_locked_reqs(ctx, cs);
8476 io_req_cache_free(&cs->free_list, NULL);
8477 mutex_unlock(&ctx->uring_lock);
8480 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8482 io_sq_thread_finish(ctx);
8483 io_sqe_buffers_unregister(ctx);
8485 if (ctx->mm_account) {
8486 mmdrop(ctx->mm_account);
8487 ctx->mm_account = NULL;
8490 mutex_lock(&ctx->uring_lock);
8491 io_sqe_files_unregister(ctx);
8493 __io_cqring_overflow_flush(ctx, true);
8494 mutex_unlock(&ctx->uring_lock);
8495 io_eventfd_unregister(ctx);
8496 io_destroy_buffers(ctx);
8498 /* there are no registered resources left, nobody uses it */
8500 io_rsrc_node_destroy(ctx->rsrc_node);
8501 if (ctx->rsrc_backup_node)
8502 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8503 flush_delayed_work(&ctx->rsrc_put_work);
8505 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8506 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8508 #if defined(CONFIG_UNIX)
8509 if (ctx->ring_sock) {
8510 ctx->ring_sock->file = NULL; /* so that iput() is called */
8511 sock_release(ctx->ring_sock);
8515 io_mem_free(ctx->rings);
8516 io_mem_free(ctx->sq_sqes);
8518 percpu_ref_exit(&ctx->refs);
8519 free_uid(ctx->user);
8520 io_req_caches_free(ctx);
8522 io_wq_put_hash(ctx->hash_map);
8523 kfree(ctx->cancel_hash);
8527 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8529 struct io_ring_ctx *ctx = file->private_data;
8532 poll_wait(file, &ctx->cq_wait, wait);
8534 * synchronizes with barrier from wq_has_sleeper call in
8538 if (!io_sqring_full(ctx))
8539 mask |= EPOLLOUT | EPOLLWRNORM;
8542 * Don't flush cqring overflow list here, just do a simple check.
8543 * Otherwise there could possible be ABBA deadlock:
8546 * lock(&ctx->uring_lock);
8548 * lock(&ctx->uring_lock);
8551 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8552 * pushs them to do the flush.
8554 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8555 mask |= EPOLLIN | EPOLLRDNORM;
8560 static int io_uring_fasync(int fd, struct file *file, int on)
8562 struct io_ring_ctx *ctx = file->private_data;
8564 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8567 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8569 const struct cred *creds;
8571 creds = xa_erase(&ctx->personalities, id);
8580 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8582 return io_run_task_work_head(&ctx->exit_task_work);
8585 struct io_tctx_exit {
8586 struct callback_head task_work;
8587 struct completion completion;
8588 struct io_ring_ctx *ctx;
8591 static void io_tctx_exit_cb(struct callback_head *cb)
8593 struct io_uring_task *tctx = current->io_uring;
8594 struct io_tctx_exit *work;
8596 work = container_of(cb, struct io_tctx_exit, task_work);
8598 * When @in_idle, we're in cancellation and it's racy to remove the
8599 * node. It'll be removed by the end of cancellation, just ignore it.
8601 if (!atomic_read(&tctx->in_idle))
8602 io_uring_del_task_file((unsigned long)work->ctx);
8603 complete(&work->completion);
8606 static void io_ring_exit_work(struct work_struct *work)
8608 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8609 unsigned long timeout = jiffies + HZ * 60 * 5;
8610 struct io_tctx_exit exit;
8611 struct io_tctx_node *node;
8614 /* prevent SQPOLL from submitting new requests */
8616 io_sq_thread_park(ctx->sq_data);
8617 list_del_init(&ctx->sqd_list);
8618 io_sqd_update_thread_idle(ctx->sq_data);
8619 io_sq_thread_unpark(ctx->sq_data);
8623 * If we're doing polled IO and end up having requests being
8624 * submitted async (out-of-line), then completions can come in while
8625 * we're waiting for refs to drop. We need to reap these manually,
8626 * as nobody else will be looking for them.
8629 io_uring_try_cancel_requests(ctx, NULL, NULL);
8631 WARN_ON_ONCE(time_after(jiffies, timeout));
8632 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8635 * Some may use context even when all refs and requests have been put,
8636 * and they are free to do so while still holding uring_lock or
8637 * completion_lock, see __io_req_task_submit(). Apart from other work,
8638 * this lock/unlock section also waits them to finish.
8640 mutex_lock(&ctx->uring_lock);
8641 while (!list_empty(&ctx->tctx_list)) {
8642 WARN_ON_ONCE(time_after(jiffies, timeout));
8644 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8647 init_completion(&exit.completion);
8648 init_task_work(&exit.task_work, io_tctx_exit_cb);
8649 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8650 if (WARN_ON_ONCE(ret))
8652 wake_up_process(node->task);
8654 mutex_unlock(&ctx->uring_lock);
8655 wait_for_completion(&exit.completion);
8657 mutex_lock(&ctx->uring_lock);
8659 mutex_unlock(&ctx->uring_lock);
8660 spin_lock_irq(&ctx->completion_lock);
8661 spin_unlock_irq(&ctx->completion_lock);
8663 io_ring_ctx_free(ctx);
8666 /* Returns true if we found and killed one or more timeouts */
8667 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8668 struct files_struct *files)
8670 struct io_kiocb *req, *tmp;
8673 spin_lock_irq(&ctx->completion_lock);
8674 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8675 if (io_match_task(req, tsk, files)) {
8676 io_kill_timeout(req, -ECANCELED);
8681 io_commit_cqring(ctx);
8682 spin_unlock_irq(&ctx->completion_lock);
8684 io_cqring_ev_posted(ctx);
8685 return canceled != 0;
8688 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8690 unsigned long index;
8691 struct creds *creds;
8693 mutex_lock(&ctx->uring_lock);
8694 percpu_ref_kill(&ctx->refs);
8696 __io_cqring_overflow_flush(ctx, true);
8697 xa_for_each(&ctx->personalities, index, creds)
8698 io_unregister_personality(ctx, index);
8699 mutex_unlock(&ctx->uring_lock);
8701 io_kill_timeouts(ctx, NULL, NULL);
8702 io_poll_remove_all(ctx, NULL, NULL);
8704 /* if we failed setting up the ctx, we might not have any rings */
8705 io_iopoll_try_reap_events(ctx);
8707 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8709 * Use system_unbound_wq to avoid spawning tons of event kworkers
8710 * if we're exiting a ton of rings at the same time. It just adds
8711 * noise and overhead, there's no discernable change in runtime
8712 * over using system_wq.
8714 queue_work(system_unbound_wq, &ctx->exit_work);
8717 static int io_uring_release(struct inode *inode, struct file *file)
8719 struct io_ring_ctx *ctx = file->private_data;
8721 file->private_data = NULL;
8722 io_ring_ctx_wait_and_kill(ctx);
8726 struct io_task_cancel {
8727 struct task_struct *task;
8728 struct files_struct *files;
8731 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8733 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8734 struct io_task_cancel *cancel = data;
8737 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8738 unsigned long flags;
8739 struct io_ring_ctx *ctx = req->ctx;
8741 /* protect against races with linked timeouts */
8742 spin_lock_irqsave(&ctx->completion_lock, flags);
8743 ret = io_match_task(req, cancel->task, cancel->files);
8744 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8746 ret = io_match_task(req, cancel->task, cancel->files);
8751 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8752 struct task_struct *task,
8753 struct files_struct *files)
8755 struct io_defer_entry *de;
8758 spin_lock_irq(&ctx->completion_lock);
8759 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8760 if (io_match_task(de->req, task, files)) {
8761 list_cut_position(&list, &ctx->defer_list, &de->list);
8765 spin_unlock_irq(&ctx->completion_lock);
8766 if (list_empty(&list))
8769 while (!list_empty(&list)) {
8770 de = list_first_entry(&list, struct io_defer_entry, list);
8771 list_del_init(&de->list);
8772 io_req_complete_failed(de->req, -ECANCELED);
8778 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8780 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8782 return req->ctx == data;
8785 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8787 struct io_tctx_node *node;
8788 enum io_wq_cancel cret;
8791 mutex_lock(&ctx->uring_lock);
8792 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8793 struct io_uring_task *tctx = node->task->io_uring;
8796 * io_wq will stay alive while we hold uring_lock, because it's
8797 * killed after ctx nodes, which requires to take the lock.
8799 if (!tctx || !tctx->io_wq)
8801 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8802 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8804 mutex_unlock(&ctx->uring_lock);
8809 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8810 struct task_struct *task,
8811 struct files_struct *files)
8813 struct io_task_cancel cancel = { .task = task, .files = files, };
8814 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8817 enum io_wq_cancel cret;
8821 ret |= io_uring_try_cancel_iowq(ctx);
8822 } else if (tctx && tctx->io_wq) {
8824 * Cancels requests of all rings, not only @ctx, but
8825 * it's fine as the task is in exit/exec.
8827 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8829 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8832 /* SQPOLL thread does its own polling */
8833 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8834 (ctx->sq_data && ctx->sq_data->thread == current)) {
8835 while (!list_empty_careful(&ctx->iopoll_list)) {
8836 io_iopoll_try_reap_events(ctx);
8841 ret |= io_cancel_defer_files(ctx, task, files);
8842 ret |= io_poll_remove_all(ctx, task, files);
8843 ret |= io_kill_timeouts(ctx, task, files);
8844 ret |= io_run_task_work();
8845 ret |= io_run_ctx_fallback(ctx);
8852 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8853 struct task_struct *task,
8854 struct files_struct *files)
8856 struct io_kiocb *req;
8859 spin_lock_irq(&ctx->inflight_lock);
8860 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8861 cnt += io_match_task(req, task, files);
8862 spin_unlock_irq(&ctx->inflight_lock);
8866 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8867 struct task_struct *task,
8868 struct files_struct *files)
8870 while (!list_empty_careful(&ctx->inflight_list)) {
8874 inflight = io_uring_count_inflight(ctx, task, files);
8878 io_uring_try_cancel_requests(ctx, task, files);
8880 prepare_to_wait(&task->io_uring->wait, &wait,
8881 TASK_UNINTERRUPTIBLE);
8882 if (inflight == io_uring_count_inflight(ctx, task, files))
8884 finish_wait(&task->io_uring->wait, &wait);
8888 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8890 struct io_uring_task *tctx = current->io_uring;
8891 struct io_tctx_node *node;
8894 if (unlikely(!tctx)) {
8895 ret = io_uring_alloc_task_context(current, ctx);
8898 tctx = current->io_uring;
8900 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8901 node = kmalloc(sizeof(*node), GFP_KERNEL);
8905 node->task = current;
8907 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8914 mutex_lock(&ctx->uring_lock);
8915 list_add(&node->ctx_node, &ctx->tctx_list);
8916 mutex_unlock(&ctx->uring_lock);
8923 * Note that this task has used io_uring. We use it for cancelation purposes.
8925 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8927 struct io_uring_task *tctx = current->io_uring;
8929 if (likely(tctx && tctx->last == ctx))
8931 return __io_uring_add_task_file(ctx);
8935 * Remove this io_uring_file -> task mapping.
8937 static void io_uring_del_task_file(unsigned long index)
8939 struct io_uring_task *tctx = current->io_uring;
8940 struct io_tctx_node *node;
8944 node = xa_erase(&tctx->xa, index);
8948 WARN_ON_ONCE(current != node->task);
8949 WARN_ON_ONCE(list_empty(&node->ctx_node));
8951 mutex_lock(&node->ctx->uring_lock);
8952 list_del(&node->ctx_node);
8953 mutex_unlock(&node->ctx->uring_lock);
8955 if (tctx->last == node->ctx)
8960 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8962 struct io_tctx_node *node;
8963 unsigned long index;
8965 xa_for_each(&tctx->xa, index, node)
8966 io_uring_del_task_file(index);
8968 io_wq_put_and_exit(tctx->io_wq);
8973 static s64 tctx_inflight(struct io_uring_task *tctx)
8975 return percpu_counter_sum(&tctx->inflight);
8978 static void io_sqpoll_cancel_cb(struct callback_head *cb)
8980 struct io_tctx_exit *work = container_of(cb, struct io_tctx_exit, task_work);
8981 struct io_ring_ctx *ctx = work->ctx;
8982 struct io_sq_data *sqd = ctx->sq_data;
8985 io_uring_cancel_sqpoll(ctx);
8986 complete(&work->completion);
8989 static void io_sqpoll_cancel_sync(struct io_ring_ctx *ctx)
8991 struct io_sq_data *sqd = ctx->sq_data;
8992 struct io_tctx_exit work = { .ctx = ctx, };
8993 struct task_struct *task;
8995 io_sq_thread_park(sqd);
8996 list_del_init(&ctx->sqd_list);
8997 io_sqd_update_thread_idle(sqd);
9000 init_completion(&work.completion);
9001 init_task_work(&work.task_work, io_sqpoll_cancel_cb);
9002 io_task_work_add_head(&sqd->park_task_work, &work.task_work);
9003 wake_up_process(task);
9005 io_sq_thread_unpark(sqd);
9008 wait_for_completion(&work.completion);
9011 void __io_uring_files_cancel(struct files_struct *files)
9013 struct io_uring_task *tctx = current->io_uring;
9014 struct io_tctx_node *node;
9015 unsigned long index;
9017 /* make sure overflow events are dropped */
9018 atomic_inc(&tctx->in_idle);
9019 xa_for_each(&tctx->xa, index, node) {
9020 struct io_ring_ctx *ctx = node->ctx;
9023 io_sqpoll_cancel_sync(ctx);
9026 io_uring_cancel_files(ctx, current, files);
9028 io_uring_try_cancel_requests(ctx, current, NULL);
9030 atomic_dec(&tctx->in_idle);
9033 io_uring_clean_tctx(tctx);
9036 /* should only be called by SQPOLL task */
9037 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9039 struct io_sq_data *sqd = ctx->sq_data;
9040 struct io_uring_task *tctx = current->io_uring;
9044 WARN_ON_ONCE(!sqd || ctx->sq_data->thread != current);
9046 atomic_inc(&tctx->in_idle);
9048 /* read completions before cancelations */
9049 inflight = tctx_inflight(tctx);
9052 io_uring_try_cancel_requests(ctx, current, NULL);
9054 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9056 * If we've seen completions, retry without waiting. This
9057 * avoids a race where a completion comes in before we did
9058 * prepare_to_wait().
9060 if (inflight == tctx_inflight(tctx))
9062 finish_wait(&tctx->wait, &wait);
9064 atomic_dec(&tctx->in_idle);
9068 * Find any io_uring fd that this task has registered or done IO on, and cancel
9071 void __io_uring_task_cancel(void)
9073 struct io_uring_task *tctx = current->io_uring;
9077 /* make sure overflow events are dropped */
9078 atomic_inc(&tctx->in_idle);
9079 __io_uring_files_cancel(NULL);
9082 /* read completions before cancelations */
9083 inflight = tctx_inflight(tctx);
9086 __io_uring_files_cancel(NULL);
9088 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9091 * If we've seen completions, retry without waiting. This
9092 * avoids a race where a completion comes in before we did
9093 * prepare_to_wait().
9095 if (inflight == tctx_inflight(tctx))
9097 finish_wait(&tctx->wait, &wait);
9100 atomic_dec(&tctx->in_idle);
9102 io_uring_clean_tctx(tctx);
9103 /* all current's requests should be gone, we can kill tctx */
9104 __io_uring_free(current);
9107 static void *io_uring_validate_mmap_request(struct file *file,
9108 loff_t pgoff, size_t sz)
9110 struct io_ring_ctx *ctx = file->private_data;
9111 loff_t offset = pgoff << PAGE_SHIFT;
9116 case IORING_OFF_SQ_RING:
9117 case IORING_OFF_CQ_RING:
9120 case IORING_OFF_SQES:
9124 return ERR_PTR(-EINVAL);
9127 page = virt_to_head_page(ptr);
9128 if (sz > page_size(page))
9129 return ERR_PTR(-EINVAL);
9136 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9138 size_t sz = vma->vm_end - vma->vm_start;
9142 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9144 return PTR_ERR(ptr);
9146 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9147 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9150 #else /* !CONFIG_MMU */
9152 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9154 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9157 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9159 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9162 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9163 unsigned long addr, unsigned long len,
9164 unsigned long pgoff, unsigned long flags)
9168 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9170 return PTR_ERR(ptr);
9172 return (unsigned long) ptr;
9175 #endif /* !CONFIG_MMU */
9177 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9182 if (!io_sqring_full(ctx))
9184 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9186 if (!io_sqring_full(ctx))
9189 } while (!signal_pending(current));
9191 finish_wait(&ctx->sqo_sq_wait, &wait);
9195 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9196 struct __kernel_timespec __user **ts,
9197 const sigset_t __user **sig)
9199 struct io_uring_getevents_arg arg;
9202 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9203 * is just a pointer to the sigset_t.
9205 if (!(flags & IORING_ENTER_EXT_ARG)) {
9206 *sig = (const sigset_t __user *) argp;
9212 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9213 * timespec and sigset_t pointers if good.
9215 if (*argsz != sizeof(arg))
9217 if (copy_from_user(&arg, argp, sizeof(arg)))
9219 *sig = u64_to_user_ptr(arg.sigmask);
9220 *argsz = arg.sigmask_sz;
9221 *ts = u64_to_user_ptr(arg.ts);
9225 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9226 u32, min_complete, u32, flags, const void __user *, argp,
9229 struct io_ring_ctx *ctx;
9236 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9237 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9241 if (unlikely(!f.file))
9245 if (unlikely(f.file->f_op != &io_uring_fops))
9249 ctx = f.file->private_data;
9250 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9254 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9258 * For SQ polling, the thread will do all submissions and completions.
9259 * Just return the requested submit count, and wake the thread if
9263 if (ctx->flags & IORING_SETUP_SQPOLL) {
9264 io_cqring_overflow_flush(ctx, false);
9267 if (unlikely(ctx->sq_data->thread == NULL)) {
9270 if (flags & IORING_ENTER_SQ_WAKEUP)
9271 wake_up(&ctx->sq_data->wait);
9272 if (flags & IORING_ENTER_SQ_WAIT) {
9273 ret = io_sqpoll_wait_sq(ctx);
9277 submitted = to_submit;
9278 } else if (to_submit) {
9279 ret = io_uring_add_task_file(ctx);
9282 mutex_lock(&ctx->uring_lock);
9283 submitted = io_submit_sqes(ctx, to_submit);
9284 mutex_unlock(&ctx->uring_lock);
9286 if (submitted != to_submit)
9289 if (flags & IORING_ENTER_GETEVENTS) {
9290 const sigset_t __user *sig;
9291 struct __kernel_timespec __user *ts;
9293 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9297 min_complete = min(min_complete, ctx->cq_entries);
9300 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9301 * space applications don't need to do io completion events
9302 * polling again, they can rely on io_sq_thread to do polling
9303 * work, which can reduce cpu usage and uring_lock contention.
9305 if (ctx->flags & IORING_SETUP_IOPOLL &&
9306 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9307 ret = io_iopoll_check(ctx, min_complete);
9309 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9314 percpu_ref_put(&ctx->refs);
9317 return submitted ? submitted : ret;
9320 #ifdef CONFIG_PROC_FS
9321 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9322 const struct cred *cred)
9324 struct user_namespace *uns = seq_user_ns(m);
9325 struct group_info *gi;
9330 seq_printf(m, "%5d\n", id);
9331 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9332 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9333 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9334 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9335 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9336 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9337 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9338 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9339 seq_puts(m, "\n\tGroups:\t");
9340 gi = cred->group_info;
9341 for (g = 0; g < gi->ngroups; g++) {
9342 seq_put_decimal_ull(m, g ? " " : "",
9343 from_kgid_munged(uns, gi->gid[g]));
9345 seq_puts(m, "\n\tCapEff:\t");
9346 cap = cred->cap_effective;
9347 CAP_FOR_EACH_U32(__capi)
9348 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9353 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9355 struct io_sq_data *sq = NULL;
9360 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9361 * since fdinfo case grabs it in the opposite direction of normal use
9362 * cases. If we fail to get the lock, we just don't iterate any
9363 * structures that could be going away outside the io_uring mutex.
9365 has_lock = mutex_trylock(&ctx->uring_lock);
9367 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9373 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9374 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9375 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9376 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9377 struct file *f = io_file_from_index(ctx, i);
9380 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9382 seq_printf(m, "%5u: <none>\n", i);
9384 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9385 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9386 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9387 unsigned int len = buf->ubuf_end - buf->ubuf;
9389 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9391 if (has_lock && !xa_empty(&ctx->personalities)) {
9392 unsigned long index;
9393 const struct cred *cred;
9395 seq_printf(m, "Personalities:\n");
9396 xa_for_each(&ctx->personalities, index, cred)
9397 io_uring_show_cred(m, index, cred);
9399 seq_printf(m, "PollList:\n");
9400 spin_lock_irq(&ctx->completion_lock);
9401 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9402 struct hlist_head *list = &ctx->cancel_hash[i];
9403 struct io_kiocb *req;
9405 hlist_for_each_entry(req, list, hash_node)
9406 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9407 req->task->task_works != NULL);
9409 spin_unlock_irq(&ctx->completion_lock);
9411 mutex_unlock(&ctx->uring_lock);
9414 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9416 struct io_ring_ctx *ctx = f->private_data;
9418 if (percpu_ref_tryget(&ctx->refs)) {
9419 __io_uring_show_fdinfo(ctx, m);
9420 percpu_ref_put(&ctx->refs);
9425 static const struct file_operations io_uring_fops = {
9426 .release = io_uring_release,
9427 .mmap = io_uring_mmap,
9429 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9430 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9432 .poll = io_uring_poll,
9433 .fasync = io_uring_fasync,
9434 #ifdef CONFIG_PROC_FS
9435 .show_fdinfo = io_uring_show_fdinfo,
9439 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9440 struct io_uring_params *p)
9442 struct io_rings *rings;
9443 size_t size, sq_array_offset;
9445 /* make sure these are sane, as we already accounted them */
9446 ctx->sq_entries = p->sq_entries;
9447 ctx->cq_entries = p->cq_entries;
9449 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9450 if (size == SIZE_MAX)
9453 rings = io_mem_alloc(size);
9458 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9459 rings->sq_ring_mask = p->sq_entries - 1;
9460 rings->cq_ring_mask = p->cq_entries - 1;
9461 rings->sq_ring_entries = p->sq_entries;
9462 rings->cq_ring_entries = p->cq_entries;
9463 ctx->sq_mask = rings->sq_ring_mask;
9464 ctx->cq_mask = rings->cq_ring_mask;
9466 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9467 if (size == SIZE_MAX) {
9468 io_mem_free(ctx->rings);
9473 ctx->sq_sqes = io_mem_alloc(size);
9474 if (!ctx->sq_sqes) {
9475 io_mem_free(ctx->rings);
9483 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9487 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9491 ret = io_uring_add_task_file(ctx);
9496 fd_install(fd, file);
9501 * Allocate an anonymous fd, this is what constitutes the application
9502 * visible backing of an io_uring instance. The application mmaps this
9503 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9504 * we have to tie this fd to a socket for file garbage collection purposes.
9506 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9509 #if defined(CONFIG_UNIX)
9512 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9515 return ERR_PTR(ret);
9518 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9519 O_RDWR | O_CLOEXEC);
9520 #if defined(CONFIG_UNIX)
9522 sock_release(ctx->ring_sock);
9523 ctx->ring_sock = NULL;
9525 ctx->ring_sock->file = file;
9531 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9532 struct io_uring_params __user *params)
9534 struct io_ring_ctx *ctx;
9540 if (entries > IORING_MAX_ENTRIES) {
9541 if (!(p->flags & IORING_SETUP_CLAMP))
9543 entries = IORING_MAX_ENTRIES;
9547 * Use twice as many entries for the CQ ring. It's possible for the
9548 * application to drive a higher depth than the size of the SQ ring,
9549 * since the sqes are only used at submission time. This allows for
9550 * some flexibility in overcommitting a bit. If the application has
9551 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9552 * of CQ ring entries manually.
9554 p->sq_entries = roundup_pow_of_two(entries);
9555 if (p->flags & IORING_SETUP_CQSIZE) {
9557 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9558 * to a power-of-two, if it isn't already. We do NOT impose
9559 * any cq vs sq ring sizing.
9563 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9564 if (!(p->flags & IORING_SETUP_CLAMP))
9566 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9568 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9569 if (p->cq_entries < p->sq_entries)
9572 p->cq_entries = 2 * p->sq_entries;
9575 ctx = io_ring_ctx_alloc(p);
9578 ctx->compat = in_compat_syscall();
9579 if (!capable(CAP_IPC_LOCK))
9580 ctx->user = get_uid(current_user());
9583 * This is just grabbed for accounting purposes. When a process exits,
9584 * the mm is exited and dropped before the files, hence we need to hang
9585 * on to this mm purely for the purposes of being able to unaccount
9586 * memory (locked/pinned vm). It's not used for anything else.
9588 mmgrab(current->mm);
9589 ctx->mm_account = current->mm;
9591 ret = io_allocate_scq_urings(ctx, p);
9595 ret = io_sq_offload_create(ctx, p);
9599 memset(&p->sq_off, 0, sizeof(p->sq_off));
9600 p->sq_off.head = offsetof(struct io_rings, sq.head);
9601 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9602 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9603 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9604 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9605 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9606 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9608 memset(&p->cq_off, 0, sizeof(p->cq_off));
9609 p->cq_off.head = offsetof(struct io_rings, cq.head);
9610 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9611 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9612 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9613 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9614 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9615 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9617 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9618 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9619 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9620 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9621 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9623 if (copy_to_user(params, p, sizeof(*p))) {
9628 file = io_uring_get_file(ctx);
9630 ret = PTR_ERR(file);
9635 * Install ring fd as the very last thing, so we don't risk someone
9636 * having closed it before we finish setup
9638 ret = io_uring_install_fd(ctx, file);
9640 /* fput will clean it up */
9645 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9648 io_ring_ctx_wait_and_kill(ctx);
9653 * Sets up an aio uring context, and returns the fd. Applications asks for a
9654 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9655 * params structure passed in.
9657 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9659 struct io_uring_params p;
9662 if (copy_from_user(&p, params, sizeof(p)))
9664 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9669 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9670 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9671 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9672 IORING_SETUP_R_DISABLED))
9675 return io_uring_create(entries, &p, params);
9678 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9679 struct io_uring_params __user *, params)
9681 return io_uring_setup(entries, params);
9684 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9686 struct io_uring_probe *p;
9690 size = struct_size(p, ops, nr_args);
9691 if (size == SIZE_MAX)
9693 p = kzalloc(size, GFP_KERNEL);
9698 if (copy_from_user(p, arg, size))
9701 if (memchr_inv(p, 0, size))
9704 p->last_op = IORING_OP_LAST - 1;
9705 if (nr_args > IORING_OP_LAST)
9706 nr_args = IORING_OP_LAST;
9708 for (i = 0; i < nr_args; i++) {
9710 if (!io_op_defs[i].not_supported)
9711 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9716 if (copy_to_user(arg, p, size))
9723 static int io_register_personality(struct io_ring_ctx *ctx)
9725 const struct cred *creds;
9729 creds = get_current_cred();
9731 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9732 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9739 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9740 unsigned int nr_args)
9742 struct io_uring_restriction *res;
9746 /* Restrictions allowed only if rings started disabled */
9747 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9750 /* We allow only a single restrictions registration */
9751 if (ctx->restrictions.registered)
9754 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9757 size = array_size(nr_args, sizeof(*res));
9758 if (size == SIZE_MAX)
9761 res = memdup_user(arg, size);
9763 return PTR_ERR(res);
9767 for (i = 0; i < nr_args; i++) {
9768 switch (res[i].opcode) {
9769 case IORING_RESTRICTION_REGISTER_OP:
9770 if (res[i].register_op >= IORING_REGISTER_LAST) {
9775 __set_bit(res[i].register_op,
9776 ctx->restrictions.register_op);
9778 case IORING_RESTRICTION_SQE_OP:
9779 if (res[i].sqe_op >= IORING_OP_LAST) {
9784 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9786 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9787 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9789 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9790 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9799 /* Reset all restrictions if an error happened */
9801 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9803 ctx->restrictions.registered = true;
9809 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9811 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9814 if (ctx->restrictions.registered)
9815 ctx->restricted = 1;
9817 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9818 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9819 wake_up(&ctx->sq_data->wait);
9823 static bool io_register_op_must_quiesce(int op)
9826 case IORING_UNREGISTER_FILES:
9827 case IORING_REGISTER_FILES_UPDATE:
9828 case IORING_REGISTER_PROBE:
9829 case IORING_REGISTER_PERSONALITY:
9830 case IORING_UNREGISTER_PERSONALITY:
9837 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9838 void __user *arg, unsigned nr_args)
9839 __releases(ctx->uring_lock)
9840 __acquires(ctx->uring_lock)
9845 * We're inside the ring mutex, if the ref is already dying, then
9846 * someone else killed the ctx or is already going through
9847 * io_uring_register().
9849 if (percpu_ref_is_dying(&ctx->refs))
9852 if (io_register_op_must_quiesce(opcode)) {
9853 percpu_ref_kill(&ctx->refs);
9856 * Drop uring mutex before waiting for references to exit. If
9857 * another thread is currently inside io_uring_enter() it might
9858 * need to grab the uring_lock to make progress. If we hold it
9859 * here across the drain wait, then we can deadlock. It's safe
9860 * to drop the mutex here, since no new references will come in
9861 * after we've killed the percpu ref.
9863 mutex_unlock(&ctx->uring_lock);
9865 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9868 ret = io_run_task_work_sig();
9873 mutex_lock(&ctx->uring_lock);
9876 percpu_ref_resurrect(&ctx->refs);
9881 if (ctx->restricted) {
9882 if (opcode >= IORING_REGISTER_LAST) {
9887 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9894 case IORING_REGISTER_BUFFERS:
9895 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9897 case IORING_UNREGISTER_BUFFERS:
9901 ret = io_sqe_buffers_unregister(ctx);
9903 case IORING_REGISTER_FILES:
9904 ret = io_sqe_files_register(ctx, arg, nr_args);
9906 case IORING_UNREGISTER_FILES:
9910 ret = io_sqe_files_unregister(ctx);
9912 case IORING_REGISTER_FILES_UPDATE:
9913 ret = io_sqe_files_update(ctx, arg, nr_args);
9915 case IORING_REGISTER_EVENTFD:
9916 case IORING_REGISTER_EVENTFD_ASYNC:
9920 ret = io_eventfd_register(ctx, arg);
9923 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9924 ctx->eventfd_async = 1;
9926 ctx->eventfd_async = 0;
9928 case IORING_UNREGISTER_EVENTFD:
9932 ret = io_eventfd_unregister(ctx);
9934 case IORING_REGISTER_PROBE:
9936 if (!arg || nr_args > 256)
9938 ret = io_probe(ctx, arg, nr_args);
9940 case IORING_REGISTER_PERSONALITY:
9944 ret = io_register_personality(ctx);
9946 case IORING_UNREGISTER_PERSONALITY:
9950 ret = io_unregister_personality(ctx, nr_args);
9952 case IORING_REGISTER_ENABLE_RINGS:
9956 ret = io_register_enable_rings(ctx);
9958 case IORING_REGISTER_RESTRICTIONS:
9959 ret = io_register_restrictions(ctx, arg, nr_args);
9967 if (io_register_op_must_quiesce(opcode)) {
9968 /* bring the ctx back to life */
9969 percpu_ref_reinit(&ctx->refs);
9971 reinit_completion(&ctx->ref_comp);
9976 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9977 void __user *, arg, unsigned int, nr_args)
9979 struct io_ring_ctx *ctx;
9988 if (f.file->f_op != &io_uring_fops)
9991 ctx = f.file->private_data;
9995 mutex_lock(&ctx->uring_lock);
9996 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9997 mutex_unlock(&ctx->uring_lock);
9998 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9999 ctx->cq_ev_fd != NULL, ret);
10005 static int __init io_uring_init(void)
10007 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10008 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10009 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10012 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10013 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10014 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10015 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10016 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10017 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10018 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10019 BUILD_BUG_SQE_ELEM(8, __u64, off);
10020 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10021 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10022 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10023 BUILD_BUG_SQE_ELEM(24, __u32, len);
10024 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10025 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10026 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10027 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10028 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10029 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10030 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10031 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10032 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10033 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10034 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10035 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10036 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10037 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10038 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10039 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10040 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10041 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10042 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10044 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10045 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10046 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10050 __initcall(io_uring_init);