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;
210 struct io_fixed_file {
211 /* file * with additional FFS_* flags */
212 unsigned long file_ptr;
216 struct list_head list;
223 struct io_file_table {
224 /* two level table */
225 struct io_fixed_file **files;
228 struct io_rsrc_node {
229 struct percpu_ref refs;
230 struct list_head node;
231 struct list_head rsrc_list;
232 struct io_rsrc_data *rsrc_data;
233 struct llist_node llist;
237 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
239 struct io_rsrc_data {
240 struct io_ring_ctx *ctx;
244 struct completion done;
249 struct list_head list;
255 struct io_restriction {
256 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
257 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
258 u8 sqe_flags_allowed;
259 u8 sqe_flags_required;
264 IO_SQ_THREAD_SHOULD_STOP = 0,
265 IO_SQ_THREAD_SHOULD_PARK,
270 atomic_t park_pending;
273 /* ctx's that are using this sqd */
274 struct list_head ctx_list;
276 struct task_struct *thread;
277 struct wait_queue_head wait;
279 unsigned sq_thread_idle;
285 struct completion exited;
286 struct callback_head *park_task_work;
289 #define IO_IOPOLL_BATCH 8
290 #define IO_COMPL_BATCH 32
291 #define IO_REQ_CACHE_SIZE 32
292 #define IO_REQ_ALLOC_BATCH 8
294 struct io_comp_state {
295 struct io_kiocb *reqs[IO_COMPL_BATCH];
297 unsigned int locked_free_nr;
298 /* inline/task_work completion list, under ->uring_lock */
299 struct list_head free_list;
300 /* IRQ completion list, under ->completion_lock */
301 struct list_head locked_free_list;
304 struct io_submit_link {
305 struct io_kiocb *head;
306 struct io_kiocb *last;
309 struct io_submit_state {
310 struct blk_plug plug;
311 struct io_submit_link link;
314 * io_kiocb alloc cache
316 void *reqs[IO_REQ_CACHE_SIZE];
317 unsigned int free_reqs;
322 * Batch completion logic
324 struct io_comp_state comp;
327 * File reference cache
331 unsigned int file_refs;
332 unsigned int ios_left;
337 struct percpu_ref refs;
338 } ____cacheline_aligned_in_smp;
342 unsigned int compat: 1;
343 unsigned int drain_next: 1;
344 unsigned int eventfd_async: 1;
345 unsigned int restricted: 1;
348 * Ring buffer of indices into array of io_uring_sqe, which is
349 * mmapped by the application using the IORING_OFF_SQES offset.
351 * This indirection could e.g. be used to assign fixed
352 * io_uring_sqe entries to operations and only submit them to
353 * the queue when needed.
355 * The kernel modifies neither the indices array nor the entries
359 unsigned cached_sq_head;
362 unsigned sq_thread_idle;
363 unsigned cached_sq_dropped;
364 unsigned cached_cq_overflow;
365 unsigned long sq_check_overflow;
367 /* hashed buffered write serialization */
368 struct io_wq_hash *hash_map;
370 struct list_head defer_list;
371 struct list_head timeout_list;
372 struct list_head cq_overflow_list;
374 struct io_uring_sqe *sq_sqes;
375 } ____cacheline_aligned_in_smp;
378 struct mutex uring_lock;
379 wait_queue_head_t wait;
380 } ____cacheline_aligned_in_smp;
382 struct io_submit_state submit_state;
384 struct io_rings *rings;
386 /* Only used for accounting purposes */
387 struct mm_struct *mm_account;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
396 * If used, fixed file set. Writers must ensure that ->refs is dead,
397 * readers must ensure that ->refs is alive as long as the file* is
398 * used. Only updated through io_uring_register(2).
400 struct io_rsrc_data *file_data;
401 struct io_file_table file_table;
402 unsigned nr_user_files;
404 /* if used, fixed mapped user buffers */
405 unsigned nr_user_bufs;
406 struct io_mapped_ubuf *user_bufs;
408 struct user_struct *user;
410 struct completion ref_comp;
412 #if defined(CONFIG_UNIX)
413 struct socket *ring_sock;
416 struct xarray io_buffers;
418 struct xarray personalities;
422 unsigned cached_cq_tail;
425 atomic_t cq_timeouts;
426 unsigned cq_last_tm_flush;
427 unsigned long cq_check_overflow;
428 struct wait_queue_head cq_wait;
429 struct fasync_struct *cq_fasync;
430 struct eventfd_ctx *cq_ev_fd;
431 } ____cacheline_aligned_in_smp;
434 spinlock_t completion_lock;
437 * ->iopoll_list is protected by the ctx->uring_lock for
438 * io_uring instances that don't use IORING_SETUP_SQPOLL.
439 * For SQPOLL, only the single threaded io_sq_thread() will
440 * manipulate the list, hence no extra locking is needed there.
442 struct list_head iopoll_list;
443 struct hlist_head *cancel_hash;
444 unsigned cancel_hash_bits;
445 bool poll_multi_file;
446 } ____cacheline_aligned_in_smp;
448 struct delayed_work rsrc_put_work;
449 struct llist_head rsrc_put_llist;
450 struct list_head rsrc_ref_list;
451 spinlock_t rsrc_ref_lock;
452 struct io_rsrc_node *rsrc_node;
453 struct io_rsrc_node *rsrc_backup_node;
455 struct io_restriction restrictions;
458 struct callback_head *exit_task_work;
460 /* Keep this last, we don't need it for the fast path */
461 struct work_struct exit_work;
462 struct list_head tctx_list;
465 struct io_uring_task {
466 /* submission side */
468 struct wait_queue_head wait;
469 const struct io_ring_ctx *last;
471 struct percpu_counter inflight;
472 atomic_t inflight_tracked;
475 spinlock_t task_lock;
476 struct io_wq_work_list task_list;
477 unsigned long task_state;
478 struct callback_head task_work;
482 * First field must be the file pointer in all the
483 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
485 struct io_poll_iocb {
487 struct wait_queue_head *head;
491 struct wait_queue_entry wait;
494 struct io_poll_update {
500 bool update_user_data;
503 struct io_poll_remove {
513 struct io_timeout_data {
514 struct io_kiocb *req;
515 struct hrtimer timer;
516 struct timespec64 ts;
517 enum hrtimer_mode mode;
522 struct sockaddr __user *addr;
523 int __user *addr_len;
525 unsigned long nofile;
545 struct list_head list;
546 /* head of the link, used by linked timeouts only */
547 struct io_kiocb *head;
550 struct io_timeout_rem {
555 struct timespec64 ts;
560 /* NOTE: kiocb has the file as the first member, so don't do it here */
568 struct sockaddr __user *addr;
575 struct compat_msghdr __user *umsg_compat;
576 struct user_msghdr __user *umsg;
582 struct io_buffer *kbuf;
588 struct filename *filename;
590 unsigned long nofile;
593 struct io_rsrc_update {
619 struct epoll_event event;
623 struct file *file_out;
624 struct file *file_in;
631 struct io_provide_buf {
645 const char __user *filename;
646 struct statx __user *buffer;
658 struct filename *oldpath;
659 struct filename *newpath;
667 struct filename *filename;
670 struct io_completion {
672 struct list_head list;
676 struct io_async_connect {
677 struct sockaddr_storage address;
680 struct io_async_msghdr {
681 struct iovec fast_iov[UIO_FASTIOV];
682 /* points to an allocated iov, if NULL we use fast_iov instead */
683 struct iovec *free_iov;
684 struct sockaddr __user *uaddr;
686 struct sockaddr_storage addr;
690 struct iovec fast_iov[UIO_FASTIOV];
691 const struct iovec *free_iovec;
692 struct iov_iter iter;
694 struct wait_page_queue wpq;
698 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
699 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
700 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
701 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
702 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
703 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
709 REQ_F_LINK_TIMEOUT_BIT,
710 REQ_F_NEED_CLEANUP_BIT,
712 REQ_F_BUFFER_SELECTED_BIT,
713 REQ_F_LTIMEOUT_ACTIVE_BIT,
714 REQ_F_COMPLETE_INLINE_BIT,
716 REQ_F_DONT_REISSUE_BIT,
717 REQ_F_POLL_UPDATE_BIT,
718 /* keep async read/write and isreg together and in order */
719 REQ_F_ASYNC_READ_BIT,
720 REQ_F_ASYNC_WRITE_BIT,
723 /* not a real bit, just to check we're not overflowing the space */
729 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
730 /* drain existing IO first */
731 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
733 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
734 /* doesn't sever on completion < 0 */
735 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
737 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
738 /* IOSQE_BUFFER_SELECT */
739 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
741 /* fail rest of links */
742 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
743 /* on inflight list, should be cancelled and waited on exit reliably */
744 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
745 /* read/write uses file position */
746 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
747 /* must not punt to workers */
748 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
749 /* has or had linked timeout */
750 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
752 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
753 /* already went through poll handler */
754 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
755 /* buffer already selected */
756 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
757 /* linked timeout is active, i.e. prepared by link's head */
758 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
759 /* completion is deferred through io_comp_state */
760 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
761 /* caller should reissue async */
762 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
763 /* don't attempt request reissue, see io_rw_reissue() */
764 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
765 /* switches between poll and poll update */
766 REQ_F_POLL_UPDATE = BIT(REQ_F_POLL_UPDATE_BIT),
767 /* supports async reads */
768 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
769 /* supports async writes */
770 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
772 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
776 struct io_poll_iocb poll;
777 struct io_poll_iocb *double_poll;
780 struct io_task_work {
781 struct io_wq_work_node node;
782 task_work_func_t func;
786 * NOTE! Each of the iocb union members has the file pointer
787 * as the first entry in their struct definition. So you can
788 * access the file pointer through any of the sub-structs,
789 * or directly as just 'ki_filp' in this struct.
795 struct io_poll_iocb poll;
796 struct io_poll_update poll_update;
797 struct io_poll_remove poll_remove;
798 struct io_accept accept;
800 struct io_cancel cancel;
801 struct io_timeout timeout;
802 struct io_timeout_rem timeout_rem;
803 struct io_connect connect;
804 struct io_sr_msg sr_msg;
806 struct io_close close;
807 struct io_rsrc_update rsrc_update;
808 struct io_fadvise fadvise;
809 struct io_madvise madvise;
810 struct io_epoll epoll;
811 struct io_splice splice;
812 struct io_provide_buf pbuf;
813 struct io_statx statx;
814 struct io_shutdown shutdown;
815 struct io_rename rename;
816 struct io_unlink unlink;
817 /* use only after cleaning per-op data, see io_clean_op() */
818 struct io_completion compl;
821 /* opcode allocated if it needs to store data for async defer */
824 /* polled IO has completed */
830 struct io_ring_ctx *ctx;
833 struct task_struct *task;
836 struct io_kiocb *link;
837 struct percpu_ref *fixed_rsrc_refs;
839 /* used with ctx->iopoll_list with reads/writes */
840 struct list_head inflight_entry;
842 struct io_task_work io_task_work;
843 struct callback_head task_work;
845 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
846 struct hlist_node hash_node;
847 struct async_poll *apoll;
848 struct io_wq_work work;
851 struct io_tctx_node {
852 struct list_head ctx_node;
853 struct task_struct *task;
854 struct io_ring_ctx *ctx;
857 struct io_defer_entry {
858 struct list_head list;
859 struct io_kiocb *req;
864 /* needs req->file assigned */
865 unsigned needs_file : 1;
866 /* hash wq insertion if file is a regular file */
867 unsigned hash_reg_file : 1;
868 /* unbound wq insertion if file is a non-regular file */
869 unsigned unbound_nonreg_file : 1;
870 /* opcode is not supported by this kernel */
871 unsigned not_supported : 1;
872 /* set if opcode supports polled "wait" */
874 unsigned pollout : 1;
875 /* op supports buffer selection */
876 unsigned buffer_select : 1;
877 /* do prep async if is going to be punted */
878 unsigned needs_async_setup : 1;
879 /* should block plug */
881 /* size of async data needed, if any */
882 unsigned short async_size;
885 static const struct io_op_def io_op_defs[] = {
886 [IORING_OP_NOP] = {},
887 [IORING_OP_READV] = {
889 .unbound_nonreg_file = 1,
892 .needs_async_setup = 1,
894 .async_size = sizeof(struct io_async_rw),
896 [IORING_OP_WRITEV] = {
899 .unbound_nonreg_file = 1,
901 .needs_async_setup = 1,
903 .async_size = sizeof(struct io_async_rw),
905 [IORING_OP_FSYNC] = {
908 [IORING_OP_READ_FIXED] = {
910 .unbound_nonreg_file = 1,
913 .async_size = sizeof(struct io_async_rw),
915 [IORING_OP_WRITE_FIXED] = {
918 .unbound_nonreg_file = 1,
921 .async_size = sizeof(struct io_async_rw),
923 [IORING_OP_POLL_ADD] = {
925 .unbound_nonreg_file = 1,
927 [IORING_OP_POLL_REMOVE] = {},
928 [IORING_OP_SYNC_FILE_RANGE] = {
931 [IORING_OP_SENDMSG] = {
933 .unbound_nonreg_file = 1,
935 .needs_async_setup = 1,
936 .async_size = sizeof(struct io_async_msghdr),
938 [IORING_OP_RECVMSG] = {
940 .unbound_nonreg_file = 1,
943 .needs_async_setup = 1,
944 .async_size = sizeof(struct io_async_msghdr),
946 [IORING_OP_TIMEOUT] = {
947 .async_size = sizeof(struct io_timeout_data),
949 [IORING_OP_TIMEOUT_REMOVE] = {
950 /* used by timeout updates' prep() */
952 [IORING_OP_ACCEPT] = {
954 .unbound_nonreg_file = 1,
957 [IORING_OP_ASYNC_CANCEL] = {},
958 [IORING_OP_LINK_TIMEOUT] = {
959 .async_size = sizeof(struct io_timeout_data),
961 [IORING_OP_CONNECT] = {
963 .unbound_nonreg_file = 1,
965 .needs_async_setup = 1,
966 .async_size = sizeof(struct io_async_connect),
968 [IORING_OP_FALLOCATE] = {
971 [IORING_OP_OPENAT] = {},
972 [IORING_OP_CLOSE] = {},
973 [IORING_OP_FILES_UPDATE] = {},
974 [IORING_OP_STATX] = {},
977 .unbound_nonreg_file = 1,
981 .async_size = sizeof(struct io_async_rw),
983 [IORING_OP_WRITE] = {
985 .unbound_nonreg_file = 1,
988 .async_size = sizeof(struct io_async_rw),
990 [IORING_OP_FADVISE] = {
993 [IORING_OP_MADVISE] = {},
996 .unbound_nonreg_file = 1,
1001 .unbound_nonreg_file = 1,
1005 [IORING_OP_OPENAT2] = {
1007 [IORING_OP_EPOLL_CTL] = {
1008 .unbound_nonreg_file = 1,
1010 [IORING_OP_SPLICE] = {
1013 .unbound_nonreg_file = 1,
1015 [IORING_OP_PROVIDE_BUFFERS] = {},
1016 [IORING_OP_REMOVE_BUFFERS] = {},
1020 .unbound_nonreg_file = 1,
1022 [IORING_OP_SHUTDOWN] = {
1025 [IORING_OP_RENAMEAT] = {},
1026 [IORING_OP_UNLINKAT] = {},
1029 static bool io_disarm_next(struct io_kiocb *req);
1030 static void io_uring_del_task_file(unsigned long index);
1031 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1032 struct task_struct *task,
1033 struct files_struct *files);
1034 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
1035 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1037 static bool io_cqring_fill_event(struct io_kiocb *req, long res, unsigned cflags);
1038 static void io_put_req(struct io_kiocb *req);
1039 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1040 static void io_dismantle_req(struct io_kiocb *req);
1041 static void io_put_task(struct task_struct *task, int nr);
1042 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1043 static void io_queue_linked_timeout(struct io_kiocb *req);
1044 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1045 struct io_uring_rsrc_update *ip,
1047 static void io_clean_op(struct io_kiocb *req);
1048 static struct file *io_file_get(struct io_submit_state *state,
1049 struct io_kiocb *req, int fd, bool fixed);
1050 static void __io_queue_sqe(struct io_kiocb *req);
1051 static void io_rsrc_put_work(struct work_struct *work);
1053 static void io_req_task_queue(struct io_kiocb *req);
1054 static void io_submit_flush_completions(struct io_comp_state *cs,
1055 struct io_ring_ctx *ctx);
1056 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1057 static int io_req_prep_async(struct io_kiocb *req);
1059 static struct kmem_cache *req_cachep;
1061 static const struct file_operations io_uring_fops;
1063 struct sock *io_uring_get_socket(struct file *file)
1065 #if defined(CONFIG_UNIX)
1066 if (file->f_op == &io_uring_fops) {
1067 struct io_ring_ctx *ctx = file->private_data;
1069 return ctx->ring_sock->sk;
1074 EXPORT_SYMBOL(io_uring_get_socket);
1076 #define io_for_each_link(pos, head) \
1077 for (pos = (head); pos; pos = pos->link)
1079 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1081 struct io_ring_ctx *ctx = req->ctx;
1083 if (!req->fixed_rsrc_refs) {
1084 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1085 percpu_ref_get(req->fixed_rsrc_refs);
1089 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1091 bool got = percpu_ref_tryget(ref);
1093 /* already at zero, wait for ->release() */
1095 wait_for_completion(compl);
1096 percpu_ref_resurrect(ref);
1098 percpu_ref_put(ref);
1101 static bool io_match_task(struct io_kiocb *head,
1102 struct task_struct *task,
1103 struct files_struct *files)
1105 struct io_kiocb *req;
1107 if (task && head->task != task)
1112 io_for_each_link(req, head) {
1113 if (req->flags & REQ_F_INFLIGHT)
1119 static inline void req_set_fail_links(struct io_kiocb *req)
1121 if (req->flags & REQ_F_LINK)
1122 req->flags |= REQ_F_FAIL_LINK;
1125 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1127 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1129 complete(&ctx->ref_comp);
1132 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1134 return !req->timeout.off;
1137 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1139 struct io_ring_ctx *ctx;
1142 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1147 * Use 5 bits less than the max cq entries, that should give us around
1148 * 32 entries per hash list if totally full and uniformly spread.
1150 hash_bits = ilog2(p->cq_entries);
1154 ctx->cancel_hash_bits = hash_bits;
1155 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1157 if (!ctx->cancel_hash)
1159 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1161 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1162 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1165 ctx->flags = p->flags;
1166 init_waitqueue_head(&ctx->sqo_sq_wait);
1167 INIT_LIST_HEAD(&ctx->sqd_list);
1168 init_waitqueue_head(&ctx->cq_wait);
1169 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1170 init_completion(&ctx->ref_comp);
1171 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1172 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1173 mutex_init(&ctx->uring_lock);
1174 init_waitqueue_head(&ctx->wait);
1175 spin_lock_init(&ctx->completion_lock);
1176 INIT_LIST_HEAD(&ctx->iopoll_list);
1177 INIT_LIST_HEAD(&ctx->defer_list);
1178 INIT_LIST_HEAD(&ctx->timeout_list);
1179 spin_lock_init(&ctx->rsrc_ref_lock);
1180 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1181 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1182 init_llist_head(&ctx->rsrc_put_llist);
1183 INIT_LIST_HEAD(&ctx->tctx_list);
1184 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1185 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1188 kfree(ctx->cancel_hash);
1193 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1195 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1196 struct io_ring_ctx *ctx = req->ctx;
1198 return seq != ctx->cached_cq_tail
1199 + READ_ONCE(ctx->cached_cq_overflow);
1205 static void io_req_track_inflight(struct io_kiocb *req)
1207 if (!(req->flags & REQ_F_INFLIGHT)) {
1208 req->flags |= REQ_F_INFLIGHT;
1209 atomic_inc(¤t->io_uring->inflight_tracked);
1213 static void io_prep_async_work(struct io_kiocb *req)
1215 const struct io_op_def *def = &io_op_defs[req->opcode];
1216 struct io_ring_ctx *ctx = req->ctx;
1218 if (!req->work.creds)
1219 req->work.creds = get_current_cred();
1221 req->work.list.next = NULL;
1222 req->work.flags = 0;
1223 if (req->flags & REQ_F_FORCE_ASYNC)
1224 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1226 if (req->flags & REQ_F_ISREG) {
1227 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1228 io_wq_hash_work(&req->work, file_inode(req->file));
1229 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1230 if (def->unbound_nonreg_file)
1231 req->work.flags |= IO_WQ_WORK_UNBOUND;
1234 switch (req->opcode) {
1235 case IORING_OP_SPLICE:
1237 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1238 req->work.flags |= IO_WQ_WORK_UNBOUND;
1243 static void io_prep_async_link(struct io_kiocb *req)
1245 struct io_kiocb *cur;
1247 io_for_each_link(cur, req)
1248 io_prep_async_work(cur);
1251 static void io_queue_async_work(struct io_kiocb *req)
1253 struct io_ring_ctx *ctx = req->ctx;
1254 struct io_kiocb *link = io_prep_linked_timeout(req);
1255 struct io_uring_task *tctx = req->task->io_uring;
1258 BUG_ON(!tctx->io_wq);
1260 /* init ->work of the whole link before punting */
1261 io_prep_async_link(req);
1262 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1263 &req->work, req->flags);
1264 io_wq_enqueue(tctx->io_wq, &req->work);
1266 io_queue_linked_timeout(link);
1269 static void io_kill_timeout(struct io_kiocb *req, int status)
1270 __must_hold(&req->ctx->completion_lock)
1272 struct io_timeout_data *io = req->async_data;
1274 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1275 atomic_set(&req->ctx->cq_timeouts,
1276 atomic_read(&req->ctx->cq_timeouts) + 1);
1277 list_del_init(&req->timeout.list);
1278 io_cqring_fill_event(req, status, 0);
1279 io_put_req_deferred(req, 1);
1283 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1286 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1287 struct io_defer_entry, list);
1289 if (req_need_defer(de->req, de->seq))
1291 list_del_init(&de->list);
1292 io_req_task_queue(de->req);
1294 } while (!list_empty(&ctx->defer_list));
1297 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1301 if (list_empty(&ctx->timeout_list))
1304 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1307 u32 events_needed, events_got;
1308 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1309 struct io_kiocb, timeout.list);
1311 if (io_is_timeout_noseq(req))
1315 * Since seq can easily wrap around over time, subtract
1316 * the last seq at which timeouts were flushed before comparing.
1317 * Assuming not more than 2^31-1 events have happened since,
1318 * these subtractions won't have wrapped, so we can check if
1319 * target is in [last_seq, current_seq] by comparing the two.
1321 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1322 events_got = seq - ctx->cq_last_tm_flush;
1323 if (events_got < events_needed)
1326 list_del_init(&req->timeout.list);
1327 io_kill_timeout(req, 0);
1328 } while (!list_empty(&ctx->timeout_list));
1330 ctx->cq_last_tm_flush = seq;
1333 static void io_commit_cqring(struct io_ring_ctx *ctx)
1335 io_flush_timeouts(ctx);
1337 /* order cqe stores with ring update */
1338 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1340 if (unlikely(!list_empty(&ctx->defer_list)))
1341 __io_queue_deferred(ctx);
1344 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1346 struct io_rings *r = ctx->rings;
1348 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1351 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1353 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1356 static inline struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1358 struct io_rings *rings = ctx->rings;
1362 * writes to the cq entry need to come after reading head; the
1363 * control dependency is enough as we're using WRITE_ONCE to
1366 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1369 tail = ctx->cached_cq_tail++;
1370 return &rings->cqes[tail & ctx->cq_mask];
1373 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1375 if (likely(!ctx->cq_ev_fd))
1377 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1379 return !ctx->eventfd_async || io_wq_current_is_worker();
1382 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1384 /* see waitqueue_active() comment */
1387 if (waitqueue_active(&ctx->wait))
1388 wake_up(&ctx->wait);
1389 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1390 wake_up(&ctx->sq_data->wait);
1391 if (io_should_trigger_evfd(ctx))
1392 eventfd_signal(ctx->cq_ev_fd, 1);
1393 if (waitqueue_active(&ctx->cq_wait)) {
1394 wake_up_interruptible(&ctx->cq_wait);
1395 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1399 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1401 /* see waitqueue_active() comment */
1404 if (ctx->flags & IORING_SETUP_SQPOLL) {
1405 if (waitqueue_active(&ctx->wait))
1406 wake_up(&ctx->wait);
1408 if (io_should_trigger_evfd(ctx))
1409 eventfd_signal(ctx->cq_ev_fd, 1);
1410 if (waitqueue_active(&ctx->cq_wait)) {
1411 wake_up_interruptible(&ctx->cq_wait);
1412 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1416 /* Returns true if there are no backlogged entries after the flush */
1417 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1419 struct io_rings *rings = ctx->rings;
1420 unsigned long flags;
1421 bool all_flushed, posted;
1423 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1427 spin_lock_irqsave(&ctx->completion_lock, flags);
1428 while (!list_empty(&ctx->cq_overflow_list)) {
1429 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1430 struct io_overflow_cqe *ocqe;
1434 ocqe = list_first_entry(&ctx->cq_overflow_list,
1435 struct io_overflow_cqe, list);
1437 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1439 WRITE_ONCE(ctx->rings->cq_overflow,
1440 ++ctx->cached_cq_overflow);
1442 list_del(&ocqe->list);
1446 all_flushed = list_empty(&ctx->cq_overflow_list);
1448 clear_bit(0, &ctx->sq_check_overflow);
1449 clear_bit(0, &ctx->cq_check_overflow);
1450 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1454 io_commit_cqring(ctx);
1455 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1457 io_cqring_ev_posted(ctx);
1461 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1465 if (test_bit(0, &ctx->cq_check_overflow)) {
1466 /* iopoll syncs against uring_lock, not completion_lock */
1467 if (ctx->flags & IORING_SETUP_IOPOLL)
1468 mutex_lock(&ctx->uring_lock);
1469 ret = __io_cqring_overflow_flush(ctx, force);
1470 if (ctx->flags & IORING_SETUP_IOPOLL)
1471 mutex_unlock(&ctx->uring_lock);
1478 * Shamelessly stolen from the mm implementation of page reference checking,
1479 * see commit f958d7b528b1 for details.
1481 #define req_ref_zero_or_close_to_overflow(req) \
1482 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1484 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1486 return atomic_inc_not_zero(&req->refs);
1489 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1491 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1492 return atomic_sub_and_test(refs, &req->refs);
1495 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1497 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1498 return atomic_dec_and_test(&req->refs);
1501 static inline void req_ref_put(struct io_kiocb *req)
1503 WARN_ON_ONCE(req_ref_put_and_test(req));
1506 static inline void req_ref_get(struct io_kiocb *req)
1508 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1509 atomic_inc(&req->refs);
1512 static bool io_cqring_event_overflow(struct io_kiocb *req, long res,
1513 unsigned int cflags)
1515 struct io_ring_ctx *ctx = req->ctx;
1516 struct io_overflow_cqe *ocqe;
1518 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1521 * If we're in ring overflow flush mode, or in task cancel mode,
1522 * or cannot allocate an overflow entry, then we need to drop it
1525 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1528 if (list_empty(&ctx->cq_overflow_list)) {
1529 set_bit(0, &ctx->sq_check_overflow);
1530 set_bit(0, &ctx->cq_check_overflow);
1531 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1533 ocqe->cqe.user_data = req->user_data;
1534 ocqe->cqe.res = res;
1535 ocqe->cqe.flags = cflags;
1536 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1540 static inline bool __io_cqring_fill_event(struct io_kiocb *req, long res,
1541 unsigned int cflags)
1543 struct io_ring_ctx *ctx = req->ctx;
1544 struct io_uring_cqe *cqe;
1546 trace_io_uring_complete(ctx, req->user_data, res, cflags);
1549 * If we can't get a cq entry, userspace overflowed the
1550 * submission (by quite a lot). Increment the overflow count in
1553 cqe = io_get_cqring(ctx);
1555 WRITE_ONCE(cqe->user_data, req->user_data);
1556 WRITE_ONCE(cqe->res, res);
1557 WRITE_ONCE(cqe->flags, cflags);
1560 return io_cqring_event_overflow(req, res, cflags);
1563 /* not as hot to bloat with inlining */
1564 static noinline bool io_cqring_fill_event(struct io_kiocb *req, long res,
1565 unsigned int cflags)
1567 return __io_cqring_fill_event(req, res, cflags);
1570 static void io_req_complete_post(struct io_kiocb *req, long res,
1571 unsigned int cflags)
1573 struct io_ring_ctx *ctx = req->ctx;
1574 unsigned long flags;
1576 spin_lock_irqsave(&ctx->completion_lock, flags);
1577 __io_cqring_fill_event(req, res, cflags);
1579 * If we're the last reference to this request, add to our locked
1582 if (req_ref_put_and_test(req)) {
1583 struct io_comp_state *cs = &ctx->submit_state.comp;
1585 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1586 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1587 io_disarm_next(req);
1589 io_req_task_queue(req->link);
1593 io_dismantle_req(req);
1594 io_put_task(req->task, 1);
1595 list_add(&req->compl.list, &cs->locked_free_list);
1596 cs->locked_free_nr++;
1598 if (!percpu_ref_tryget(&ctx->refs))
1601 io_commit_cqring(ctx);
1602 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1605 io_cqring_ev_posted(ctx);
1606 percpu_ref_put(&ctx->refs);
1610 static void io_req_complete_state(struct io_kiocb *req, long res,
1611 unsigned int cflags)
1613 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1616 req->compl.cflags = cflags;
1617 req->flags |= REQ_F_COMPLETE_INLINE;
1620 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1621 long res, unsigned cflags)
1623 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1624 io_req_complete_state(req, res, cflags);
1626 io_req_complete_post(req, res, cflags);
1629 static inline void io_req_complete(struct io_kiocb *req, long res)
1631 __io_req_complete(req, 0, res, 0);
1634 static void io_req_complete_failed(struct io_kiocb *req, long res)
1636 req_set_fail_links(req);
1638 io_req_complete_post(req, res, 0);
1641 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1642 struct io_comp_state *cs)
1644 spin_lock_irq(&ctx->completion_lock);
1645 list_splice_init(&cs->locked_free_list, &cs->free_list);
1646 cs->locked_free_nr = 0;
1647 spin_unlock_irq(&ctx->completion_lock);
1650 /* Returns true IFF there are requests in the cache */
1651 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1653 struct io_submit_state *state = &ctx->submit_state;
1654 struct io_comp_state *cs = &state->comp;
1658 * If we have more than a batch's worth of requests in our IRQ side
1659 * locked cache, grab the lock and move them over to our submission
1662 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
1663 io_flush_cached_locked_reqs(ctx, cs);
1665 nr = state->free_reqs;
1666 while (!list_empty(&cs->free_list)) {
1667 struct io_kiocb *req = list_first_entry(&cs->free_list,
1668 struct io_kiocb, compl.list);
1670 list_del(&req->compl.list);
1671 state->reqs[nr++] = req;
1672 if (nr == ARRAY_SIZE(state->reqs))
1676 state->free_reqs = nr;
1680 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1682 struct io_submit_state *state = &ctx->submit_state;
1684 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1686 if (!state->free_reqs) {
1687 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1690 if (io_flush_cached_reqs(ctx))
1693 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1697 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1698 * retry single alloc to be on the safe side.
1700 if (unlikely(ret <= 0)) {
1701 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1702 if (!state->reqs[0])
1706 state->free_reqs = ret;
1710 return state->reqs[state->free_reqs];
1713 static inline void io_put_file(struct file *file)
1719 static void io_dismantle_req(struct io_kiocb *req)
1721 unsigned int flags = req->flags;
1723 if (!(flags & REQ_F_FIXED_FILE))
1724 io_put_file(req->file);
1725 if (flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1729 if (req->flags & REQ_F_INFLIGHT) {
1730 struct io_uring_task *tctx = req->task->io_uring;
1732 atomic_dec(&tctx->inflight_tracked);
1733 req->flags &= ~REQ_F_INFLIGHT;
1736 if (req->fixed_rsrc_refs)
1737 percpu_ref_put(req->fixed_rsrc_refs);
1738 if (req->async_data)
1739 kfree(req->async_data);
1740 if (req->work.creds) {
1741 put_cred(req->work.creds);
1742 req->work.creds = NULL;
1746 /* must to be called somewhat shortly after putting a request */
1747 static inline void io_put_task(struct task_struct *task, int nr)
1749 struct io_uring_task *tctx = task->io_uring;
1751 percpu_counter_sub(&tctx->inflight, nr);
1752 if (unlikely(atomic_read(&tctx->in_idle)))
1753 wake_up(&tctx->wait);
1754 put_task_struct_many(task, nr);
1757 static void __io_free_req(struct io_kiocb *req)
1759 struct io_ring_ctx *ctx = req->ctx;
1761 io_dismantle_req(req);
1762 io_put_task(req->task, 1);
1764 kmem_cache_free(req_cachep, req);
1765 percpu_ref_put(&ctx->refs);
1768 static inline void io_remove_next_linked(struct io_kiocb *req)
1770 struct io_kiocb *nxt = req->link;
1772 req->link = nxt->link;
1776 static bool io_kill_linked_timeout(struct io_kiocb *req)
1777 __must_hold(&req->ctx->completion_lock)
1779 struct io_kiocb *link = req->link;
1782 * Can happen if a linked timeout fired and link had been like
1783 * req -> link t-out -> link t-out [-> ...]
1785 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1786 struct io_timeout_data *io = link->async_data;
1788 io_remove_next_linked(req);
1789 link->timeout.head = NULL;
1790 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1791 io_cqring_fill_event(link, -ECANCELED, 0);
1792 io_put_req_deferred(link, 1);
1799 static void io_fail_links(struct io_kiocb *req)
1800 __must_hold(&req->ctx->completion_lock)
1802 struct io_kiocb *nxt, *link = req->link;
1809 trace_io_uring_fail_link(req, link);
1810 io_cqring_fill_event(link, -ECANCELED, 0);
1811 io_put_req_deferred(link, 2);
1816 static bool io_disarm_next(struct io_kiocb *req)
1817 __must_hold(&req->ctx->completion_lock)
1819 bool posted = false;
1821 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1822 posted = io_kill_linked_timeout(req);
1823 if (unlikely((req->flags & REQ_F_FAIL_LINK) &&
1824 !(req->flags & REQ_F_HARDLINK))) {
1825 posted |= (req->link != NULL);
1831 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1833 struct io_kiocb *nxt;
1836 * If LINK is set, we have dependent requests in this chain. If we
1837 * didn't fail this request, queue the first one up, moving any other
1838 * dependencies to the next request. In case of failure, fail the rest
1841 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1842 struct io_ring_ctx *ctx = req->ctx;
1843 unsigned long flags;
1846 spin_lock_irqsave(&ctx->completion_lock, flags);
1847 posted = io_disarm_next(req);
1849 io_commit_cqring(req->ctx);
1850 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1852 io_cqring_ev_posted(ctx);
1859 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1861 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1863 return __io_req_find_next(req);
1866 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1870 if (ctx->submit_state.comp.nr) {
1871 mutex_lock(&ctx->uring_lock);
1872 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1873 mutex_unlock(&ctx->uring_lock);
1875 percpu_ref_put(&ctx->refs);
1878 static bool __tctx_task_work(struct io_uring_task *tctx)
1880 struct io_ring_ctx *ctx = NULL;
1881 struct io_wq_work_list list;
1882 struct io_wq_work_node *node;
1884 if (wq_list_empty(&tctx->task_list))
1887 spin_lock_irq(&tctx->task_lock);
1888 list = tctx->task_list;
1889 INIT_WQ_LIST(&tctx->task_list);
1890 spin_unlock_irq(&tctx->task_lock);
1894 struct io_wq_work_node *next = node->next;
1895 struct io_kiocb *req;
1897 req = container_of(node, struct io_kiocb, io_task_work.node);
1898 if (req->ctx != ctx) {
1899 ctx_flush_and_put(ctx);
1901 percpu_ref_get(&ctx->refs);
1904 req->task_work.func(&req->task_work);
1908 ctx_flush_and_put(ctx);
1909 return list.first != NULL;
1912 static void tctx_task_work(struct callback_head *cb)
1914 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1916 clear_bit(0, &tctx->task_state);
1918 while (__tctx_task_work(tctx))
1922 static int io_req_task_work_add(struct io_kiocb *req)
1924 struct task_struct *tsk = req->task;
1925 struct io_uring_task *tctx = tsk->io_uring;
1926 enum task_work_notify_mode notify;
1927 struct io_wq_work_node *node, *prev;
1928 unsigned long flags;
1931 if (unlikely(tsk->flags & PF_EXITING))
1934 WARN_ON_ONCE(!tctx);
1936 spin_lock_irqsave(&tctx->task_lock, flags);
1937 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1938 spin_unlock_irqrestore(&tctx->task_lock, flags);
1940 /* task_work already pending, we're done */
1941 if (test_bit(0, &tctx->task_state) ||
1942 test_and_set_bit(0, &tctx->task_state))
1946 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1947 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1948 * processing task_work. There's no reliable way to tell if TWA_RESUME
1951 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1953 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1954 wake_up_process(tsk);
1959 * Slow path - we failed, find and delete work. if the work is not
1960 * in the list, it got run and we're fine.
1962 spin_lock_irqsave(&tctx->task_lock, flags);
1963 wq_list_for_each(node, prev, &tctx->task_list) {
1964 if (&req->io_task_work.node == node) {
1965 wq_list_del(&tctx->task_list, node, prev);
1970 spin_unlock_irqrestore(&tctx->task_lock, flags);
1971 clear_bit(0, &tctx->task_state);
1975 static bool io_run_task_work_head(struct callback_head **work_head)
1977 struct callback_head *work, *next;
1978 bool executed = false;
1981 work = xchg(work_head, NULL);
1997 static void io_task_work_add_head(struct callback_head **work_head,
1998 struct callback_head *task_work)
2000 struct callback_head *head;
2003 head = READ_ONCE(*work_head);
2004 task_work->next = head;
2005 } while (cmpxchg(work_head, head, task_work) != head);
2008 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2009 task_work_func_t cb)
2011 init_task_work(&req->task_work, cb);
2012 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2015 static void io_req_task_cancel(struct callback_head *cb)
2017 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2018 struct io_ring_ctx *ctx = req->ctx;
2020 /* ctx is guaranteed to stay alive while we hold uring_lock */
2021 mutex_lock(&ctx->uring_lock);
2022 io_req_complete_failed(req, req->result);
2023 mutex_unlock(&ctx->uring_lock);
2026 static void __io_req_task_submit(struct io_kiocb *req)
2028 struct io_ring_ctx *ctx = req->ctx;
2030 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2031 mutex_lock(&ctx->uring_lock);
2032 if (!(current->flags & PF_EXITING) && !current->in_execve)
2033 __io_queue_sqe(req);
2035 io_req_complete_failed(req, -EFAULT);
2036 mutex_unlock(&ctx->uring_lock);
2039 static void io_req_task_submit(struct callback_head *cb)
2041 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2043 __io_req_task_submit(req);
2046 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2049 req->task_work.func = io_req_task_cancel;
2051 if (unlikely(io_req_task_work_add(req)))
2052 io_req_task_work_add_fallback(req, io_req_task_cancel);
2055 static void io_req_task_queue(struct io_kiocb *req)
2057 req->task_work.func = io_req_task_submit;
2059 if (unlikely(io_req_task_work_add(req)))
2060 io_req_task_queue_fail(req, -ECANCELED);
2063 static inline void io_queue_next(struct io_kiocb *req)
2065 struct io_kiocb *nxt = io_req_find_next(req);
2068 io_req_task_queue(nxt);
2071 static void io_free_req(struct io_kiocb *req)
2078 struct task_struct *task;
2083 static inline void io_init_req_batch(struct req_batch *rb)
2090 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2091 struct req_batch *rb)
2094 io_put_task(rb->task, rb->task_refs);
2096 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2099 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2100 struct io_submit_state *state)
2103 io_dismantle_req(req);
2105 if (req->task != rb->task) {
2107 io_put_task(rb->task, rb->task_refs);
2108 rb->task = req->task;
2114 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2115 state->reqs[state->free_reqs++] = req;
2117 list_add(&req->compl.list, &state->comp.free_list);
2120 static void io_submit_flush_completions(struct io_comp_state *cs,
2121 struct io_ring_ctx *ctx)
2124 struct io_kiocb *req;
2125 struct req_batch rb;
2127 io_init_req_batch(&rb);
2128 spin_lock_irq(&ctx->completion_lock);
2129 for (i = 0; i < nr; i++) {
2131 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2133 io_commit_cqring(ctx);
2134 spin_unlock_irq(&ctx->completion_lock);
2136 io_cqring_ev_posted(ctx);
2137 for (i = 0; i < nr; i++) {
2140 /* submission and completion refs */
2141 if (req_ref_sub_and_test(req, 2))
2142 io_req_free_batch(&rb, req, &ctx->submit_state);
2145 io_req_free_batch_finish(ctx, &rb);
2150 * Drop reference to request, return next in chain (if there is one) if this
2151 * was the last reference to this request.
2153 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2155 struct io_kiocb *nxt = NULL;
2157 if (req_ref_put_and_test(req)) {
2158 nxt = io_req_find_next(req);
2164 static inline void io_put_req(struct io_kiocb *req)
2166 if (req_ref_put_and_test(req))
2170 static void io_put_req_deferred_cb(struct callback_head *cb)
2172 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2177 static void io_free_req_deferred(struct io_kiocb *req)
2179 req->task_work.func = io_put_req_deferred_cb;
2180 if (unlikely(io_req_task_work_add(req)))
2181 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2184 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2186 if (req_ref_sub_and_test(req, refs))
2187 io_free_req_deferred(req);
2190 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2192 /* See comment at the top of this file */
2194 return __io_cqring_events(ctx);
2197 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2199 struct io_rings *rings = ctx->rings;
2201 /* make sure SQ entry isn't read before tail */
2202 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2205 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2207 unsigned int cflags;
2209 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2210 cflags |= IORING_CQE_F_BUFFER;
2211 req->flags &= ~REQ_F_BUFFER_SELECTED;
2216 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2218 struct io_buffer *kbuf;
2220 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2221 return io_put_kbuf(req, kbuf);
2224 static inline bool io_run_task_work(void)
2227 * Not safe to run on exiting task, and the task_work handling will
2228 * not add work to such a task.
2230 if (unlikely(current->flags & PF_EXITING))
2232 if (current->task_works) {
2233 __set_current_state(TASK_RUNNING);
2242 * Find and free completed poll iocbs
2244 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2245 struct list_head *done)
2247 struct req_batch rb;
2248 struct io_kiocb *req;
2250 /* order with ->result store in io_complete_rw_iopoll() */
2253 io_init_req_batch(&rb);
2254 while (!list_empty(done)) {
2257 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2258 list_del(&req->inflight_entry);
2260 if (READ_ONCE(req->result) == -EAGAIN &&
2261 !(req->flags & REQ_F_DONT_REISSUE)) {
2262 req->iopoll_completed = 0;
2264 io_queue_async_work(req);
2268 if (req->flags & REQ_F_BUFFER_SELECTED)
2269 cflags = io_put_rw_kbuf(req);
2271 __io_cqring_fill_event(req, req->result, cflags);
2274 if (req_ref_put_and_test(req))
2275 io_req_free_batch(&rb, req, &ctx->submit_state);
2278 io_commit_cqring(ctx);
2279 io_cqring_ev_posted_iopoll(ctx);
2280 io_req_free_batch_finish(ctx, &rb);
2283 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2286 struct io_kiocb *req, *tmp;
2292 * Only spin for completions if we don't have multiple devices hanging
2293 * off our complete list, and we're under the requested amount.
2295 spin = !ctx->poll_multi_file && *nr_events < min;
2298 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2299 struct kiocb *kiocb = &req->rw.kiocb;
2302 * Move completed and retryable entries to our local lists.
2303 * If we find a request that requires polling, break out
2304 * and complete those lists first, if we have entries there.
2306 if (READ_ONCE(req->iopoll_completed)) {
2307 list_move_tail(&req->inflight_entry, &done);
2310 if (!list_empty(&done))
2313 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2317 /* iopoll may have completed current req */
2318 if (READ_ONCE(req->iopoll_completed))
2319 list_move_tail(&req->inflight_entry, &done);
2326 if (!list_empty(&done))
2327 io_iopoll_complete(ctx, nr_events, &done);
2333 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2334 * non-spinning poll check - we'll still enter the driver poll loop, but only
2335 * as a non-spinning completion check.
2337 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2340 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2343 ret = io_do_iopoll(ctx, nr_events, min);
2346 if (*nr_events >= min)
2354 * We can't just wait for polled events to come to us, we have to actively
2355 * find and complete them.
2357 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2359 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2362 mutex_lock(&ctx->uring_lock);
2363 while (!list_empty(&ctx->iopoll_list)) {
2364 unsigned int nr_events = 0;
2366 io_do_iopoll(ctx, &nr_events, 0);
2368 /* let it sleep and repeat later if can't complete a request */
2372 * Ensure we allow local-to-the-cpu processing to take place,
2373 * in this case we need to ensure that we reap all events.
2374 * Also let task_work, etc. to progress by releasing the mutex
2376 if (need_resched()) {
2377 mutex_unlock(&ctx->uring_lock);
2379 mutex_lock(&ctx->uring_lock);
2382 mutex_unlock(&ctx->uring_lock);
2385 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2387 unsigned int nr_events = 0;
2391 * We disallow the app entering submit/complete with polling, but we
2392 * still need to lock the ring to prevent racing with polled issue
2393 * that got punted to a workqueue.
2395 mutex_lock(&ctx->uring_lock);
2398 * Don't enter poll loop if we already have events pending.
2399 * If we do, we can potentially be spinning for commands that
2400 * already triggered a CQE (eg in error).
2402 if (test_bit(0, &ctx->cq_check_overflow))
2403 __io_cqring_overflow_flush(ctx, false);
2404 if (io_cqring_events(ctx))
2408 * If a submit got punted to a workqueue, we can have the
2409 * application entering polling for a command before it gets
2410 * issued. That app will hold the uring_lock for the duration
2411 * of the poll right here, so we need to take a breather every
2412 * now and then to ensure that the issue has a chance to add
2413 * the poll to the issued list. Otherwise we can spin here
2414 * forever, while the workqueue is stuck trying to acquire the
2417 if (list_empty(&ctx->iopoll_list)) {
2418 mutex_unlock(&ctx->uring_lock);
2420 mutex_lock(&ctx->uring_lock);
2422 if (list_empty(&ctx->iopoll_list))
2426 ret = io_iopoll_getevents(ctx, &nr_events, min);
2430 } while (min && !nr_events && !need_resched());
2432 mutex_unlock(&ctx->uring_lock);
2436 static void kiocb_end_write(struct io_kiocb *req)
2439 * Tell lockdep we inherited freeze protection from submission
2442 if (req->flags & REQ_F_ISREG) {
2443 struct super_block *sb = file_inode(req->file)->i_sb;
2445 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2451 static bool io_resubmit_prep(struct io_kiocb *req)
2453 struct io_async_rw *rw = req->async_data;
2456 return !io_req_prep_async(req);
2457 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2458 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2462 static bool io_rw_should_reissue(struct io_kiocb *req)
2464 umode_t mode = file_inode(req->file)->i_mode;
2465 struct io_ring_ctx *ctx = req->ctx;
2467 if (!S_ISBLK(mode) && !S_ISREG(mode))
2469 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2470 !(ctx->flags & IORING_SETUP_IOPOLL)))
2473 * If ref is dying, we might be running poll reap from the exit work.
2474 * Don't attempt to reissue from that path, just let it fail with
2477 if (percpu_ref_is_dying(&ctx->refs))
2482 static bool io_resubmit_prep(struct io_kiocb *req)
2486 static bool io_rw_should_reissue(struct io_kiocb *req)
2492 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2493 unsigned int issue_flags)
2497 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2498 kiocb_end_write(req);
2499 if (res != req->result) {
2500 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2501 io_rw_should_reissue(req)) {
2502 req->flags |= REQ_F_REISSUE;
2505 req_set_fail_links(req);
2507 if (req->flags & REQ_F_BUFFER_SELECTED)
2508 cflags = io_put_rw_kbuf(req);
2509 __io_req_complete(req, issue_flags, res, cflags);
2512 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2514 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2516 __io_complete_rw(req, res, res2, 0);
2519 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2521 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2523 if (kiocb->ki_flags & IOCB_WRITE)
2524 kiocb_end_write(req);
2525 if (unlikely(res != req->result)) {
2526 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2527 io_resubmit_prep(req))) {
2528 req_set_fail_links(req);
2529 req->flags |= REQ_F_DONT_REISSUE;
2533 WRITE_ONCE(req->result, res);
2534 /* order with io_iopoll_complete() checking ->result */
2536 WRITE_ONCE(req->iopoll_completed, 1);
2540 * After the iocb has been issued, it's safe to be found on the poll list.
2541 * Adding the kiocb to the list AFTER submission ensures that we don't
2542 * find it from a io_iopoll_getevents() thread before the issuer is done
2543 * accessing the kiocb cookie.
2545 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2547 struct io_ring_ctx *ctx = req->ctx;
2550 * Track whether we have multiple files in our lists. This will impact
2551 * how we do polling eventually, not spinning if we're on potentially
2552 * different devices.
2554 if (list_empty(&ctx->iopoll_list)) {
2555 ctx->poll_multi_file = false;
2556 } else if (!ctx->poll_multi_file) {
2557 struct io_kiocb *list_req;
2559 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2561 if (list_req->file != req->file)
2562 ctx->poll_multi_file = true;
2566 * For fast devices, IO may have already completed. If it has, add
2567 * it to the front so we find it first.
2569 if (READ_ONCE(req->iopoll_completed))
2570 list_add(&req->inflight_entry, &ctx->iopoll_list);
2572 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2575 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2576 * task context or in io worker task context. If current task context is
2577 * sq thread, we don't need to check whether should wake up sq thread.
2579 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2580 wq_has_sleeper(&ctx->sq_data->wait))
2581 wake_up(&ctx->sq_data->wait);
2584 static inline void io_state_file_put(struct io_submit_state *state)
2586 if (state->file_refs) {
2587 fput_many(state->file, state->file_refs);
2588 state->file_refs = 0;
2593 * Get as many references to a file as we have IOs left in this submission,
2594 * assuming most submissions are for one file, or at least that each file
2595 * has more than one submission.
2597 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2602 if (state->file_refs) {
2603 if (state->fd == fd) {
2607 io_state_file_put(state);
2609 state->file = fget_many(fd, state->ios_left);
2610 if (unlikely(!state->file))
2614 state->file_refs = state->ios_left - 1;
2618 static bool io_bdev_nowait(struct block_device *bdev)
2620 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2624 * If we tracked the file through the SCM inflight mechanism, we could support
2625 * any file. For now, just ensure that anything potentially problematic is done
2628 static bool __io_file_supports_async(struct file *file, int rw)
2630 umode_t mode = file_inode(file)->i_mode;
2632 if (S_ISBLK(mode)) {
2633 if (IS_ENABLED(CONFIG_BLOCK) &&
2634 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2638 if (S_ISCHR(mode) || S_ISSOCK(mode))
2640 if (S_ISREG(mode)) {
2641 if (IS_ENABLED(CONFIG_BLOCK) &&
2642 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2643 file->f_op != &io_uring_fops)
2648 /* any ->read/write should understand O_NONBLOCK */
2649 if (file->f_flags & O_NONBLOCK)
2652 if (!(file->f_mode & FMODE_NOWAIT))
2656 return file->f_op->read_iter != NULL;
2658 return file->f_op->write_iter != NULL;
2661 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2663 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2665 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2668 return __io_file_supports_async(req->file, rw);
2671 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2673 struct io_ring_ctx *ctx = req->ctx;
2674 struct kiocb *kiocb = &req->rw.kiocb;
2675 struct file *file = req->file;
2679 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2680 req->flags |= REQ_F_ISREG;
2682 kiocb->ki_pos = READ_ONCE(sqe->off);
2683 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2684 req->flags |= REQ_F_CUR_POS;
2685 kiocb->ki_pos = file->f_pos;
2687 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2688 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2689 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2693 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2694 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2695 req->flags |= REQ_F_NOWAIT;
2697 ioprio = READ_ONCE(sqe->ioprio);
2699 ret = ioprio_check_cap(ioprio);
2703 kiocb->ki_ioprio = ioprio;
2705 kiocb->ki_ioprio = get_current_ioprio();
2707 if (ctx->flags & IORING_SETUP_IOPOLL) {
2708 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2709 !kiocb->ki_filp->f_op->iopoll)
2712 kiocb->ki_flags |= IOCB_HIPRI;
2713 kiocb->ki_complete = io_complete_rw_iopoll;
2714 req->iopoll_completed = 0;
2716 if (kiocb->ki_flags & IOCB_HIPRI)
2718 kiocb->ki_complete = io_complete_rw;
2721 req->rw.addr = READ_ONCE(sqe->addr);
2722 req->rw.len = READ_ONCE(sqe->len);
2723 req->buf_index = READ_ONCE(sqe->buf_index);
2727 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2733 case -ERESTARTNOINTR:
2734 case -ERESTARTNOHAND:
2735 case -ERESTART_RESTARTBLOCK:
2737 * We can't just restart the syscall, since previously
2738 * submitted sqes may already be in progress. Just fail this
2744 kiocb->ki_complete(kiocb, ret, 0);
2748 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2749 unsigned int issue_flags)
2751 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2752 struct io_async_rw *io = req->async_data;
2753 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2755 /* add previously done IO, if any */
2756 if (io && io->bytes_done > 0) {
2758 ret = io->bytes_done;
2760 ret += io->bytes_done;
2763 if (req->flags & REQ_F_CUR_POS)
2764 req->file->f_pos = kiocb->ki_pos;
2765 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2766 __io_complete_rw(req, ret, 0, issue_flags);
2768 io_rw_done(kiocb, ret);
2770 if (check_reissue && req->flags & REQ_F_REISSUE) {
2771 req->flags &= ~REQ_F_REISSUE;
2772 if (!io_resubmit_prep(req)) {
2774 io_queue_async_work(req);
2778 req_set_fail_links(req);
2779 if (req->flags & REQ_F_BUFFER_SELECTED)
2780 cflags = io_put_rw_kbuf(req);
2781 __io_req_complete(req, issue_flags, ret, cflags);
2786 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2788 struct io_ring_ctx *ctx = req->ctx;
2789 size_t len = req->rw.len;
2790 struct io_mapped_ubuf *imu;
2791 u16 index, buf_index = req->buf_index;
2792 u64 buf_end, buf_addr = req->rw.addr;
2795 if (unlikely(buf_index >= ctx->nr_user_bufs))
2797 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2798 imu = &ctx->user_bufs[index];
2799 buf_addr = req->rw.addr;
2801 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2803 /* not inside the mapped region */
2804 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2808 * May not be a start of buffer, set size appropriately
2809 * and advance us to the beginning.
2811 offset = buf_addr - imu->ubuf;
2812 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2816 * Don't use iov_iter_advance() here, as it's really slow for
2817 * using the latter parts of a big fixed buffer - it iterates
2818 * over each segment manually. We can cheat a bit here, because
2821 * 1) it's a BVEC iter, we set it up
2822 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2823 * first and last bvec
2825 * So just find our index, and adjust the iterator afterwards.
2826 * If the offset is within the first bvec (or the whole first
2827 * bvec, just use iov_iter_advance(). This makes it easier
2828 * since we can just skip the first segment, which may not
2829 * be PAGE_SIZE aligned.
2831 const struct bio_vec *bvec = imu->bvec;
2833 if (offset <= bvec->bv_len) {
2834 iov_iter_advance(iter, offset);
2836 unsigned long seg_skip;
2838 /* skip first vec */
2839 offset -= bvec->bv_len;
2840 seg_skip = 1 + (offset >> PAGE_SHIFT);
2842 iter->bvec = bvec + seg_skip;
2843 iter->nr_segs -= seg_skip;
2844 iter->count -= bvec->bv_len + offset;
2845 iter->iov_offset = offset & ~PAGE_MASK;
2852 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2855 mutex_unlock(&ctx->uring_lock);
2858 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2861 * "Normal" inline submissions always hold the uring_lock, since we
2862 * grab it from the system call. Same is true for the SQPOLL offload.
2863 * The only exception is when we've detached the request and issue it
2864 * from an async worker thread, grab the lock for that case.
2867 mutex_lock(&ctx->uring_lock);
2870 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2871 int bgid, struct io_buffer *kbuf,
2874 struct io_buffer *head;
2876 if (req->flags & REQ_F_BUFFER_SELECTED)
2879 io_ring_submit_lock(req->ctx, needs_lock);
2881 lockdep_assert_held(&req->ctx->uring_lock);
2883 head = xa_load(&req->ctx->io_buffers, bgid);
2885 if (!list_empty(&head->list)) {
2886 kbuf = list_last_entry(&head->list, struct io_buffer,
2888 list_del(&kbuf->list);
2891 xa_erase(&req->ctx->io_buffers, bgid);
2893 if (*len > kbuf->len)
2896 kbuf = ERR_PTR(-ENOBUFS);
2899 io_ring_submit_unlock(req->ctx, needs_lock);
2904 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2907 struct io_buffer *kbuf;
2910 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2911 bgid = req->buf_index;
2912 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2915 req->rw.addr = (u64) (unsigned long) kbuf;
2916 req->flags |= REQ_F_BUFFER_SELECTED;
2917 return u64_to_user_ptr(kbuf->addr);
2920 #ifdef CONFIG_COMPAT
2921 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2924 struct compat_iovec __user *uiov;
2925 compat_ssize_t clen;
2929 uiov = u64_to_user_ptr(req->rw.addr);
2930 if (!access_ok(uiov, sizeof(*uiov)))
2932 if (__get_user(clen, &uiov->iov_len))
2938 buf = io_rw_buffer_select(req, &len, needs_lock);
2940 return PTR_ERR(buf);
2941 iov[0].iov_base = buf;
2942 iov[0].iov_len = (compat_size_t) len;
2947 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2950 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2954 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2957 len = iov[0].iov_len;
2960 buf = io_rw_buffer_select(req, &len, needs_lock);
2962 return PTR_ERR(buf);
2963 iov[0].iov_base = buf;
2964 iov[0].iov_len = len;
2968 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2971 if (req->flags & REQ_F_BUFFER_SELECTED) {
2972 struct io_buffer *kbuf;
2974 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2975 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2976 iov[0].iov_len = kbuf->len;
2979 if (req->rw.len != 1)
2982 #ifdef CONFIG_COMPAT
2983 if (req->ctx->compat)
2984 return io_compat_import(req, iov, needs_lock);
2987 return __io_iov_buffer_select(req, iov, needs_lock);
2990 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2991 struct iov_iter *iter, bool needs_lock)
2993 void __user *buf = u64_to_user_ptr(req->rw.addr);
2994 size_t sqe_len = req->rw.len;
2995 u8 opcode = req->opcode;
2998 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3000 return io_import_fixed(req, rw, iter);
3003 /* buffer index only valid with fixed read/write, or buffer select */
3004 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3007 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3008 if (req->flags & REQ_F_BUFFER_SELECT) {
3009 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3011 return PTR_ERR(buf);
3012 req->rw.len = sqe_len;
3015 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3020 if (req->flags & REQ_F_BUFFER_SELECT) {
3021 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3023 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3028 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3032 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3034 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3038 * For files that don't have ->read_iter() and ->write_iter(), handle them
3039 * by looping over ->read() or ->write() manually.
3041 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3043 struct kiocb *kiocb = &req->rw.kiocb;
3044 struct file *file = req->file;
3048 * Don't support polled IO through this interface, and we can't
3049 * support non-blocking either. For the latter, this just causes
3050 * the kiocb to be handled from an async context.
3052 if (kiocb->ki_flags & IOCB_HIPRI)
3054 if (kiocb->ki_flags & IOCB_NOWAIT)
3057 while (iov_iter_count(iter)) {
3061 if (!iov_iter_is_bvec(iter)) {
3062 iovec = iov_iter_iovec(iter);
3064 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3065 iovec.iov_len = req->rw.len;
3069 nr = file->f_op->read(file, iovec.iov_base,
3070 iovec.iov_len, io_kiocb_ppos(kiocb));
3072 nr = file->f_op->write(file, iovec.iov_base,
3073 iovec.iov_len, io_kiocb_ppos(kiocb));
3082 if (nr != iovec.iov_len)
3086 iov_iter_advance(iter, nr);
3092 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3093 const struct iovec *fast_iov, struct iov_iter *iter)
3095 struct io_async_rw *rw = req->async_data;
3097 memcpy(&rw->iter, iter, sizeof(*iter));
3098 rw->free_iovec = iovec;
3100 /* can only be fixed buffers, no need to do anything */
3101 if (iov_iter_is_bvec(iter))
3104 unsigned iov_off = 0;
3106 rw->iter.iov = rw->fast_iov;
3107 if (iter->iov != fast_iov) {
3108 iov_off = iter->iov - fast_iov;
3109 rw->iter.iov += iov_off;
3111 if (rw->fast_iov != fast_iov)
3112 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3113 sizeof(struct iovec) * iter->nr_segs);
3115 req->flags |= REQ_F_NEED_CLEANUP;
3119 static inline int io_alloc_async_data(struct io_kiocb *req)
3121 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3122 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3123 return req->async_data == NULL;
3126 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3127 const struct iovec *fast_iov,
3128 struct iov_iter *iter, bool force)
3130 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3132 if (!req->async_data) {
3133 if (io_alloc_async_data(req)) {
3138 io_req_map_rw(req, iovec, fast_iov, iter);
3143 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3145 struct io_async_rw *iorw = req->async_data;
3146 struct iovec *iov = iorw->fast_iov;
3149 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3150 if (unlikely(ret < 0))
3153 iorw->bytes_done = 0;
3154 iorw->free_iovec = iov;
3156 req->flags |= REQ_F_NEED_CLEANUP;
3160 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3162 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3164 return io_prep_rw(req, sqe);
3168 * This is our waitqueue callback handler, registered through lock_page_async()
3169 * when we initially tried to do the IO with the iocb armed our waitqueue.
3170 * This gets called when the page is unlocked, and we generally expect that to
3171 * happen when the page IO is completed and the page is now uptodate. This will
3172 * queue a task_work based retry of the operation, attempting to copy the data
3173 * again. If the latter fails because the page was NOT uptodate, then we will
3174 * do a thread based blocking retry of the operation. That's the unexpected
3177 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3178 int sync, void *arg)
3180 struct wait_page_queue *wpq;
3181 struct io_kiocb *req = wait->private;
3182 struct wait_page_key *key = arg;
3184 wpq = container_of(wait, struct wait_page_queue, wait);
3186 if (!wake_page_match(wpq, key))
3189 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3190 list_del_init(&wait->entry);
3192 /* submit ref gets dropped, acquire a new one */
3194 io_req_task_queue(req);
3199 * This controls whether a given IO request should be armed for async page
3200 * based retry. If we return false here, the request is handed to the async
3201 * worker threads for retry. If we're doing buffered reads on a regular file,
3202 * we prepare a private wait_page_queue entry and retry the operation. This
3203 * will either succeed because the page is now uptodate and unlocked, or it
3204 * will register a callback when the page is unlocked at IO completion. Through
3205 * that callback, io_uring uses task_work to setup a retry of the operation.
3206 * That retry will attempt the buffered read again. The retry will generally
3207 * succeed, or in rare cases where it fails, we then fall back to using the
3208 * async worker threads for a blocking retry.
3210 static bool io_rw_should_retry(struct io_kiocb *req)
3212 struct io_async_rw *rw = req->async_data;
3213 struct wait_page_queue *wait = &rw->wpq;
3214 struct kiocb *kiocb = &req->rw.kiocb;
3216 /* never retry for NOWAIT, we just complete with -EAGAIN */
3217 if (req->flags & REQ_F_NOWAIT)
3220 /* Only for buffered IO */
3221 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3225 * just use poll if we can, and don't attempt if the fs doesn't
3226 * support callback based unlocks
3228 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3231 wait->wait.func = io_async_buf_func;
3232 wait->wait.private = req;
3233 wait->wait.flags = 0;
3234 INIT_LIST_HEAD(&wait->wait.entry);
3235 kiocb->ki_flags |= IOCB_WAITQ;
3236 kiocb->ki_flags &= ~IOCB_NOWAIT;
3237 kiocb->ki_waitq = wait;
3241 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3243 if (req->file->f_op->read_iter)
3244 return call_read_iter(req->file, &req->rw.kiocb, iter);
3245 else if (req->file->f_op->read)
3246 return loop_rw_iter(READ, req, iter);
3251 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3253 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3254 struct kiocb *kiocb = &req->rw.kiocb;
3255 struct iov_iter __iter, *iter = &__iter;
3256 struct io_async_rw *rw = req->async_data;
3257 ssize_t io_size, ret, ret2;
3258 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3264 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3268 io_size = iov_iter_count(iter);
3269 req->result = io_size;
3271 /* Ensure we clear previously set non-block flag */
3272 if (!force_nonblock)
3273 kiocb->ki_flags &= ~IOCB_NOWAIT;
3275 kiocb->ki_flags |= IOCB_NOWAIT;
3277 /* If the file doesn't support async, just async punt */
3278 if (force_nonblock && !io_file_supports_async(req, READ)) {
3279 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3280 return ret ?: -EAGAIN;
3283 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3284 if (unlikely(ret)) {
3289 ret = io_iter_do_read(req, iter);
3291 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3292 req->flags &= ~REQ_F_REISSUE;
3293 /* IOPOLL retry should happen for io-wq threads */
3294 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3296 /* no retry on NONBLOCK nor RWF_NOWAIT */
3297 if (req->flags & REQ_F_NOWAIT)
3299 /* some cases will consume bytes even on error returns */
3300 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3302 } else if (ret == -EIOCBQUEUED) {
3304 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3305 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3306 /* read all, failed, already did sync or don't want to retry */
3310 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3315 rw = req->async_data;
3316 /* now use our persistent iterator, if we aren't already */
3321 rw->bytes_done += ret;
3322 /* if we can retry, do so with the callbacks armed */
3323 if (!io_rw_should_retry(req)) {
3324 kiocb->ki_flags &= ~IOCB_WAITQ;
3329 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3330 * we get -EIOCBQUEUED, then we'll get a notification when the
3331 * desired page gets unlocked. We can also get a partial read
3332 * here, and if we do, then just retry at the new offset.
3334 ret = io_iter_do_read(req, iter);
3335 if (ret == -EIOCBQUEUED)
3337 /* we got some bytes, but not all. retry. */
3338 kiocb->ki_flags &= ~IOCB_WAITQ;
3339 } while (ret > 0 && ret < io_size);
3341 kiocb_done(kiocb, ret, issue_flags);
3343 /* it's faster to check here then delegate to kfree */
3349 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3351 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3353 return io_prep_rw(req, sqe);
3356 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3358 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3359 struct kiocb *kiocb = &req->rw.kiocb;
3360 struct iov_iter __iter, *iter = &__iter;
3361 struct io_async_rw *rw = req->async_data;
3362 ssize_t ret, ret2, io_size;
3363 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3369 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3373 io_size = iov_iter_count(iter);
3374 req->result = io_size;
3376 /* Ensure we clear previously set non-block flag */
3377 if (!force_nonblock)
3378 kiocb->ki_flags &= ~IOCB_NOWAIT;
3380 kiocb->ki_flags |= IOCB_NOWAIT;
3382 /* If the file doesn't support async, just async punt */
3383 if (force_nonblock && !io_file_supports_async(req, WRITE))
3386 /* file path doesn't support NOWAIT for non-direct_IO */
3387 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3388 (req->flags & REQ_F_ISREG))
3391 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3396 * Open-code file_start_write here to grab freeze protection,
3397 * which will be released by another thread in
3398 * io_complete_rw(). Fool lockdep by telling it the lock got
3399 * released so that it doesn't complain about the held lock when
3400 * we return to userspace.
3402 if (req->flags & REQ_F_ISREG) {
3403 sb_start_write(file_inode(req->file)->i_sb);
3404 __sb_writers_release(file_inode(req->file)->i_sb,
3407 kiocb->ki_flags |= IOCB_WRITE;
3409 if (req->file->f_op->write_iter)
3410 ret2 = call_write_iter(req->file, kiocb, iter);
3411 else if (req->file->f_op->write)
3412 ret2 = loop_rw_iter(WRITE, req, iter);
3416 if (req->flags & REQ_F_REISSUE) {
3417 req->flags &= ~REQ_F_REISSUE;
3422 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3423 * retry them without IOCB_NOWAIT.
3425 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3427 /* no retry on NONBLOCK nor RWF_NOWAIT */
3428 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3430 if (!force_nonblock || ret2 != -EAGAIN) {
3431 /* IOPOLL retry should happen for io-wq threads */
3432 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3435 kiocb_done(kiocb, ret2, issue_flags);
3438 /* some cases will consume bytes even on error returns */
3439 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3440 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3441 return ret ?: -EAGAIN;
3444 /* it's reportedly faster than delegating the null check to kfree() */
3450 static int io_renameat_prep(struct io_kiocb *req,
3451 const struct io_uring_sqe *sqe)
3453 struct io_rename *ren = &req->rename;
3454 const char __user *oldf, *newf;
3456 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3459 ren->old_dfd = READ_ONCE(sqe->fd);
3460 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3461 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3462 ren->new_dfd = READ_ONCE(sqe->len);
3463 ren->flags = READ_ONCE(sqe->rename_flags);
3465 ren->oldpath = getname(oldf);
3466 if (IS_ERR(ren->oldpath))
3467 return PTR_ERR(ren->oldpath);
3469 ren->newpath = getname(newf);
3470 if (IS_ERR(ren->newpath)) {
3471 putname(ren->oldpath);
3472 return PTR_ERR(ren->newpath);
3475 req->flags |= REQ_F_NEED_CLEANUP;
3479 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3481 struct io_rename *ren = &req->rename;
3484 if (issue_flags & IO_URING_F_NONBLOCK)
3487 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3488 ren->newpath, ren->flags);
3490 req->flags &= ~REQ_F_NEED_CLEANUP;
3492 req_set_fail_links(req);
3493 io_req_complete(req, ret);
3497 static int io_unlinkat_prep(struct io_kiocb *req,
3498 const struct io_uring_sqe *sqe)
3500 struct io_unlink *un = &req->unlink;
3501 const char __user *fname;
3503 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3506 un->dfd = READ_ONCE(sqe->fd);
3508 un->flags = READ_ONCE(sqe->unlink_flags);
3509 if (un->flags & ~AT_REMOVEDIR)
3512 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3513 un->filename = getname(fname);
3514 if (IS_ERR(un->filename))
3515 return PTR_ERR(un->filename);
3517 req->flags |= REQ_F_NEED_CLEANUP;
3521 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3523 struct io_unlink *un = &req->unlink;
3526 if (issue_flags & IO_URING_F_NONBLOCK)
3529 if (un->flags & AT_REMOVEDIR)
3530 ret = do_rmdir(un->dfd, un->filename);
3532 ret = do_unlinkat(un->dfd, un->filename);
3534 req->flags &= ~REQ_F_NEED_CLEANUP;
3536 req_set_fail_links(req);
3537 io_req_complete(req, ret);
3541 static int io_shutdown_prep(struct io_kiocb *req,
3542 const struct io_uring_sqe *sqe)
3544 #if defined(CONFIG_NET)
3545 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3547 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3551 req->shutdown.how = READ_ONCE(sqe->len);
3558 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3560 #if defined(CONFIG_NET)
3561 struct socket *sock;
3564 if (issue_flags & IO_URING_F_NONBLOCK)
3567 sock = sock_from_file(req->file);
3568 if (unlikely(!sock))
3571 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3573 req_set_fail_links(req);
3574 io_req_complete(req, ret);
3581 static int __io_splice_prep(struct io_kiocb *req,
3582 const struct io_uring_sqe *sqe)
3584 struct io_splice* sp = &req->splice;
3585 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3587 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3591 sp->len = READ_ONCE(sqe->len);
3592 sp->flags = READ_ONCE(sqe->splice_flags);
3594 if (unlikely(sp->flags & ~valid_flags))
3597 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3598 (sp->flags & SPLICE_F_FD_IN_FIXED));
3601 req->flags |= REQ_F_NEED_CLEANUP;
3605 static int io_tee_prep(struct io_kiocb *req,
3606 const struct io_uring_sqe *sqe)
3608 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3610 return __io_splice_prep(req, sqe);
3613 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3615 struct io_splice *sp = &req->splice;
3616 struct file *in = sp->file_in;
3617 struct file *out = sp->file_out;
3618 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3621 if (issue_flags & IO_URING_F_NONBLOCK)
3624 ret = do_tee(in, out, sp->len, flags);
3626 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3628 req->flags &= ~REQ_F_NEED_CLEANUP;
3631 req_set_fail_links(req);
3632 io_req_complete(req, ret);
3636 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3638 struct io_splice* sp = &req->splice;
3640 sp->off_in = READ_ONCE(sqe->splice_off_in);
3641 sp->off_out = READ_ONCE(sqe->off);
3642 return __io_splice_prep(req, sqe);
3645 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3647 struct io_splice *sp = &req->splice;
3648 struct file *in = sp->file_in;
3649 struct file *out = sp->file_out;
3650 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3651 loff_t *poff_in, *poff_out;
3654 if (issue_flags & IO_URING_F_NONBLOCK)
3657 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3658 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3661 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3663 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3665 req->flags &= ~REQ_F_NEED_CLEANUP;
3668 req_set_fail_links(req);
3669 io_req_complete(req, ret);
3674 * IORING_OP_NOP just posts a completion event, nothing else.
3676 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3678 struct io_ring_ctx *ctx = req->ctx;
3680 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3683 __io_req_complete(req, issue_flags, 0, 0);
3687 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3689 struct io_ring_ctx *ctx = req->ctx;
3694 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3696 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3699 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3700 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3703 req->sync.off = READ_ONCE(sqe->off);
3704 req->sync.len = READ_ONCE(sqe->len);
3708 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3710 loff_t end = req->sync.off + req->sync.len;
3713 /* fsync always requires a blocking context */
3714 if (issue_flags & IO_URING_F_NONBLOCK)
3717 ret = vfs_fsync_range(req->file, req->sync.off,
3718 end > 0 ? end : LLONG_MAX,
3719 req->sync.flags & IORING_FSYNC_DATASYNC);
3721 req_set_fail_links(req);
3722 io_req_complete(req, ret);
3726 static int io_fallocate_prep(struct io_kiocb *req,
3727 const struct io_uring_sqe *sqe)
3729 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3731 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3734 req->sync.off = READ_ONCE(sqe->off);
3735 req->sync.len = READ_ONCE(sqe->addr);
3736 req->sync.mode = READ_ONCE(sqe->len);
3740 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3744 /* fallocate always requiring blocking context */
3745 if (issue_flags & IO_URING_F_NONBLOCK)
3747 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3750 req_set_fail_links(req);
3751 io_req_complete(req, ret);
3755 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3757 const char __user *fname;
3760 if (unlikely(sqe->ioprio || sqe->buf_index))
3762 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3765 /* open.how should be already initialised */
3766 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3767 req->open.how.flags |= O_LARGEFILE;
3769 req->open.dfd = READ_ONCE(sqe->fd);
3770 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3771 req->open.filename = getname(fname);
3772 if (IS_ERR(req->open.filename)) {
3773 ret = PTR_ERR(req->open.filename);
3774 req->open.filename = NULL;
3777 req->open.nofile = rlimit(RLIMIT_NOFILE);
3778 req->flags |= REQ_F_NEED_CLEANUP;
3782 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3786 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3788 mode = READ_ONCE(sqe->len);
3789 flags = READ_ONCE(sqe->open_flags);
3790 req->open.how = build_open_how(flags, mode);
3791 return __io_openat_prep(req, sqe);
3794 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3796 struct open_how __user *how;
3800 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3802 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3803 len = READ_ONCE(sqe->len);
3804 if (len < OPEN_HOW_SIZE_VER0)
3807 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3812 return __io_openat_prep(req, sqe);
3815 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3817 struct open_flags op;
3820 bool resolve_nonblock;
3823 ret = build_open_flags(&req->open.how, &op);
3826 nonblock_set = op.open_flag & O_NONBLOCK;
3827 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3828 if (issue_flags & IO_URING_F_NONBLOCK) {
3830 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3831 * it'll always -EAGAIN
3833 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3835 op.lookup_flags |= LOOKUP_CACHED;
3836 op.open_flag |= O_NONBLOCK;
3839 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3843 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3844 /* only retry if RESOLVE_CACHED wasn't already set by application */
3845 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3846 file == ERR_PTR(-EAGAIN)) {
3848 * We could hang on to this 'fd', but seems like marginal
3849 * gain for something that is now known to be a slower path.
3850 * So just put it, and we'll get a new one when we retry.
3858 ret = PTR_ERR(file);
3860 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3861 file->f_flags &= ~O_NONBLOCK;
3862 fsnotify_open(file);
3863 fd_install(ret, file);
3866 putname(req->open.filename);
3867 req->flags &= ~REQ_F_NEED_CLEANUP;
3869 req_set_fail_links(req);
3870 __io_req_complete(req, issue_flags, ret, 0);
3874 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3876 return io_openat2(req, issue_flags);
3879 static int io_remove_buffers_prep(struct io_kiocb *req,
3880 const struct io_uring_sqe *sqe)
3882 struct io_provide_buf *p = &req->pbuf;
3885 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3888 tmp = READ_ONCE(sqe->fd);
3889 if (!tmp || tmp > USHRT_MAX)
3892 memset(p, 0, sizeof(*p));
3894 p->bgid = READ_ONCE(sqe->buf_group);
3898 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3899 int bgid, unsigned nbufs)
3903 /* shouldn't happen */
3907 /* the head kbuf is the list itself */
3908 while (!list_empty(&buf->list)) {
3909 struct io_buffer *nxt;
3911 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3912 list_del(&nxt->list);
3919 xa_erase(&ctx->io_buffers, bgid);
3924 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3926 struct io_provide_buf *p = &req->pbuf;
3927 struct io_ring_ctx *ctx = req->ctx;
3928 struct io_buffer *head;
3930 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3932 io_ring_submit_lock(ctx, !force_nonblock);
3934 lockdep_assert_held(&ctx->uring_lock);
3937 head = xa_load(&ctx->io_buffers, p->bgid);
3939 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3941 req_set_fail_links(req);
3943 /* complete before unlock, IOPOLL may need the lock */
3944 __io_req_complete(req, issue_flags, ret, 0);
3945 io_ring_submit_unlock(ctx, !force_nonblock);
3949 static int io_provide_buffers_prep(struct io_kiocb *req,
3950 const struct io_uring_sqe *sqe)
3953 struct io_provide_buf *p = &req->pbuf;
3956 if (sqe->ioprio || sqe->rw_flags)
3959 tmp = READ_ONCE(sqe->fd);
3960 if (!tmp || tmp > USHRT_MAX)
3963 p->addr = READ_ONCE(sqe->addr);
3964 p->len = READ_ONCE(sqe->len);
3966 size = (unsigned long)p->len * p->nbufs;
3967 if (!access_ok(u64_to_user_ptr(p->addr), size))
3970 p->bgid = READ_ONCE(sqe->buf_group);
3971 tmp = READ_ONCE(sqe->off);
3972 if (tmp > USHRT_MAX)
3978 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3980 struct io_buffer *buf;
3981 u64 addr = pbuf->addr;
3982 int i, bid = pbuf->bid;
3984 for (i = 0; i < pbuf->nbufs; i++) {
3985 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3990 buf->len = pbuf->len;
3995 INIT_LIST_HEAD(&buf->list);
3998 list_add_tail(&buf->list, &(*head)->list);
4002 return i ? i : -ENOMEM;
4005 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4007 struct io_provide_buf *p = &req->pbuf;
4008 struct io_ring_ctx *ctx = req->ctx;
4009 struct io_buffer *head, *list;
4011 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4013 io_ring_submit_lock(ctx, !force_nonblock);
4015 lockdep_assert_held(&ctx->uring_lock);
4017 list = head = xa_load(&ctx->io_buffers, p->bgid);
4019 ret = io_add_buffers(p, &head);
4020 if (ret >= 0 && !list) {
4021 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4023 __io_remove_buffers(ctx, head, p->bgid, -1U);
4026 req_set_fail_links(req);
4027 /* complete before unlock, IOPOLL may need the lock */
4028 __io_req_complete(req, issue_flags, ret, 0);
4029 io_ring_submit_unlock(ctx, !force_nonblock);
4033 static int io_epoll_ctl_prep(struct io_kiocb *req,
4034 const struct io_uring_sqe *sqe)
4036 #if defined(CONFIG_EPOLL)
4037 if (sqe->ioprio || sqe->buf_index)
4039 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4042 req->epoll.epfd = READ_ONCE(sqe->fd);
4043 req->epoll.op = READ_ONCE(sqe->len);
4044 req->epoll.fd = READ_ONCE(sqe->off);
4046 if (ep_op_has_event(req->epoll.op)) {
4047 struct epoll_event __user *ev;
4049 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4050 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4060 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4062 #if defined(CONFIG_EPOLL)
4063 struct io_epoll *ie = &req->epoll;
4065 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4067 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4068 if (force_nonblock && ret == -EAGAIN)
4072 req_set_fail_links(req);
4073 __io_req_complete(req, issue_flags, ret, 0);
4080 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4082 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4083 if (sqe->ioprio || sqe->buf_index || sqe->off)
4085 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4088 req->madvise.addr = READ_ONCE(sqe->addr);
4089 req->madvise.len = READ_ONCE(sqe->len);
4090 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4097 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4099 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4100 struct io_madvise *ma = &req->madvise;
4103 if (issue_flags & IO_URING_F_NONBLOCK)
4106 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4108 req_set_fail_links(req);
4109 io_req_complete(req, ret);
4116 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4118 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4120 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4123 req->fadvise.offset = READ_ONCE(sqe->off);
4124 req->fadvise.len = READ_ONCE(sqe->len);
4125 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4129 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4131 struct io_fadvise *fa = &req->fadvise;
4134 if (issue_flags & IO_URING_F_NONBLOCK) {
4135 switch (fa->advice) {
4136 case POSIX_FADV_NORMAL:
4137 case POSIX_FADV_RANDOM:
4138 case POSIX_FADV_SEQUENTIAL:
4145 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4147 req_set_fail_links(req);
4148 __io_req_complete(req, issue_flags, ret, 0);
4152 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4154 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4156 if (sqe->ioprio || sqe->buf_index)
4158 if (req->flags & REQ_F_FIXED_FILE)
4161 req->statx.dfd = READ_ONCE(sqe->fd);
4162 req->statx.mask = READ_ONCE(sqe->len);
4163 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4164 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4165 req->statx.flags = READ_ONCE(sqe->statx_flags);
4170 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4172 struct io_statx *ctx = &req->statx;
4175 if (issue_flags & IO_URING_F_NONBLOCK)
4178 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4182 req_set_fail_links(req);
4183 io_req_complete(req, ret);
4187 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4189 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4191 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4192 sqe->rw_flags || sqe->buf_index)
4194 if (req->flags & REQ_F_FIXED_FILE)
4197 req->close.fd = READ_ONCE(sqe->fd);
4201 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4203 struct files_struct *files = current->files;
4204 struct io_close *close = &req->close;
4205 struct fdtable *fdt;
4206 struct file *file = NULL;
4209 spin_lock(&files->file_lock);
4210 fdt = files_fdtable(files);
4211 if (close->fd >= fdt->max_fds) {
4212 spin_unlock(&files->file_lock);
4215 file = fdt->fd[close->fd];
4216 if (!file || file->f_op == &io_uring_fops) {
4217 spin_unlock(&files->file_lock);
4222 /* if the file has a flush method, be safe and punt to async */
4223 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4224 spin_unlock(&files->file_lock);
4228 ret = __close_fd_get_file(close->fd, &file);
4229 spin_unlock(&files->file_lock);
4236 /* No ->flush() or already async, safely close from here */
4237 ret = filp_close(file, current->files);
4240 req_set_fail_links(req);
4243 __io_req_complete(req, issue_flags, ret, 0);
4247 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4249 struct io_ring_ctx *ctx = req->ctx;
4251 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4253 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4256 req->sync.off = READ_ONCE(sqe->off);
4257 req->sync.len = READ_ONCE(sqe->len);
4258 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4262 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4266 /* sync_file_range always requires a blocking context */
4267 if (issue_flags & IO_URING_F_NONBLOCK)
4270 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4273 req_set_fail_links(req);
4274 io_req_complete(req, ret);
4278 #if defined(CONFIG_NET)
4279 static int io_setup_async_msg(struct io_kiocb *req,
4280 struct io_async_msghdr *kmsg)
4282 struct io_async_msghdr *async_msg = req->async_data;
4286 if (io_alloc_async_data(req)) {
4287 kfree(kmsg->free_iov);
4290 async_msg = req->async_data;
4291 req->flags |= REQ_F_NEED_CLEANUP;
4292 memcpy(async_msg, kmsg, sizeof(*kmsg));
4293 async_msg->msg.msg_name = &async_msg->addr;
4294 /* if were using fast_iov, set it to the new one */
4295 if (!async_msg->free_iov)
4296 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4301 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4302 struct io_async_msghdr *iomsg)
4304 iomsg->msg.msg_name = &iomsg->addr;
4305 iomsg->free_iov = iomsg->fast_iov;
4306 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4307 req->sr_msg.msg_flags, &iomsg->free_iov);
4310 static int io_sendmsg_prep_async(struct io_kiocb *req)
4314 ret = io_sendmsg_copy_hdr(req, req->async_data);
4316 req->flags |= REQ_F_NEED_CLEANUP;
4320 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4322 struct io_sr_msg *sr = &req->sr_msg;
4324 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4327 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4328 sr->len = READ_ONCE(sqe->len);
4329 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4330 if (sr->msg_flags & MSG_DONTWAIT)
4331 req->flags |= REQ_F_NOWAIT;
4333 #ifdef CONFIG_COMPAT
4334 if (req->ctx->compat)
4335 sr->msg_flags |= MSG_CMSG_COMPAT;
4340 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4342 struct io_async_msghdr iomsg, *kmsg;
4343 struct socket *sock;
4348 sock = sock_from_file(req->file);
4349 if (unlikely(!sock))
4352 kmsg = req->async_data;
4354 ret = io_sendmsg_copy_hdr(req, &iomsg);
4360 flags = req->sr_msg.msg_flags;
4361 if (issue_flags & IO_URING_F_NONBLOCK)
4362 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;
4406 if (issue_flags & IO_URING_F_NONBLOCK)
4407 flags |= MSG_DONTWAIT;
4408 if (flags & MSG_WAITALL)
4409 min_ret = iov_iter_count(&msg.msg_iter);
4411 msg.msg_flags = flags;
4412 ret = sock_sendmsg(sock, &msg);
4413 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4415 if (ret == -ERESTARTSYS)
4419 req_set_fail_links(req);
4420 __io_req_complete(req, issue_flags, ret, 0);
4424 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4425 struct io_async_msghdr *iomsg)
4427 struct io_sr_msg *sr = &req->sr_msg;
4428 struct iovec __user *uiov;
4432 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4433 &iomsg->uaddr, &uiov, &iov_len);
4437 if (req->flags & REQ_F_BUFFER_SELECT) {
4440 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4442 sr->len = iomsg->fast_iov[0].iov_len;
4443 iomsg->free_iov = NULL;
4445 iomsg->free_iov = iomsg->fast_iov;
4446 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4447 &iomsg->free_iov, &iomsg->msg.msg_iter,
4456 #ifdef CONFIG_COMPAT
4457 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4458 struct io_async_msghdr *iomsg)
4460 struct io_sr_msg *sr = &req->sr_msg;
4461 struct compat_iovec __user *uiov;
4466 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4471 uiov = compat_ptr(ptr);
4472 if (req->flags & REQ_F_BUFFER_SELECT) {
4473 compat_ssize_t clen;
4477 if (!access_ok(uiov, sizeof(*uiov)))
4479 if (__get_user(clen, &uiov->iov_len))
4484 iomsg->free_iov = NULL;
4486 iomsg->free_iov = iomsg->fast_iov;
4487 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4488 UIO_FASTIOV, &iomsg->free_iov,
4489 &iomsg->msg.msg_iter, true);
4498 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4499 struct io_async_msghdr *iomsg)
4501 iomsg->msg.msg_name = &iomsg->addr;
4503 #ifdef CONFIG_COMPAT
4504 if (req->ctx->compat)
4505 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4508 return __io_recvmsg_copy_hdr(req, iomsg);
4511 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4514 struct io_sr_msg *sr = &req->sr_msg;
4515 struct io_buffer *kbuf;
4517 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4522 req->flags |= REQ_F_BUFFER_SELECTED;
4526 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4528 return io_put_kbuf(req, req->sr_msg.kbuf);
4531 static int io_recvmsg_prep_async(struct io_kiocb *req)
4535 ret = io_recvmsg_copy_hdr(req, req->async_data);
4537 req->flags |= REQ_F_NEED_CLEANUP;
4541 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4543 struct io_sr_msg *sr = &req->sr_msg;
4545 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4548 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4549 sr->len = READ_ONCE(sqe->len);
4550 sr->bgid = READ_ONCE(sqe->buf_group);
4551 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4552 if (sr->msg_flags & MSG_DONTWAIT)
4553 req->flags |= REQ_F_NOWAIT;
4555 #ifdef CONFIG_COMPAT
4556 if (req->ctx->compat)
4557 sr->msg_flags |= MSG_CMSG_COMPAT;
4562 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4564 struct io_async_msghdr iomsg, *kmsg;
4565 struct socket *sock;
4566 struct io_buffer *kbuf;
4569 int ret, cflags = 0;
4570 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4572 sock = sock_from_file(req->file);
4573 if (unlikely(!sock))
4576 kmsg = req->async_data;
4578 ret = io_recvmsg_copy_hdr(req, &iomsg);
4584 if (req->flags & REQ_F_BUFFER_SELECT) {
4585 kbuf = io_recv_buffer_select(req, !force_nonblock);
4587 return PTR_ERR(kbuf);
4588 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4589 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4590 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4591 1, req->sr_msg.len);
4594 flags = req->sr_msg.msg_flags;
4596 flags |= MSG_DONTWAIT;
4597 if (flags & MSG_WAITALL)
4598 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4600 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4601 kmsg->uaddr, flags);
4602 if (force_nonblock && ret == -EAGAIN)
4603 return io_setup_async_msg(req, kmsg);
4604 if (ret == -ERESTARTSYS)
4607 if (req->flags & REQ_F_BUFFER_SELECTED)
4608 cflags = io_put_recv_kbuf(req);
4609 /* fast path, check for non-NULL to avoid function call */
4611 kfree(kmsg->free_iov);
4612 req->flags &= ~REQ_F_NEED_CLEANUP;
4613 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4614 req_set_fail_links(req);
4615 __io_req_complete(req, issue_flags, ret, cflags);
4619 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4621 struct io_buffer *kbuf;
4622 struct io_sr_msg *sr = &req->sr_msg;
4624 void __user *buf = sr->buf;
4625 struct socket *sock;
4629 int ret, cflags = 0;
4630 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4632 sock = sock_from_file(req->file);
4633 if (unlikely(!sock))
4636 if (req->flags & REQ_F_BUFFER_SELECT) {
4637 kbuf = io_recv_buffer_select(req, !force_nonblock);
4639 return PTR_ERR(kbuf);
4640 buf = u64_to_user_ptr(kbuf->addr);
4643 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4647 msg.msg_name = NULL;
4648 msg.msg_control = NULL;
4649 msg.msg_controllen = 0;
4650 msg.msg_namelen = 0;
4651 msg.msg_iocb = NULL;
4654 flags = req->sr_msg.msg_flags;
4656 flags |= MSG_DONTWAIT;
4657 if (flags & MSG_WAITALL)
4658 min_ret = iov_iter_count(&msg.msg_iter);
4660 ret = sock_recvmsg(sock, &msg, flags);
4661 if (force_nonblock && ret == -EAGAIN)
4663 if (ret == -ERESTARTSYS)
4666 if (req->flags & REQ_F_BUFFER_SELECTED)
4667 cflags = io_put_recv_kbuf(req);
4668 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4669 req_set_fail_links(req);
4670 __io_req_complete(req, issue_flags, ret, cflags);
4674 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4676 struct io_accept *accept = &req->accept;
4678 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4680 if (sqe->ioprio || sqe->len || sqe->buf_index)
4683 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4684 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4685 accept->flags = READ_ONCE(sqe->accept_flags);
4686 accept->nofile = rlimit(RLIMIT_NOFILE);
4690 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4692 struct io_accept *accept = &req->accept;
4693 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4694 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4697 if (req->file->f_flags & O_NONBLOCK)
4698 req->flags |= REQ_F_NOWAIT;
4700 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4701 accept->addr_len, accept->flags,
4703 if (ret == -EAGAIN && force_nonblock)
4706 if (ret == -ERESTARTSYS)
4708 req_set_fail_links(req);
4710 __io_req_complete(req, issue_flags, ret, 0);
4714 static int io_connect_prep_async(struct io_kiocb *req)
4716 struct io_async_connect *io = req->async_data;
4717 struct io_connect *conn = &req->connect;
4719 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4722 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4724 struct io_connect *conn = &req->connect;
4726 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4728 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4731 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4732 conn->addr_len = READ_ONCE(sqe->addr2);
4736 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4738 struct io_async_connect __io, *io;
4739 unsigned file_flags;
4741 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4743 if (req->async_data) {
4744 io = req->async_data;
4746 ret = move_addr_to_kernel(req->connect.addr,
4747 req->connect.addr_len,
4754 file_flags = force_nonblock ? O_NONBLOCK : 0;
4756 ret = __sys_connect_file(req->file, &io->address,
4757 req->connect.addr_len, file_flags);
4758 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4759 if (req->async_data)
4761 if (io_alloc_async_data(req)) {
4765 memcpy(req->async_data, &__io, sizeof(__io));
4768 if (ret == -ERESTARTSYS)
4772 req_set_fail_links(req);
4773 __io_req_complete(req, issue_flags, ret, 0);
4776 #else /* !CONFIG_NET */
4777 #define IO_NETOP_FN(op) \
4778 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4780 return -EOPNOTSUPP; \
4783 #define IO_NETOP_PREP(op) \
4785 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4787 return -EOPNOTSUPP; \
4790 #define IO_NETOP_PREP_ASYNC(op) \
4792 static int io_##op##_prep_async(struct io_kiocb *req) \
4794 return -EOPNOTSUPP; \
4797 IO_NETOP_PREP_ASYNC(sendmsg);
4798 IO_NETOP_PREP_ASYNC(recvmsg);
4799 IO_NETOP_PREP_ASYNC(connect);
4800 IO_NETOP_PREP(accept);
4803 #endif /* CONFIG_NET */
4805 struct io_poll_table {
4806 struct poll_table_struct pt;
4807 struct io_kiocb *req;
4811 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4812 __poll_t mask, task_work_func_t func)
4816 /* for instances that support it check for an event match first: */
4817 if (mask && !(mask & poll->events))
4820 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4822 list_del_init(&poll->wait.entry);
4825 req->task_work.func = func;
4828 * If this fails, then the task is exiting. When a task exits, the
4829 * work gets canceled, so just cancel this request as well instead
4830 * of executing it. We can't safely execute it anyway, as we may not
4831 * have the needed state needed for it anyway.
4833 ret = io_req_task_work_add(req);
4834 if (unlikely(ret)) {
4835 WRITE_ONCE(poll->canceled, true);
4836 io_req_task_work_add_fallback(req, func);
4841 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4842 __acquires(&req->ctx->completion_lock)
4844 struct io_ring_ctx *ctx = req->ctx;
4846 if (!req->result && !READ_ONCE(poll->canceled)) {
4847 struct poll_table_struct pt = { ._key = poll->events };
4849 req->result = vfs_poll(req->file, &pt) & poll->events;
4852 spin_lock_irq(&ctx->completion_lock);
4853 if (!req->result && !READ_ONCE(poll->canceled)) {
4854 add_wait_queue(poll->head, &poll->wait);
4861 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4863 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4864 if (req->opcode == IORING_OP_POLL_ADD)
4865 return req->async_data;
4866 return req->apoll->double_poll;
4869 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4871 if (req->opcode == IORING_OP_POLL_ADD)
4873 return &req->apoll->poll;
4876 static void io_poll_remove_double(struct io_kiocb *req)
4877 __must_hold(&req->ctx->completion_lock)
4879 struct io_poll_iocb *poll = io_poll_get_double(req);
4881 lockdep_assert_held(&req->ctx->completion_lock);
4883 if (poll && poll->head) {
4884 struct wait_queue_head *head = poll->head;
4886 spin_lock(&head->lock);
4887 list_del_init(&poll->wait.entry);
4888 if (poll->wait.private)
4891 spin_unlock(&head->lock);
4895 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4896 __must_hold(&req->ctx->completion_lock)
4898 struct io_ring_ctx *ctx = req->ctx;
4899 unsigned flags = IORING_CQE_F_MORE;
4902 if (READ_ONCE(req->poll.canceled)) {
4904 req->poll.events |= EPOLLONESHOT;
4906 error = mangle_poll(mask);
4908 if (req->poll.events & EPOLLONESHOT)
4910 if (!io_cqring_fill_event(req, error, flags)) {
4911 io_poll_remove_waitqs(req);
4912 req->poll.done = true;
4915 io_commit_cqring(ctx);
4916 return !(flags & IORING_CQE_F_MORE);
4919 static void io_poll_task_func(struct callback_head *cb)
4921 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4922 struct io_ring_ctx *ctx = req->ctx;
4923 struct io_kiocb *nxt;
4925 if (io_poll_rewait(req, &req->poll)) {
4926 spin_unlock_irq(&ctx->completion_lock);
4930 done = io_poll_complete(req, req->result);
4932 hash_del(&req->hash_node);
4935 add_wait_queue(req->poll.head, &req->poll.wait);
4937 spin_unlock_irq(&ctx->completion_lock);
4938 io_cqring_ev_posted(ctx);
4941 nxt = io_put_req_find_next(req);
4943 __io_req_task_submit(nxt);
4948 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4949 int sync, void *key)
4951 struct io_kiocb *req = wait->private;
4952 struct io_poll_iocb *poll = io_poll_get_single(req);
4953 __poll_t mask = key_to_poll(key);
4955 /* for instances that support it check for an event match first: */
4956 if (mask && !(mask & poll->events))
4958 if (!(poll->events & EPOLLONESHOT))
4959 return poll->wait.func(&poll->wait, mode, sync, key);
4961 list_del_init(&wait->entry);
4963 if (poll && poll->head) {
4966 spin_lock(&poll->head->lock);
4967 done = list_empty(&poll->wait.entry);
4969 list_del_init(&poll->wait.entry);
4970 /* make sure double remove sees this as being gone */
4971 wait->private = NULL;
4972 spin_unlock(&poll->head->lock);
4974 /* use wait func handler, so it matches the rq type */
4975 poll->wait.func(&poll->wait, mode, sync, key);
4982 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4983 wait_queue_func_t wake_func)
4987 poll->canceled = false;
4988 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4989 /* mask in events that we always want/need */
4990 poll->events = events | IO_POLL_UNMASK;
4991 INIT_LIST_HEAD(&poll->wait.entry);
4992 init_waitqueue_func_entry(&poll->wait, wake_func);
4995 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4996 struct wait_queue_head *head,
4997 struct io_poll_iocb **poll_ptr)
4999 struct io_kiocb *req = pt->req;
5002 * If poll->head is already set, it's because the file being polled
5003 * uses multiple waitqueues for poll handling (eg one for read, one
5004 * for write). Setup a separate io_poll_iocb if this happens.
5006 if (unlikely(poll->head)) {
5007 struct io_poll_iocb *poll_one = poll;
5009 /* already have a 2nd entry, fail a third attempt */
5011 pt->error = -EINVAL;
5014 /* double add on the same waitqueue head, ignore */
5015 if (poll->head == head)
5017 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5019 pt->error = -ENOMEM;
5022 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5024 poll->wait.private = req;
5031 if (poll->events & EPOLLEXCLUSIVE)
5032 add_wait_queue_exclusive(head, &poll->wait);
5034 add_wait_queue(head, &poll->wait);
5037 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5038 struct poll_table_struct *p)
5040 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5041 struct async_poll *apoll = pt->req->apoll;
5043 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5046 static void io_async_task_func(struct callback_head *cb)
5048 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5049 struct async_poll *apoll = req->apoll;
5050 struct io_ring_ctx *ctx = req->ctx;
5052 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5054 if (io_poll_rewait(req, &apoll->poll)) {
5055 spin_unlock_irq(&ctx->completion_lock);
5059 hash_del(&req->hash_node);
5060 io_poll_remove_double(req);
5061 spin_unlock_irq(&ctx->completion_lock);
5063 if (!READ_ONCE(apoll->poll.canceled))
5064 __io_req_task_submit(req);
5066 io_req_complete_failed(req, -ECANCELED);
5068 kfree(apoll->double_poll);
5072 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5075 struct io_kiocb *req = wait->private;
5076 struct io_poll_iocb *poll = &req->apoll->poll;
5078 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5081 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5084 static void io_poll_req_insert(struct io_kiocb *req)
5086 struct io_ring_ctx *ctx = req->ctx;
5087 struct hlist_head *list;
5089 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5090 hlist_add_head(&req->hash_node, list);
5093 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5094 struct io_poll_iocb *poll,
5095 struct io_poll_table *ipt, __poll_t mask,
5096 wait_queue_func_t wake_func)
5097 __acquires(&ctx->completion_lock)
5099 struct io_ring_ctx *ctx = req->ctx;
5100 bool cancel = false;
5102 INIT_HLIST_NODE(&req->hash_node);
5103 io_init_poll_iocb(poll, mask, wake_func);
5104 poll->file = req->file;
5105 poll->wait.private = req;
5107 ipt->pt._key = mask;
5109 ipt->error = -EINVAL;
5111 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5113 spin_lock_irq(&ctx->completion_lock);
5114 if (likely(poll->head)) {
5115 spin_lock(&poll->head->lock);
5116 if (unlikely(list_empty(&poll->wait.entry))) {
5122 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5123 list_del_init(&poll->wait.entry);
5125 WRITE_ONCE(poll->canceled, true);
5126 else if (!poll->done) /* actually waiting for an event */
5127 io_poll_req_insert(req);
5128 spin_unlock(&poll->head->lock);
5134 static bool io_arm_poll_handler(struct io_kiocb *req)
5136 const struct io_op_def *def = &io_op_defs[req->opcode];
5137 struct io_ring_ctx *ctx = req->ctx;
5138 struct async_poll *apoll;
5139 struct io_poll_table ipt;
5143 if (!req->file || !file_can_poll(req->file))
5145 if (req->flags & REQ_F_POLLED)
5149 else if (def->pollout)
5153 /* if we can't nonblock try, then no point in arming a poll handler */
5154 if (!io_file_supports_async(req, rw))
5157 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5158 if (unlikely(!apoll))
5160 apoll->double_poll = NULL;
5162 req->flags |= REQ_F_POLLED;
5165 mask = EPOLLONESHOT;
5167 mask |= POLLIN | POLLRDNORM;
5169 mask |= POLLOUT | POLLWRNORM;
5171 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5172 if ((req->opcode == IORING_OP_RECVMSG) &&
5173 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5176 mask |= POLLERR | POLLPRI;
5178 ipt.pt._qproc = io_async_queue_proc;
5180 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5182 if (ret || ipt.error) {
5183 io_poll_remove_double(req);
5184 spin_unlock_irq(&ctx->completion_lock);
5185 kfree(apoll->double_poll);
5189 spin_unlock_irq(&ctx->completion_lock);
5190 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5191 apoll->poll.events);
5195 static bool __io_poll_remove_one(struct io_kiocb *req,
5196 struct io_poll_iocb *poll, bool do_cancel)
5197 __must_hold(&req->ctx->completion_lock)
5199 bool do_complete = false;
5203 spin_lock(&poll->head->lock);
5205 WRITE_ONCE(poll->canceled, true);
5206 if (!list_empty(&poll->wait.entry)) {
5207 list_del_init(&poll->wait.entry);
5210 spin_unlock(&poll->head->lock);
5211 hash_del(&req->hash_node);
5215 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5216 __must_hold(&req->ctx->completion_lock)
5220 io_poll_remove_double(req);
5221 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5223 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5224 struct async_poll *apoll = req->apoll;
5226 /* non-poll requests have submit ref still */
5228 kfree(apoll->double_poll);
5234 static bool io_poll_remove_one(struct io_kiocb *req)
5235 __must_hold(&req->ctx->completion_lock)
5239 do_complete = io_poll_remove_waitqs(req);
5241 io_cqring_fill_event(req, -ECANCELED, 0);
5242 io_commit_cqring(req->ctx);
5243 req_set_fail_links(req);
5244 io_put_req_deferred(req, 1);
5251 * Returns true if we found and killed one or more poll requests
5253 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5254 struct files_struct *files)
5256 struct hlist_node *tmp;
5257 struct io_kiocb *req;
5260 spin_lock_irq(&ctx->completion_lock);
5261 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5262 struct hlist_head *list;
5264 list = &ctx->cancel_hash[i];
5265 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5266 if (io_match_task(req, tsk, files))
5267 posted += io_poll_remove_one(req);
5270 spin_unlock_irq(&ctx->completion_lock);
5273 io_cqring_ev_posted(ctx);
5278 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr)
5279 __must_hold(&ctx->completion_lock)
5281 struct hlist_head *list;
5282 struct io_kiocb *req;
5284 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5285 hlist_for_each_entry(req, list, hash_node) {
5286 if (sqe_addr != req->user_data)
5294 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5295 __must_hold(&ctx->completion_lock)
5297 struct io_kiocb *req;
5299 req = io_poll_find(ctx, sqe_addr);
5302 if (io_poll_remove_one(req))
5308 static int io_poll_remove_prep(struct io_kiocb *req,
5309 const struct io_uring_sqe *sqe)
5311 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5313 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5317 req->poll_remove.addr = READ_ONCE(sqe->addr);
5322 * Find a running poll command that matches one specified in sqe->addr,
5323 * and remove it if found.
5325 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5327 struct io_ring_ctx *ctx = req->ctx;
5330 spin_lock_irq(&ctx->completion_lock);
5331 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5332 spin_unlock_irq(&ctx->completion_lock);
5335 req_set_fail_links(req);
5336 __io_req_complete(req, issue_flags, ret, 0);
5340 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5343 struct io_kiocb *req = wait->private;
5344 struct io_poll_iocb *poll = &req->poll;
5346 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5349 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5350 struct poll_table_struct *p)
5352 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5354 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5357 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5361 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5363 if (sqe->ioprio || sqe->buf_index)
5365 flags = READ_ONCE(sqe->len);
5366 if (flags & ~(IORING_POLL_ADD_MULTI | IORING_POLL_UPDATE_EVENTS |
5367 IORING_POLL_UPDATE_USER_DATA))
5369 events = READ_ONCE(sqe->poll32_events);
5371 events = swahw32(events);
5373 if (!(flags & IORING_POLL_ADD_MULTI))
5374 events |= EPOLLONESHOT;
5375 events = demangle_poll(events) |
5376 (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5378 if (flags & (IORING_POLL_UPDATE_EVENTS|IORING_POLL_UPDATE_USER_DATA)) {
5379 struct io_poll_update *poll_upd = &req->poll_update;
5381 req->flags |= REQ_F_POLL_UPDATE;
5382 poll_upd->events = events;
5383 poll_upd->old_user_data = READ_ONCE(sqe->addr);
5384 poll_upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5385 poll_upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5386 if (poll_upd->update_user_data)
5387 poll_upd->new_user_data = READ_ONCE(sqe->off);
5389 struct io_poll_iocb *poll = &req->poll;
5391 poll->events = events;
5392 if (sqe->off || sqe->addr)
5398 static int __io_poll_add(struct io_kiocb *req)
5400 struct io_poll_iocb *poll = &req->poll;
5401 struct io_ring_ctx *ctx = req->ctx;
5402 struct io_poll_table ipt;
5405 ipt.pt._qproc = io_poll_queue_proc;
5407 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5410 if (mask) { /* no async, we'd stolen it */
5412 io_poll_complete(req, mask);
5414 spin_unlock_irq(&ctx->completion_lock);
5417 io_cqring_ev_posted(ctx);
5418 if (poll->events & EPOLLONESHOT)
5424 static int io_poll_update(struct io_kiocb *req)
5426 struct io_ring_ctx *ctx = req->ctx;
5427 struct io_kiocb *preq;
5431 spin_lock_irq(&ctx->completion_lock);
5432 preq = io_poll_find(ctx, req->poll_update.old_user_data);
5436 } else if (preq->opcode != IORING_OP_POLL_ADD) {
5437 /* don't allow internal poll updates */
5443 * Don't allow racy completion with singleshot, as we cannot safely
5444 * update those. For multishot, if we're racing with completion, just
5445 * let completion re-add it.
5447 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5448 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5452 /* we now have a detached poll request. reissue. */
5456 spin_unlock_irq(&ctx->completion_lock);
5457 req_set_fail_links(req);
5458 io_req_complete(req, ret);
5461 /* only mask one event flags, keep behavior flags */
5462 if (req->poll_update.update_events) {
5463 preq->poll.events &= ~0xffff;
5464 preq->poll.events |= req->poll_update.events & 0xffff;
5465 preq->poll.events |= IO_POLL_UNMASK;
5467 if (req->poll_update.update_user_data)
5468 preq->user_data = req->poll_update.new_user_data;
5470 spin_unlock_irq(&ctx->completion_lock);
5472 /* complete update request, we're done with it */
5473 io_req_complete(req, ret);
5476 ret = __io_poll_add(preq);
5478 req_set_fail_links(preq);
5479 io_req_complete(preq, ret);
5485 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5487 if (!(req->flags & REQ_F_POLL_UPDATE))
5488 return __io_poll_add(req);
5489 return io_poll_update(req);
5492 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5494 struct io_timeout_data *data = container_of(timer,
5495 struct io_timeout_data, timer);
5496 struct io_kiocb *req = data->req;
5497 struct io_ring_ctx *ctx = req->ctx;
5498 unsigned long flags;
5500 spin_lock_irqsave(&ctx->completion_lock, flags);
5501 list_del_init(&req->timeout.list);
5502 atomic_set(&req->ctx->cq_timeouts,
5503 atomic_read(&req->ctx->cq_timeouts) + 1);
5505 io_cqring_fill_event(req, -ETIME, 0);
5506 io_commit_cqring(ctx);
5507 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5509 io_cqring_ev_posted(ctx);
5510 req_set_fail_links(req);
5512 return HRTIMER_NORESTART;
5515 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5517 __must_hold(&ctx->completion_lock)
5519 struct io_timeout_data *io;
5520 struct io_kiocb *req;
5523 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5524 found = user_data == req->user_data;
5529 return ERR_PTR(-ENOENT);
5531 io = req->async_data;
5532 if (hrtimer_try_to_cancel(&io->timer) == -1)
5533 return ERR_PTR(-EALREADY);
5534 list_del_init(&req->timeout.list);
5538 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5539 __must_hold(&ctx->completion_lock)
5541 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5544 return PTR_ERR(req);
5546 req_set_fail_links(req);
5547 io_cqring_fill_event(req, -ECANCELED, 0);
5548 io_put_req_deferred(req, 1);
5552 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5553 struct timespec64 *ts, enum hrtimer_mode mode)
5554 __must_hold(&ctx->completion_lock)
5556 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5557 struct io_timeout_data *data;
5560 return PTR_ERR(req);
5562 req->timeout.off = 0; /* noseq */
5563 data = req->async_data;
5564 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5565 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5566 data->timer.function = io_timeout_fn;
5567 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5571 static int io_timeout_remove_prep(struct io_kiocb *req,
5572 const struct io_uring_sqe *sqe)
5574 struct io_timeout_rem *tr = &req->timeout_rem;
5576 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5578 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5580 if (sqe->ioprio || sqe->buf_index || sqe->len)
5583 tr->addr = READ_ONCE(sqe->addr);
5584 tr->flags = READ_ONCE(sqe->timeout_flags);
5585 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5586 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5588 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5590 } else if (tr->flags) {
5591 /* timeout removal doesn't support flags */
5598 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5600 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5605 * Remove or update an existing timeout command
5607 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5609 struct io_timeout_rem *tr = &req->timeout_rem;
5610 struct io_ring_ctx *ctx = req->ctx;
5613 spin_lock_irq(&ctx->completion_lock);
5614 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5615 ret = io_timeout_cancel(ctx, tr->addr);
5617 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5618 io_translate_timeout_mode(tr->flags));
5620 io_cqring_fill_event(req, ret, 0);
5621 io_commit_cqring(ctx);
5622 spin_unlock_irq(&ctx->completion_lock);
5623 io_cqring_ev_posted(ctx);
5625 req_set_fail_links(req);
5630 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5631 bool is_timeout_link)
5633 struct io_timeout_data *data;
5635 u32 off = READ_ONCE(sqe->off);
5637 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5639 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5641 if (off && is_timeout_link)
5643 flags = READ_ONCE(sqe->timeout_flags);
5644 if (flags & ~IORING_TIMEOUT_ABS)
5647 req->timeout.off = off;
5649 if (!req->async_data && io_alloc_async_data(req))
5652 data = req->async_data;
5655 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5658 data->mode = io_translate_timeout_mode(flags);
5659 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5660 if (is_timeout_link)
5661 io_req_track_inflight(req);
5665 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5667 struct io_ring_ctx *ctx = req->ctx;
5668 struct io_timeout_data *data = req->async_data;
5669 struct list_head *entry;
5670 u32 tail, off = req->timeout.off;
5672 spin_lock_irq(&ctx->completion_lock);
5675 * sqe->off holds how many events that need to occur for this
5676 * timeout event to be satisfied. If it isn't set, then this is
5677 * a pure timeout request, sequence isn't used.
5679 if (io_is_timeout_noseq(req)) {
5680 entry = ctx->timeout_list.prev;
5684 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5685 req->timeout.target_seq = tail + off;
5687 /* Update the last seq here in case io_flush_timeouts() hasn't.
5688 * This is safe because ->completion_lock is held, and submissions
5689 * and completions are never mixed in the same ->completion_lock section.
5691 ctx->cq_last_tm_flush = tail;
5694 * Insertion sort, ensuring the first entry in the list is always
5695 * the one we need first.
5697 list_for_each_prev(entry, &ctx->timeout_list) {
5698 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5701 if (io_is_timeout_noseq(nxt))
5703 /* nxt.seq is behind @tail, otherwise would've been completed */
5704 if (off >= nxt->timeout.target_seq - tail)
5708 list_add(&req->timeout.list, entry);
5709 data->timer.function = io_timeout_fn;
5710 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5711 spin_unlock_irq(&ctx->completion_lock);
5715 struct io_cancel_data {
5716 struct io_ring_ctx *ctx;
5720 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5722 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5723 struct io_cancel_data *cd = data;
5725 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5728 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5729 struct io_ring_ctx *ctx)
5731 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5732 enum io_wq_cancel cancel_ret;
5735 if (!tctx || !tctx->io_wq)
5738 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5739 switch (cancel_ret) {
5740 case IO_WQ_CANCEL_OK:
5743 case IO_WQ_CANCEL_RUNNING:
5746 case IO_WQ_CANCEL_NOTFOUND:
5754 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5755 struct io_kiocb *req, __u64 sqe_addr,
5758 unsigned long flags;
5761 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5762 spin_lock_irqsave(&ctx->completion_lock, flags);
5765 ret = io_timeout_cancel(ctx, sqe_addr);
5768 ret = io_poll_cancel(ctx, sqe_addr);
5772 io_cqring_fill_event(req, ret, 0);
5773 io_commit_cqring(ctx);
5774 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5775 io_cqring_ev_posted(ctx);
5778 req_set_fail_links(req);
5781 static int io_async_cancel_prep(struct io_kiocb *req,
5782 const struct io_uring_sqe *sqe)
5784 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5786 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5788 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5791 req->cancel.addr = READ_ONCE(sqe->addr);
5795 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5797 struct io_ring_ctx *ctx = req->ctx;
5798 u64 sqe_addr = req->cancel.addr;
5799 struct io_tctx_node *node;
5802 /* tasks should wait for their io-wq threads, so safe w/o sync */
5803 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5804 spin_lock_irq(&ctx->completion_lock);
5807 ret = io_timeout_cancel(ctx, sqe_addr);
5810 ret = io_poll_cancel(ctx, sqe_addr);
5813 spin_unlock_irq(&ctx->completion_lock);
5815 /* slow path, try all io-wq's */
5816 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5818 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5819 struct io_uring_task *tctx = node->task->io_uring;
5821 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5825 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5827 spin_lock_irq(&ctx->completion_lock);
5829 io_cqring_fill_event(req, ret, 0);
5830 io_commit_cqring(ctx);
5831 spin_unlock_irq(&ctx->completion_lock);
5832 io_cqring_ev_posted(ctx);
5835 req_set_fail_links(req);
5840 static int io_rsrc_update_prep(struct io_kiocb *req,
5841 const struct io_uring_sqe *sqe)
5843 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5845 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5847 if (sqe->ioprio || sqe->rw_flags)
5850 req->rsrc_update.offset = READ_ONCE(sqe->off);
5851 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5852 if (!req->rsrc_update.nr_args)
5854 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5858 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5860 struct io_ring_ctx *ctx = req->ctx;
5861 struct io_uring_rsrc_update up;
5864 if (issue_flags & IO_URING_F_NONBLOCK)
5867 up.offset = req->rsrc_update.offset;
5868 up.data = req->rsrc_update.arg;
5870 mutex_lock(&ctx->uring_lock);
5871 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5872 mutex_unlock(&ctx->uring_lock);
5875 req_set_fail_links(req);
5876 __io_req_complete(req, issue_flags, ret, 0);
5880 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5882 switch (req->opcode) {
5885 case IORING_OP_READV:
5886 case IORING_OP_READ_FIXED:
5887 case IORING_OP_READ:
5888 return io_read_prep(req, sqe);
5889 case IORING_OP_WRITEV:
5890 case IORING_OP_WRITE_FIXED:
5891 case IORING_OP_WRITE:
5892 return io_write_prep(req, sqe);
5893 case IORING_OP_POLL_ADD:
5894 return io_poll_add_prep(req, sqe);
5895 case IORING_OP_POLL_REMOVE:
5896 return io_poll_remove_prep(req, sqe);
5897 case IORING_OP_FSYNC:
5898 return io_fsync_prep(req, sqe);
5899 case IORING_OP_SYNC_FILE_RANGE:
5900 return io_sfr_prep(req, sqe);
5901 case IORING_OP_SENDMSG:
5902 case IORING_OP_SEND:
5903 return io_sendmsg_prep(req, sqe);
5904 case IORING_OP_RECVMSG:
5905 case IORING_OP_RECV:
5906 return io_recvmsg_prep(req, sqe);
5907 case IORING_OP_CONNECT:
5908 return io_connect_prep(req, sqe);
5909 case IORING_OP_TIMEOUT:
5910 return io_timeout_prep(req, sqe, false);
5911 case IORING_OP_TIMEOUT_REMOVE:
5912 return io_timeout_remove_prep(req, sqe);
5913 case IORING_OP_ASYNC_CANCEL:
5914 return io_async_cancel_prep(req, sqe);
5915 case IORING_OP_LINK_TIMEOUT:
5916 return io_timeout_prep(req, sqe, true);
5917 case IORING_OP_ACCEPT:
5918 return io_accept_prep(req, sqe);
5919 case IORING_OP_FALLOCATE:
5920 return io_fallocate_prep(req, sqe);
5921 case IORING_OP_OPENAT:
5922 return io_openat_prep(req, sqe);
5923 case IORING_OP_CLOSE:
5924 return io_close_prep(req, sqe);
5925 case IORING_OP_FILES_UPDATE:
5926 return io_rsrc_update_prep(req, sqe);
5927 case IORING_OP_STATX:
5928 return io_statx_prep(req, sqe);
5929 case IORING_OP_FADVISE:
5930 return io_fadvise_prep(req, sqe);
5931 case IORING_OP_MADVISE:
5932 return io_madvise_prep(req, sqe);
5933 case IORING_OP_OPENAT2:
5934 return io_openat2_prep(req, sqe);
5935 case IORING_OP_EPOLL_CTL:
5936 return io_epoll_ctl_prep(req, sqe);
5937 case IORING_OP_SPLICE:
5938 return io_splice_prep(req, sqe);
5939 case IORING_OP_PROVIDE_BUFFERS:
5940 return io_provide_buffers_prep(req, sqe);
5941 case IORING_OP_REMOVE_BUFFERS:
5942 return io_remove_buffers_prep(req, sqe);
5944 return io_tee_prep(req, sqe);
5945 case IORING_OP_SHUTDOWN:
5946 return io_shutdown_prep(req, sqe);
5947 case IORING_OP_RENAMEAT:
5948 return io_renameat_prep(req, sqe);
5949 case IORING_OP_UNLINKAT:
5950 return io_unlinkat_prep(req, sqe);
5953 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5958 static int io_req_prep_async(struct io_kiocb *req)
5960 if (!io_op_defs[req->opcode].needs_async_setup)
5962 if (WARN_ON_ONCE(req->async_data))
5964 if (io_alloc_async_data(req))
5967 switch (req->opcode) {
5968 case IORING_OP_READV:
5969 return io_rw_prep_async(req, READ);
5970 case IORING_OP_WRITEV:
5971 return io_rw_prep_async(req, WRITE);
5972 case IORING_OP_SENDMSG:
5973 return io_sendmsg_prep_async(req);
5974 case IORING_OP_RECVMSG:
5975 return io_recvmsg_prep_async(req);
5976 case IORING_OP_CONNECT:
5977 return io_connect_prep_async(req);
5979 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5984 static u32 io_get_sequence(struct io_kiocb *req)
5986 struct io_kiocb *pos;
5987 struct io_ring_ctx *ctx = req->ctx;
5988 u32 total_submitted, nr_reqs = 0;
5990 io_for_each_link(pos, req)
5993 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5994 return total_submitted - nr_reqs;
5997 static int io_req_defer(struct io_kiocb *req)
5999 struct io_ring_ctx *ctx = req->ctx;
6000 struct io_defer_entry *de;
6004 /* Still need defer if there is pending req in defer list. */
6005 if (likely(list_empty_careful(&ctx->defer_list) &&
6006 !(req->flags & REQ_F_IO_DRAIN)))
6009 seq = io_get_sequence(req);
6010 /* Still a chance to pass the sequence check */
6011 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6014 ret = io_req_prep_async(req);
6017 io_prep_async_link(req);
6018 de = kmalloc(sizeof(*de), GFP_KERNEL);
6022 spin_lock_irq(&ctx->completion_lock);
6023 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6024 spin_unlock_irq(&ctx->completion_lock);
6026 io_queue_async_work(req);
6027 return -EIOCBQUEUED;
6030 trace_io_uring_defer(ctx, req, req->user_data);
6033 list_add_tail(&de->list, &ctx->defer_list);
6034 spin_unlock_irq(&ctx->completion_lock);
6035 return -EIOCBQUEUED;
6038 static void io_clean_op(struct io_kiocb *req)
6040 if (req->flags & REQ_F_BUFFER_SELECTED) {
6041 switch (req->opcode) {
6042 case IORING_OP_READV:
6043 case IORING_OP_READ_FIXED:
6044 case IORING_OP_READ:
6045 kfree((void *)(unsigned long)req->rw.addr);
6047 case IORING_OP_RECVMSG:
6048 case IORING_OP_RECV:
6049 kfree(req->sr_msg.kbuf);
6052 req->flags &= ~REQ_F_BUFFER_SELECTED;
6055 if (req->flags & REQ_F_NEED_CLEANUP) {
6056 switch (req->opcode) {
6057 case IORING_OP_READV:
6058 case IORING_OP_READ_FIXED:
6059 case IORING_OP_READ:
6060 case IORING_OP_WRITEV:
6061 case IORING_OP_WRITE_FIXED:
6062 case IORING_OP_WRITE: {
6063 struct io_async_rw *io = req->async_data;
6065 kfree(io->free_iovec);
6068 case IORING_OP_RECVMSG:
6069 case IORING_OP_SENDMSG: {
6070 struct io_async_msghdr *io = req->async_data;
6072 kfree(io->free_iov);
6075 case IORING_OP_SPLICE:
6077 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6078 io_put_file(req->splice.file_in);
6080 case IORING_OP_OPENAT:
6081 case IORING_OP_OPENAT2:
6082 if (req->open.filename)
6083 putname(req->open.filename);
6085 case IORING_OP_RENAMEAT:
6086 putname(req->rename.oldpath);
6087 putname(req->rename.newpath);
6089 case IORING_OP_UNLINKAT:
6090 putname(req->unlink.filename);
6093 req->flags &= ~REQ_F_NEED_CLEANUP;
6097 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6099 struct io_ring_ctx *ctx = req->ctx;
6100 const struct cred *creds = NULL;
6103 if (req->work.creds && req->work.creds != current_cred())
6104 creds = override_creds(req->work.creds);
6106 switch (req->opcode) {
6108 ret = io_nop(req, issue_flags);
6110 case IORING_OP_READV:
6111 case IORING_OP_READ_FIXED:
6112 case IORING_OP_READ:
6113 ret = io_read(req, issue_flags);
6115 case IORING_OP_WRITEV:
6116 case IORING_OP_WRITE_FIXED:
6117 case IORING_OP_WRITE:
6118 ret = io_write(req, issue_flags);
6120 case IORING_OP_FSYNC:
6121 ret = io_fsync(req, issue_flags);
6123 case IORING_OP_POLL_ADD:
6124 ret = io_poll_add(req, issue_flags);
6126 case IORING_OP_POLL_REMOVE:
6127 ret = io_poll_remove(req, issue_flags);
6129 case IORING_OP_SYNC_FILE_RANGE:
6130 ret = io_sync_file_range(req, issue_flags);
6132 case IORING_OP_SENDMSG:
6133 ret = io_sendmsg(req, issue_flags);
6135 case IORING_OP_SEND:
6136 ret = io_send(req, issue_flags);
6138 case IORING_OP_RECVMSG:
6139 ret = io_recvmsg(req, issue_flags);
6141 case IORING_OP_RECV:
6142 ret = io_recv(req, issue_flags);
6144 case IORING_OP_TIMEOUT:
6145 ret = io_timeout(req, issue_flags);
6147 case IORING_OP_TIMEOUT_REMOVE:
6148 ret = io_timeout_remove(req, issue_flags);
6150 case IORING_OP_ACCEPT:
6151 ret = io_accept(req, issue_flags);
6153 case IORING_OP_CONNECT:
6154 ret = io_connect(req, issue_flags);
6156 case IORING_OP_ASYNC_CANCEL:
6157 ret = io_async_cancel(req, issue_flags);
6159 case IORING_OP_FALLOCATE:
6160 ret = io_fallocate(req, issue_flags);
6162 case IORING_OP_OPENAT:
6163 ret = io_openat(req, issue_flags);
6165 case IORING_OP_CLOSE:
6166 ret = io_close(req, issue_flags);
6168 case IORING_OP_FILES_UPDATE:
6169 ret = io_files_update(req, issue_flags);
6171 case IORING_OP_STATX:
6172 ret = io_statx(req, issue_flags);
6174 case IORING_OP_FADVISE:
6175 ret = io_fadvise(req, issue_flags);
6177 case IORING_OP_MADVISE:
6178 ret = io_madvise(req, issue_flags);
6180 case IORING_OP_OPENAT2:
6181 ret = io_openat2(req, issue_flags);
6183 case IORING_OP_EPOLL_CTL:
6184 ret = io_epoll_ctl(req, issue_flags);
6186 case IORING_OP_SPLICE:
6187 ret = io_splice(req, issue_flags);
6189 case IORING_OP_PROVIDE_BUFFERS:
6190 ret = io_provide_buffers(req, issue_flags);
6192 case IORING_OP_REMOVE_BUFFERS:
6193 ret = io_remove_buffers(req, issue_flags);
6196 ret = io_tee(req, issue_flags);
6198 case IORING_OP_SHUTDOWN:
6199 ret = io_shutdown(req, issue_flags);
6201 case IORING_OP_RENAMEAT:
6202 ret = io_renameat(req, issue_flags);
6204 case IORING_OP_UNLINKAT:
6205 ret = io_unlinkat(req, issue_flags);
6213 revert_creds(creds);
6218 /* If the op doesn't have a file, we're not polling for it */
6219 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6220 const bool in_async = io_wq_current_is_worker();
6222 /* workqueue context doesn't hold uring_lock, grab it now */
6224 mutex_lock(&ctx->uring_lock);
6226 io_iopoll_req_issued(req, in_async);
6229 mutex_unlock(&ctx->uring_lock);
6235 static void io_wq_submit_work(struct io_wq_work *work)
6237 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6238 struct io_kiocb *timeout;
6241 timeout = io_prep_linked_timeout(req);
6243 io_queue_linked_timeout(timeout);
6245 if (work->flags & IO_WQ_WORK_CANCEL)
6250 ret = io_issue_sqe(req, 0);
6252 * We can get EAGAIN for polled IO even though we're
6253 * forcing a sync submission from here, since we can't
6254 * wait for request slots on the block side.
6262 /* avoid locking problems by failing it from a clean context */
6264 /* io-wq is going to take one down */
6266 io_req_task_queue_fail(req, ret);
6270 #define FFS_ASYNC_READ 0x1UL
6271 #define FFS_ASYNC_WRITE 0x2UL
6273 #define FFS_ISREG 0x4UL
6275 #define FFS_ISREG 0x0UL
6277 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6279 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6282 struct io_fixed_file *table_l2;
6284 table_l2 = table->files[i >> IORING_FILE_TABLE_SHIFT];
6285 return &table_l2[i & IORING_FILE_TABLE_MASK];
6288 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6291 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6293 return (struct file *) (slot->file_ptr & FFS_MASK);
6296 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6298 unsigned long file_ptr = (unsigned long) file;
6300 if (__io_file_supports_async(file, READ))
6301 file_ptr |= FFS_ASYNC_READ;
6302 if (__io_file_supports_async(file, WRITE))
6303 file_ptr |= FFS_ASYNC_WRITE;
6304 if (S_ISREG(file_inode(file)->i_mode))
6305 file_ptr |= FFS_ISREG;
6306 file_slot->file_ptr = file_ptr;
6309 static struct file *io_file_get(struct io_submit_state *state,
6310 struct io_kiocb *req, int fd, bool fixed)
6312 struct io_ring_ctx *ctx = req->ctx;
6316 unsigned long file_ptr;
6318 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6320 fd = array_index_nospec(fd, ctx->nr_user_files);
6321 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6322 file = (struct file *) (file_ptr & FFS_MASK);
6323 file_ptr &= ~FFS_MASK;
6324 /* mask in overlapping REQ_F and FFS bits */
6325 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6326 io_req_set_rsrc_node(req);
6328 trace_io_uring_file_get(ctx, fd);
6329 file = __io_file_get(state, fd);
6331 /* we don't allow fixed io_uring files */
6332 if (file && unlikely(file->f_op == &io_uring_fops))
6333 io_req_track_inflight(req);
6339 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6341 struct io_timeout_data *data = container_of(timer,
6342 struct io_timeout_data, timer);
6343 struct io_kiocb *prev, *req = data->req;
6344 struct io_ring_ctx *ctx = req->ctx;
6345 unsigned long flags;
6347 spin_lock_irqsave(&ctx->completion_lock, flags);
6348 prev = req->timeout.head;
6349 req->timeout.head = NULL;
6352 * We don't expect the list to be empty, that will only happen if we
6353 * race with the completion of the linked work.
6355 if (prev && req_ref_inc_not_zero(prev))
6356 io_remove_next_linked(prev);
6359 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6362 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6363 io_put_req_deferred(prev, 1);
6365 io_req_complete_post(req, -ETIME, 0);
6367 io_put_req_deferred(req, 1);
6368 return HRTIMER_NORESTART;
6371 static void io_queue_linked_timeout(struct io_kiocb *req)
6373 struct io_ring_ctx *ctx = req->ctx;
6375 spin_lock_irq(&ctx->completion_lock);
6377 * If the back reference is NULL, then our linked request finished
6378 * before we got a chance to setup the timer
6380 if (req->timeout.head) {
6381 struct io_timeout_data *data = req->async_data;
6383 data->timer.function = io_link_timeout_fn;
6384 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6387 spin_unlock_irq(&ctx->completion_lock);
6388 /* drop submission reference */
6392 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6394 struct io_kiocb *nxt = req->link;
6396 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6397 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6400 nxt->timeout.head = req;
6401 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6402 req->flags |= REQ_F_LINK_TIMEOUT;
6406 static void __io_queue_sqe(struct io_kiocb *req)
6408 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6411 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6414 * We async punt it if the file wasn't marked NOWAIT, or if the file
6415 * doesn't support non-blocking read/write attempts
6418 /* drop submission reference */
6419 if (req->flags & REQ_F_COMPLETE_INLINE) {
6420 struct io_ring_ctx *ctx = req->ctx;
6421 struct io_comp_state *cs = &ctx->submit_state.comp;
6423 cs->reqs[cs->nr++] = req;
6424 if (cs->nr == ARRAY_SIZE(cs->reqs))
6425 io_submit_flush_completions(cs, ctx);
6429 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6430 if (!io_arm_poll_handler(req)) {
6432 * Queued up for async execution, worker will release
6433 * submit reference when the iocb is actually submitted.
6435 io_queue_async_work(req);
6438 io_req_complete_failed(req, ret);
6441 io_queue_linked_timeout(linked_timeout);
6444 static void io_queue_sqe(struct io_kiocb *req)
6448 ret = io_req_defer(req);
6450 if (ret != -EIOCBQUEUED) {
6452 io_req_complete_failed(req, ret);
6454 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6455 ret = io_req_prep_async(req);
6458 io_queue_async_work(req);
6460 __io_queue_sqe(req);
6465 * Check SQE restrictions (opcode and flags).
6467 * Returns 'true' if SQE is allowed, 'false' otherwise.
6469 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6470 struct io_kiocb *req,
6471 unsigned int sqe_flags)
6473 if (!ctx->restricted)
6476 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6479 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6480 ctx->restrictions.sqe_flags_required)
6483 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6484 ctx->restrictions.sqe_flags_required))
6490 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6491 const struct io_uring_sqe *sqe)
6493 struct io_submit_state *state;
6494 unsigned int sqe_flags;
6495 int personality, ret = 0;
6497 req->opcode = READ_ONCE(sqe->opcode);
6498 /* same numerical values with corresponding REQ_F_*, safe to copy */
6499 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6500 req->user_data = READ_ONCE(sqe->user_data);
6501 req->async_data = NULL;
6505 req->fixed_rsrc_refs = NULL;
6506 /* one is dropped after submission, the other at completion */
6507 atomic_set(&req->refs, 2);
6508 req->task = current;
6510 req->work.creds = NULL;
6512 /* enforce forwards compatibility on users */
6513 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6518 if (unlikely(req->opcode >= IORING_OP_LAST))
6521 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6524 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6525 !io_op_defs[req->opcode].buffer_select)
6528 personality = READ_ONCE(sqe->personality);
6530 req->work.creds = xa_load(&ctx->personalities, personality);
6531 if (!req->work.creds)
6533 get_cred(req->work.creds);
6535 state = &ctx->submit_state;
6538 * Plug now if we have more than 1 IO left after this, and the target
6539 * is potentially a read/write to block based storage.
6541 if (!state->plug_started && state->ios_left > 1 &&
6542 io_op_defs[req->opcode].plug) {
6543 blk_start_plug(&state->plug);
6544 state->plug_started = true;
6547 if (io_op_defs[req->opcode].needs_file) {
6548 bool fixed = req->flags & REQ_F_FIXED_FILE;
6550 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6551 if (unlikely(!req->file))
6559 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6560 const struct io_uring_sqe *sqe)
6562 struct io_submit_link *link = &ctx->submit_state.link;
6565 ret = io_init_req(ctx, req, sqe);
6566 if (unlikely(ret)) {
6569 /* fail even hard links since we don't submit */
6570 link->head->flags |= REQ_F_FAIL_LINK;
6571 io_req_complete_failed(link->head, -ECANCELED);
6574 io_req_complete_failed(req, ret);
6577 ret = io_req_prep(req, sqe);
6581 /* don't need @sqe from now on */
6582 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6583 true, ctx->flags & IORING_SETUP_SQPOLL);
6586 * If we already have a head request, queue this one for async
6587 * submittal once the head completes. If we don't have a head but
6588 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6589 * submitted sync once the chain is complete. If none of those
6590 * conditions are true (normal request), then just queue it.
6593 struct io_kiocb *head = link->head;
6596 * Taking sequential execution of a link, draining both sides
6597 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6598 * requests in the link. So, it drains the head and the
6599 * next after the link request. The last one is done via
6600 * drain_next flag to persist the effect across calls.
6602 if (req->flags & REQ_F_IO_DRAIN) {
6603 head->flags |= REQ_F_IO_DRAIN;
6604 ctx->drain_next = 1;
6606 ret = io_req_prep_async(req);
6609 trace_io_uring_link(ctx, req, head);
6610 link->last->link = req;
6613 /* last request of a link, enqueue the link */
6614 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6619 if (unlikely(ctx->drain_next)) {
6620 req->flags |= REQ_F_IO_DRAIN;
6621 ctx->drain_next = 0;
6623 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6635 * Batched submission is done, ensure local IO is flushed out.
6637 static void io_submit_state_end(struct io_submit_state *state,
6638 struct io_ring_ctx *ctx)
6640 if (state->link.head)
6641 io_queue_sqe(state->link.head);
6643 io_submit_flush_completions(&state->comp, ctx);
6644 if (state->plug_started)
6645 blk_finish_plug(&state->plug);
6646 io_state_file_put(state);
6650 * Start submission side cache.
6652 static void io_submit_state_start(struct io_submit_state *state,
6653 unsigned int max_ios)
6655 state->plug_started = false;
6656 state->ios_left = max_ios;
6657 /* set only head, no need to init link_last in advance */
6658 state->link.head = NULL;
6661 static void io_commit_sqring(struct io_ring_ctx *ctx)
6663 struct io_rings *rings = ctx->rings;
6666 * Ensure any loads from the SQEs are done at this point,
6667 * since once we write the new head, the application could
6668 * write new data to them.
6670 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6674 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6675 * that is mapped by userspace. This means that care needs to be taken to
6676 * ensure that reads are stable, as we cannot rely on userspace always
6677 * being a good citizen. If members of the sqe are validated and then later
6678 * used, it's important that those reads are done through READ_ONCE() to
6679 * prevent a re-load down the line.
6681 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6683 u32 *sq_array = ctx->sq_array;
6687 * The cached sq head (or cq tail) serves two purposes:
6689 * 1) allows us to batch the cost of updating the user visible
6691 * 2) allows the kernel side to track the head on its own, even
6692 * though the application is the one updating it.
6694 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6695 if (likely(head < ctx->sq_entries))
6696 return &ctx->sq_sqes[head];
6698 /* drop invalid entries */
6699 ctx->cached_sq_dropped++;
6700 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6704 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6708 /* if we have a backlog and couldn't flush it all, return BUSY */
6709 if (test_bit(0, &ctx->sq_check_overflow)) {
6710 if (!__io_cqring_overflow_flush(ctx, false))
6714 /* make sure SQ entry isn't read before tail */
6715 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6717 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6720 percpu_counter_add(¤t->io_uring->inflight, nr);
6721 refcount_add(nr, ¤t->usage);
6722 io_submit_state_start(&ctx->submit_state, nr);
6724 while (submitted < nr) {
6725 const struct io_uring_sqe *sqe;
6726 struct io_kiocb *req;
6728 req = io_alloc_req(ctx);
6729 if (unlikely(!req)) {
6731 submitted = -EAGAIN;
6734 sqe = io_get_sqe(ctx);
6735 if (unlikely(!sqe)) {
6736 kmem_cache_free(req_cachep, req);
6739 /* will complete beyond this point, count as submitted */
6741 if (io_submit_sqe(ctx, req, sqe))
6745 if (unlikely(submitted != nr)) {
6746 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6747 struct io_uring_task *tctx = current->io_uring;
6748 int unused = nr - ref_used;
6750 percpu_ref_put_many(&ctx->refs, unused);
6751 percpu_counter_sub(&tctx->inflight, unused);
6752 put_task_struct_many(current, unused);
6755 io_submit_state_end(&ctx->submit_state, ctx);
6756 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6757 io_commit_sqring(ctx);
6762 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6764 /* Tell userspace we may need a wakeup call */
6765 spin_lock_irq(&ctx->completion_lock);
6766 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6767 spin_unlock_irq(&ctx->completion_lock);
6770 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6772 spin_lock_irq(&ctx->completion_lock);
6773 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6774 spin_unlock_irq(&ctx->completion_lock);
6777 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6779 unsigned int to_submit;
6782 to_submit = io_sqring_entries(ctx);
6783 /* if we're handling multiple rings, cap submit size for fairness */
6784 if (cap_entries && to_submit > 8)
6787 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6788 unsigned nr_events = 0;
6790 mutex_lock(&ctx->uring_lock);
6791 if (!list_empty(&ctx->iopoll_list))
6792 io_do_iopoll(ctx, &nr_events, 0);
6794 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6795 !(ctx->flags & IORING_SETUP_R_DISABLED))
6796 ret = io_submit_sqes(ctx, to_submit);
6797 mutex_unlock(&ctx->uring_lock);
6800 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6801 wake_up(&ctx->sqo_sq_wait);
6806 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6808 struct io_ring_ctx *ctx;
6809 unsigned sq_thread_idle = 0;
6811 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6812 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6813 sqd->sq_thread_idle = sq_thread_idle;
6816 static int io_sq_thread(void *data)
6818 struct io_sq_data *sqd = data;
6819 struct io_ring_ctx *ctx;
6820 unsigned long timeout = 0;
6821 char buf[TASK_COMM_LEN];
6824 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6825 set_task_comm(current, buf);
6826 current->pf_io_worker = NULL;
6828 if (sqd->sq_cpu != -1)
6829 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6831 set_cpus_allowed_ptr(current, cpu_online_mask);
6832 current->flags |= PF_NO_SETAFFINITY;
6834 mutex_lock(&sqd->lock);
6835 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6837 bool cap_entries, sqt_spin, needs_sched;
6839 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6840 signal_pending(current)) {
6841 bool did_sig = false;
6843 mutex_unlock(&sqd->lock);
6844 if (signal_pending(current)) {
6845 struct ksignal ksig;
6847 did_sig = get_signal(&ksig);
6850 mutex_lock(&sqd->lock);
6854 io_run_task_work_head(&sqd->park_task_work);
6855 timeout = jiffies + sqd->sq_thread_idle;
6859 cap_entries = !list_is_singular(&sqd->ctx_list);
6860 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6861 const struct cred *creds = NULL;
6863 if (ctx->sq_creds != current_cred())
6864 creds = override_creds(ctx->sq_creds);
6865 ret = __io_sq_thread(ctx, cap_entries);
6867 revert_creds(creds);
6868 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6872 if (sqt_spin || !time_after(jiffies, timeout)) {
6876 timeout = jiffies + sqd->sq_thread_idle;
6881 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6882 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6883 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6884 !list_empty_careful(&ctx->iopoll_list)) {
6885 needs_sched = false;
6888 if (io_sqring_entries(ctx)) {
6889 needs_sched = false;
6894 if (needs_sched && !test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6895 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6896 io_ring_set_wakeup_flag(ctx);
6898 mutex_unlock(&sqd->lock);
6900 mutex_lock(&sqd->lock);
6901 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6902 io_ring_clear_wakeup_flag(ctx);
6905 finish_wait(&sqd->wait, &wait);
6906 io_run_task_work_head(&sqd->park_task_work);
6907 timeout = jiffies + sqd->sq_thread_idle;
6910 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6911 io_uring_cancel_sqpoll(ctx);
6913 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6914 io_ring_set_wakeup_flag(ctx);
6915 mutex_unlock(&sqd->lock);
6918 io_run_task_work_head(&sqd->park_task_work);
6919 complete(&sqd->exited);
6923 struct io_wait_queue {
6924 struct wait_queue_entry wq;
6925 struct io_ring_ctx *ctx;
6927 unsigned nr_timeouts;
6930 static inline bool io_should_wake(struct io_wait_queue *iowq)
6932 struct io_ring_ctx *ctx = iowq->ctx;
6935 * Wake up if we have enough events, or if a timeout occurred since we
6936 * started waiting. For timeouts, we always want to return to userspace,
6937 * regardless of event count.
6939 return io_cqring_events(ctx) >= iowq->to_wait ||
6940 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6943 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6944 int wake_flags, void *key)
6946 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6950 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6951 * the task, and the next invocation will do it.
6953 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6954 return autoremove_wake_function(curr, mode, wake_flags, key);
6958 static int io_run_task_work_sig(void)
6960 if (io_run_task_work())
6962 if (!signal_pending(current))
6964 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6965 return -ERESTARTSYS;
6969 /* when returns >0, the caller should retry */
6970 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6971 struct io_wait_queue *iowq,
6972 signed long *timeout)
6976 /* make sure we run task_work before checking for signals */
6977 ret = io_run_task_work_sig();
6978 if (ret || io_should_wake(iowq))
6980 /* let the caller flush overflows, retry */
6981 if (test_bit(0, &ctx->cq_check_overflow))
6984 *timeout = schedule_timeout(*timeout);
6985 return !*timeout ? -ETIME : 1;
6989 * Wait until events become available, if we don't already have some. The
6990 * application must reap them itself, as they reside on the shared cq ring.
6992 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6993 const sigset_t __user *sig, size_t sigsz,
6994 struct __kernel_timespec __user *uts)
6996 struct io_wait_queue iowq = {
6999 .func = io_wake_function,
7000 .entry = LIST_HEAD_INIT(iowq.wq.entry),
7003 .to_wait = min_events,
7005 struct io_rings *rings = ctx->rings;
7006 signed long timeout = MAX_SCHEDULE_TIMEOUT;
7010 io_cqring_overflow_flush(ctx, false);
7011 if (io_cqring_events(ctx) >= min_events)
7013 if (!io_run_task_work())
7018 #ifdef CONFIG_COMPAT
7019 if (in_compat_syscall())
7020 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7024 ret = set_user_sigmask(sig, sigsz);
7031 struct timespec64 ts;
7033 if (get_timespec64(&ts, uts))
7035 timeout = timespec64_to_jiffies(&ts);
7038 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7039 trace_io_uring_cqring_wait(ctx, min_events);
7041 /* if we can't even flush overflow, don't wait for more */
7042 if (!io_cqring_overflow_flush(ctx, false)) {
7046 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7047 TASK_INTERRUPTIBLE);
7048 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7049 finish_wait(&ctx->wait, &iowq.wq);
7053 restore_saved_sigmask_unless(ret == -EINTR);
7055 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7058 static void io_free_file_tables(struct io_file_table *table, unsigned nr_files)
7060 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7062 for (i = 0; i < nr_tables; i++)
7063 kfree(table->files[i]);
7064 kfree(table->files);
7065 table->files = NULL;
7068 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7070 #if defined(CONFIG_UNIX)
7071 if (ctx->ring_sock) {
7072 struct sock *sock = ctx->ring_sock->sk;
7073 struct sk_buff *skb;
7075 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7081 for (i = 0; i < ctx->nr_user_files; i++) {
7084 file = io_file_from_index(ctx, i);
7089 io_free_file_tables(&ctx->file_table, ctx->nr_user_files);
7090 kfree(ctx->file_data);
7091 ctx->file_data = NULL;
7092 ctx->nr_user_files = 0;
7095 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7097 spin_lock_bh(&ctx->rsrc_ref_lock);
7100 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7102 spin_unlock_bh(&ctx->rsrc_ref_lock);
7105 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7107 percpu_ref_exit(&ref_node->refs);
7111 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7112 struct io_rsrc_data *data_to_kill)
7114 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7115 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7118 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7120 rsrc_node->rsrc_data = data_to_kill;
7121 io_rsrc_ref_lock(ctx);
7122 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7123 io_rsrc_ref_unlock(ctx);
7125 atomic_inc(&data_to_kill->refs);
7126 percpu_ref_kill(&rsrc_node->refs);
7127 ctx->rsrc_node = NULL;
7130 if (!ctx->rsrc_node) {
7131 ctx->rsrc_node = ctx->rsrc_backup_node;
7132 ctx->rsrc_backup_node = NULL;
7136 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7138 if (ctx->rsrc_backup_node)
7140 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7141 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7144 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7148 /* As we may drop ->uring_lock, other task may have started quiesce */
7152 data->quiesce = true;
7154 ret = io_rsrc_node_switch_start(ctx);
7157 io_rsrc_node_switch(ctx, data);
7159 /* kill initial ref, already quiesced if zero */
7160 if (atomic_dec_and_test(&data->refs))
7162 flush_delayed_work(&ctx->rsrc_put_work);
7163 ret = wait_for_completion_interruptible(&data->done);
7167 atomic_inc(&data->refs);
7168 /* wait for all works potentially completing data->done */
7169 flush_delayed_work(&ctx->rsrc_put_work);
7170 reinit_completion(&data->done);
7172 mutex_unlock(&ctx->uring_lock);
7173 ret = io_run_task_work_sig();
7174 mutex_lock(&ctx->uring_lock);
7176 data->quiesce = false;
7181 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7182 rsrc_put_fn *do_put)
7184 struct io_rsrc_data *data;
7186 data = kzalloc(sizeof(*data), GFP_KERNEL);
7190 atomic_set(&data->refs, 1);
7192 data->do_put = do_put;
7193 init_completion(&data->done);
7197 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7201 if (!ctx->file_data)
7203 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
7205 __io_sqe_files_unregister(ctx);
7209 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7210 __releases(&sqd->lock)
7212 WARN_ON_ONCE(sqd->thread == current);
7215 * Do the dance but not conditional clear_bit() because it'd race with
7216 * other threads incrementing park_pending and setting the bit.
7218 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7219 if (atomic_dec_return(&sqd->park_pending))
7220 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7221 mutex_unlock(&sqd->lock);
7224 static void io_sq_thread_park(struct io_sq_data *sqd)
7225 __acquires(&sqd->lock)
7227 WARN_ON_ONCE(sqd->thread == current);
7229 atomic_inc(&sqd->park_pending);
7230 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7231 mutex_lock(&sqd->lock);
7233 wake_up_process(sqd->thread);
7236 static void io_sq_thread_stop(struct io_sq_data *sqd)
7238 WARN_ON_ONCE(sqd->thread == current);
7239 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
7241 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7242 mutex_lock(&sqd->lock);
7244 wake_up_process(sqd->thread);
7245 mutex_unlock(&sqd->lock);
7246 wait_for_completion(&sqd->exited);
7249 static void io_put_sq_data(struct io_sq_data *sqd)
7251 if (refcount_dec_and_test(&sqd->refs)) {
7252 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7254 io_sq_thread_stop(sqd);
7259 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7261 struct io_sq_data *sqd = ctx->sq_data;
7264 io_sq_thread_park(sqd);
7265 list_del_init(&ctx->sqd_list);
7266 io_sqd_update_thread_idle(sqd);
7267 io_sq_thread_unpark(sqd);
7269 io_put_sq_data(sqd);
7270 ctx->sq_data = NULL;
7272 put_cred(ctx->sq_creds);
7276 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7278 struct io_ring_ctx *ctx_attach;
7279 struct io_sq_data *sqd;
7282 f = fdget(p->wq_fd);
7284 return ERR_PTR(-ENXIO);
7285 if (f.file->f_op != &io_uring_fops) {
7287 return ERR_PTR(-EINVAL);
7290 ctx_attach = f.file->private_data;
7291 sqd = ctx_attach->sq_data;
7294 return ERR_PTR(-EINVAL);
7296 if (sqd->task_tgid != current->tgid) {
7298 return ERR_PTR(-EPERM);
7301 refcount_inc(&sqd->refs);
7306 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7309 struct io_sq_data *sqd;
7312 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7313 sqd = io_attach_sq_data(p);
7318 /* fall through for EPERM case, setup new sqd/task */
7319 if (PTR_ERR(sqd) != -EPERM)
7323 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7325 return ERR_PTR(-ENOMEM);
7327 atomic_set(&sqd->park_pending, 0);
7328 refcount_set(&sqd->refs, 1);
7329 INIT_LIST_HEAD(&sqd->ctx_list);
7330 mutex_init(&sqd->lock);
7331 init_waitqueue_head(&sqd->wait);
7332 init_completion(&sqd->exited);
7336 #if defined(CONFIG_UNIX)
7338 * Ensure the UNIX gc is aware of our file set, so we are certain that
7339 * the io_uring can be safely unregistered on process exit, even if we have
7340 * loops in the file referencing.
7342 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7344 struct sock *sk = ctx->ring_sock->sk;
7345 struct scm_fp_list *fpl;
7346 struct sk_buff *skb;
7349 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7353 skb = alloc_skb(0, GFP_KERNEL);
7362 fpl->user = get_uid(current_user());
7363 for (i = 0; i < nr; i++) {
7364 struct file *file = io_file_from_index(ctx, i + offset);
7368 fpl->fp[nr_files] = get_file(file);
7369 unix_inflight(fpl->user, fpl->fp[nr_files]);
7374 fpl->max = SCM_MAX_FD;
7375 fpl->count = nr_files;
7376 UNIXCB(skb).fp = fpl;
7377 skb->destructor = unix_destruct_scm;
7378 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7379 skb_queue_head(&sk->sk_receive_queue, skb);
7381 for (i = 0; i < nr_files; i++)
7392 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7393 * causes regular reference counting to break down. We rely on the UNIX
7394 * garbage collection to take care of this problem for us.
7396 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7398 unsigned left, total;
7402 left = ctx->nr_user_files;
7404 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7406 ret = __io_sqe_files_scm(ctx, this_files, total);
7410 total += this_files;
7416 while (total < ctx->nr_user_files) {
7417 struct file *file = io_file_from_index(ctx, total);
7427 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7433 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7435 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7437 table->files = kcalloc(nr_tables, sizeof(*table->files), GFP_KERNEL);
7441 for (i = 0; i < nr_tables; i++) {
7442 unsigned int this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7444 table->files[i] = kcalloc(this_files, sizeof(*table->files[i]),
7446 if (!table->files[i])
7448 nr_files -= this_files;
7454 io_free_file_tables(table, nr_tables * IORING_MAX_FILES_TABLE);
7458 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7460 struct file *file = prsrc->file;
7461 #if defined(CONFIG_UNIX)
7462 struct sock *sock = ctx->ring_sock->sk;
7463 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7464 struct sk_buff *skb;
7467 __skb_queue_head_init(&list);
7470 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7471 * remove this entry and rearrange the file array.
7473 skb = skb_dequeue(head);
7475 struct scm_fp_list *fp;
7477 fp = UNIXCB(skb).fp;
7478 for (i = 0; i < fp->count; i++) {
7481 if (fp->fp[i] != file)
7484 unix_notinflight(fp->user, fp->fp[i]);
7485 left = fp->count - 1 - i;
7487 memmove(&fp->fp[i], &fp->fp[i + 1],
7488 left * sizeof(struct file *));
7495 __skb_queue_tail(&list, skb);
7505 __skb_queue_tail(&list, skb);
7507 skb = skb_dequeue(head);
7510 if (skb_peek(&list)) {
7511 spin_lock_irq(&head->lock);
7512 while ((skb = __skb_dequeue(&list)) != NULL)
7513 __skb_queue_tail(head, skb);
7514 spin_unlock_irq(&head->lock);
7521 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7523 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7524 struct io_ring_ctx *ctx = rsrc_data->ctx;
7525 struct io_rsrc_put *prsrc, *tmp;
7527 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7528 list_del(&prsrc->list);
7529 rsrc_data->do_put(ctx, prsrc);
7533 io_rsrc_node_destroy(ref_node);
7534 if (atomic_dec_and_test(&rsrc_data->refs))
7535 complete(&rsrc_data->done);
7538 static void io_rsrc_put_work(struct work_struct *work)
7540 struct io_ring_ctx *ctx;
7541 struct llist_node *node;
7543 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7544 node = llist_del_all(&ctx->rsrc_put_llist);
7547 struct io_rsrc_node *ref_node;
7548 struct llist_node *next = node->next;
7550 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7551 __io_rsrc_put_work(ref_node);
7556 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7558 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7559 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7560 bool first_add = false;
7562 io_rsrc_ref_lock(ctx);
7565 while (!list_empty(&ctx->rsrc_ref_list)) {
7566 node = list_first_entry(&ctx->rsrc_ref_list,
7567 struct io_rsrc_node, node);
7568 /* recycle ref nodes in order */
7571 list_del(&node->node);
7572 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7574 io_rsrc_ref_unlock(ctx);
7577 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7580 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7582 struct io_rsrc_node *ref_node;
7584 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7588 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7593 INIT_LIST_HEAD(&ref_node->node);
7594 INIT_LIST_HEAD(&ref_node->rsrc_list);
7595 ref_node->done = false;
7599 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7602 __s32 __user *fds = (__s32 __user *) arg;
7606 struct io_rsrc_data *file_data;
7612 if (nr_args > IORING_MAX_FIXED_FILES)
7614 ret = io_rsrc_node_switch_start(ctx);
7618 file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put);
7621 ctx->file_data = file_data;
7623 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7626 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7627 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7631 /* allow sparse sets */
7641 * Don't allow io_uring instances to be registered. If UNIX
7642 * isn't enabled, then this causes a reference cycle and this
7643 * instance can never get freed. If UNIX is enabled we'll
7644 * handle it just fine, but there's still no point in allowing
7645 * a ring fd as it doesn't support regular read/write anyway.
7647 if (file->f_op == &io_uring_fops) {
7651 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7654 ret = io_sqe_files_scm(ctx);
7656 __io_sqe_files_unregister(ctx);
7660 io_rsrc_node_switch(ctx, NULL);
7663 for (i = 0; i < ctx->nr_user_files; i++) {
7664 file = io_file_from_index(ctx, i);
7668 io_free_file_tables(&ctx->file_table, nr_args);
7669 ctx->nr_user_files = 0;
7671 kfree(ctx->file_data);
7672 ctx->file_data = NULL;
7676 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7679 #if defined(CONFIG_UNIX)
7680 struct sock *sock = ctx->ring_sock->sk;
7681 struct sk_buff_head *head = &sock->sk_receive_queue;
7682 struct sk_buff *skb;
7685 * See if we can merge this file into an existing skb SCM_RIGHTS
7686 * file set. If there's no room, fall back to allocating a new skb
7687 * and filling it in.
7689 spin_lock_irq(&head->lock);
7690 skb = skb_peek(head);
7692 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7694 if (fpl->count < SCM_MAX_FD) {
7695 __skb_unlink(skb, head);
7696 spin_unlock_irq(&head->lock);
7697 fpl->fp[fpl->count] = get_file(file);
7698 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7700 spin_lock_irq(&head->lock);
7701 __skb_queue_head(head, skb);
7706 spin_unlock_irq(&head->lock);
7713 return __io_sqe_files_scm(ctx, 1, index);
7719 static int io_queue_rsrc_removal(struct io_rsrc_data *data,
7720 struct io_rsrc_node *node, void *rsrc)
7722 struct io_rsrc_put *prsrc;
7724 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7729 list_add(&prsrc->list, &node->rsrc_list);
7733 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7734 struct io_uring_rsrc_update *up,
7737 struct io_rsrc_data *data = ctx->file_data;
7738 struct io_fixed_file *file_slot;
7743 bool needs_switch = false;
7745 if (check_add_overflow(up->offset, nr_args, &done))
7747 if (done > ctx->nr_user_files)
7749 err = io_rsrc_node_switch_start(ctx);
7753 fds = u64_to_user_ptr(up->data);
7754 for (done = 0; done < nr_args; done++) {
7756 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7760 if (fd == IORING_REGISTER_FILES_SKIP)
7763 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7764 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7766 if (file_slot->file_ptr) {
7767 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7768 err = io_queue_rsrc_removal(data, ctx->rsrc_node, file);
7771 file_slot->file_ptr = 0;
7772 needs_switch = true;
7781 * Don't allow io_uring instances to be registered. If
7782 * UNIX isn't enabled, then this causes a reference
7783 * cycle and this instance can never get freed. If UNIX
7784 * is enabled we'll handle it just fine, but there's
7785 * still no point in allowing a ring fd as it doesn't
7786 * support regular read/write anyway.
7788 if (file->f_op == &io_uring_fops) {
7793 io_fixed_file_set(file_slot, file);
7794 err = io_sqe_file_register(ctx, file, i);
7796 file_slot->file_ptr = 0;
7804 io_rsrc_node_switch(ctx, data);
7805 return done ? done : err;
7808 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7811 struct io_uring_rsrc_update up;
7813 if (!ctx->file_data)
7817 if (copy_from_user(&up, arg, sizeof(up)))
7822 return __io_sqe_files_update(ctx, &up, nr_args);
7825 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7827 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7829 req = io_put_req_find_next(req);
7830 return req ? &req->work : NULL;
7833 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7834 struct task_struct *task)
7836 struct io_wq_hash *hash;
7837 struct io_wq_data data;
7838 unsigned int concurrency;
7840 hash = ctx->hash_map;
7842 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7844 return ERR_PTR(-ENOMEM);
7845 refcount_set(&hash->refs, 1);
7846 init_waitqueue_head(&hash->wait);
7847 ctx->hash_map = hash;
7852 data.free_work = io_free_work;
7853 data.do_work = io_wq_submit_work;
7855 /* Do QD, or 4 * CPUS, whatever is smallest */
7856 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7858 return io_wq_create(concurrency, &data);
7861 static int io_uring_alloc_task_context(struct task_struct *task,
7862 struct io_ring_ctx *ctx)
7864 struct io_uring_task *tctx;
7867 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7868 if (unlikely(!tctx))
7871 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7872 if (unlikely(ret)) {
7877 tctx->io_wq = io_init_wq_offload(ctx, task);
7878 if (IS_ERR(tctx->io_wq)) {
7879 ret = PTR_ERR(tctx->io_wq);
7880 percpu_counter_destroy(&tctx->inflight);
7886 init_waitqueue_head(&tctx->wait);
7888 atomic_set(&tctx->in_idle, 0);
7889 atomic_set(&tctx->inflight_tracked, 0);
7890 task->io_uring = tctx;
7891 spin_lock_init(&tctx->task_lock);
7892 INIT_WQ_LIST(&tctx->task_list);
7893 tctx->task_state = 0;
7894 init_task_work(&tctx->task_work, tctx_task_work);
7898 void __io_uring_free(struct task_struct *tsk)
7900 struct io_uring_task *tctx = tsk->io_uring;
7902 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7903 WARN_ON_ONCE(tctx->io_wq);
7905 percpu_counter_destroy(&tctx->inflight);
7907 tsk->io_uring = NULL;
7910 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7911 struct io_uring_params *p)
7915 /* Retain compatibility with failing for an invalid attach attempt */
7916 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7917 IORING_SETUP_ATTACH_WQ) {
7920 f = fdget(p->wq_fd);
7923 if (f.file->f_op != &io_uring_fops) {
7929 if (ctx->flags & IORING_SETUP_SQPOLL) {
7930 struct task_struct *tsk;
7931 struct io_sq_data *sqd;
7934 sqd = io_get_sq_data(p, &attached);
7940 ctx->sq_creds = get_current_cred();
7942 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7943 if (!ctx->sq_thread_idle)
7944 ctx->sq_thread_idle = HZ;
7947 io_sq_thread_park(sqd);
7948 list_add(&ctx->sqd_list, &sqd->ctx_list);
7949 io_sqd_update_thread_idle(sqd);
7950 /* don't attach to a dying SQPOLL thread, would be racy */
7951 if (attached && !sqd->thread)
7953 io_sq_thread_unpark(sqd);
7960 if (p->flags & IORING_SETUP_SQ_AFF) {
7961 int cpu = p->sq_thread_cpu;
7964 if (cpu >= nr_cpu_ids)
7966 if (!cpu_online(cpu))
7974 sqd->task_pid = current->pid;
7975 sqd->task_tgid = current->tgid;
7976 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7983 ret = io_uring_alloc_task_context(tsk, ctx);
7984 wake_up_new_task(tsk);
7987 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7988 /* Can't have SQ_AFF without SQPOLL */
7995 io_sq_thread_finish(ctx);
7998 complete(&ctx->sq_data->exited);
8002 static inline void __io_unaccount_mem(struct user_struct *user,
8003 unsigned long nr_pages)
8005 atomic_long_sub(nr_pages, &user->locked_vm);
8008 static inline int __io_account_mem(struct user_struct *user,
8009 unsigned long nr_pages)
8011 unsigned long page_limit, cur_pages, new_pages;
8013 /* Don't allow more pages than we can safely lock */
8014 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8017 cur_pages = atomic_long_read(&user->locked_vm);
8018 new_pages = cur_pages + nr_pages;
8019 if (new_pages > page_limit)
8021 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8022 new_pages) != cur_pages);
8027 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8030 __io_unaccount_mem(ctx->user, nr_pages);
8032 if (ctx->mm_account)
8033 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8036 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8041 ret = __io_account_mem(ctx->user, nr_pages);
8046 if (ctx->mm_account)
8047 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8052 static void io_mem_free(void *ptr)
8059 page = virt_to_head_page(ptr);
8060 if (put_page_testzero(page))
8061 free_compound_page(page);
8064 static void *io_mem_alloc(size_t size)
8066 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8067 __GFP_NORETRY | __GFP_ACCOUNT;
8069 return (void *) __get_free_pages(gfp_flags, get_order(size));
8072 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8075 struct io_rings *rings;
8076 size_t off, sq_array_size;
8078 off = struct_size(rings, cqes, cq_entries);
8079 if (off == SIZE_MAX)
8083 off = ALIGN(off, SMP_CACHE_BYTES);
8091 sq_array_size = array_size(sizeof(u32), sq_entries);
8092 if (sq_array_size == SIZE_MAX)
8095 if (check_add_overflow(off, sq_array_size, &off))
8101 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf *imu)
8105 for (i = 0; i < imu->nr_bvecs; i++)
8106 unpin_user_page(imu->bvec[i].bv_page);
8107 if (imu->acct_pages)
8108 io_unaccount_mem(ctx, imu->acct_pages);
8113 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8117 if (!ctx->user_bufs)
8120 for (i = 0; i < ctx->nr_user_bufs; i++)
8121 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8122 kfree(ctx->user_bufs);
8123 ctx->user_bufs = NULL;
8124 ctx->nr_user_bufs = 0;
8128 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8129 void __user *arg, unsigned index)
8131 struct iovec __user *src;
8133 #ifdef CONFIG_COMPAT
8135 struct compat_iovec __user *ciovs;
8136 struct compat_iovec ciov;
8138 ciovs = (struct compat_iovec __user *) arg;
8139 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8142 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8143 dst->iov_len = ciov.iov_len;
8147 src = (struct iovec __user *) arg;
8148 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8154 * Not super efficient, but this is just a registration time. And we do cache
8155 * the last compound head, so generally we'll only do a full search if we don't
8158 * We check if the given compound head page has already been accounted, to
8159 * avoid double accounting it. This allows us to account the full size of the
8160 * page, not just the constituent pages of a huge page.
8162 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8163 int nr_pages, struct page *hpage)
8167 /* check current page array */
8168 for (i = 0; i < nr_pages; i++) {
8169 if (!PageCompound(pages[i]))
8171 if (compound_head(pages[i]) == hpage)
8175 /* check previously registered pages */
8176 for (i = 0; i < ctx->nr_user_bufs; i++) {
8177 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8179 for (j = 0; j < imu->nr_bvecs; j++) {
8180 if (!PageCompound(imu->bvec[j].bv_page))
8182 if (compound_head(imu->bvec[j].bv_page) == hpage)
8190 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8191 int nr_pages, struct io_mapped_ubuf *imu,
8192 struct page **last_hpage)
8196 for (i = 0; i < nr_pages; i++) {
8197 if (!PageCompound(pages[i])) {
8202 hpage = compound_head(pages[i]);
8203 if (hpage == *last_hpage)
8205 *last_hpage = hpage;
8206 if (headpage_already_acct(ctx, pages, i, hpage))
8208 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8212 if (!imu->acct_pages)
8215 ret = io_account_mem(ctx, imu->acct_pages);
8217 imu->acct_pages = 0;
8221 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8222 struct io_mapped_ubuf *imu,
8223 struct page **last_hpage)
8225 struct vm_area_struct **vmas = NULL;
8226 struct page **pages = NULL;
8227 unsigned long off, start, end, ubuf;
8229 int ret, pret, nr_pages, i;
8231 ubuf = (unsigned long) iov->iov_base;
8232 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8233 start = ubuf >> PAGE_SHIFT;
8234 nr_pages = end - start;
8238 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8242 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8247 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8253 mmap_read_lock(current->mm);
8254 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8256 if (pret == nr_pages) {
8257 /* don't support file backed memory */
8258 for (i = 0; i < nr_pages; i++) {
8259 struct vm_area_struct *vma = vmas[i];
8262 !is_file_hugepages(vma->vm_file)) {
8268 ret = pret < 0 ? pret : -EFAULT;
8270 mmap_read_unlock(current->mm);
8273 * if we did partial map, or found file backed vmas,
8274 * release any pages we did get
8277 unpin_user_pages(pages, pret);
8282 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8284 unpin_user_pages(pages, pret);
8289 off = ubuf & ~PAGE_MASK;
8290 size = iov->iov_len;
8291 for (i = 0; i < nr_pages; i++) {
8294 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8295 imu->bvec[i].bv_page = pages[i];
8296 imu->bvec[i].bv_len = vec_len;
8297 imu->bvec[i].bv_offset = off;
8301 /* store original address for later verification */
8303 imu->ubuf_end = ubuf + iov->iov_len;
8304 imu->nr_bvecs = nr_pages;
8312 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8314 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8315 return ctx->user_bufs ? 0 : -ENOMEM;
8318 static int io_buffer_validate(struct iovec *iov)
8320 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8323 * Don't impose further limits on the size and buffer
8324 * constraints here, we'll -EINVAL later when IO is
8325 * submitted if they are wrong.
8327 if (!iov->iov_base || !iov->iov_len)
8330 /* arbitrary limit, but we need something */
8331 if (iov->iov_len > SZ_1G)
8334 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8340 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8341 unsigned int nr_args)
8345 struct page *last_hpage = NULL;
8349 if (!nr_args || nr_args > UIO_MAXIOV)
8351 ret = io_buffers_map_alloc(ctx, nr_args);
8355 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8356 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8358 ret = io_copy_iov(ctx, &iov, arg, i);
8361 ret = io_buffer_validate(&iov);
8364 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8370 io_sqe_buffers_unregister(ctx);
8375 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8377 __s32 __user *fds = arg;
8383 if (copy_from_user(&fd, fds, sizeof(*fds)))
8386 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8387 if (IS_ERR(ctx->cq_ev_fd)) {
8388 int ret = PTR_ERR(ctx->cq_ev_fd);
8389 ctx->cq_ev_fd = NULL;
8396 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8398 if (ctx->cq_ev_fd) {
8399 eventfd_ctx_put(ctx->cq_ev_fd);
8400 ctx->cq_ev_fd = NULL;
8407 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8409 struct io_buffer *buf;
8410 unsigned long index;
8412 xa_for_each(&ctx->io_buffers, index, buf)
8413 __io_remove_buffers(ctx, buf, index, -1U);
8416 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8418 struct io_kiocb *req, *nxt;
8420 list_for_each_entry_safe(req, nxt, list, compl.list) {
8421 if (tsk && req->task != tsk)
8423 list_del(&req->compl.list);
8424 kmem_cache_free(req_cachep, req);
8428 static void io_req_caches_free(struct io_ring_ctx *ctx)
8430 struct io_submit_state *submit_state = &ctx->submit_state;
8431 struct io_comp_state *cs = &ctx->submit_state.comp;
8433 mutex_lock(&ctx->uring_lock);
8435 if (submit_state->free_reqs) {
8436 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8437 submit_state->reqs);
8438 submit_state->free_reqs = 0;
8441 io_flush_cached_locked_reqs(ctx, cs);
8442 io_req_cache_free(&cs->free_list, NULL);
8443 mutex_unlock(&ctx->uring_lock);
8446 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8448 io_sq_thread_finish(ctx);
8449 io_sqe_buffers_unregister(ctx);
8451 if (ctx->mm_account) {
8452 mmdrop(ctx->mm_account);
8453 ctx->mm_account = NULL;
8456 mutex_lock(&ctx->uring_lock);
8457 if (ctx->file_data) {
8458 if (!atomic_dec_and_test(&ctx->file_data->refs))
8459 wait_for_completion(&ctx->file_data->done);
8460 __io_sqe_files_unregister(ctx);
8463 __io_cqring_overflow_flush(ctx, true);
8464 mutex_unlock(&ctx->uring_lock);
8465 io_eventfd_unregister(ctx);
8466 io_destroy_buffers(ctx);
8468 /* there are no registered resources left, nobody uses it */
8470 io_rsrc_node_destroy(ctx->rsrc_node);
8471 if (ctx->rsrc_backup_node)
8472 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8473 flush_delayed_work(&ctx->rsrc_put_work);
8475 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8476 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8478 #if defined(CONFIG_UNIX)
8479 if (ctx->ring_sock) {
8480 ctx->ring_sock->file = NULL; /* so that iput() is called */
8481 sock_release(ctx->ring_sock);
8485 io_mem_free(ctx->rings);
8486 io_mem_free(ctx->sq_sqes);
8488 percpu_ref_exit(&ctx->refs);
8489 free_uid(ctx->user);
8490 io_req_caches_free(ctx);
8492 io_wq_put_hash(ctx->hash_map);
8493 kfree(ctx->cancel_hash);
8497 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8499 struct io_ring_ctx *ctx = file->private_data;
8502 poll_wait(file, &ctx->cq_wait, wait);
8504 * synchronizes with barrier from wq_has_sleeper call in
8508 if (!io_sqring_full(ctx))
8509 mask |= EPOLLOUT | EPOLLWRNORM;
8512 * Don't flush cqring overflow list here, just do a simple check.
8513 * Otherwise there could possible be ABBA deadlock:
8516 * lock(&ctx->uring_lock);
8518 * lock(&ctx->uring_lock);
8521 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8522 * pushs them to do the flush.
8524 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8525 mask |= EPOLLIN | EPOLLRDNORM;
8530 static int io_uring_fasync(int fd, struct file *file, int on)
8532 struct io_ring_ctx *ctx = file->private_data;
8534 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8537 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8539 const struct cred *creds;
8541 creds = xa_erase(&ctx->personalities, id);
8550 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8552 return io_run_task_work_head(&ctx->exit_task_work);
8555 struct io_tctx_exit {
8556 struct callback_head task_work;
8557 struct completion completion;
8558 struct io_ring_ctx *ctx;
8561 static void io_tctx_exit_cb(struct callback_head *cb)
8563 struct io_uring_task *tctx = current->io_uring;
8564 struct io_tctx_exit *work;
8566 work = container_of(cb, struct io_tctx_exit, task_work);
8568 * When @in_idle, we're in cancellation and it's racy to remove the
8569 * node. It'll be removed by the end of cancellation, just ignore it.
8571 if (!atomic_read(&tctx->in_idle))
8572 io_uring_del_task_file((unsigned long)work->ctx);
8573 complete(&work->completion);
8576 static void io_ring_exit_work(struct work_struct *work)
8578 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8579 unsigned long timeout = jiffies + HZ * 60 * 5;
8580 struct io_tctx_exit exit;
8581 struct io_tctx_node *node;
8584 /* prevent SQPOLL from submitting new requests */
8586 io_sq_thread_park(ctx->sq_data);
8587 list_del_init(&ctx->sqd_list);
8588 io_sqd_update_thread_idle(ctx->sq_data);
8589 io_sq_thread_unpark(ctx->sq_data);
8593 * If we're doing polled IO and end up having requests being
8594 * submitted async (out-of-line), then completions can come in while
8595 * we're waiting for refs to drop. We need to reap these manually,
8596 * as nobody else will be looking for them.
8599 io_uring_try_cancel_requests(ctx, NULL, NULL);
8601 WARN_ON_ONCE(time_after(jiffies, timeout));
8602 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8605 * Some may use context even when all refs and requests have been put,
8606 * and they are free to do so while still holding uring_lock or
8607 * completion_lock, see __io_req_task_submit(). Apart from other work,
8608 * this lock/unlock section also waits them to finish.
8610 mutex_lock(&ctx->uring_lock);
8611 while (!list_empty(&ctx->tctx_list)) {
8612 WARN_ON_ONCE(time_after(jiffies, timeout));
8614 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8617 init_completion(&exit.completion);
8618 init_task_work(&exit.task_work, io_tctx_exit_cb);
8619 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8620 if (WARN_ON_ONCE(ret))
8622 wake_up_process(node->task);
8624 mutex_unlock(&ctx->uring_lock);
8625 wait_for_completion(&exit.completion);
8627 mutex_lock(&ctx->uring_lock);
8629 mutex_unlock(&ctx->uring_lock);
8630 spin_lock_irq(&ctx->completion_lock);
8631 spin_unlock_irq(&ctx->completion_lock);
8633 io_ring_ctx_free(ctx);
8636 /* Returns true if we found and killed one or more timeouts */
8637 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8638 struct files_struct *files)
8640 struct io_kiocb *req, *tmp;
8643 spin_lock_irq(&ctx->completion_lock);
8644 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8645 if (io_match_task(req, tsk, files)) {
8646 io_kill_timeout(req, -ECANCELED);
8651 io_commit_cqring(ctx);
8652 spin_unlock_irq(&ctx->completion_lock);
8654 io_cqring_ev_posted(ctx);
8655 return canceled != 0;
8658 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8660 unsigned long index;
8661 struct creds *creds;
8663 mutex_lock(&ctx->uring_lock);
8664 percpu_ref_kill(&ctx->refs);
8666 __io_cqring_overflow_flush(ctx, true);
8667 xa_for_each(&ctx->personalities, index, creds)
8668 io_unregister_personality(ctx, index);
8669 mutex_unlock(&ctx->uring_lock);
8671 io_kill_timeouts(ctx, NULL, NULL);
8672 io_poll_remove_all(ctx, NULL, NULL);
8674 /* if we failed setting up the ctx, we might not have any rings */
8675 io_iopoll_try_reap_events(ctx);
8677 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8679 * Use system_unbound_wq to avoid spawning tons of event kworkers
8680 * if we're exiting a ton of rings at the same time. It just adds
8681 * noise and overhead, there's no discernable change in runtime
8682 * over using system_wq.
8684 queue_work(system_unbound_wq, &ctx->exit_work);
8687 static int io_uring_release(struct inode *inode, struct file *file)
8689 struct io_ring_ctx *ctx = file->private_data;
8691 file->private_data = NULL;
8692 io_ring_ctx_wait_and_kill(ctx);
8696 struct io_task_cancel {
8697 struct task_struct *task;
8698 struct files_struct *files;
8701 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8703 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8704 struct io_task_cancel *cancel = data;
8707 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8708 unsigned long flags;
8709 struct io_ring_ctx *ctx = req->ctx;
8711 /* protect against races with linked timeouts */
8712 spin_lock_irqsave(&ctx->completion_lock, flags);
8713 ret = io_match_task(req, cancel->task, cancel->files);
8714 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8716 ret = io_match_task(req, cancel->task, cancel->files);
8721 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8722 struct task_struct *task,
8723 struct files_struct *files)
8725 struct io_defer_entry *de;
8728 spin_lock_irq(&ctx->completion_lock);
8729 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8730 if (io_match_task(de->req, task, files)) {
8731 list_cut_position(&list, &ctx->defer_list, &de->list);
8735 spin_unlock_irq(&ctx->completion_lock);
8736 if (list_empty(&list))
8739 while (!list_empty(&list)) {
8740 de = list_first_entry(&list, struct io_defer_entry, list);
8741 list_del_init(&de->list);
8742 io_req_complete_failed(de->req, -ECANCELED);
8748 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8750 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8752 return req->ctx == data;
8755 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8757 struct io_tctx_node *node;
8758 enum io_wq_cancel cret;
8761 mutex_lock(&ctx->uring_lock);
8762 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8763 struct io_uring_task *tctx = node->task->io_uring;
8766 * io_wq will stay alive while we hold uring_lock, because it's
8767 * killed after ctx nodes, which requires to take the lock.
8769 if (!tctx || !tctx->io_wq)
8771 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8772 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8774 mutex_unlock(&ctx->uring_lock);
8779 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8780 struct task_struct *task,
8781 struct files_struct *files)
8783 struct io_task_cancel cancel = { .task = task, .files = files, };
8784 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8787 enum io_wq_cancel cret;
8791 ret |= io_uring_try_cancel_iowq(ctx);
8792 } else if (tctx && tctx->io_wq) {
8794 * Cancels requests of all rings, not only @ctx, but
8795 * it's fine as the task is in exit/exec.
8797 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8799 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8802 /* SQPOLL thread does its own polling */
8803 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8804 (ctx->sq_data && ctx->sq_data->thread == current)) {
8805 while (!list_empty_careful(&ctx->iopoll_list)) {
8806 io_iopoll_try_reap_events(ctx);
8811 ret |= io_cancel_defer_files(ctx, task, files);
8812 ret |= io_poll_remove_all(ctx, task, files);
8813 ret |= io_kill_timeouts(ctx, task, files);
8814 ret |= io_run_task_work();
8815 ret |= io_run_ctx_fallback(ctx);
8822 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8824 struct io_uring_task *tctx = current->io_uring;
8825 struct io_tctx_node *node;
8828 if (unlikely(!tctx)) {
8829 ret = io_uring_alloc_task_context(current, ctx);
8832 tctx = current->io_uring;
8834 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8835 node = kmalloc(sizeof(*node), GFP_KERNEL);
8839 node->task = current;
8841 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8848 mutex_lock(&ctx->uring_lock);
8849 list_add(&node->ctx_node, &ctx->tctx_list);
8850 mutex_unlock(&ctx->uring_lock);
8857 * Note that this task has used io_uring. We use it for cancelation purposes.
8859 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8861 struct io_uring_task *tctx = current->io_uring;
8863 if (likely(tctx && tctx->last == ctx))
8865 return __io_uring_add_task_file(ctx);
8869 * Remove this io_uring_file -> task mapping.
8871 static void io_uring_del_task_file(unsigned long index)
8873 struct io_uring_task *tctx = current->io_uring;
8874 struct io_tctx_node *node;
8878 node = xa_erase(&tctx->xa, index);
8882 WARN_ON_ONCE(current != node->task);
8883 WARN_ON_ONCE(list_empty(&node->ctx_node));
8885 mutex_lock(&node->ctx->uring_lock);
8886 list_del(&node->ctx_node);
8887 mutex_unlock(&node->ctx->uring_lock);
8889 if (tctx->last == node->ctx)
8894 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8896 struct io_tctx_node *node;
8897 unsigned long index;
8899 xa_for_each(&tctx->xa, index, node)
8900 io_uring_del_task_file(index);
8902 io_wq_put_and_exit(tctx->io_wq);
8907 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
8910 return atomic_read(&tctx->inflight_tracked);
8911 return percpu_counter_sum(&tctx->inflight);
8914 static void io_sqpoll_cancel_cb(struct callback_head *cb)
8916 struct io_tctx_exit *work = container_of(cb, struct io_tctx_exit, task_work);
8917 struct io_ring_ctx *ctx = work->ctx;
8918 struct io_sq_data *sqd = ctx->sq_data;
8921 io_uring_cancel_sqpoll(ctx);
8922 complete(&work->completion);
8925 static void io_sqpoll_cancel_sync(struct io_ring_ctx *ctx)
8927 struct io_sq_data *sqd = ctx->sq_data;
8928 struct io_tctx_exit work = { .ctx = ctx, };
8929 struct task_struct *task;
8931 io_sq_thread_park(sqd);
8932 list_del_init(&ctx->sqd_list);
8933 io_sqd_update_thread_idle(sqd);
8936 init_completion(&work.completion);
8937 init_task_work(&work.task_work, io_sqpoll_cancel_cb);
8938 io_task_work_add_head(&sqd->park_task_work, &work.task_work);
8939 wake_up_process(task);
8941 io_sq_thread_unpark(sqd);
8944 wait_for_completion(&work.completion);
8947 static void io_uring_try_cancel(struct files_struct *files)
8949 struct io_uring_task *tctx = current->io_uring;
8950 struct io_tctx_node *node;
8951 unsigned long index;
8953 xa_for_each(&tctx->xa, index, node) {
8954 struct io_ring_ctx *ctx = node->ctx;
8957 io_sqpoll_cancel_sync(ctx);
8960 io_uring_try_cancel_requests(ctx, current, files);
8964 /* should only be called by SQPOLL task */
8965 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8967 struct io_sq_data *sqd = ctx->sq_data;
8968 struct io_uring_task *tctx = current->io_uring;
8972 WARN_ON_ONCE(!sqd || ctx->sq_data->thread != current);
8974 atomic_inc(&tctx->in_idle);
8976 /* read completions before cancelations */
8977 inflight = tctx_inflight(tctx, false);
8980 io_uring_try_cancel_requests(ctx, current, NULL);
8982 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8984 * If we've seen completions, retry without waiting. This
8985 * avoids a race where a completion comes in before we did
8986 * prepare_to_wait().
8988 if (inflight == tctx_inflight(tctx, false))
8990 finish_wait(&tctx->wait, &wait);
8992 atomic_dec(&tctx->in_idle);
8996 * Find any io_uring fd that this task has registered or done IO on, and cancel
8999 void __io_uring_cancel(struct files_struct *files)
9001 struct io_uring_task *tctx = current->io_uring;
9005 /* make sure overflow events are dropped */
9006 atomic_inc(&tctx->in_idle);
9007 io_uring_try_cancel(files);
9010 /* read completions before cancelations */
9011 inflight = tctx_inflight(tctx, !!files);
9014 io_uring_try_cancel(files);
9015 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9018 * If we've seen completions, retry without waiting. This
9019 * avoids a race where a completion comes in before we did
9020 * prepare_to_wait().
9022 if (inflight == tctx_inflight(tctx, !!files))
9024 finish_wait(&tctx->wait, &wait);
9026 atomic_dec(&tctx->in_idle);
9028 io_uring_clean_tctx(tctx);
9030 /* for exec all current's requests should be gone, kill tctx */
9031 __io_uring_free(current);
9035 static void *io_uring_validate_mmap_request(struct file *file,
9036 loff_t pgoff, size_t sz)
9038 struct io_ring_ctx *ctx = file->private_data;
9039 loff_t offset = pgoff << PAGE_SHIFT;
9044 case IORING_OFF_SQ_RING:
9045 case IORING_OFF_CQ_RING:
9048 case IORING_OFF_SQES:
9052 return ERR_PTR(-EINVAL);
9055 page = virt_to_head_page(ptr);
9056 if (sz > page_size(page))
9057 return ERR_PTR(-EINVAL);
9064 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9066 size_t sz = vma->vm_end - vma->vm_start;
9070 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9072 return PTR_ERR(ptr);
9074 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9075 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9078 #else /* !CONFIG_MMU */
9080 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9082 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9085 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9087 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9090 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9091 unsigned long addr, unsigned long len,
9092 unsigned long pgoff, unsigned long flags)
9096 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9098 return PTR_ERR(ptr);
9100 return (unsigned long) ptr;
9103 #endif /* !CONFIG_MMU */
9105 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9110 if (!io_sqring_full(ctx))
9112 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9114 if (!io_sqring_full(ctx))
9117 } while (!signal_pending(current));
9119 finish_wait(&ctx->sqo_sq_wait, &wait);
9123 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9124 struct __kernel_timespec __user **ts,
9125 const sigset_t __user **sig)
9127 struct io_uring_getevents_arg arg;
9130 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9131 * is just a pointer to the sigset_t.
9133 if (!(flags & IORING_ENTER_EXT_ARG)) {
9134 *sig = (const sigset_t __user *) argp;
9140 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9141 * timespec and sigset_t pointers if good.
9143 if (*argsz != sizeof(arg))
9145 if (copy_from_user(&arg, argp, sizeof(arg)))
9147 *sig = u64_to_user_ptr(arg.sigmask);
9148 *argsz = arg.sigmask_sz;
9149 *ts = u64_to_user_ptr(arg.ts);
9153 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9154 u32, min_complete, u32, flags, const void __user *, argp,
9157 struct io_ring_ctx *ctx;
9164 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9165 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9169 if (unlikely(!f.file))
9173 if (unlikely(f.file->f_op != &io_uring_fops))
9177 ctx = f.file->private_data;
9178 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9182 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9186 * For SQ polling, the thread will do all submissions and completions.
9187 * Just return the requested submit count, and wake the thread if
9191 if (ctx->flags & IORING_SETUP_SQPOLL) {
9192 io_cqring_overflow_flush(ctx, false);
9195 if (unlikely(ctx->sq_data->thread == NULL)) {
9198 if (flags & IORING_ENTER_SQ_WAKEUP)
9199 wake_up(&ctx->sq_data->wait);
9200 if (flags & IORING_ENTER_SQ_WAIT) {
9201 ret = io_sqpoll_wait_sq(ctx);
9205 submitted = to_submit;
9206 } else if (to_submit) {
9207 ret = io_uring_add_task_file(ctx);
9210 mutex_lock(&ctx->uring_lock);
9211 submitted = io_submit_sqes(ctx, to_submit);
9212 mutex_unlock(&ctx->uring_lock);
9214 if (submitted != to_submit)
9217 if (flags & IORING_ENTER_GETEVENTS) {
9218 const sigset_t __user *sig;
9219 struct __kernel_timespec __user *ts;
9221 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9225 min_complete = min(min_complete, ctx->cq_entries);
9228 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9229 * space applications don't need to do io completion events
9230 * polling again, they can rely on io_sq_thread to do polling
9231 * work, which can reduce cpu usage and uring_lock contention.
9233 if (ctx->flags & IORING_SETUP_IOPOLL &&
9234 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9235 ret = io_iopoll_check(ctx, min_complete);
9237 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9242 percpu_ref_put(&ctx->refs);
9245 return submitted ? submitted : ret;
9248 #ifdef CONFIG_PROC_FS
9249 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9250 const struct cred *cred)
9252 struct user_namespace *uns = seq_user_ns(m);
9253 struct group_info *gi;
9258 seq_printf(m, "%5d\n", id);
9259 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9260 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9261 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9262 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9263 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9264 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9265 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9266 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9267 seq_puts(m, "\n\tGroups:\t");
9268 gi = cred->group_info;
9269 for (g = 0; g < gi->ngroups; g++) {
9270 seq_put_decimal_ull(m, g ? " " : "",
9271 from_kgid_munged(uns, gi->gid[g]));
9273 seq_puts(m, "\n\tCapEff:\t");
9274 cap = cred->cap_effective;
9275 CAP_FOR_EACH_U32(__capi)
9276 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9281 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9283 struct io_sq_data *sq = NULL;
9288 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9289 * since fdinfo case grabs it in the opposite direction of normal use
9290 * cases. If we fail to get the lock, we just don't iterate any
9291 * structures that could be going away outside the io_uring mutex.
9293 has_lock = mutex_trylock(&ctx->uring_lock);
9295 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9301 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9302 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9303 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9304 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9305 struct file *f = io_file_from_index(ctx, i);
9308 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9310 seq_printf(m, "%5u: <none>\n", i);
9312 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9313 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9314 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9315 unsigned int len = buf->ubuf_end - buf->ubuf;
9317 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9319 if (has_lock && !xa_empty(&ctx->personalities)) {
9320 unsigned long index;
9321 const struct cred *cred;
9323 seq_printf(m, "Personalities:\n");
9324 xa_for_each(&ctx->personalities, index, cred)
9325 io_uring_show_cred(m, index, cred);
9327 seq_printf(m, "PollList:\n");
9328 spin_lock_irq(&ctx->completion_lock);
9329 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9330 struct hlist_head *list = &ctx->cancel_hash[i];
9331 struct io_kiocb *req;
9333 hlist_for_each_entry(req, list, hash_node)
9334 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9335 req->task->task_works != NULL);
9337 spin_unlock_irq(&ctx->completion_lock);
9339 mutex_unlock(&ctx->uring_lock);
9342 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9344 struct io_ring_ctx *ctx = f->private_data;
9346 if (percpu_ref_tryget(&ctx->refs)) {
9347 __io_uring_show_fdinfo(ctx, m);
9348 percpu_ref_put(&ctx->refs);
9353 static const struct file_operations io_uring_fops = {
9354 .release = io_uring_release,
9355 .mmap = io_uring_mmap,
9357 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9358 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9360 .poll = io_uring_poll,
9361 .fasync = io_uring_fasync,
9362 #ifdef CONFIG_PROC_FS
9363 .show_fdinfo = io_uring_show_fdinfo,
9367 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9368 struct io_uring_params *p)
9370 struct io_rings *rings;
9371 size_t size, sq_array_offset;
9373 /* make sure these are sane, as we already accounted them */
9374 ctx->sq_entries = p->sq_entries;
9375 ctx->cq_entries = p->cq_entries;
9377 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9378 if (size == SIZE_MAX)
9381 rings = io_mem_alloc(size);
9386 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9387 rings->sq_ring_mask = p->sq_entries - 1;
9388 rings->cq_ring_mask = p->cq_entries - 1;
9389 rings->sq_ring_entries = p->sq_entries;
9390 rings->cq_ring_entries = p->cq_entries;
9391 ctx->sq_mask = rings->sq_ring_mask;
9392 ctx->cq_mask = rings->cq_ring_mask;
9394 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9395 if (size == SIZE_MAX) {
9396 io_mem_free(ctx->rings);
9401 ctx->sq_sqes = io_mem_alloc(size);
9402 if (!ctx->sq_sqes) {
9403 io_mem_free(ctx->rings);
9411 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9415 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9419 ret = io_uring_add_task_file(ctx);
9424 fd_install(fd, file);
9429 * Allocate an anonymous fd, this is what constitutes the application
9430 * visible backing of an io_uring instance. The application mmaps this
9431 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9432 * we have to tie this fd to a socket for file garbage collection purposes.
9434 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9437 #if defined(CONFIG_UNIX)
9440 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9443 return ERR_PTR(ret);
9446 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9447 O_RDWR | O_CLOEXEC);
9448 #if defined(CONFIG_UNIX)
9450 sock_release(ctx->ring_sock);
9451 ctx->ring_sock = NULL;
9453 ctx->ring_sock->file = file;
9459 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9460 struct io_uring_params __user *params)
9462 struct io_ring_ctx *ctx;
9468 if (entries > IORING_MAX_ENTRIES) {
9469 if (!(p->flags & IORING_SETUP_CLAMP))
9471 entries = IORING_MAX_ENTRIES;
9475 * Use twice as many entries for the CQ ring. It's possible for the
9476 * application to drive a higher depth than the size of the SQ ring,
9477 * since the sqes are only used at submission time. This allows for
9478 * some flexibility in overcommitting a bit. If the application has
9479 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9480 * of CQ ring entries manually.
9482 p->sq_entries = roundup_pow_of_two(entries);
9483 if (p->flags & IORING_SETUP_CQSIZE) {
9485 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9486 * to a power-of-two, if it isn't already. We do NOT impose
9487 * any cq vs sq ring sizing.
9491 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9492 if (!(p->flags & IORING_SETUP_CLAMP))
9494 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9496 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9497 if (p->cq_entries < p->sq_entries)
9500 p->cq_entries = 2 * p->sq_entries;
9503 ctx = io_ring_ctx_alloc(p);
9506 ctx->compat = in_compat_syscall();
9507 if (!capable(CAP_IPC_LOCK))
9508 ctx->user = get_uid(current_user());
9511 * This is just grabbed for accounting purposes. When a process exits,
9512 * the mm is exited and dropped before the files, hence we need to hang
9513 * on to this mm purely for the purposes of being able to unaccount
9514 * memory (locked/pinned vm). It's not used for anything else.
9516 mmgrab(current->mm);
9517 ctx->mm_account = current->mm;
9519 ret = io_allocate_scq_urings(ctx, p);
9523 ret = io_sq_offload_create(ctx, p);
9527 memset(&p->sq_off, 0, sizeof(p->sq_off));
9528 p->sq_off.head = offsetof(struct io_rings, sq.head);
9529 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9530 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9531 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9532 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9533 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9534 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9536 memset(&p->cq_off, 0, sizeof(p->cq_off));
9537 p->cq_off.head = offsetof(struct io_rings, cq.head);
9538 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9539 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9540 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9541 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9542 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9543 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9545 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9546 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9547 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9548 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9549 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9551 if (copy_to_user(params, p, sizeof(*p))) {
9556 file = io_uring_get_file(ctx);
9558 ret = PTR_ERR(file);
9563 * Install ring fd as the very last thing, so we don't risk someone
9564 * having closed it before we finish setup
9566 ret = io_uring_install_fd(ctx, file);
9568 /* fput will clean it up */
9573 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9576 io_ring_ctx_wait_and_kill(ctx);
9581 * Sets up an aio uring context, and returns the fd. Applications asks for a
9582 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9583 * params structure passed in.
9585 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9587 struct io_uring_params p;
9590 if (copy_from_user(&p, params, sizeof(p)))
9592 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9597 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9598 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9599 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9600 IORING_SETUP_R_DISABLED))
9603 return io_uring_create(entries, &p, params);
9606 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9607 struct io_uring_params __user *, params)
9609 return io_uring_setup(entries, params);
9612 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9614 struct io_uring_probe *p;
9618 size = struct_size(p, ops, nr_args);
9619 if (size == SIZE_MAX)
9621 p = kzalloc(size, GFP_KERNEL);
9626 if (copy_from_user(p, arg, size))
9629 if (memchr_inv(p, 0, size))
9632 p->last_op = IORING_OP_LAST - 1;
9633 if (nr_args > IORING_OP_LAST)
9634 nr_args = IORING_OP_LAST;
9636 for (i = 0; i < nr_args; i++) {
9638 if (!io_op_defs[i].not_supported)
9639 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9644 if (copy_to_user(arg, p, size))
9651 static int io_register_personality(struct io_ring_ctx *ctx)
9653 const struct cred *creds;
9657 creds = get_current_cred();
9659 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9660 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9667 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9668 unsigned int nr_args)
9670 struct io_uring_restriction *res;
9674 /* Restrictions allowed only if rings started disabled */
9675 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9678 /* We allow only a single restrictions registration */
9679 if (ctx->restrictions.registered)
9682 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9685 size = array_size(nr_args, sizeof(*res));
9686 if (size == SIZE_MAX)
9689 res = memdup_user(arg, size);
9691 return PTR_ERR(res);
9695 for (i = 0; i < nr_args; i++) {
9696 switch (res[i].opcode) {
9697 case IORING_RESTRICTION_REGISTER_OP:
9698 if (res[i].register_op >= IORING_REGISTER_LAST) {
9703 __set_bit(res[i].register_op,
9704 ctx->restrictions.register_op);
9706 case IORING_RESTRICTION_SQE_OP:
9707 if (res[i].sqe_op >= IORING_OP_LAST) {
9712 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9714 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9715 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9717 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9718 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9727 /* Reset all restrictions if an error happened */
9729 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9731 ctx->restrictions.registered = true;
9737 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9739 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9742 if (ctx->restrictions.registered)
9743 ctx->restricted = 1;
9745 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9746 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9747 wake_up(&ctx->sq_data->wait);
9751 static bool io_register_op_must_quiesce(int op)
9754 case IORING_REGISTER_FILES:
9755 case IORING_UNREGISTER_FILES:
9756 case IORING_REGISTER_FILES_UPDATE:
9757 case IORING_REGISTER_PROBE:
9758 case IORING_REGISTER_PERSONALITY:
9759 case IORING_UNREGISTER_PERSONALITY:
9766 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9767 void __user *arg, unsigned nr_args)
9768 __releases(ctx->uring_lock)
9769 __acquires(ctx->uring_lock)
9774 * We're inside the ring mutex, if the ref is already dying, then
9775 * someone else killed the ctx or is already going through
9776 * io_uring_register().
9778 if (percpu_ref_is_dying(&ctx->refs))
9781 if (io_register_op_must_quiesce(opcode)) {
9782 percpu_ref_kill(&ctx->refs);
9785 * Drop uring mutex before waiting for references to exit. If
9786 * another thread is currently inside io_uring_enter() it might
9787 * need to grab the uring_lock to make progress. If we hold it
9788 * here across the drain wait, then we can deadlock. It's safe
9789 * to drop the mutex here, since no new references will come in
9790 * after we've killed the percpu ref.
9792 mutex_unlock(&ctx->uring_lock);
9794 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9797 ret = io_run_task_work_sig();
9801 mutex_lock(&ctx->uring_lock);
9804 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
9809 if (ctx->restricted) {
9810 if (opcode >= IORING_REGISTER_LAST) {
9815 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9822 case IORING_REGISTER_BUFFERS:
9823 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9825 case IORING_UNREGISTER_BUFFERS:
9829 ret = io_sqe_buffers_unregister(ctx);
9831 case IORING_REGISTER_FILES:
9832 ret = io_sqe_files_register(ctx, arg, nr_args);
9834 case IORING_UNREGISTER_FILES:
9838 ret = io_sqe_files_unregister(ctx);
9840 case IORING_REGISTER_FILES_UPDATE:
9841 ret = io_sqe_files_update(ctx, arg, nr_args);
9843 case IORING_REGISTER_EVENTFD:
9844 case IORING_REGISTER_EVENTFD_ASYNC:
9848 ret = io_eventfd_register(ctx, arg);
9851 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9852 ctx->eventfd_async = 1;
9854 ctx->eventfd_async = 0;
9856 case IORING_UNREGISTER_EVENTFD:
9860 ret = io_eventfd_unregister(ctx);
9862 case IORING_REGISTER_PROBE:
9864 if (!arg || nr_args > 256)
9866 ret = io_probe(ctx, arg, nr_args);
9868 case IORING_REGISTER_PERSONALITY:
9872 ret = io_register_personality(ctx);
9874 case IORING_UNREGISTER_PERSONALITY:
9878 ret = io_unregister_personality(ctx, nr_args);
9880 case IORING_REGISTER_ENABLE_RINGS:
9884 ret = io_register_enable_rings(ctx);
9886 case IORING_REGISTER_RESTRICTIONS:
9887 ret = io_register_restrictions(ctx, arg, nr_args);
9895 if (io_register_op_must_quiesce(opcode)) {
9896 /* bring the ctx back to life */
9897 percpu_ref_reinit(&ctx->refs);
9898 reinit_completion(&ctx->ref_comp);
9903 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9904 void __user *, arg, unsigned int, nr_args)
9906 struct io_ring_ctx *ctx;
9915 if (f.file->f_op != &io_uring_fops)
9918 ctx = f.file->private_data;
9922 mutex_lock(&ctx->uring_lock);
9923 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9924 mutex_unlock(&ctx->uring_lock);
9925 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9926 ctx->cq_ev_fd != NULL, ret);
9932 static int __init io_uring_init(void)
9934 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9935 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9936 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9939 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9940 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9941 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9942 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9943 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9944 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9945 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9946 BUILD_BUG_SQE_ELEM(8, __u64, off);
9947 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9948 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9949 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9950 BUILD_BUG_SQE_ELEM(24, __u32, len);
9951 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9952 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9953 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9954 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9955 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9956 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9957 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9958 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9959 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9960 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9961 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9962 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9963 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9964 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9965 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9966 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9967 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9968 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9969 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9971 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9972 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9973 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9977 __initcall(io_uring_init);