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 unsigned int nr_bvecs;
199 unsigned long acct_pages;
200 struct bio_vec bvec[];
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;
221 struct io_mapped_ubuf *buf;
225 struct io_file_table {
226 /* two level table */
227 struct io_fixed_file **files;
230 struct io_rsrc_node {
231 struct percpu_ref refs;
232 struct list_head node;
233 struct list_head rsrc_list;
234 struct io_rsrc_data *rsrc_data;
235 struct llist_node llist;
239 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
241 struct io_rsrc_data {
242 struct io_ring_ctx *ctx;
247 struct completion done;
252 struct list_head list;
258 struct io_restriction {
259 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
260 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
261 u8 sqe_flags_allowed;
262 u8 sqe_flags_required;
267 IO_SQ_THREAD_SHOULD_STOP = 0,
268 IO_SQ_THREAD_SHOULD_PARK,
273 atomic_t park_pending;
276 /* ctx's that are using this sqd */
277 struct list_head ctx_list;
279 struct task_struct *thread;
280 struct wait_queue_head wait;
282 unsigned sq_thread_idle;
288 struct completion exited;
289 struct callback_head *park_task_work;
292 #define IO_IOPOLL_BATCH 8
293 #define IO_COMPL_BATCH 32
294 #define IO_REQ_CACHE_SIZE 32
295 #define IO_REQ_ALLOC_BATCH 8
297 struct io_comp_state {
298 struct io_kiocb *reqs[IO_COMPL_BATCH];
300 unsigned int locked_free_nr;
301 /* inline/task_work completion list, under ->uring_lock */
302 struct list_head free_list;
303 /* IRQ completion list, under ->completion_lock */
304 struct list_head locked_free_list;
307 struct io_submit_link {
308 struct io_kiocb *head;
309 struct io_kiocb *last;
312 struct io_submit_state {
313 struct blk_plug plug;
314 struct io_submit_link link;
317 * io_kiocb alloc cache
319 void *reqs[IO_REQ_CACHE_SIZE];
320 unsigned int free_reqs;
325 * Batch completion logic
327 struct io_comp_state comp;
330 * File reference cache
334 unsigned int file_refs;
335 unsigned int ios_left;
340 struct percpu_ref refs;
341 } ____cacheline_aligned_in_smp;
345 unsigned int compat: 1;
346 unsigned int drain_next: 1;
347 unsigned int eventfd_async: 1;
348 unsigned int restricted: 1;
351 * Ring buffer of indices into array of io_uring_sqe, which is
352 * mmapped by the application using the IORING_OFF_SQES offset.
354 * This indirection could e.g. be used to assign fixed
355 * io_uring_sqe entries to operations and only submit them to
356 * the queue when needed.
358 * The kernel modifies neither the indices array nor the entries
362 unsigned cached_sq_head;
365 unsigned sq_thread_idle;
366 unsigned cached_sq_dropped;
367 unsigned cached_cq_overflow;
368 unsigned long sq_check_overflow;
370 /* hashed buffered write serialization */
371 struct io_wq_hash *hash_map;
373 struct list_head defer_list;
374 struct list_head timeout_list;
375 struct list_head cq_overflow_list;
377 struct io_uring_sqe *sq_sqes;
378 } ____cacheline_aligned_in_smp;
381 struct mutex uring_lock;
382 wait_queue_head_t wait;
383 } ____cacheline_aligned_in_smp;
385 struct io_submit_state submit_state;
387 struct io_rings *rings;
389 /* Only used for accounting purposes */
390 struct mm_struct *mm_account;
392 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
393 struct io_sq_data *sq_data; /* if using sq thread polling */
395 struct wait_queue_head sqo_sq_wait;
396 struct list_head sqd_list;
399 * If used, fixed file set. Writers must ensure that ->refs is dead,
400 * readers must ensure that ->refs is alive as long as the file* is
401 * used. Only updated through io_uring_register(2).
403 struct io_rsrc_data *file_data;
404 struct io_file_table file_table;
405 unsigned nr_user_files;
407 /* if used, fixed mapped user buffers */
408 struct io_rsrc_data *buf_data;
409 unsigned nr_user_bufs;
410 struct io_mapped_ubuf **user_bufs;
412 struct user_struct *user;
414 struct completion ref_comp;
416 #if defined(CONFIG_UNIX)
417 struct socket *ring_sock;
420 struct xarray io_buffers;
422 struct xarray personalities;
426 unsigned cached_cq_tail;
429 atomic_t cq_timeouts;
430 unsigned cq_last_tm_flush;
431 unsigned long cq_check_overflow;
432 struct wait_queue_head cq_wait;
433 struct fasync_struct *cq_fasync;
434 struct eventfd_ctx *cq_ev_fd;
435 } ____cacheline_aligned_in_smp;
438 spinlock_t completion_lock;
441 * ->iopoll_list is protected by the ctx->uring_lock for
442 * io_uring instances that don't use IORING_SETUP_SQPOLL.
443 * For SQPOLL, only the single threaded io_sq_thread() will
444 * manipulate the list, hence no extra locking is needed there.
446 struct list_head iopoll_list;
447 struct hlist_head *cancel_hash;
448 unsigned cancel_hash_bits;
449 bool poll_multi_file;
450 } ____cacheline_aligned_in_smp;
452 struct delayed_work rsrc_put_work;
453 struct llist_head rsrc_put_llist;
454 struct list_head rsrc_ref_list;
455 spinlock_t rsrc_ref_lock;
456 struct io_rsrc_node *rsrc_node;
457 struct io_rsrc_node *rsrc_backup_node;
459 struct io_restriction restrictions;
462 struct callback_head *exit_task_work;
464 /* Keep this last, we don't need it for the fast path */
465 struct work_struct exit_work;
466 struct list_head tctx_list;
469 struct io_uring_task {
470 /* submission side */
472 struct wait_queue_head wait;
473 const struct io_ring_ctx *last;
475 struct percpu_counter inflight;
476 atomic_t inflight_tracked;
479 spinlock_t task_lock;
480 struct io_wq_work_list task_list;
481 unsigned long task_state;
482 struct callback_head task_work;
486 * First field must be the file pointer in all the
487 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
489 struct io_poll_iocb {
491 struct wait_queue_head *head;
495 struct wait_queue_entry wait;
498 struct io_poll_update {
504 bool update_user_data;
512 struct io_timeout_data {
513 struct io_kiocb *req;
514 struct hrtimer timer;
515 struct timespec64 ts;
516 enum hrtimer_mode mode;
521 struct sockaddr __user *addr;
522 int __user *addr_len;
524 unsigned long nofile;
544 struct list_head list;
545 /* head of the link, used by linked timeouts only */
546 struct io_kiocb *head;
549 struct io_timeout_rem {
554 struct timespec64 ts;
559 /* NOTE: kiocb has the file as the first member, so don't do it here */
567 struct sockaddr __user *addr;
574 struct compat_msghdr __user *umsg_compat;
575 struct user_msghdr __user *umsg;
581 struct io_buffer *kbuf;
587 struct filename *filename;
589 unsigned long nofile;
592 struct io_rsrc_update {
618 struct epoll_event event;
622 struct file *file_out;
623 struct file *file_in;
630 struct io_provide_buf {
644 const char __user *filename;
645 struct statx __user *buffer;
657 struct filename *oldpath;
658 struct filename *newpath;
666 struct filename *filename;
669 struct io_completion {
671 struct list_head list;
675 struct io_async_connect {
676 struct sockaddr_storage address;
679 struct io_async_msghdr {
680 struct iovec fast_iov[UIO_FASTIOV];
681 /* points to an allocated iov, if NULL we use fast_iov instead */
682 struct iovec *free_iov;
683 struct sockaddr __user *uaddr;
685 struct sockaddr_storage addr;
689 struct iovec fast_iov[UIO_FASTIOV];
690 const struct iovec *free_iovec;
691 struct iov_iter iter;
693 struct wait_page_queue wpq;
697 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
698 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
699 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
700 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
701 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
702 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
708 REQ_F_LINK_TIMEOUT_BIT,
709 REQ_F_NEED_CLEANUP_BIT,
711 REQ_F_BUFFER_SELECTED_BIT,
712 REQ_F_LTIMEOUT_ACTIVE_BIT,
713 REQ_F_COMPLETE_INLINE_BIT,
715 REQ_F_DONT_REISSUE_BIT,
716 /* keep async read/write and isreg together and in order */
717 REQ_F_ASYNC_READ_BIT,
718 REQ_F_ASYNC_WRITE_BIT,
721 /* not a real bit, just to check we're not overflowing the space */
727 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
728 /* drain existing IO first */
729 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
731 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
732 /* doesn't sever on completion < 0 */
733 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
735 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
736 /* IOSQE_BUFFER_SELECT */
737 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
739 /* fail rest of links */
740 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
741 /* on inflight list, should be cancelled and waited on exit reliably */
742 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
743 /* read/write uses file position */
744 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
745 /* must not punt to workers */
746 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
747 /* has or had linked timeout */
748 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
750 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
751 /* already went through poll handler */
752 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
753 /* buffer already selected */
754 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
755 /* linked timeout is active, i.e. prepared by link's head */
756 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
757 /* completion is deferred through io_comp_state */
758 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
759 /* caller should reissue async */
760 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
761 /* don't attempt request reissue, see io_rw_reissue() */
762 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
763 /* supports async reads */
764 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
765 /* supports async writes */
766 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
768 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
772 struct io_poll_iocb poll;
773 struct io_poll_iocb *double_poll;
776 struct io_task_work {
777 struct io_wq_work_node node;
778 task_work_func_t func;
782 * NOTE! Each of the iocb union members has the file pointer
783 * as the first entry in their struct definition. So you can
784 * access the file pointer through any of the sub-structs,
785 * or directly as just 'ki_filp' in this struct.
791 struct io_poll_iocb poll;
792 struct io_poll_update poll_update;
793 struct io_accept accept;
795 struct io_cancel cancel;
796 struct io_timeout timeout;
797 struct io_timeout_rem timeout_rem;
798 struct io_connect connect;
799 struct io_sr_msg sr_msg;
801 struct io_close close;
802 struct io_rsrc_update rsrc_update;
803 struct io_fadvise fadvise;
804 struct io_madvise madvise;
805 struct io_epoll epoll;
806 struct io_splice splice;
807 struct io_provide_buf pbuf;
808 struct io_statx statx;
809 struct io_shutdown shutdown;
810 struct io_rename rename;
811 struct io_unlink unlink;
812 /* use only after cleaning per-op data, see io_clean_op() */
813 struct io_completion compl;
816 /* opcode allocated if it needs to store data for async defer */
819 /* polled IO has completed */
825 struct io_ring_ctx *ctx;
828 struct task_struct *task;
831 struct io_kiocb *link;
832 struct percpu_ref *fixed_rsrc_refs;
834 /* used with ctx->iopoll_list with reads/writes */
835 struct list_head inflight_entry;
837 struct io_task_work io_task_work;
838 struct callback_head task_work;
840 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
841 struct hlist_node hash_node;
842 struct async_poll *apoll;
843 struct io_wq_work work;
844 /* store used ubuf, so we can prevent reloading */
845 struct io_mapped_ubuf *imu;
848 struct io_tctx_node {
849 struct list_head ctx_node;
850 struct task_struct *task;
851 struct io_ring_ctx *ctx;
854 struct io_defer_entry {
855 struct list_head list;
856 struct io_kiocb *req;
861 /* needs req->file assigned */
862 unsigned needs_file : 1;
863 /* hash wq insertion if file is a regular file */
864 unsigned hash_reg_file : 1;
865 /* unbound wq insertion if file is a non-regular file */
866 unsigned unbound_nonreg_file : 1;
867 /* opcode is not supported by this kernel */
868 unsigned not_supported : 1;
869 /* set if opcode supports polled "wait" */
871 unsigned pollout : 1;
872 /* op supports buffer selection */
873 unsigned buffer_select : 1;
874 /* do prep async if is going to be punted */
875 unsigned needs_async_setup : 1;
876 /* should block plug */
878 /* size of async data needed, if any */
879 unsigned short async_size;
882 static const struct io_op_def io_op_defs[] = {
883 [IORING_OP_NOP] = {},
884 [IORING_OP_READV] = {
886 .unbound_nonreg_file = 1,
889 .needs_async_setup = 1,
891 .async_size = sizeof(struct io_async_rw),
893 [IORING_OP_WRITEV] = {
896 .unbound_nonreg_file = 1,
898 .needs_async_setup = 1,
900 .async_size = sizeof(struct io_async_rw),
902 [IORING_OP_FSYNC] = {
905 [IORING_OP_READ_FIXED] = {
907 .unbound_nonreg_file = 1,
910 .async_size = sizeof(struct io_async_rw),
912 [IORING_OP_WRITE_FIXED] = {
915 .unbound_nonreg_file = 1,
918 .async_size = sizeof(struct io_async_rw),
920 [IORING_OP_POLL_ADD] = {
922 .unbound_nonreg_file = 1,
924 [IORING_OP_POLL_REMOVE] = {},
925 [IORING_OP_SYNC_FILE_RANGE] = {
928 [IORING_OP_SENDMSG] = {
930 .unbound_nonreg_file = 1,
932 .needs_async_setup = 1,
933 .async_size = sizeof(struct io_async_msghdr),
935 [IORING_OP_RECVMSG] = {
937 .unbound_nonreg_file = 1,
940 .needs_async_setup = 1,
941 .async_size = sizeof(struct io_async_msghdr),
943 [IORING_OP_TIMEOUT] = {
944 .async_size = sizeof(struct io_timeout_data),
946 [IORING_OP_TIMEOUT_REMOVE] = {
947 /* used by timeout updates' prep() */
949 [IORING_OP_ACCEPT] = {
951 .unbound_nonreg_file = 1,
954 [IORING_OP_ASYNC_CANCEL] = {},
955 [IORING_OP_LINK_TIMEOUT] = {
956 .async_size = sizeof(struct io_timeout_data),
958 [IORING_OP_CONNECT] = {
960 .unbound_nonreg_file = 1,
962 .needs_async_setup = 1,
963 .async_size = sizeof(struct io_async_connect),
965 [IORING_OP_FALLOCATE] = {
968 [IORING_OP_OPENAT] = {},
969 [IORING_OP_CLOSE] = {},
970 [IORING_OP_FILES_UPDATE] = {},
971 [IORING_OP_STATX] = {},
974 .unbound_nonreg_file = 1,
978 .async_size = sizeof(struct io_async_rw),
980 [IORING_OP_WRITE] = {
982 .unbound_nonreg_file = 1,
985 .async_size = sizeof(struct io_async_rw),
987 [IORING_OP_FADVISE] = {
990 [IORING_OP_MADVISE] = {},
993 .unbound_nonreg_file = 1,
998 .unbound_nonreg_file = 1,
1002 [IORING_OP_OPENAT2] = {
1004 [IORING_OP_EPOLL_CTL] = {
1005 .unbound_nonreg_file = 1,
1007 [IORING_OP_SPLICE] = {
1010 .unbound_nonreg_file = 1,
1012 [IORING_OP_PROVIDE_BUFFERS] = {},
1013 [IORING_OP_REMOVE_BUFFERS] = {},
1017 .unbound_nonreg_file = 1,
1019 [IORING_OP_SHUTDOWN] = {
1022 [IORING_OP_RENAMEAT] = {},
1023 [IORING_OP_UNLINKAT] = {},
1026 static bool io_disarm_next(struct io_kiocb *req);
1027 static void io_uring_del_task_file(unsigned long index);
1028 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1029 struct task_struct *task,
1030 struct files_struct *files);
1031 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd);
1032 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1034 static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1035 long res, unsigned int cflags);
1036 static void io_put_req(struct io_kiocb *req);
1037 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1038 static void io_dismantle_req(struct io_kiocb *req);
1039 static void io_put_task(struct task_struct *task, int nr);
1040 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1041 static void io_queue_linked_timeout(struct io_kiocb *req);
1042 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1043 struct io_uring_rsrc_update2 *up,
1045 static void io_clean_op(struct io_kiocb *req);
1046 static struct file *io_file_get(struct io_submit_state *state,
1047 struct io_kiocb *req, int fd, bool fixed);
1048 static void __io_queue_sqe(struct io_kiocb *req);
1049 static void io_rsrc_put_work(struct work_struct *work);
1051 static void io_req_task_queue(struct io_kiocb *req);
1052 static void io_submit_flush_completions(struct io_comp_state *cs,
1053 struct io_ring_ctx *ctx);
1054 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1055 static int io_req_prep_async(struct io_kiocb *req);
1057 static struct kmem_cache *req_cachep;
1059 static const struct file_operations io_uring_fops;
1061 struct sock *io_uring_get_socket(struct file *file)
1063 #if defined(CONFIG_UNIX)
1064 if (file->f_op == &io_uring_fops) {
1065 struct io_ring_ctx *ctx = file->private_data;
1067 return ctx->ring_sock->sk;
1072 EXPORT_SYMBOL(io_uring_get_socket);
1074 #define io_for_each_link(pos, head) \
1075 for (pos = (head); pos; pos = pos->link)
1077 static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1079 struct io_ring_ctx *ctx = req->ctx;
1081 if (!req->fixed_rsrc_refs) {
1082 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1083 percpu_ref_get(req->fixed_rsrc_refs);
1087 static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1089 bool got = percpu_ref_tryget(ref);
1091 /* already at zero, wait for ->release() */
1093 wait_for_completion(compl);
1094 percpu_ref_resurrect(ref);
1096 percpu_ref_put(ref);
1099 static bool io_match_task(struct io_kiocb *head,
1100 struct task_struct *task,
1101 struct files_struct *files)
1103 struct io_kiocb *req;
1105 if (task && head->task != task)
1110 io_for_each_link(req, head) {
1111 if (req->flags & REQ_F_INFLIGHT)
1117 static inline void req_set_fail_links(struct io_kiocb *req)
1119 if (req->flags & REQ_F_LINK)
1120 req->flags |= REQ_F_FAIL_LINK;
1123 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1125 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1127 complete(&ctx->ref_comp);
1130 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1132 return !req->timeout.off;
1135 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1137 struct io_ring_ctx *ctx;
1140 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1145 * Use 5 bits less than the max cq entries, that should give us around
1146 * 32 entries per hash list if totally full and uniformly spread.
1148 hash_bits = ilog2(p->cq_entries);
1152 ctx->cancel_hash_bits = hash_bits;
1153 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1155 if (!ctx->cancel_hash)
1157 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1159 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1160 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1163 ctx->flags = p->flags;
1164 init_waitqueue_head(&ctx->sqo_sq_wait);
1165 INIT_LIST_HEAD(&ctx->sqd_list);
1166 init_waitqueue_head(&ctx->cq_wait);
1167 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1168 init_completion(&ctx->ref_comp);
1169 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1170 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1171 mutex_init(&ctx->uring_lock);
1172 init_waitqueue_head(&ctx->wait);
1173 spin_lock_init(&ctx->completion_lock);
1174 INIT_LIST_HEAD(&ctx->iopoll_list);
1175 INIT_LIST_HEAD(&ctx->defer_list);
1176 INIT_LIST_HEAD(&ctx->timeout_list);
1177 spin_lock_init(&ctx->rsrc_ref_lock);
1178 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1179 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1180 init_llist_head(&ctx->rsrc_put_llist);
1181 INIT_LIST_HEAD(&ctx->tctx_list);
1182 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1183 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1186 kfree(ctx->cancel_hash);
1191 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1193 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1194 struct io_ring_ctx *ctx = req->ctx;
1196 return seq != ctx->cached_cq_tail
1197 + READ_ONCE(ctx->cached_cq_overflow);
1203 static void io_req_track_inflight(struct io_kiocb *req)
1205 if (!(req->flags & REQ_F_INFLIGHT)) {
1206 req->flags |= REQ_F_INFLIGHT;
1207 atomic_inc(¤t->io_uring->inflight_tracked);
1211 static void io_prep_async_work(struct io_kiocb *req)
1213 const struct io_op_def *def = &io_op_defs[req->opcode];
1214 struct io_ring_ctx *ctx = req->ctx;
1216 if (!req->work.creds)
1217 req->work.creds = get_current_cred();
1219 req->work.list.next = NULL;
1220 req->work.flags = 0;
1221 if (req->flags & REQ_F_FORCE_ASYNC)
1222 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1224 if (req->flags & REQ_F_ISREG) {
1225 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1226 io_wq_hash_work(&req->work, file_inode(req->file));
1227 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1228 if (def->unbound_nonreg_file)
1229 req->work.flags |= IO_WQ_WORK_UNBOUND;
1232 switch (req->opcode) {
1233 case IORING_OP_SPLICE:
1235 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1236 req->work.flags |= IO_WQ_WORK_UNBOUND;
1241 static void io_prep_async_link(struct io_kiocb *req)
1243 struct io_kiocb *cur;
1245 io_for_each_link(cur, req)
1246 io_prep_async_work(cur);
1249 static void io_queue_async_work(struct io_kiocb *req)
1251 struct io_ring_ctx *ctx = req->ctx;
1252 struct io_kiocb *link = io_prep_linked_timeout(req);
1253 struct io_uring_task *tctx = req->task->io_uring;
1256 BUG_ON(!tctx->io_wq);
1258 /* init ->work of the whole link before punting */
1259 io_prep_async_link(req);
1260 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1261 &req->work, req->flags);
1262 io_wq_enqueue(tctx->io_wq, &req->work);
1264 io_queue_linked_timeout(link);
1267 static void io_kill_timeout(struct io_kiocb *req, int status)
1268 __must_hold(&req->ctx->completion_lock)
1270 struct io_timeout_data *io = req->async_data;
1272 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1273 atomic_set(&req->ctx->cq_timeouts,
1274 atomic_read(&req->ctx->cq_timeouts) + 1);
1275 list_del_init(&req->timeout.list);
1276 io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1277 io_put_req_deferred(req, 1);
1281 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1284 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1285 struct io_defer_entry, list);
1287 if (req_need_defer(de->req, de->seq))
1289 list_del_init(&de->list);
1290 io_req_task_queue(de->req);
1292 } while (!list_empty(&ctx->defer_list));
1295 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1299 if (list_empty(&ctx->timeout_list))
1302 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1305 u32 events_needed, events_got;
1306 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1307 struct io_kiocb, timeout.list);
1309 if (io_is_timeout_noseq(req))
1313 * Since seq can easily wrap around over time, subtract
1314 * the last seq at which timeouts were flushed before comparing.
1315 * Assuming not more than 2^31-1 events have happened since,
1316 * these subtractions won't have wrapped, so we can check if
1317 * target is in [last_seq, current_seq] by comparing the two.
1319 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1320 events_got = seq - ctx->cq_last_tm_flush;
1321 if (events_got < events_needed)
1324 list_del_init(&req->timeout.list);
1325 io_kill_timeout(req, 0);
1326 } while (!list_empty(&ctx->timeout_list));
1328 ctx->cq_last_tm_flush = seq;
1331 static void io_commit_cqring(struct io_ring_ctx *ctx)
1333 io_flush_timeouts(ctx);
1335 /* order cqe stores with ring update */
1336 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1338 if (unlikely(!list_empty(&ctx->defer_list)))
1339 __io_queue_deferred(ctx);
1342 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1344 struct io_rings *r = ctx->rings;
1346 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1349 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1351 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1354 static inline struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1356 struct io_rings *rings = ctx->rings;
1360 * writes to the cq entry need to come after reading head; the
1361 * control dependency is enough as we're using WRITE_ONCE to
1364 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1367 tail = ctx->cached_cq_tail++;
1368 return &rings->cqes[tail & ctx->cq_mask];
1371 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1373 if (likely(!ctx->cq_ev_fd))
1375 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1377 return !ctx->eventfd_async || io_wq_current_is_worker();
1380 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1382 /* see waitqueue_active() comment */
1385 if (waitqueue_active(&ctx->wait))
1386 wake_up(&ctx->wait);
1387 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1388 wake_up(&ctx->sq_data->wait);
1389 if (io_should_trigger_evfd(ctx))
1390 eventfd_signal(ctx->cq_ev_fd, 1);
1391 if (waitqueue_active(&ctx->cq_wait)) {
1392 wake_up_interruptible(&ctx->cq_wait);
1393 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1397 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1399 /* see waitqueue_active() comment */
1402 if (ctx->flags & IORING_SETUP_SQPOLL) {
1403 if (waitqueue_active(&ctx->wait))
1404 wake_up(&ctx->wait);
1406 if (io_should_trigger_evfd(ctx))
1407 eventfd_signal(ctx->cq_ev_fd, 1);
1408 if (waitqueue_active(&ctx->cq_wait)) {
1409 wake_up_interruptible(&ctx->cq_wait);
1410 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1414 /* Returns true if there are no backlogged entries after the flush */
1415 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1417 struct io_rings *rings = ctx->rings;
1418 unsigned long flags;
1419 bool all_flushed, posted;
1421 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1425 spin_lock_irqsave(&ctx->completion_lock, flags);
1426 while (!list_empty(&ctx->cq_overflow_list)) {
1427 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1428 struct io_overflow_cqe *ocqe;
1432 ocqe = list_first_entry(&ctx->cq_overflow_list,
1433 struct io_overflow_cqe, list);
1435 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1437 WRITE_ONCE(ctx->rings->cq_overflow,
1438 ++ctx->cached_cq_overflow);
1440 list_del(&ocqe->list);
1444 all_flushed = list_empty(&ctx->cq_overflow_list);
1446 clear_bit(0, &ctx->sq_check_overflow);
1447 clear_bit(0, &ctx->cq_check_overflow);
1448 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1452 io_commit_cqring(ctx);
1453 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1455 io_cqring_ev_posted(ctx);
1459 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1463 if (test_bit(0, &ctx->cq_check_overflow)) {
1464 /* iopoll syncs against uring_lock, not completion_lock */
1465 if (ctx->flags & IORING_SETUP_IOPOLL)
1466 mutex_lock(&ctx->uring_lock);
1467 ret = __io_cqring_overflow_flush(ctx, force);
1468 if (ctx->flags & IORING_SETUP_IOPOLL)
1469 mutex_unlock(&ctx->uring_lock);
1476 * Shamelessly stolen from the mm implementation of page reference checking,
1477 * see commit f958d7b528b1 for details.
1479 #define req_ref_zero_or_close_to_overflow(req) \
1480 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1482 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1484 return atomic_inc_not_zero(&req->refs);
1487 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1489 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1490 return atomic_sub_and_test(refs, &req->refs);
1493 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1495 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1496 return atomic_dec_and_test(&req->refs);
1499 static inline void req_ref_put(struct io_kiocb *req)
1501 WARN_ON_ONCE(req_ref_put_and_test(req));
1504 static inline void req_ref_get(struct io_kiocb *req)
1506 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1507 atomic_inc(&req->refs);
1510 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1511 long res, unsigned int cflags)
1513 struct io_overflow_cqe *ocqe;
1515 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1518 * If we're in ring overflow flush mode, or in task cancel mode,
1519 * or cannot allocate an overflow entry, then we need to drop it
1522 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1525 if (list_empty(&ctx->cq_overflow_list)) {
1526 set_bit(0, &ctx->sq_check_overflow);
1527 set_bit(0, &ctx->cq_check_overflow);
1528 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1530 ocqe->cqe.user_data = user_data;
1531 ocqe->cqe.res = res;
1532 ocqe->cqe.flags = cflags;
1533 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1537 static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1538 long res, unsigned int cflags)
1540 struct io_uring_cqe *cqe;
1542 trace_io_uring_complete(ctx, user_data, res, cflags);
1545 * If we can't get a cq entry, userspace overflowed the
1546 * submission (by quite a lot). Increment the overflow count in
1549 cqe = io_get_cqring(ctx);
1551 WRITE_ONCE(cqe->user_data, user_data);
1552 WRITE_ONCE(cqe->res, res);
1553 WRITE_ONCE(cqe->flags, cflags);
1556 return io_cqring_event_overflow(ctx, user_data, res, cflags);
1559 /* not as hot to bloat with inlining */
1560 static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1561 long res, unsigned int cflags)
1563 return __io_cqring_fill_event(ctx, user_data, res, cflags);
1566 static void io_req_complete_post(struct io_kiocb *req, long res,
1567 unsigned int cflags)
1569 struct io_ring_ctx *ctx = req->ctx;
1570 unsigned long flags;
1572 spin_lock_irqsave(&ctx->completion_lock, flags);
1573 __io_cqring_fill_event(ctx, req->user_data, res, cflags);
1575 * If we're the last reference to this request, add to our locked
1578 if (req_ref_put_and_test(req)) {
1579 struct io_comp_state *cs = &ctx->submit_state.comp;
1581 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1582 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1583 io_disarm_next(req);
1585 io_req_task_queue(req->link);
1589 io_dismantle_req(req);
1590 io_put_task(req->task, 1);
1591 list_add(&req->compl.list, &cs->locked_free_list);
1592 cs->locked_free_nr++;
1594 if (!percpu_ref_tryget(&ctx->refs))
1597 io_commit_cqring(ctx);
1598 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1601 io_cqring_ev_posted(ctx);
1602 percpu_ref_put(&ctx->refs);
1606 static inline bool io_req_needs_clean(struct io_kiocb *req)
1608 return req->flags & (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP |
1609 REQ_F_POLLED | REQ_F_INFLIGHT);
1612 static void io_req_complete_state(struct io_kiocb *req, long res,
1613 unsigned int cflags)
1615 if (io_req_needs_clean(req))
1618 req->compl.cflags = cflags;
1619 req->flags |= REQ_F_COMPLETE_INLINE;
1622 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1623 long res, unsigned cflags)
1625 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1626 io_req_complete_state(req, res, cflags);
1628 io_req_complete_post(req, res, cflags);
1631 static inline void io_req_complete(struct io_kiocb *req, long res)
1633 __io_req_complete(req, 0, res, 0);
1636 static void io_req_complete_failed(struct io_kiocb *req, long res)
1638 req_set_fail_links(req);
1640 io_req_complete_post(req, res, 0);
1643 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1644 struct io_comp_state *cs)
1646 spin_lock_irq(&ctx->completion_lock);
1647 list_splice_init(&cs->locked_free_list, &cs->free_list);
1648 cs->locked_free_nr = 0;
1649 spin_unlock_irq(&ctx->completion_lock);
1652 /* Returns true IFF there are requests in the cache */
1653 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1655 struct io_submit_state *state = &ctx->submit_state;
1656 struct io_comp_state *cs = &state->comp;
1660 * If we have more than a batch's worth of requests in our IRQ side
1661 * locked cache, grab the lock and move them over to our submission
1664 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
1665 io_flush_cached_locked_reqs(ctx, cs);
1667 nr = state->free_reqs;
1668 while (!list_empty(&cs->free_list)) {
1669 struct io_kiocb *req = list_first_entry(&cs->free_list,
1670 struct io_kiocb, compl.list);
1672 list_del(&req->compl.list);
1673 state->reqs[nr++] = req;
1674 if (nr == ARRAY_SIZE(state->reqs))
1678 state->free_reqs = nr;
1682 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1684 struct io_submit_state *state = &ctx->submit_state;
1686 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1688 if (!state->free_reqs) {
1689 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1692 if (io_flush_cached_reqs(ctx))
1695 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1699 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1700 * retry single alloc to be on the safe side.
1702 if (unlikely(ret <= 0)) {
1703 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1704 if (!state->reqs[0])
1708 state->free_reqs = ret;
1712 return state->reqs[state->free_reqs];
1715 static inline void io_put_file(struct file *file)
1721 static void io_dismantle_req(struct io_kiocb *req)
1723 unsigned int flags = req->flags;
1725 if (io_req_needs_clean(req))
1727 if (!(flags & REQ_F_FIXED_FILE))
1728 io_put_file(req->file);
1729 if (req->fixed_rsrc_refs)
1730 percpu_ref_put(req->fixed_rsrc_refs);
1731 if (req->async_data)
1732 kfree(req->async_data);
1733 if (req->work.creds) {
1734 put_cred(req->work.creds);
1735 req->work.creds = NULL;
1739 /* must to be called somewhat shortly after putting a request */
1740 static inline void io_put_task(struct task_struct *task, int nr)
1742 struct io_uring_task *tctx = task->io_uring;
1744 percpu_counter_sub(&tctx->inflight, nr);
1745 if (unlikely(atomic_read(&tctx->in_idle)))
1746 wake_up(&tctx->wait);
1747 put_task_struct_many(task, nr);
1750 static void __io_free_req(struct io_kiocb *req)
1752 struct io_ring_ctx *ctx = req->ctx;
1754 io_dismantle_req(req);
1755 io_put_task(req->task, 1);
1757 kmem_cache_free(req_cachep, req);
1758 percpu_ref_put(&ctx->refs);
1761 static inline void io_remove_next_linked(struct io_kiocb *req)
1763 struct io_kiocb *nxt = req->link;
1765 req->link = nxt->link;
1769 static bool io_kill_linked_timeout(struct io_kiocb *req)
1770 __must_hold(&req->ctx->completion_lock)
1772 struct io_kiocb *link = req->link;
1775 * Can happen if a linked timeout fired and link had been like
1776 * req -> link t-out -> link t-out [-> ...]
1778 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1779 struct io_timeout_data *io = link->async_data;
1781 io_remove_next_linked(req);
1782 link->timeout.head = NULL;
1783 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1784 io_cqring_fill_event(link->ctx, link->user_data,
1786 io_put_req_deferred(link, 1);
1793 static void io_fail_links(struct io_kiocb *req)
1794 __must_hold(&req->ctx->completion_lock)
1796 struct io_kiocb *nxt, *link = req->link;
1803 trace_io_uring_fail_link(req, link);
1804 io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1805 io_put_req_deferred(link, 2);
1810 static bool io_disarm_next(struct io_kiocb *req)
1811 __must_hold(&req->ctx->completion_lock)
1813 bool posted = false;
1815 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1816 posted = io_kill_linked_timeout(req);
1817 if (unlikely((req->flags & REQ_F_FAIL_LINK) &&
1818 !(req->flags & REQ_F_HARDLINK))) {
1819 posted |= (req->link != NULL);
1825 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1827 struct io_kiocb *nxt;
1830 * If LINK is set, we have dependent requests in this chain. If we
1831 * didn't fail this request, queue the first one up, moving any other
1832 * dependencies to the next request. In case of failure, fail the rest
1835 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1836 struct io_ring_ctx *ctx = req->ctx;
1837 unsigned long flags;
1840 spin_lock_irqsave(&ctx->completion_lock, flags);
1841 posted = io_disarm_next(req);
1843 io_commit_cqring(req->ctx);
1844 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1846 io_cqring_ev_posted(ctx);
1853 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1855 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1857 return __io_req_find_next(req);
1860 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1864 if (ctx->submit_state.comp.nr) {
1865 mutex_lock(&ctx->uring_lock);
1866 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1867 mutex_unlock(&ctx->uring_lock);
1869 percpu_ref_put(&ctx->refs);
1872 static bool __tctx_task_work(struct io_uring_task *tctx)
1874 struct io_ring_ctx *ctx = NULL;
1875 struct io_wq_work_list list;
1876 struct io_wq_work_node *node;
1878 if (wq_list_empty(&tctx->task_list))
1881 spin_lock_irq(&tctx->task_lock);
1882 list = tctx->task_list;
1883 INIT_WQ_LIST(&tctx->task_list);
1884 spin_unlock_irq(&tctx->task_lock);
1888 struct io_wq_work_node *next = node->next;
1889 struct io_kiocb *req;
1891 req = container_of(node, struct io_kiocb, io_task_work.node);
1892 if (req->ctx != ctx) {
1893 ctx_flush_and_put(ctx);
1895 percpu_ref_get(&ctx->refs);
1898 req->task_work.func(&req->task_work);
1902 ctx_flush_and_put(ctx);
1903 return list.first != NULL;
1906 static void tctx_task_work(struct callback_head *cb)
1908 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1910 clear_bit(0, &tctx->task_state);
1912 while (__tctx_task_work(tctx))
1916 static int io_req_task_work_add(struct io_kiocb *req)
1918 struct task_struct *tsk = req->task;
1919 struct io_uring_task *tctx = tsk->io_uring;
1920 enum task_work_notify_mode notify;
1921 struct io_wq_work_node *node, *prev;
1922 unsigned long flags;
1925 if (unlikely(tsk->flags & PF_EXITING))
1928 WARN_ON_ONCE(!tctx);
1930 spin_lock_irqsave(&tctx->task_lock, flags);
1931 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1932 spin_unlock_irqrestore(&tctx->task_lock, flags);
1934 /* task_work already pending, we're done */
1935 if (test_bit(0, &tctx->task_state) ||
1936 test_and_set_bit(0, &tctx->task_state))
1940 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1941 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1942 * processing task_work. There's no reliable way to tell if TWA_RESUME
1945 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1947 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1948 wake_up_process(tsk);
1953 * Slow path - we failed, find and delete work. if the work is not
1954 * in the list, it got run and we're fine.
1956 spin_lock_irqsave(&tctx->task_lock, flags);
1957 wq_list_for_each(node, prev, &tctx->task_list) {
1958 if (&req->io_task_work.node == node) {
1959 wq_list_del(&tctx->task_list, node, prev);
1964 spin_unlock_irqrestore(&tctx->task_lock, flags);
1965 clear_bit(0, &tctx->task_state);
1969 static bool io_run_task_work_head(struct callback_head **work_head)
1971 struct callback_head *work, *next;
1972 bool executed = false;
1975 work = xchg(work_head, NULL);
1991 static void io_task_work_add_head(struct callback_head **work_head,
1992 struct callback_head *task_work)
1994 struct callback_head *head;
1997 head = READ_ONCE(*work_head);
1998 task_work->next = head;
1999 } while (cmpxchg(work_head, head, task_work) != head);
2002 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2003 task_work_func_t cb)
2005 init_task_work(&req->task_work, cb);
2006 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2009 static void io_req_task_cancel(struct callback_head *cb)
2011 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2012 struct io_ring_ctx *ctx = req->ctx;
2014 /* ctx is guaranteed to stay alive while we hold uring_lock */
2015 mutex_lock(&ctx->uring_lock);
2016 io_req_complete_failed(req, req->result);
2017 mutex_unlock(&ctx->uring_lock);
2020 static void __io_req_task_submit(struct io_kiocb *req)
2022 struct io_ring_ctx *ctx = req->ctx;
2024 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2025 mutex_lock(&ctx->uring_lock);
2026 if (!(current->flags & PF_EXITING) && !current->in_execve)
2027 __io_queue_sqe(req);
2029 io_req_complete_failed(req, -EFAULT);
2030 mutex_unlock(&ctx->uring_lock);
2033 static void io_req_task_submit(struct callback_head *cb)
2035 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2037 __io_req_task_submit(req);
2040 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2043 req->task_work.func = io_req_task_cancel;
2045 if (unlikely(io_req_task_work_add(req)))
2046 io_req_task_work_add_fallback(req, io_req_task_cancel);
2049 static void io_req_task_queue(struct io_kiocb *req)
2051 req->task_work.func = io_req_task_submit;
2053 if (unlikely(io_req_task_work_add(req)))
2054 io_req_task_queue_fail(req, -ECANCELED);
2057 static inline void io_queue_next(struct io_kiocb *req)
2059 struct io_kiocb *nxt = io_req_find_next(req);
2062 io_req_task_queue(nxt);
2065 static void io_free_req(struct io_kiocb *req)
2072 struct task_struct *task;
2077 static inline void io_init_req_batch(struct req_batch *rb)
2084 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2085 struct req_batch *rb)
2088 io_put_task(rb->task, rb->task_refs);
2090 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2093 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2094 struct io_submit_state *state)
2097 io_dismantle_req(req);
2099 if (req->task != rb->task) {
2101 io_put_task(rb->task, rb->task_refs);
2102 rb->task = req->task;
2108 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2109 state->reqs[state->free_reqs++] = req;
2111 list_add(&req->compl.list, &state->comp.free_list);
2114 static void io_submit_flush_completions(struct io_comp_state *cs,
2115 struct io_ring_ctx *ctx)
2118 struct io_kiocb *req;
2119 struct req_batch rb;
2121 io_init_req_batch(&rb);
2122 spin_lock_irq(&ctx->completion_lock);
2123 for (i = 0; i < nr; i++) {
2125 __io_cqring_fill_event(ctx, req->user_data, req->result,
2128 io_commit_cqring(ctx);
2129 spin_unlock_irq(&ctx->completion_lock);
2131 io_cqring_ev_posted(ctx);
2132 for (i = 0; i < nr; i++) {
2135 /* submission and completion refs */
2136 if (req_ref_sub_and_test(req, 2))
2137 io_req_free_batch(&rb, req, &ctx->submit_state);
2140 io_req_free_batch_finish(ctx, &rb);
2145 * Drop reference to request, return next in chain (if there is one) if this
2146 * was the last reference to this request.
2148 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2150 struct io_kiocb *nxt = NULL;
2152 if (req_ref_put_and_test(req)) {
2153 nxt = io_req_find_next(req);
2159 static inline void io_put_req(struct io_kiocb *req)
2161 if (req_ref_put_and_test(req))
2165 static void io_put_req_deferred_cb(struct callback_head *cb)
2167 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2172 static void io_free_req_deferred(struct io_kiocb *req)
2174 req->task_work.func = io_put_req_deferred_cb;
2175 if (unlikely(io_req_task_work_add(req)))
2176 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2179 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2181 if (req_ref_sub_and_test(req, refs))
2182 io_free_req_deferred(req);
2185 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2187 /* See comment at the top of this file */
2189 return __io_cqring_events(ctx);
2192 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2194 struct io_rings *rings = ctx->rings;
2196 /* make sure SQ entry isn't read before tail */
2197 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2200 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2202 unsigned int cflags;
2204 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2205 cflags |= IORING_CQE_F_BUFFER;
2206 req->flags &= ~REQ_F_BUFFER_SELECTED;
2211 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2213 struct io_buffer *kbuf;
2215 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2216 return io_put_kbuf(req, kbuf);
2219 static inline bool io_run_task_work(void)
2222 * Not safe to run on exiting task, and the task_work handling will
2223 * not add work to such a task.
2225 if (unlikely(current->flags & PF_EXITING))
2227 if (current->task_works) {
2228 __set_current_state(TASK_RUNNING);
2237 * Find and free completed poll iocbs
2239 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2240 struct list_head *done)
2242 struct req_batch rb;
2243 struct io_kiocb *req;
2245 /* order with ->result store in io_complete_rw_iopoll() */
2248 io_init_req_batch(&rb);
2249 while (!list_empty(done)) {
2252 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2253 list_del(&req->inflight_entry);
2255 if (READ_ONCE(req->result) == -EAGAIN &&
2256 !(req->flags & REQ_F_DONT_REISSUE)) {
2257 req->iopoll_completed = 0;
2259 io_queue_async_work(req);
2263 if (req->flags & REQ_F_BUFFER_SELECTED)
2264 cflags = io_put_rw_kbuf(req);
2266 __io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2269 if (req_ref_put_and_test(req))
2270 io_req_free_batch(&rb, req, &ctx->submit_state);
2273 io_commit_cqring(ctx);
2274 io_cqring_ev_posted_iopoll(ctx);
2275 io_req_free_batch_finish(ctx, &rb);
2278 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2281 struct io_kiocb *req, *tmp;
2287 * Only spin for completions if we don't have multiple devices hanging
2288 * off our complete list, and we're under the requested amount.
2290 spin = !ctx->poll_multi_file && *nr_events < min;
2293 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2294 struct kiocb *kiocb = &req->rw.kiocb;
2297 * Move completed and retryable entries to our local lists.
2298 * If we find a request that requires polling, break out
2299 * and complete those lists first, if we have entries there.
2301 if (READ_ONCE(req->iopoll_completed)) {
2302 list_move_tail(&req->inflight_entry, &done);
2305 if (!list_empty(&done))
2308 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2312 /* iopoll may have completed current req */
2313 if (READ_ONCE(req->iopoll_completed))
2314 list_move_tail(&req->inflight_entry, &done);
2321 if (!list_empty(&done))
2322 io_iopoll_complete(ctx, nr_events, &done);
2328 * We can't just wait for polled events to come to us, we have to actively
2329 * find and complete them.
2331 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2333 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2336 mutex_lock(&ctx->uring_lock);
2337 while (!list_empty(&ctx->iopoll_list)) {
2338 unsigned int nr_events = 0;
2340 io_do_iopoll(ctx, &nr_events, 0);
2342 /* let it sleep and repeat later if can't complete a request */
2346 * Ensure we allow local-to-the-cpu processing to take place,
2347 * in this case we need to ensure that we reap all events.
2348 * Also let task_work, etc. to progress by releasing the mutex
2350 if (need_resched()) {
2351 mutex_unlock(&ctx->uring_lock);
2353 mutex_lock(&ctx->uring_lock);
2356 mutex_unlock(&ctx->uring_lock);
2359 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2361 unsigned int nr_events = 0;
2365 * We disallow the app entering submit/complete with polling, but we
2366 * still need to lock the ring to prevent racing with polled issue
2367 * that got punted to a workqueue.
2369 mutex_lock(&ctx->uring_lock);
2371 * Don't enter poll loop if we already have events pending.
2372 * If we do, we can potentially be spinning for commands that
2373 * already triggered a CQE (eg in error).
2375 if (test_bit(0, &ctx->cq_check_overflow))
2376 __io_cqring_overflow_flush(ctx, false);
2377 if (io_cqring_events(ctx))
2381 * If a submit got punted to a workqueue, we can have the
2382 * application entering polling for a command before it gets
2383 * issued. That app will hold the uring_lock for the duration
2384 * of the poll right here, so we need to take a breather every
2385 * now and then to ensure that the issue has a chance to add
2386 * the poll to the issued list. Otherwise we can spin here
2387 * forever, while the workqueue is stuck trying to acquire the
2390 if (list_empty(&ctx->iopoll_list)) {
2391 mutex_unlock(&ctx->uring_lock);
2393 mutex_lock(&ctx->uring_lock);
2395 if (list_empty(&ctx->iopoll_list))
2398 ret = io_do_iopoll(ctx, &nr_events, min);
2399 } while (!ret && nr_events < min && !need_resched());
2401 mutex_unlock(&ctx->uring_lock);
2405 static void kiocb_end_write(struct io_kiocb *req)
2408 * Tell lockdep we inherited freeze protection from submission
2411 if (req->flags & REQ_F_ISREG) {
2412 struct super_block *sb = file_inode(req->file)->i_sb;
2414 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2420 static bool io_resubmit_prep(struct io_kiocb *req)
2422 struct io_async_rw *rw = req->async_data;
2425 return !io_req_prep_async(req);
2426 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2427 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2431 static bool io_rw_should_reissue(struct io_kiocb *req)
2433 umode_t mode = file_inode(req->file)->i_mode;
2434 struct io_ring_ctx *ctx = req->ctx;
2436 if (!S_ISBLK(mode) && !S_ISREG(mode))
2438 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2439 !(ctx->flags & IORING_SETUP_IOPOLL)))
2442 * If ref is dying, we might be running poll reap from the exit work.
2443 * Don't attempt to reissue from that path, just let it fail with
2446 if (percpu_ref_is_dying(&ctx->refs))
2451 static bool io_resubmit_prep(struct io_kiocb *req)
2455 static bool io_rw_should_reissue(struct io_kiocb *req)
2461 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2462 unsigned int issue_flags)
2466 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2467 kiocb_end_write(req);
2468 if (res != req->result) {
2469 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2470 io_rw_should_reissue(req)) {
2471 req->flags |= REQ_F_REISSUE;
2474 req_set_fail_links(req);
2476 if (req->flags & REQ_F_BUFFER_SELECTED)
2477 cflags = io_put_rw_kbuf(req);
2478 __io_req_complete(req, issue_flags, res, cflags);
2481 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2483 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2485 __io_complete_rw(req, res, res2, 0);
2488 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2490 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2492 if (kiocb->ki_flags & IOCB_WRITE)
2493 kiocb_end_write(req);
2494 if (unlikely(res != req->result)) {
2495 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2496 io_resubmit_prep(req))) {
2497 req_set_fail_links(req);
2498 req->flags |= REQ_F_DONT_REISSUE;
2502 WRITE_ONCE(req->result, res);
2503 /* order with io_iopoll_complete() checking ->result */
2505 WRITE_ONCE(req->iopoll_completed, 1);
2509 * After the iocb has been issued, it's safe to be found on the poll list.
2510 * Adding the kiocb to the list AFTER submission ensures that we don't
2511 * find it from a io_do_iopoll() thread before the issuer is done
2512 * accessing the kiocb cookie.
2514 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2516 struct io_ring_ctx *ctx = req->ctx;
2519 * Track whether we have multiple files in our lists. This will impact
2520 * how we do polling eventually, not spinning if we're on potentially
2521 * different devices.
2523 if (list_empty(&ctx->iopoll_list)) {
2524 ctx->poll_multi_file = false;
2525 } else if (!ctx->poll_multi_file) {
2526 struct io_kiocb *list_req;
2528 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2530 if (list_req->file != req->file)
2531 ctx->poll_multi_file = true;
2535 * For fast devices, IO may have already completed. If it has, add
2536 * it to the front so we find it first.
2538 if (READ_ONCE(req->iopoll_completed))
2539 list_add(&req->inflight_entry, &ctx->iopoll_list);
2541 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2544 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2545 * task context or in io worker task context. If current task context is
2546 * sq thread, we don't need to check whether should wake up sq thread.
2548 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2549 wq_has_sleeper(&ctx->sq_data->wait))
2550 wake_up(&ctx->sq_data->wait);
2553 static inline void io_state_file_put(struct io_submit_state *state)
2555 if (state->file_refs) {
2556 fput_many(state->file, state->file_refs);
2557 state->file_refs = 0;
2562 * Get as many references to a file as we have IOs left in this submission,
2563 * assuming most submissions are for one file, or at least that each file
2564 * has more than one submission.
2566 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2571 if (state->file_refs) {
2572 if (state->fd == fd) {
2576 io_state_file_put(state);
2578 state->file = fget_many(fd, state->ios_left);
2579 if (unlikely(!state->file))
2583 state->file_refs = state->ios_left - 1;
2587 static bool io_bdev_nowait(struct block_device *bdev)
2589 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2593 * If we tracked the file through the SCM inflight mechanism, we could support
2594 * any file. For now, just ensure that anything potentially problematic is done
2597 static bool __io_file_supports_async(struct file *file, int rw)
2599 umode_t mode = file_inode(file)->i_mode;
2601 if (S_ISBLK(mode)) {
2602 if (IS_ENABLED(CONFIG_BLOCK) &&
2603 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2607 if (S_ISCHR(mode) || S_ISSOCK(mode))
2609 if (S_ISREG(mode)) {
2610 if (IS_ENABLED(CONFIG_BLOCK) &&
2611 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2612 file->f_op != &io_uring_fops)
2617 /* any ->read/write should understand O_NONBLOCK */
2618 if (file->f_flags & O_NONBLOCK)
2621 if (!(file->f_mode & FMODE_NOWAIT))
2625 return file->f_op->read_iter != NULL;
2627 return file->f_op->write_iter != NULL;
2630 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2632 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2634 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2637 return __io_file_supports_async(req->file, rw);
2640 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2642 struct io_ring_ctx *ctx = req->ctx;
2643 struct kiocb *kiocb = &req->rw.kiocb;
2644 struct file *file = req->file;
2648 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2649 req->flags |= REQ_F_ISREG;
2651 kiocb->ki_pos = READ_ONCE(sqe->off);
2652 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2653 req->flags |= REQ_F_CUR_POS;
2654 kiocb->ki_pos = file->f_pos;
2656 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2657 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2658 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2662 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2663 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2664 req->flags |= REQ_F_NOWAIT;
2666 ioprio = READ_ONCE(sqe->ioprio);
2668 ret = ioprio_check_cap(ioprio);
2672 kiocb->ki_ioprio = ioprio;
2674 kiocb->ki_ioprio = get_current_ioprio();
2676 if (ctx->flags & IORING_SETUP_IOPOLL) {
2677 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2678 !kiocb->ki_filp->f_op->iopoll)
2681 kiocb->ki_flags |= IOCB_HIPRI;
2682 kiocb->ki_complete = io_complete_rw_iopoll;
2683 req->iopoll_completed = 0;
2685 if (kiocb->ki_flags & IOCB_HIPRI)
2687 kiocb->ki_complete = io_complete_rw;
2690 if (req->opcode == IORING_OP_READ_FIXED ||
2691 req->opcode == IORING_OP_WRITE_FIXED) {
2693 io_req_set_rsrc_node(req);
2696 req->rw.addr = READ_ONCE(sqe->addr);
2697 req->rw.len = READ_ONCE(sqe->len);
2698 req->buf_index = READ_ONCE(sqe->buf_index);
2702 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2708 case -ERESTARTNOINTR:
2709 case -ERESTARTNOHAND:
2710 case -ERESTART_RESTARTBLOCK:
2712 * We can't just restart the syscall, since previously
2713 * submitted sqes may already be in progress. Just fail this
2719 kiocb->ki_complete(kiocb, ret, 0);
2723 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2724 unsigned int issue_flags)
2726 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2727 struct io_async_rw *io = req->async_data;
2728 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2730 /* add previously done IO, if any */
2731 if (io && io->bytes_done > 0) {
2733 ret = io->bytes_done;
2735 ret += io->bytes_done;
2738 if (req->flags & REQ_F_CUR_POS)
2739 req->file->f_pos = kiocb->ki_pos;
2740 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2741 __io_complete_rw(req, ret, 0, issue_flags);
2743 io_rw_done(kiocb, ret);
2745 if (check_reissue && req->flags & REQ_F_REISSUE) {
2746 req->flags &= ~REQ_F_REISSUE;
2747 if (io_resubmit_prep(req)) {
2749 io_queue_async_work(req);
2753 req_set_fail_links(req);
2754 if (req->flags & REQ_F_BUFFER_SELECTED)
2755 cflags = io_put_rw_kbuf(req);
2756 __io_req_complete(req, issue_flags, ret, cflags);
2761 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2762 struct io_mapped_ubuf *imu)
2764 size_t len = req->rw.len;
2765 u64 buf_end, buf_addr = req->rw.addr;
2768 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2770 /* not inside the mapped region */
2771 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2775 * May not be a start of buffer, set size appropriately
2776 * and advance us to the beginning.
2778 offset = buf_addr - imu->ubuf;
2779 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2783 * Don't use iov_iter_advance() here, as it's really slow for
2784 * using the latter parts of a big fixed buffer - it iterates
2785 * over each segment manually. We can cheat a bit here, because
2788 * 1) it's a BVEC iter, we set it up
2789 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2790 * first and last bvec
2792 * So just find our index, and adjust the iterator afterwards.
2793 * If the offset is within the first bvec (or the whole first
2794 * bvec, just use iov_iter_advance(). This makes it easier
2795 * since we can just skip the first segment, which may not
2796 * be PAGE_SIZE aligned.
2798 const struct bio_vec *bvec = imu->bvec;
2800 if (offset <= bvec->bv_len) {
2801 iov_iter_advance(iter, offset);
2803 unsigned long seg_skip;
2805 /* skip first vec */
2806 offset -= bvec->bv_len;
2807 seg_skip = 1 + (offset >> PAGE_SHIFT);
2809 iter->bvec = bvec + seg_skip;
2810 iter->nr_segs -= seg_skip;
2811 iter->count -= bvec->bv_len + offset;
2812 iter->iov_offset = offset & ~PAGE_MASK;
2819 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2821 struct io_ring_ctx *ctx = req->ctx;
2822 struct io_mapped_ubuf *imu = req->imu;
2823 u16 index, buf_index = req->buf_index;
2826 if (unlikely(buf_index >= ctx->nr_user_bufs))
2828 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2829 imu = READ_ONCE(ctx->user_bufs[index]);
2832 return __io_import_fixed(req, rw, iter, imu);
2835 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2838 mutex_unlock(&ctx->uring_lock);
2841 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2844 * "Normal" inline submissions always hold the uring_lock, since we
2845 * grab it from the system call. Same is true for the SQPOLL offload.
2846 * The only exception is when we've detached the request and issue it
2847 * from an async worker thread, grab the lock for that case.
2850 mutex_lock(&ctx->uring_lock);
2853 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2854 int bgid, struct io_buffer *kbuf,
2857 struct io_buffer *head;
2859 if (req->flags & REQ_F_BUFFER_SELECTED)
2862 io_ring_submit_lock(req->ctx, needs_lock);
2864 lockdep_assert_held(&req->ctx->uring_lock);
2866 head = xa_load(&req->ctx->io_buffers, bgid);
2868 if (!list_empty(&head->list)) {
2869 kbuf = list_last_entry(&head->list, struct io_buffer,
2871 list_del(&kbuf->list);
2874 xa_erase(&req->ctx->io_buffers, bgid);
2876 if (*len > kbuf->len)
2879 kbuf = ERR_PTR(-ENOBUFS);
2882 io_ring_submit_unlock(req->ctx, needs_lock);
2887 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2890 struct io_buffer *kbuf;
2893 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2894 bgid = req->buf_index;
2895 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2898 req->rw.addr = (u64) (unsigned long) kbuf;
2899 req->flags |= REQ_F_BUFFER_SELECTED;
2900 return u64_to_user_ptr(kbuf->addr);
2903 #ifdef CONFIG_COMPAT
2904 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2907 struct compat_iovec __user *uiov;
2908 compat_ssize_t clen;
2912 uiov = u64_to_user_ptr(req->rw.addr);
2913 if (!access_ok(uiov, sizeof(*uiov)))
2915 if (__get_user(clen, &uiov->iov_len))
2921 buf = io_rw_buffer_select(req, &len, needs_lock);
2923 return PTR_ERR(buf);
2924 iov[0].iov_base = buf;
2925 iov[0].iov_len = (compat_size_t) len;
2930 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2933 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2937 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2940 len = iov[0].iov_len;
2943 buf = io_rw_buffer_select(req, &len, needs_lock);
2945 return PTR_ERR(buf);
2946 iov[0].iov_base = buf;
2947 iov[0].iov_len = len;
2951 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2954 if (req->flags & REQ_F_BUFFER_SELECTED) {
2955 struct io_buffer *kbuf;
2957 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2958 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2959 iov[0].iov_len = kbuf->len;
2962 if (req->rw.len != 1)
2965 #ifdef CONFIG_COMPAT
2966 if (req->ctx->compat)
2967 return io_compat_import(req, iov, needs_lock);
2970 return __io_iov_buffer_select(req, iov, needs_lock);
2973 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2974 struct iov_iter *iter, bool needs_lock)
2976 void __user *buf = u64_to_user_ptr(req->rw.addr);
2977 size_t sqe_len = req->rw.len;
2978 u8 opcode = req->opcode;
2981 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2983 return io_import_fixed(req, rw, iter);
2986 /* buffer index only valid with fixed read/write, or buffer select */
2987 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2990 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2991 if (req->flags & REQ_F_BUFFER_SELECT) {
2992 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2994 return PTR_ERR(buf);
2995 req->rw.len = sqe_len;
2998 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3003 if (req->flags & REQ_F_BUFFER_SELECT) {
3004 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3006 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3011 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3015 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3017 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3021 * For files that don't have ->read_iter() and ->write_iter(), handle them
3022 * by looping over ->read() or ->write() manually.
3024 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3026 struct kiocb *kiocb = &req->rw.kiocb;
3027 struct file *file = req->file;
3031 * Don't support polled IO through this interface, and we can't
3032 * support non-blocking either. For the latter, this just causes
3033 * the kiocb to be handled from an async context.
3035 if (kiocb->ki_flags & IOCB_HIPRI)
3037 if (kiocb->ki_flags & IOCB_NOWAIT)
3040 while (iov_iter_count(iter)) {
3044 if (!iov_iter_is_bvec(iter)) {
3045 iovec = iov_iter_iovec(iter);
3047 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3048 iovec.iov_len = req->rw.len;
3052 nr = file->f_op->read(file, iovec.iov_base,
3053 iovec.iov_len, io_kiocb_ppos(kiocb));
3055 nr = file->f_op->write(file, iovec.iov_base,
3056 iovec.iov_len, io_kiocb_ppos(kiocb));
3065 if (nr != iovec.iov_len)
3069 iov_iter_advance(iter, nr);
3075 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3076 const struct iovec *fast_iov, struct iov_iter *iter)
3078 struct io_async_rw *rw = req->async_data;
3080 memcpy(&rw->iter, iter, sizeof(*iter));
3081 rw->free_iovec = iovec;
3083 /* can only be fixed buffers, no need to do anything */
3084 if (iov_iter_is_bvec(iter))
3087 unsigned iov_off = 0;
3089 rw->iter.iov = rw->fast_iov;
3090 if (iter->iov != fast_iov) {
3091 iov_off = iter->iov - fast_iov;
3092 rw->iter.iov += iov_off;
3094 if (rw->fast_iov != fast_iov)
3095 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3096 sizeof(struct iovec) * iter->nr_segs);
3098 req->flags |= REQ_F_NEED_CLEANUP;
3102 static inline int io_alloc_async_data(struct io_kiocb *req)
3104 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3105 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3106 return req->async_data == NULL;
3109 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3110 const struct iovec *fast_iov,
3111 struct iov_iter *iter, bool force)
3113 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3115 if (!req->async_data) {
3116 if (io_alloc_async_data(req)) {
3121 io_req_map_rw(req, iovec, fast_iov, iter);
3126 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3128 struct io_async_rw *iorw = req->async_data;
3129 struct iovec *iov = iorw->fast_iov;
3132 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3133 if (unlikely(ret < 0))
3136 iorw->bytes_done = 0;
3137 iorw->free_iovec = iov;
3139 req->flags |= REQ_F_NEED_CLEANUP;
3143 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3145 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3147 return io_prep_rw(req, sqe);
3151 * This is our waitqueue callback handler, registered through lock_page_async()
3152 * when we initially tried to do the IO with the iocb armed our waitqueue.
3153 * This gets called when the page is unlocked, and we generally expect that to
3154 * happen when the page IO is completed and the page is now uptodate. This will
3155 * queue a task_work based retry of the operation, attempting to copy the data
3156 * again. If the latter fails because the page was NOT uptodate, then we will
3157 * do a thread based blocking retry of the operation. That's the unexpected
3160 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3161 int sync, void *arg)
3163 struct wait_page_queue *wpq;
3164 struct io_kiocb *req = wait->private;
3165 struct wait_page_key *key = arg;
3167 wpq = container_of(wait, struct wait_page_queue, wait);
3169 if (!wake_page_match(wpq, key))
3172 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3173 list_del_init(&wait->entry);
3175 /* submit ref gets dropped, acquire a new one */
3177 io_req_task_queue(req);
3182 * This controls whether a given IO request should be armed for async page
3183 * based retry. If we return false here, the request is handed to the async
3184 * worker threads for retry. If we're doing buffered reads on a regular file,
3185 * we prepare a private wait_page_queue entry and retry the operation. This
3186 * will either succeed because the page is now uptodate and unlocked, or it
3187 * will register a callback when the page is unlocked at IO completion. Through
3188 * that callback, io_uring uses task_work to setup a retry of the operation.
3189 * That retry will attempt the buffered read again. The retry will generally
3190 * succeed, or in rare cases where it fails, we then fall back to using the
3191 * async worker threads for a blocking retry.
3193 static bool io_rw_should_retry(struct io_kiocb *req)
3195 struct io_async_rw *rw = req->async_data;
3196 struct wait_page_queue *wait = &rw->wpq;
3197 struct kiocb *kiocb = &req->rw.kiocb;
3199 /* never retry for NOWAIT, we just complete with -EAGAIN */
3200 if (req->flags & REQ_F_NOWAIT)
3203 /* Only for buffered IO */
3204 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3208 * just use poll if we can, and don't attempt if the fs doesn't
3209 * support callback based unlocks
3211 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3214 wait->wait.func = io_async_buf_func;
3215 wait->wait.private = req;
3216 wait->wait.flags = 0;
3217 INIT_LIST_HEAD(&wait->wait.entry);
3218 kiocb->ki_flags |= IOCB_WAITQ;
3219 kiocb->ki_flags &= ~IOCB_NOWAIT;
3220 kiocb->ki_waitq = wait;
3224 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3226 if (req->file->f_op->read_iter)
3227 return call_read_iter(req->file, &req->rw.kiocb, iter);
3228 else if (req->file->f_op->read)
3229 return loop_rw_iter(READ, req, iter);
3234 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3236 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3237 struct kiocb *kiocb = &req->rw.kiocb;
3238 struct iov_iter __iter, *iter = &__iter;
3239 struct io_async_rw *rw = req->async_data;
3240 ssize_t io_size, ret, ret2;
3241 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3247 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3251 io_size = iov_iter_count(iter);
3252 req->result = io_size;
3254 /* Ensure we clear previously set non-block flag */
3255 if (!force_nonblock)
3256 kiocb->ki_flags &= ~IOCB_NOWAIT;
3258 kiocb->ki_flags |= IOCB_NOWAIT;
3260 /* If the file doesn't support async, just async punt */
3261 if (force_nonblock && !io_file_supports_async(req, READ)) {
3262 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3263 return ret ?: -EAGAIN;
3266 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3267 if (unlikely(ret)) {
3272 ret = io_iter_do_read(req, iter);
3274 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3275 req->flags &= ~REQ_F_REISSUE;
3276 /* IOPOLL retry should happen for io-wq threads */
3277 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3279 /* no retry on NONBLOCK nor RWF_NOWAIT */
3280 if (req->flags & REQ_F_NOWAIT)
3282 /* some cases will consume bytes even on error returns */
3283 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3285 } else if (ret == -EIOCBQUEUED) {
3287 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3288 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3289 /* read all, failed, already did sync or don't want to retry */
3293 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3298 rw = req->async_data;
3299 /* now use our persistent iterator, if we aren't already */
3304 rw->bytes_done += ret;
3305 /* if we can retry, do so with the callbacks armed */
3306 if (!io_rw_should_retry(req)) {
3307 kiocb->ki_flags &= ~IOCB_WAITQ;
3312 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3313 * we get -EIOCBQUEUED, then we'll get a notification when the
3314 * desired page gets unlocked. We can also get a partial read
3315 * here, and if we do, then just retry at the new offset.
3317 ret = io_iter_do_read(req, iter);
3318 if (ret == -EIOCBQUEUED)
3320 /* we got some bytes, but not all. retry. */
3321 kiocb->ki_flags &= ~IOCB_WAITQ;
3322 } while (ret > 0 && ret < io_size);
3324 kiocb_done(kiocb, ret, issue_flags);
3326 /* it's faster to check here then delegate to kfree */
3332 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3334 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3336 return io_prep_rw(req, sqe);
3339 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3341 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3342 struct kiocb *kiocb = &req->rw.kiocb;
3343 struct iov_iter __iter, *iter = &__iter;
3344 struct io_async_rw *rw = req->async_data;
3345 ssize_t ret, ret2, io_size;
3346 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3352 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3356 io_size = iov_iter_count(iter);
3357 req->result = io_size;
3359 /* Ensure we clear previously set non-block flag */
3360 if (!force_nonblock)
3361 kiocb->ki_flags &= ~IOCB_NOWAIT;
3363 kiocb->ki_flags |= IOCB_NOWAIT;
3365 /* If the file doesn't support async, just async punt */
3366 if (force_nonblock && !io_file_supports_async(req, WRITE))
3369 /* file path doesn't support NOWAIT for non-direct_IO */
3370 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3371 (req->flags & REQ_F_ISREG))
3374 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3379 * Open-code file_start_write here to grab freeze protection,
3380 * which will be released by another thread in
3381 * io_complete_rw(). Fool lockdep by telling it the lock got
3382 * released so that it doesn't complain about the held lock when
3383 * we return to userspace.
3385 if (req->flags & REQ_F_ISREG) {
3386 sb_start_write(file_inode(req->file)->i_sb);
3387 __sb_writers_release(file_inode(req->file)->i_sb,
3390 kiocb->ki_flags |= IOCB_WRITE;
3392 if (req->file->f_op->write_iter)
3393 ret2 = call_write_iter(req->file, kiocb, iter);
3394 else if (req->file->f_op->write)
3395 ret2 = loop_rw_iter(WRITE, req, iter);
3399 if (req->flags & REQ_F_REISSUE) {
3400 req->flags &= ~REQ_F_REISSUE;
3405 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3406 * retry them without IOCB_NOWAIT.
3408 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3410 /* no retry on NONBLOCK nor RWF_NOWAIT */
3411 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3413 if (!force_nonblock || ret2 != -EAGAIN) {
3414 /* IOPOLL retry should happen for io-wq threads */
3415 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3418 kiocb_done(kiocb, ret2, issue_flags);
3421 /* some cases will consume bytes even on error returns */
3422 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3423 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3424 return ret ?: -EAGAIN;
3427 /* it's reportedly faster than delegating the null check to kfree() */
3433 static int io_renameat_prep(struct io_kiocb *req,
3434 const struct io_uring_sqe *sqe)
3436 struct io_rename *ren = &req->rename;
3437 const char __user *oldf, *newf;
3439 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3442 ren->old_dfd = READ_ONCE(sqe->fd);
3443 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3444 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3445 ren->new_dfd = READ_ONCE(sqe->len);
3446 ren->flags = READ_ONCE(sqe->rename_flags);
3448 ren->oldpath = getname(oldf);
3449 if (IS_ERR(ren->oldpath))
3450 return PTR_ERR(ren->oldpath);
3452 ren->newpath = getname(newf);
3453 if (IS_ERR(ren->newpath)) {
3454 putname(ren->oldpath);
3455 return PTR_ERR(ren->newpath);
3458 req->flags |= REQ_F_NEED_CLEANUP;
3462 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3464 struct io_rename *ren = &req->rename;
3467 if (issue_flags & IO_URING_F_NONBLOCK)
3470 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3471 ren->newpath, ren->flags);
3473 req->flags &= ~REQ_F_NEED_CLEANUP;
3475 req_set_fail_links(req);
3476 io_req_complete(req, ret);
3480 static int io_unlinkat_prep(struct io_kiocb *req,
3481 const struct io_uring_sqe *sqe)
3483 struct io_unlink *un = &req->unlink;
3484 const char __user *fname;
3486 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3489 un->dfd = READ_ONCE(sqe->fd);
3491 un->flags = READ_ONCE(sqe->unlink_flags);
3492 if (un->flags & ~AT_REMOVEDIR)
3495 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3496 un->filename = getname(fname);
3497 if (IS_ERR(un->filename))
3498 return PTR_ERR(un->filename);
3500 req->flags |= REQ_F_NEED_CLEANUP;
3504 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3506 struct io_unlink *un = &req->unlink;
3509 if (issue_flags & IO_URING_F_NONBLOCK)
3512 if (un->flags & AT_REMOVEDIR)
3513 ret = do_rmdir(un->dfd, un->filename);
3515 ret = do_unlinkat(un->dfd, un->filename);
3517 req->flags &= ~REQ_F_NEED_CLEANUP;
3519 req_set_fail_links(req);
3520 io_req_complete(req, ret);
3524 static int io_shutdown_prep(struct io_kiocb *req,
3525 const struct io_uring_sqe *sqe)
3527 #if defined(CONFIG_NET)
3528 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3530 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3534 req->shutdown.how = READ_ONCE(sqe->len);
3541 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3543 #if defined(CONFIG_NET)
3544 struct socket *sock;
3547 if (issue_flags & IO_URING_F_NONBLOCK)
3550 sock = sock_from_file(req->file);
3551 if (unlikely(!sock))
3554 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3556 req_set_fail_links(req);
3557 io_req_complete(req, ret);
3564 static int __io_splice_prep(struct io_kiocb *req,
3565 const struct io_uring_sqe *sqe)
3567 struct io_splice* sp = &req->splice;
3568 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3570 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3574 sp->len = READ_ONCE(sqe->len);
3575 sp->flags = READ_ONCE(sqe->splice_flags);
3577 if (unlikely(sp->flags & ~valid_flags))
3580 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3581 (sp->flags & SPLICE_F_FD_IN_FIXED));
3584 req->flags |= REQ_F_NEED_CLEANUP;
3588 static int io_tee_prep(struct io_kiocb *req,
3589 const struct io_uring_sqe *sqe)
3591 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3593 return __io_splice_prep(req, sqe);
3596 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3598 struct io_splice *sp = &req->splice;
3599 struct file *in = sp->file_in;
3600 struct file *out = sp->file_out;
3601 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3604 if (issue_flags & IO_URING_F_NONBLOCK)
3607 ret = do_tee(in, out, sp->len, flags);
3609 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3611 req->flags &= ~REQ_F_NEED_CLEANUP;
3614 req_set_fail_links(req);
3615 io_req_complete(req, ret);
3619 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3621 struct io_splice* sp = &req->splice;
3623 sp->off_in = READ_ONCE(sqe->splice_off_in);
3624 sp->off_out = READ_ONCE(sqe->off);
3625 return __io_splice_prep(req, sqe);
3628 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3630 struct io_splice *sp = &req->splice;
3631 struct file *in = sp->file_in;
3632 struct file *out = sp->file_out;
3633 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3634 loff_t *poff_in, *poff_out;
3637 if (issue_flags & IO_URING_F_NONBLOCK)
3640 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3641 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3644 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3646 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3648 req->flags &= ~REQ_F_NEED_CLEANUP;
3651 req_set_fail_links(req);
3652 io_req_complete(req, ret);
3657 * IORING_OP_NOP just posts a completion event, nothing else.
3659 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3661 struct io_ring_ctx *ctx = req->ctx;
3663 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3666 __io_req_complete(req, issue_flags, 0, 0);
3670 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3672 struct io_ring_ctx *ctx = req->ctx;
3677 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3679 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3682 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3683 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3686 req->sync.off = READ_ONCE(sqe->off);
3687 req->sync.len = READ_ONCE(sqe->len);
3691 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3693 loff_t end = req->sync.off + req->sync.len;
3696 /* fsync always requires a blocking context */
3697 if (issue_flags & IO_URING_F_NONBLOCK)
3700 ret = vfs_fsync_range(req->file, req->sync.off,
3701 end > 0 ? end : LLONG_MAX,
3702 req->sync.flags & IORING_FSYNC_DATASYNC);
3704 req_set_fail_links(req);
3705 io_req_complete(req, ret);
3709 static int io_fallocate_prep(struct io_kiocb *req,
3710 const struct io_uring_sqe *sqe)
3712 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3714 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3717 req->sync.off = READ_ONCE(sqe->off);
3718 req->sync.len = READ_ONCE(sqe->addr);
3719 req->sync.mode = READ_ONCE(sqe->len);
3723 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3727 /* fallocate always requiring blocking context */
3728 if (issue_flags & IO_URING_F_NONBLOCK)
3730 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3733 req_set_fail_links(req);
3734 io_req_complete(req, ret);
3738 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3740 const char __user *fname;
3743 if (unlikely(sqe->ioprio || sqe->buf_index))
3745 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3748 /* open.how should be already initialised */
3749 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3750 req->open.how.flags |= O_LARGEFILE;
3752 req->open.dfd = READ_ONCE(sqe->fd);
3753 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3754 req->open.filename = getname(fname);
3755 if (IS_ERR(req->open.filename)) {
3756 ret = PTR_ERR(req->open.filename);
3757 req->open.filename = NULL;
3760 req->open.nofile = rlimit(RLIMIT_NOFILE);
3761 req->flags |= REQ_F_NEED_CLEANUP;
3765 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3769 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3771 mode = READ_ONCE(sqe->len);
3772 flags = READ_ONCE(sqe->open_flags);
3773 req->open.how = build_open_how(flags, mode);
3774 return __io_openat_prep(req, sqe);
3777 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3779 struct open_how __user *how;
3783 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3785 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3786 len = READ_ONCE(sqe->len);
3787 if (len < OPEN_HOW_SIZE_VER0)
3790 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3795 return __io_openat_prep(req, sqe);
3798 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3800 struct open_flags op;
3803 bool resolve_nonblock;
3806 ret = build_open_flags(&req->open.how, &op);
3809 nonblock_set = op.open_flag & O_NONBLOCK;
3810 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3811 if (issue_flags & IO_URING_F_NONBLOCK) {
3813 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3814 * it'll always -EAGAIN
3816 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3818 op.lookup_flags |= LOOKUP_CACHED;
3819 op.open_flag |= O_NONBLOCK;
3822 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3826 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3827 /* only retry if RESOLVE_CACHED wasn't already set by application */
3828 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3829 file == ERR_PTR(-EAGAIN)) {
3831 * We could hang on to this 'fd', but seems like marginal
3832 * gain for something that is now known to be a slower path.
3833 * So just put it, and we'll get a new one when we retry.
3841 ret = PTR_ERR(file);
3843 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3844 file->f_flags &= ~O_NONBLOCK;
3845 fsnotify_open(file);
3846 fd_install(ret, file);
3849 putname(req->open.filename);
3850 req->flags &= ~REQ_F_NEED_CLEANUP;
3852 req_set_fail_links(req);
3853 __io_req_complete(req, issue_flags, ret, 0);
3857 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3859 return io_openat2(req, issue_flags);
3862 static int io_remove_buffers_prep(struct io_kiocb *req,
3863 const struct io_uring_sqe *sqe)
3865 struct io_provide_buf *p = &req->pbuf;
3868 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3871 tmp = READ_ONCE(sqe->fd);
3872 if (!tmp || tmp > USHRT_MAX)
3875 memset(p, 0, sizeof(*p));
3877 p->bgid = READ_ONCE(sqe->buf_group);
3881 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3882 int bgid, unsigned nbufs)
3886 /* shouldn't happen */
3890 /* the head kbuf is the list itself */
3891 while (!list_empty(&buf->list)) {
3892 struct io_buffer *nxt;
3894 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3895 list_del(&nxt->list);
3902 xa_erase(&ctx->io_buffers, bgid);
3907 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3909 struct io_provide_buf *p = &req->pbuf;
3910 struct io_ring_ctx *ctx = req->ctx;
3911 struct io_buffer *head;
3913 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3915 io_ring_submit_lock(ctx, !force_nonblock);
3917 lockdep_assert_held(&ctx->uring_lock);
3920 head = xa_load(&ctx->io_buffers, p->bgid);
3922 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3924 req_set_fail_links(req);
3926 /* complete before unlock, IOPOLL may need the lock */
3927 __io_req_complete(req, issue_flags, ret, 0);
3928 io_ring_submit_unlock(ctx, !force_nonblock);
3932 static int io_provide_buffers_prep(struct io_kiocb *req,
3933 const struct io_uring_sqe *sqe)
3935 unsigned long size, tmp_check;
3936 struct io_provide_buf *p = &req->pbuf;
3939 if (sqe->ioprio || sqe->rw_flags)
3942 tmp = READ_ONCE(sqe->fd);
3943 if (!tmp || tmp > USHRT_MAX)
3946 p->addr = READ_ONCE(sqe->addr);
3947 p->len = READ_ONCE(sqe->len);
3949 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3952 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3955 size = (unsigned long)p->len * p->nbufs;
3956 if (!access_ok(u64_to_user_ptr(p->addr), size))
3959 p->bgid = READ_ONCE(sqe->buf_group);
3960 tmp = READ_ONCE(sqe->off);
3961 if (tmp > USHRT_MAX)
3967 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3969 struct io_buffer *buf;
3970 u64 addr = pbuf->addr;
3971 int i, bid = pbuf->bid;
3973 for (i = 0; i < pbuf->nbufs; i++) {
3974 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3979 buf->len = pbuf->len;
3984 INIT_LIST_HEAD(&buf->list);
3987 list_add_tail(&buf->list, &(*head)->list);
3991 return i ? i : -ENOMEM;
3994 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3996 struct io_provide_buf *p = &req->pbuf;
3997 struct io_ring_ctx *ctx = req->ctx;
3998 struct io_buffer *head, *list;
4000 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4002 io_ring_submit_lock(ctx, !force_nonblock);
4004 lockdep_assert_held(&ctx->uring_lock);
4006 list = head = xa_load(&ctx->io_buffers, p->bgid);
4008 ret = io_add_buffers(p, &head);
4009 if (ret >= 0 && !list) {
4010 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4012 __io_remove_buffers(ctx, head, p->bgid, -1U);
4015 req_set_fail_links(req);
4016 /* complete before unlock, IOPOLL may need the lock */
4017 __io_req_complete(req, issue_flags, ret, 0);
4018 io_ring_submit_unlock(ctx, !force_nonblock);
4022 static int io_epoll_ctl_prep(struct io_kiocb *req,
4023 const struct io_uring_sqe *sqe)
4025 #if defined(CONFIG_EPOLL)
4026 if (sqe->ioprio || sqe->buf_index)
4028 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4031 req->epoll.epfd = READ_ONCE(sqe->fd);
4032 req->epoll.op = READ_ONCE(sqe->len);
4033 req->epoll.fd = READ_ONCE(sqe->off);
4035 if (ep_op_has_event(req->epoll.op)) {
4036 struct epoll_event __user *ev;
4038 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4039 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4049 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4051 #if defined(CONFIG_EPOLL)
4052 struct io_epoll *ie = &req->epoll;
4054 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4056 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4057 if (force_nonblock && ret == -EAGAIN)
4061 req_set_fail_links(req);
4062 __io_req_complete(req, issue_flags, ret, 0);
4069 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4071 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4072 if (sqe->ioprio || sqe->buf_index || sqe->off)
4074 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4077 req->madvise.addr = READ_ONCE(sqe->addr);
4078 req->madvise.len = READ_ONCE(sqe->len);
4079 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4086 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4088 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4089 struct io_madvise *ma = &req->madvise;
4092 if (issue_flags & IO_URING_F_NONBLOCK)
4095 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4097 req_set_fail_links(req);
4098 io_req_complete(req, ret);
4105 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4107 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4109 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4112 req->fadvise.offset = READ_ONCE(sqe->off);
4113 req->fadvise.len = READ_ONCE(sqe->len);
4114 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4118 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4120 struct io_fadvise *fa = &req->fadvise;
4123 if (issue_flags & IO_URING_F_NONBLOCK) {
4124 switch (fa->advice) {
4125 case POSIX_FADV_NORMAL:
4126 case POSIX_FADV_RANDOM:
4127 case POSIX_FADV_SEQUENTIAL:
4134 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4136 req_set_fail_links(req);
4137 __io_req_complete(req, issue_flags, ret, 0);
4141 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4143 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4145 if (sqe->ioprio || sqe->buf_index)
4147 if (req->flags & REQ_F_FIXED_FILE)
4150 req->statx.dfd = READ_ONCE(sqe->fd);
4151 req->statx.mask = READ_ONCE(sqe->len);
4152 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4153 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4154 req->statx.flags = READ_ONCE(sqe->statx_flags);
4159 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4161 struct io_statx *ctx = &req->statx;
4164 if (issue_flags & IO_URING_F_NONBLOCK)
4167 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4171 req_set_fail_links(req);
4172 io_req_complete(req, ret);
4176 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4178 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4180 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4181 sqe->rw_flags || sqe->buf_index)
4183 if (req->flags & REQ_F_FIXED_FILE)
4186 req->close.fd = READ_ONCE(sqe->fd);
4190 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4192 struct files_struct *files = current->files;
4193 struct io_close *close = &req->close;
4194 struct fdtable *fdt;
4195 struct file *file = NULL;
4198 spin_lock(&files->file_lock);
4199 fdt = files_fdtable(files);
4200 if (close->fd >= fdt->max_fds) {
4201 spin_unlock(&files->file_lock);
4204 file = fdt->fd[close->fd];
4205 if (!file || file->f_op == &io_uring_fops) {
4206 spin_unlock(&files->file_lock);
4211 /* if the file has a flush method, be safe and punt to async */
4212 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4213 spin_unlock(&files->file_lock);
4217 ret = __close_fd_get_file(close->fd, &file);
4218 spin_unlock(&files->file_lock);
4225 /* No ->flush() or already async, safely close from here */
4226 ret = filp_close(file, current->files);
4229 req_set_fail_links(req);
4232 __io_req_complete(req, issue_flags, ret, 0);
4236 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4238 struct io_ring_ctx *ctx = req->ctx;
4240 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4242 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4245 req->sync.off = READ_ONCE(sqe->off);
4246 req->sync.len = READ_ONCE(sqe->len);
4247 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4251 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4255 /* sync_file_range always requires a blocking context */
4256 if (issue_flags & IO_URING_F_NONBLOCK)
4259 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4262 req_set_fail_links(req);
4263 io_req_complete(req, ret);
4267 #if defined(CONFIG_NET)
4268 static int io_setup_async_msg(struct io_kiocb *req,
4269 struct io_async_msghdr *kmsg)
4271 struct io_async_msghdr *async_msg = req->async_data;
4275 if (io_alloc_async_data(req)) {
4276 kfree(kmsg->free_iov);
4279 async_msg = req->async_data;
4280 req->flags |= REQ_F_NEED_CLEANUP;
4281 memcpy(async_msg, kmsg, sizeof(*kmsg));
4282 async_msg->msg.msg_name = &async_msg->addr;
4283 /* if were using fast_iov, set it to the new one */
4284 if (!async_msg->free_iov)
4285 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4290 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4291 struct io_async_msghdr *iomsg)
4293 iomsg->msg.msg_name = &iomsg->addr;
4294 iomsg->free_iov = iomsg->fast_iov;
4295 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4296 req->sr_msg.msg_flags, &iomsg->free_iov);
4299 static int io_sendmsg_prep_async(struct io_kiocb *req)
4303 ret = io_sendmsg_copy_hdr(req, req->async_data);
4305 req->flags |= REQ_F_NEED_CLEANUP;
4309 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4311 struct io_sr_msg *sr = &req->sr_msg;
4313 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4316 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4317 sr->len = READ_ONCE(sqe->len);
4318 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4319 if (sr->msg_flags & MSG_DONTWAIT)
4320 req->flags |= REQ_F_NOWAIT;
4322 #ifdef CONFIG_COMPAT
4323 if (req->ctx->compat)
4324 sr->msg_flags |= MSG_CMSG_COMPAT;
4329 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4331 struct io_async_msghdr iomsg, *kmsg;
4332 struct socket *sock;
4337 sock = sock_from_file(req->file);
4338 if (unlikely(!sock))
4341 kmsg = req->async_data;
4343 ret = io_sendmsg_copy_hdr(req, &iomsg);
4349 flags = req->sr_msg.msg_flags;
4350 if (issue_flags & IO_URING_F_NONBLOCK)
4351 flags |= MSG_DONTWAIT;
4352 if (flags & MSG_WAITALL)
4353 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4355 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4356 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4357 return io_setup_async_msg(req, kmsg);
4358 if (ret == -ERESTARTSYS)
4361 /* fast path, check for non-NULL to avoid function call */
4363 kfree(kmsg->free_iov);
4364 req->flags &= ~REQ_F_NEED_CLEANUP;
4366 req_set_fail_links(req);
4367 __io_req_complete(req, issue_flags, ret, 0);
4371 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4373 struct io_sr_msg *sr = &req->sr_msg;
4376 struct socket *sock;
4381 sock = sock_from_file(req->file);
4382 if (unlikely(!sock))
4385 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4389 msg.msg_name = NULL;
4390 msg.msg_control = NULL;
4391 msg.msg_controllen = 0;
4392 msg.msg_namelen = 0;
4394 flags = req->sr_msg.msg_flags;
4395 if (issue_flags & IO_URING_F_NONBLOCK)
4396 flags |= MSG_DONTWAIT;
4397 if (flags & MSG_WAITALL)
4398 min_ret = iov_iter_count(&msg.msg_iter);
4400 msg.msg_flags = flags;
4401 ret = sock_sendmsg(sock, &msg);
4402 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4404 if (ret == -ERESTARTSYS)
4408 req_set_fail_links(req);
4409 __io_req_complete(req, issue_flags, ret, 0);
4413 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4414 struct io_async_msghdr *iomsg)
4416 struct io_sr_msg *sr = &req->sr_msg;
4417 struct iovec __user *uiov;
4421 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4422 &iomsg->uaddr, &uiov, &iov_len);
4426 if (req->flags & REQ_F_BUFFER_SELECT) {
4429 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4431 sr->len = iomsg->fast_iov[0].iov_len;
4432 iomsg->free_iov = NULL;
4434 iomsg->free_iov = iomsg->fast_iov;
4435 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4436 &iomsg->free_iov, &iomsg->msg.msg_iter,
4445 #ifdef CONFIG_COMPAT
4446 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4447 struct io_async_msghdr *iomsg)
4449 struct io_sr_msg *sr = &req->sr_msg;
4450 struct compat_iovec __user *uiov;
4455 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4460 uiov = compat_ptr(ptr);
4461 if (req->flags & REQ_F_BUFFER_SELECT) {
4462 compat_ssize_t clen;
4466 if (!access_ok(uiov, sizeof(*uiov)))
4468 if (__get_user(clen, &uiov->iov_len))
4473 iomsg->free_iov = NULL;
4475 iomsg->free_iov = iomsg->fast_iov;
4476 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4477 UIO_FASTIOV, &iomsg->free_iov,
4478 &iomsg->msg.msg_iter, true);
4487 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4488 struct io_async_msghdr *iomsg)
4490 iomsg->msg.msg_name = &iomsg->addr;
4492 #ifdef CONFIG_COMPAT
4493 if (req->ctx->compat)
4494 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4497 return __io_recvmsg_copy_hdr(req, iomsg);
4500 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4503 struct io_sr_msg *sr = &req->sr_msg;
4504 struct io_buffer *kbuf;
4506 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4511 req->flags |= REQ_F_BUFFER_SELECTED;
4515 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4517 return io_put_kbuf(req, req->sr_msg.kbuf);
4520 static int io_recvmsg_prep_async(struct io_kiocb *req)
4524 ret = io_recvmsg_copy_hdr(req, req->async_data);
4526 req->flags |= REQ_F_NEED_CLEANUP;
4530 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4532 struct io_sr_msg *sr = &req->sr_msg;
4534 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4537 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4538 sr->len = READ_ONCE(sqe->len);
4539 sr->bgid = READ_ONCE(sqe->buf_group);
4540 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4541 if (sr->msg_flags & MSG_DONTWAIT)
4542 req->flags |= REQ_F_NOWAIT;
4544 #ifdef CONFIG_COMPAT
4545 if (req->ctx->compat)
4546 sr->msg_flags |= MSG_CMSG_COMPAT;
4551 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4553 struct io_async_msghdr iomsg, *kmsg;
4554 struct socket *sock;
4555 struct io_buffer *kbuf;
4558 int ret, cflags = 0;
4559 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4561 sock = sock_from_file(req->file);
4562 if (unlikely(!sock))
4565 kmsg = req->async_data;
4567 ret = io_recvmsg_copy_hdr(req, &iomsg);
4573 if (req->flags & REQ_F_BUFFER_SELECT) {
4574 kbuf = io_recv_buffer_select(req, !force_nonblock);
4576 return PTR_ERR(kbuf);
4577 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4578 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4579 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4580 1, req->sr_msg.len);
4583 flags = req->sr_msg.msg_flags;
4585 flags |= MSG_DONTWAIT;
4586 if (flags & MSG_WAITALL)
4587 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4589 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4590 kmsg->uaddr, flags);
4591 if (force_nonblock && ret == -EAGAIN)
4592 return io_setup_async_msg(req, kmsg);
4593 if (ret == -ERESTARTSYS)
4596 if (req->flags & REQ_F_BUFFER_SELECTED)
4597 cflags = io_put_recv_kbuf(req);
4598 /* fast path, check for non-NULL to avoid function call */
4600 kfree(kmsg->free_iov);
4601 req->flags &= ~REQ_F_NEED_CLEANUP;
4602 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4603 req_set_fail_links(req);
4604 __io_req_complete(req, issue_flags, ret, cflags);
4608 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4610 struct io_buffer *kbuf;
4611 struct io_sr_msg *sr = &req->sr_msg;
4613 void __user *buf = sr->buf;
4614 struct socket *sock;
4618 int ret, cflags = 0;
4619 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4621 sock = sock_from_file(req->file);
4622 if (unlikely(!sock))
4625 if (req->flags & REQ_F_BUFFER_SELECT) {
4626 kbuf = io_recv_buffer_select(req, !force_nonblock);
4628 return PTR_ERR(kbuf);
4629 buf = u64_to_user_ptr(kbuf->addr);
4632 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4636 msg.msg_name = NULL;
4637 msg.msg_control = NULL;
4638 msg.msg_controllen = 0;
4639 msg.msg_namelen = 0;
4640 msg.msg_iocb = NULL;
4643 flags = req->sr_msg.msg_flags;
4645 flags |= MSG_DONTWAIT;
4646 if (flags & MSG_WAITALL)
4647 min_ret = iov_iter_count(&msg.msg_iter);
4649 ret = sock_recvmsg(sock, &msg, flags);
4650 if (force_nonblock && ret == -EAGAIN)
4652 if (ret == -ERESTARTSYS)
4655 if (req->flags & REQ_F_BUFFER_SELECTED)
4656 cflags = io_put_recv_kbuf(req);
4657 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4658 req_set_fail_links(req);
4659 __io_req_complete(req, issue_flags, ret, cflags);
4663 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4665 struct io_accept *accept = &req->accept;
4667 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4669 if (sqe->ioprio || sqe->len || sqe->buf_index)
4672 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4673 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4674 accept->flags = READ_ONCE(sqe->accept_flags);
4675 accept->nofile = rlimit(RLIMIT_NOFILE);
4679 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4681 struct io_accept *accept = &req->accept;
4682 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4683 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4686 if (req->file->f_flags & O_NONBLOCK)
4687 req->flags |= REQ_F_NOWAIT;
4689 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4690 accept->addr_len, accept->flags,
4692 if (ret == -EAGAIN && force_nonblock)
4695 if (ret == -ERESTARTSYS)
4697 req_set_fail_links(req);
4699 __io_req_complete(req, issue_flags, ret, 0);
4703 static int io_connect_prep_async(struct io_kiocb *req)
4705 struct io_async_connect *io = req->async_data;
4706 struct io_connect *conn = &req->connect;
4708 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4711 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4713 struct io_connect *conn = &req->connect;
4715 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4717 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4720 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4721 conn->addr_len = READ_ONCE(sqe->addr2);
4725 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4727 struct io_async_connect __io, *io;
4728 unsigned file_flags;
4730 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4732 if (req->async_data) {
4733 io = req->async_data;
4735 ret = move_addr_to_kernel(req->connect.addr,
4736 req->connect.addr_len,
4743 file_flags = force_nonblock ? O_NONBLOCK : 0;
4745 ret = __sys_connect_file(req->file, &io->address,
4746 req->connect.addr_len, file_flags);
4747 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4748 if (req->async_data)
4750 if (io_alloc_async_data(req)) {
4754 memcpy(req->async_data, &__io, sizeof(__io));
4757 if (ret == -ERESTARTSYS)
4761 req_set_fail_links(req);
4762 __io_req_complete(req, issue_flags, ret, 0);
4765 #else /* !CONFIG_NET */
4766 #define IO_NETOP_FN(op) \
4767 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4769 return -EOPNOTSUPP; \
4772 #define IO_NETOP_PREP(op) \
4774 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4776 return -EOPNOTSUPP; \
4779 #define IO_NETOP_PREP_ASYNC(op) \
4781 static int io_##op##_prep_async(struct io_kiocb *req) \
4783 return -EOPNOTSUPP; \
4786 IO_NETOP_PREP_ASYNC(sendmsg);
4787 IO_NETOP_PREP_ASYNC(recvmsg);
4788 IO_NETOP_PREP_ASYNC(connect);
4789 IO_NETOP_PREP(accept);
4792 #endif /* CONFIG_NET */
4794 struct io_poll_table {
4795 struct poll_table_struct pt;
4796 struct io_kiocb *req;
4800 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4801 __poll_t mask, task_work_func_t func)
4805 /* for instances that support it check for an event match first: */
4806 if (mask && !(mask & poll->events))
4809 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4811 list_del_init(&poll->wait.entry);
4814 req->task_work.func = func;
4817 * If this fails, then the task is exiting. When a task exits, the
4818 * work gets canceled, so just cancel this request as well instead
4819 * of executing it. We can't safely execute it anyway, as we may not
4820 * have the needed state needed for it anyway.
4822 ret = io_req_task_work_add(req);
4823 if (unlikely(ret)) {
4824 WRITE_ONCE(poll->canceled, true);
4825 io_req_task_work_add_fallback(req, func);
4830 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4831 __acquires(&req->ctx->completion_lock)
4833 struct io_ring_ctx *ctx = req->ctx;
4835 if (!req->result && !READ_ONCE(poll->canceled)) {
4836 struct poll_table_struct pt = { ._key = poll->events };
4838 req->result = vfs_poll(req->file, &pt) & poll->events;
4841 spin_lock_irq(&ctx->completion_lock);
4842 if (!req->result && !READ_ONCE(poll->canceled)) {
4843 add_wait_queue(poll->head, &poll->wait);
4850 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4852 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4853 if (req->opcode == IORING_OP_POLL_ADD)
4854 return req->async_data;
4855 return req->apoll->double_poll;
4858 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4860 if (req->opcode == IORING_OP_POLL_ADD)
4862 return &req->apoll->poll;
4865 static void io_poll_remove_double(struct io_kiocb *req)
4866 __must_hold(&req->ctx->completion_lock)
4868 struct io_poll_iocb *poll = io_poll_get_double(req);
4870 lockdep_assert_held(&req->ctx->completion_lock);
4872 if (poll && poll->head) {
4873 struct wait_queue_head *head = poll->head;
4875 spin_lock(&head->lock);
4876 list_del_init(&poll->wait.entry);
4877 if (poll->wait.private)
4880 spin_unlock(&head->lock);
4884 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4885 __must_hold(&req->ctx->completion_lock)
4887 struct io_ring_ctx *ctx = req->ctx;
4888 unsigned flags = IORING_CQE_F_MORE;
4891 if (READ_ONCE(req->poll.canceled)) {
4893 req->poll.events |= EPOLLONESHOT;
4895 error = mangle_poll(mask);
4897 if (req->poll.events & EPOLLONESHOT)
4899 if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4900 io_poll_remove_waitqs(req);
4901 req->poll.done = true;
4904 io_commit_cqring(ctx);
4905 return !(flags & IORING_CQE_F_MORE);
4908 static void io_poll_task_func(struct callback_head *cb)
4910 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4911 struct io_ring_ctx *ctx = req->ctx;
4912 struct io_kiocb *nxt;
4914 if (io_poll_rewait(req, &req->poll)) {
4915 spin_unlock_irq(&ctx->completion_lock);
4919 done = io_poll_complete(req, req->result);
4921 hash_del(&req->hash_node);
4924 add_wait_queue(req->poll.head, &req->poll.wait);
4926 spin_unlock_irq(&ctx->completion_lock);
4927 io_cqring_ev_posted(ctx);
4930 nxt = io_put_req_find_next(req);
4932 __io_req_task_submit(nxt);
4937 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4938 int sync, void *key)
4940 struct io_kiocb *req = wait->private;
4941 struct io_poll_iocb *poll = io_poll_get_single(req);
4942 __poll_t mask = key_to_poll(key);
4944 /* for instances that support it check for an event match first: */
4945 if (mask && !(mask & poll->events))
4947 if (!(poll->events & EPOLLONESHOT))
4948 return poll->wait.func(&poll->wait, mode, sync, key);
4950 list_del_init(&wait->entry);
4952 if (poll && poll->head) {
4955 spin_lock(&poll->head->lock);
4956 done = list_empty(&poll->wait.entry);
4958 list_del_init(&poll->wait.entry);
4959 /* make sure double remove sees this as being gone */
4960 wait->private = NULL;
4961 spin_unlock(&poll->head->lock);
4963 /* use wait func handler, so it matches the rq type */
4964 poll->wait.func(&poll->wait, mode, sync, key);
4971 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4972 wait_queue_func_t wake_func)
4976 poll->canceled = false;
4977 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4978 /* mask in events that we always want/need */
4979 poll->events = events | IO_POLL_UNMASK;
4980 INIT_LIST_HEAD(&poll->wait.entry);
4981 init_waitqueue_func_entry(&poll->wait, wake_func);
4984 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4985 struct wait_queue_head *head,
4986 struct io_poll_iocb **poll_ptr)
4988 struct io_kiocb *req = pt->req;
4991 * If poll->head is already set, it's because the file being polled
4992 * uses multiple waitqueues for poll handling (eg one for read, one
4993 * for write). Setup a separate io_poll_iocb if this happens.
4995 if (unlikely(poll->head)) {
4996 struct io_poll_iocb *poll_one = poll;
4998 /* already have a 2nd entry, fail a third attempt */
5000 pt->error = -EINVAL;
5004 * Can't handle multishot for double wait for now, turn it
5005 * into one-shot mode.
5007 if (!(req->poll.events & EPOLLONESHOT))
5008 req->poll.events |= EPOLLONESHOT;
5009 /* double add on the same waitqueue head, ignore */
5010 if (poll->head == head)
5012 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5014 pt->error = -ENOMEM;
5017 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5019 poll->wait.private = req;
5026 if (poll->events & EPOLLEXCLUSIVE)
5027 add_wait_queue_exclusive(head, &poll->wait);
5029 add_wait_queue(head, &poll->wait);
5032 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5033 struct poll_table_struct *p)
5035 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5036 struct async_poll *apoll = pt->req->apoll;
5038 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5041 static void io_async_task_func(struct callback_head *cb)
5043 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5044 struct async_poll *apoll = req->apoll;
5045 struct io_ring_ctx *ctx = req->ctx;
5047 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5049 if (io_poll_rewait(req, &apoll->poll)) {
5050 spin_unlock_irq(&ctx->completion_lock);
5054 hash_del(&req->hash_node);
5055 io_poll_remove_double(req);
5056 spin_unlock_irq(&ctx->completion_lock);
5058 if (!READ_ONCE(apoll->poll.canceled))
5059 __io_req_task_submit(req);
5061 io_req_complete_failed(req, -ECANCELED);
5064 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5067 struct io_kiocb *req = wait->private;
5068 struct io_poll_iocb *poll = &req->apoll->poll;
5070 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5073 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5076 static void io_poll_req_insert(struct io_kiocb *req)
5078 struct io_ring_ctx *ctx = req->ctx;
5079 struct hlist_head *list;
5081 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5082 hlist_add_head(&req->hash_node, list);
5085 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5086 struct io_poll_iocb *poll,
5087 struct io_poll_table *ipt, __poll_t mask,
5088 wait_queue_func_t wake_func)
5089 __acquires(&ctx->completion_lock)
5091 struct io_ring_ctx *ctx = req->ctx;
5092 bool cancel = false;
5094 INIT_HLIST_NODE(&req->hash_node);
5095 io_init_poll_iocb(poll, mask, wake_func);
5096 poll->file = req->file;
5097 poll->wait.private = req;
5099 ipt->pt._key = mask;
5101 ipt->error = -EINVAL;
5103 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5105 spin_lock_irq(&ctx->completion_lock);
5106 if (likely(poll->head)) {
5107 spin_lock(&poll->head->lock);
5108 if (unlikely(list_empty(&poll->wait.entry))) {
5114 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5115 list_del_init(&poll->wait.entry);
5117 WRITE_ONCE(poll->canceled, true);
5118 else if (!poll->done) /* actually waiting for an event */
5119 io_poll_req_insert(req);
5120 spin_unlock(&poll->head->lock);
5126 static bool io_arm_poll_handler(struct io_kiocb *req)
5128 const struct io_op_def *def = &io_op_defs[req->opcode];
5129 struct io_ring_ctx *ctx = req->ctx;
5130 struct async_poll *apoll;
5131 struct io_poll_table ipt;
5135 if (!req->file || !file_can_poll(req->file))
5137 if (req->flags & REQ_F_POLLED)
5141 else if (def->pollout)
5145 /* if we can't nonblock try, then no point in arming a poll handler */
5146 if (!io_file_supports_async(req, rw))
5149 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5150 if (unlikely(!apoll))
5152 apoll->double_poll = NULL;
5154 req->flags |= REQ_F_POLLED;
5157 mask = EPOLLONESHOT;
5159 mask |= POLLIN | POLLRDNORM;
5161 mask |= POLLOUT | POLLWRNORM;
5163 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5164 if ((req->opcode == IORING_OP_RECVMSG) &&
5165 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5168 mask |= POLLERR | POLLPRI;
5170 ipt.pt._qproc = io_async_queue_proc;
5172 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5174 if (ret || ipt.error) {
5175 io_poll_remove_double(req);
5176 spin_unlock_irq(&ctx->completion_lock);
5179 spin_unlock_irq(&ctx->completion_lock);
5180 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5181 apoll->poll.events);
5185 static bool __io_poll_remove_one(struct io_kiocb *req,
5186 struct io_poll_iocb *poll, bool do_cancel)
5187 __must_hold(&req->ctx->completion_lock)
5189 bool do_complete = false;
5193 spin_lock(&poll->head->lock);
5195 WRITE_ONCE(poll->canceled, true);
5196 if (!list_empty(&poll->wait.entry)) {
5197 list_del_init(&poll->wait.entry);
5200 spin_unlock(&poll->head->lock);
5201 hash_del(&req->hash_node);
5205 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5206 __must_hold(&req->ctx->completion_lock)
5210 io_poll_remove_double(req);
5211 do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5213 if (req->opcode != IORING_OP_POLL_ADD && do_complete) {
5214 /* non-poll requests have submit ref still */
5220 static bool io_poll_remove_one(struct io_kiocb *req)
5221 __must_hold(&req->ctx->completion_lock)
5225 do_complete = io_poll_remove_waitqs(req);
5227 io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5228 io_commit_cqring(req->ctx);
5229 req_set_fail_links(req);
5230 io_put_req_deferred(req, 1);
5237 * Returns true if we found and killed one or more poll requests
5239 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5240 struct files_struct *files)
5242 struct hlist_node *tmp;
5243 struct io_kiocb *req;
5246 spin_lock_irq(&ctx->completion_lock);
5247 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5248 struct hlist_head *list;
5250 list = &ctx->cancel_hash[i];
5251 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5252 if (io_match_task(req, tsk, files))
5253 posted += io_poll_remove_one(req);
5256 spin_unlock_irq(&ctx->completion_lock);
5259 io_cqring_ev_posted(ctx);
5264 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5266 __must_hold(&ctx->completion_lock)
5268 struct hlist_head *list;
5269 struct io_kiocb *req;
5271 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5272 hlist_for_each_entry(req, list, hash_node) {
5273 if (sqe_addr != req->user_data)
5275 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5282 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5284 __must_hold(&ctx->completion_lock)
5286 struct io_kiocb *req;
5288 req = io_poll_find(ctx, sqe_addr, poll_only);
5291 if (io_poll_remove_one(req))
5297 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5302 events = READ_ONCE(sqe->poll32_events);
5304 events = swahw32(events);
5306 if (!(flags & IORING_POLL_ADD_MULTI))
5307 events |= EPOLLONESHOT;
5308 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5311 static int io_poll_update_prep(struct io_kiocb *req,
5312 const struct io_uring_sqe *sqe)
5314 struct io_poll_update *upd = &req->poll_update;
5317 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5319 if (sqe->ioprio || sqe->buf_index)
5321 flags = READ_ONCE(sqe->len);
5322 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5323 IORING_POLL_ADD_MULTI))
5325 /* meaningless without update */
5326 if (flags == IORING_POLL_ADD_MULTI)
5329 upd->old_user_data = READ_ONCE(sqe->addr);
5330 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5331 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5333 upd->new_user_data = READ_ONCE(sqe->off);
5334 if (!upd->update_user_data && upd->new_user_data)
5336 if (upd->update_events)
5337 upd->events = io_poll_parse_events(sqe, flags);
5338 else if (sqe->poll32_events)
5344 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5347 struct io_kiocb *req = wait->private;
5348 struct io_poll_iocb *poll = &req->poll;
5350 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5353 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5354 struct poll_table_struct *p)
5356 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5358 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5361 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5363 struct io_poll_iocb *poll = &req->poll;
5366 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5368 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5370 flags = READ_ONCE(sqe->len);
5371 if (flags & ~IORING_POLL_ADD_MULTI)
5374 poll->events = io_poll_parse_events(sqe, flags);
5378 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5380 struct io_poll_iocb *poll = &req->poll;
5381 struct io_ring_ctx *ctx = req->ctx;
5382 struct io_poll_table ipt;
5385 ipt.pt._qproc = io_poll_queue_proc;
5387 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5390 if (mask) { /* no async, we'd stolen it */
5392 io_poll_complete(req, mask);
5394 spin_unlock_irq(&ctx->completion_lock);
5397 io_cqring_ev_posted(ctx);
5398 if (poll->events & EPOLLONESHOT)
5404 static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5406 struct io_ring_ctx *ctx = req->ctx;
5407 struct io_kiocb *preq;
5411 spin_lock_irq(&ctx->completion_lock);
5412 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5418 if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5420 ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5425 * Don't allow racy completion with singleshot, as we cannot safely
5426 * update those. For multishot, if we're racing with completion, just
5427 * let completion re-add it.
5429 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5430 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5434 /* we now have a detached poll request. reissue. */
5438 spin_unlock_irq(&ctx->completion_lock);
5439 req_set_fail_links(req);
5440 io_req_complete(req, ret);
5443 /* only mask one event flags, keep behavior flags */
5444 if (req->poll_update.update_events) {
5445 preq->poll.events &= ~0xffff;
5446 preq->poll.events |= req->poll_update.events & 0xffff;
5447 preq->poll.events |= IO_POLL_UNMASK;
5449 if (req->poll_update.update_user_data)
5450 preq->user_data = req->poll_update.new_user_data;
5451 spin_unlock_irq(&ctx->completion_lock);
5453 /* complete update request, we're done with it */
5454 io_req_complete(req, ret);
5457 ret = io_poll_add(preq, issue_flags);
5459 req_set_fail_links(preq);
5460 io_req_complete(preq, ret);
5466 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5468 struct io_timeout_data *data = container_of(timer,
5469 struct io_timeout_data, timer);
5470 struct io_kiocb *req = data->req;
5471 struct io_ring_ctx *ctx = req->ctx;
5472 unsigned long flags;
5474 spin_lock_irqsave(&ctx->completion_lock, flags);
5475 list_del_init(&req->timeout.list);
5476 atomic_set(&req->ctx->cq_timeouts,
5477 atomic_read(&req->ctx->cq_timeouts) + 1);
5479 io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5480 io_commit_cqring(ctx);
5481 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5483 io_cqring_ev_posted(ctx);
5484 req_set_fail_links(req);
5486 return HRTIMER_NORESTART;
5489 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5491 __must_hold(&ctx->completion_lock)
5493 struct io_timeout_data *io;
5494 struct io_kiocb *req;
5497 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5498 found = user_data == req->user_data;
5503 return ERR_PTR(-ENOENT);
5505 io = req->async_data;
5506 if (hrtimer_try_to_cancel(&io->timer) == -1)
5507 return ERR_PTR(-EALREADY);
5508 list_del_init(&req->timeout.list);
5512 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5513 __must_hold(&ctx->completion_lock)
5515 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5518 return PTR_ERR(req);
5520 req_set_fail_links(req);
5521 io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5522 io_put_req_deferred(req, 1);
5526 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5527 struct timespec64 *ts, enum hrtimer_mode mode)
5528 __must_hold(&ctx->completion_lock)
5530 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5531 struct io_timeout_data *data;
5534 return PTR_ERR(req);
5536 req->timeout.off = 0; /* noseq */
5537 data = req->async_data;
5538 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5539 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5540 data->timer.function = io_timeout_fn;
5541 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5545 static int io_timeout_remove_prep(struct io_kiocb *req,
5546 const struct io_uring_sqe *sqe)
5548 struct io_timeout_rem *tr = &req->timeout_rem;
5550 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5552 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5554 if (sqe->ioprio || sqe->buf_index || sqe->len)
5557 tr->addr = READ_ONCE(sqe->addr);
5558 tr->flags = READ_ONCE(sqe->timeout_flags);
5559 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5560 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5562 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5564 } else if (tr->flags) {
5565 /* timeout removal doesn't support flags */
5572 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5574 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5579 * Remove or update an existing timeout command
5581 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5583 struct io_timeout_rem *tr = &req->timeout_rem;
5584 struct io_ring_ctx *ctx = req->ctx;
5587 spin_lock_irq(&ctx->completion_lock);
5588 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5589 ret = io_timeout_cancel(ctx, tr->addr);
5591 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5592 io_translate_timeout_mode(tr->flags));
5594 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5595 io_commit_cqring(ctx);
5596 spin_unlock_irq(&ctx->completion_lock);
5597 io_cqring_ev_posted(ctx);
5599 req_set_fail_links(req);
5604 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5605 bool is_timeout_link)
5607 struct io_timeout_data *data;
5609 u32 off = READ_ONCE(sqe->off);
5611 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5613 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5615 if (off && is_timeout_link)
5617 flags = READ_ONCE(sqe->timeout_flags);
5618 if (flags & ~IORING_TIMEOUT_ABS)
5621 req->timeout.off = off;
5623 if (!req->async_data && io_alloc_async_data(req))
5626 data = req->async_data;
5629 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5632 data->mode = io_translate_timeout_mode(flags);
5633 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5634 if (is_timeout_link)
5635 io_req_track_inflight(req);
5639 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5641 struct io_ring_ctx *ctx = req->ctx;
5642 struct io_timeout_data *data = req->async_data;
5643 struct list_head *entry;
5644 u32 tail, off = req->timeout.off;
5646 spin_lock_irq(&ctx->completion_lock);
5649 * sqe->off holds how many events that need to occur for this
5650 * timeout event to be satisfied. If it isn't set, then this is
5651 * a pure timeout request, sequence isn't used.
5653 if (io_is_timeout_noseq(req)) {
5654 entry = ctx->timeout_list.prev;
5658 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5659 req->timeout.target_seq = tail + off;
5661 /* Update the last seq here in case io_flush_timeouts() hasn't.
5662 * This is safe because ->completion_lock is held, and submissions
5663 * and completions are never mixed in the same ->completion_lock section.
5665 ctx->cq_last_tm_flush = tail;
5668 * Insertion sort, ensuring the first entry in the list is always
5669 * the one we need first.
5671 list_for_each_prev(entry, &ctx->timeout_list) {
5672 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5675 if (io_is_timeout_noseq(nxt))
5677 /* nxt.seq is behind @tail, otherwise would've been completed */
5678 if (off >= nxt->timeout.target_seq - tail)
5682 list_add(&req->timeout.list, entry);
5683 data->timer.function = io_timeout_fn;
5684 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5685 spin_unlock_irq(&ctx->completion_lock);
5689 struct io_cancel_data {
5690 struct io_ring_ctx *ctx;
5694 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5696 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5697 struct io_cancel_data *cd = data;
5699 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5702 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5703 struct io_ring_ctx *ctx)
5705 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5706 enum io_wq_cancel cancel_ret;
5709 if (!tctx || !tctx->io_wq)
5712 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5713 switch (cancel_ret) {
5714 case IO_WQ_CANCEL_OK:
5717 case IO_WQ_CANCEL_RUNNING:
5720 case IO_WQ_CANCEL_NOTFOUND:
5728 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5729 struct io_kiocb *req, __u64 sqe_addr,
5732 unsigned long flags;
5735 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5736 spin_lock_irqsave(&ctx->completion_lock, flags);
5739 ret = io_timeout_cancel(ctx, sqe_addr);
5742 ret = io_poll_cancel(ctx, sqe_addr, false);
5746 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5747 io_commit_cqring(ctx);
5748 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5749 io_cqring_ev_posted(ctx);
5752 req_set_fail_links(req);
5755 static int io_async_cancel_prep(struct io_kiocb *req,
5756 const struct io_uring_sqe *sqe)
5758 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5760 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5762 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5765 req->cancel.addr = READ_ONCE(sqe->addr);
5769 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5771 struct io_ring_ctx *ctx = req->ctx;
5772 u64 sqe_addr = req->cancel.addr;
5773 struct io_tctx_node *node;
5776 /* tasks should wait for their io-wq threads, so safe w/o sync */
5777 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5778 spin_lock_irq(&ctx->completion_lock);
5781 ret = io_timeout_cancel(ctx, sqe_addr);
5784 ret = io_poll_cancel(ctx, sqe_addr, false);
5787 spin_unlock_irq(&ctx->completion_lock);
5789 /* slow path, try all io-wq's */
5790 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5792 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5793 struct io_uring_task *tctx = node->task->io_uring;
5795 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5799 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5801 spin_lock_irq(&ctx->completion_lock);
5803 io_cqring_fill_event(ctx, req->user_data, ret, 0);
5804 io_commit_cqring(ctx);
5805 spin_unlock_irq(&ctx->completion_lock);
5806 io_cqring_ev_posted(ctx);
5809 req_set_fail_links(req);
5814 static int io_rsrc_update_prep(struct io_kiocb *req,
5815 const struct io_uring_sqe *sqe)
5817 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5819 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5821 if (sqe->ioprio || sqe->rw_flags)
5824 req->rsrc_update.offset = READ_ONCE(sqe->off);
5825 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5826 if (!req->rsrc_update.nr_args)
5828 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5832 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5834 struct io_ring_ctx *ctx = req->ctx;
5835 struct io_uring_rsrc_update2 up;
5838 if (issue_flags & IO_URING_F_NONBLOCK)
5841 up.offset = req->rsrc_update.offset;
5842 up.data = req->rsrc_update.arg;
5847 mutex_lock(&ctx->uring_lock);
5848 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
5849 &up, req->rsrc_update.nr_args);
5850 mutex_unlock(&ctx->uring_lock);
5853 req_set_fail_links(req);
5854 __io_req_complete(req, issue_flags, ret, 0);
5858 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5860 switch (req->opcode) {
5863 case IORING_OP_READV:
5864 case IORING_OP_READ_FIXED:
5865 case IORING_OP_READ:
5866 return io_read_prep(req, sqe);
5867 case IORING_OP_WRITEV:
5868 case IORING_OP_WRITE_FIXED:
5869 case IORING_OP_WRITE:
5870 return io_write_prep(req, sqe);
5871 case IORING_OP_POLL_ADD:
5872 return io_poll_add_prep(req, sqe);
5873 case IORING_OP_POLL_REMOVE:
5874 return io_poll_update_prep(req, sqe);
5875 case IORING_OP_FSYNC:
5876 return io_fsync_prep(req, sqe);
5877 case IORING_OP_SYNC_FILE_RANGE:
5878 return io_sfr_prep(req, sqe);
5879 case IORING_OP_SENDMSG:
5880 case IORING_OP_SEND:
5881 return io_sendmsg_prep(req, sqe);
5882 case IORING_OP_RECVMSG:
5883 case IORING_OP_RECV:
5884 return io_recvmsg_prep(req, sqe);
5885 case IORING_OP_CONNECT:
5886 return io_connect_prep(req, sqe);
5887 case IORING_OP_TIMEOUT:
5888 return io_timeout_prep(req, sqe, false);
5889 case IORING_OP_TIMEOUT_REMOVE:
5890 return io_timeout_remove_prep(req, sqe);
5891 case IORING_OP_ASYNC_CANCEL:
5892 return io_async_cancel_prep(req, sqe);
5893 case IORING_OP_LINK_TIMEOUT:
5894 return io_timeout_prep(req, sqe, true);
5895 case IORING_OP_ACCEPT:
5896 return io_accept_prep(req, sqe);
5897 case IORING_OP_FALLOCATE:
5898 return io_fallocate_prep(req, sqe);
5899 case IORING_OP_OPENAT:
5900 return io_openat_prep(req, sqe);
5901 case IORING_OP_CLOSE:
5902 return io_close_prep(req, sqe);
5903 case IORING_OP_FILES_UPDATE:
5904 return io_rsrc_update_prep(req, sqe);
5905 case IORING_OP_STATX:
5906 return io_statx_prep(req, sqe);
5907 case IORING_OP_FADVISE:
5908 return io_fadvise_prep(req, sqe);
5909 case IORING_OP_MADVISE:
5910 return io_madvise_prep(req, sqe);
5911 case IORING_OP_OPENAT2:
5912 return io_openat2_prep(req, sqe);
5913 case IORING_OP_EPOLL_CTL:
5914 return io_epoll_ctl_prep(req, sqe);
5915 case IORING_OP_SPLICE:
5916 return io_splice_prep(req, sqe);
5917 case IORING_OP_PROVIDE_BUFFERS:
5918 return io_provide_buffers_prep(req, sqe);
5919 case IORING_OP_REMOVE_BUFFERS:
5920 return io_remove_buffers_prep(req, sqe);
5922 return io_tee_prep(req, sqe);
5923 case IORING_OP_SHUTDOWN:
5924 return io_shutdown_prep(req, sqe);
5925 case IORING_OP_RENAMEAT:
5926 return io_renameat_prep(req, sqe);
5927 case IORING_OP_UNLINKAT:
5928 return io_unlinkat_prep(req, sqe);
5931 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5936 static int io_req_prep_async(struct io_kiocb *req)
5938 if (!io_op_defs[req->opcode].needs_async_setup)
5940 if (WARN_ON_ONCE(req->async_data))
5942 if (io_alloc_async_data(req))
5945 switch (req->opcode) {
5946 case IORING_OP_READV:
5947 return io_rw_prep_async(req, READ);
5948 case IORING_OP_WRITEV:
5949 return io_rw_prep_async(req, WRITE);
5950 case IORING_OP_SENDMSG:
5951 return io_sendmsg_prep_async(req);
5952 case IORING_OP_RECVMSG:
5953 return io_recvmsg_prep_async(req);
5954 case IORING_OP_CONNECT:
5955 return io_connect_prep_async(req);
5957 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5962 static u32 io_get_sequence(struct io_kiocb *req)
5964 struct io_kiocb *pos;
5965 struct io_ring_ctx *ctx = req->ctx;
5966 u32 total_submitted, nr_reqs = 0;
5968 io_for_each_link(pos, req)
5971 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5972 return total_submitted - nr_reqs;
5975 static int io_req_defer(struct io_kiocb *req)
5977 struct io_ring_ctx *ctx = req->ctx;
5978 struct io_defer_entry *de;
5982 /* Still need defer if there is pending req in defer list. */
5983 if (likely(list_empty_careful(&ctx->defer_list) &&
5984 !(req->flags & REQ_F_IO_DRAIN)))
5987 seq = io_get_sequence(req);
5988 /* Still a chance to pass the sequence check */
5989 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5992 ret = io_req_prep_async(req);
5995 io_prep_async_link(req);
5996 de = kmalloc(sizeof(*de), GFP_KERNEL);
6000 spin_lock_irq(&ctx->completion_lock);
6001 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6002 spin_unlock_irq(&ctx->completion_lock);
6004 io_queue_async_work(req);
6005 return -EIOCBQUEUED;
6008 trace_io_uring_defer(ctx, req, req->user_data);
6011 list_add_tail(&de->list, &ctx->defer_list);
6012 spin_unlock_irq(&ctx->completion_lock);
6013 return -EIOCBQUEUED;
6016 static void io_clean_op(struct io_kiocb *req)
6018 if (req->flags & REQ_F_BUFFER_SELECTED) {
6019 switch (req->opcode) {
6020 case IORING_OP_READV:
6021 case IORING_OP_READ_FIXED:
6022 case IORING_OP_READ:
6023 kfree((void *)(unsigned long)req->rw.addr);
6025 case IORING_OP_RECVMSG:
6026 case IORING_OP_RECV:
6027 kfree(req->sr_msg.kbuf);
6030 req->flags &= ~REQ_F_BUFFER_SELECTED;
6033 if (req->flags & REQ_F_NEED_CLEANUP) {
6034 switch (req->opcode) {
6035 case IORING_OP_READV:
6036 case IORING_OP_READ_FIXED:
6037 case IORING_OP_READ:
6038 case IORING_OP_WRITEV:
6039 case IORING_OP_WRITE_FIXED:
6040 case IORING_OP_WRITE: {
6041 struct io_async_rw *io = req->async_data;
6043 kfree(io->free_iovec);
6046 case IORING_OP_RECVMSG:
6047 case IORING_OP_SENDMSG: {
6048 struct io_async_msghdr *io = req->async_data;
6050 kfree(io->free_iov);
6053 case IORING_OP_SPLICE:
6055 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6056 io_put_file(req->splice.file_in);
6058 case IORING_OP_OPENAT:
6059 case IORING_OP_OPENAT2:
6060 if (req->open.filename)
6061 putname(req->open.filename);
6063 case IORING_OP_RENAMEAT:
6064 putname(req->rename.oldpath);
6065 putname(req->rename.newpath);
6067 case IORING_OP_UNLINKAT:
6068 putname(req->unlink.filename);
6071 req->flags &= ~REQ_F_NEED_CLEANUP;
6073 if ((req->flags & REQ_F_POLLED) && req->apoll) {
6074 kfree(req->apoll->double_poll);
6078 if (req->flags & REQ_F_INFLIGHT) {
6079 struct io_uring_task *tctx = req->task->io_uring;
6081 atomic_dec(&tctx->inflight_tracked);
6082 req->flags &= ~REQ_F_INFLIGHT;
6086 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6088 struct io_ring_ctx *ctx = req->ctx;
6089 const struct cred *creds = NULL;
6092 if (req->work.creds && req->work.creds != current_cred())
6093 creds = override_creds(req->work.creds);
6095 switch (req->opcode) {
6097 ret = io_nop(req, issue_flags);
6099 case IORING_OP_READV:
6100 case IORING_OP_READ_FIXED:
6101 case IORING_OP_READ:
6102 ret = io_read(req, issue_flags);
6104 case IORING_OP_WRITEV:
6105 case IORING_OP_WRITE_FIXED:
6106 case IORING_OP_WRITE:
6107 ret = io_write(req, issue_flags);
6109 case IORING_OP_FSYNC:
6110 ret = io_fsync(req, issue_flags);
6112 case IORING_OP_POLL_ADD:
6113 ret = io_poll_add(req, issue_flags);
6115 case IORING_OP_POLL_REMOVE:
6116 ret = io_poll_update(req, issue_flags);
6118 case IORING_OP_SYNC_FILE_RANGE:
6119 ret = io_sync_file_range(req, issue_flags);
6121 case IORING_OP_SENDMSG:
6122 ret = io_sendmsg(req, issue_flags);
6124 case IORING_OP_SEND:
6125 ret = io_send(req, issue_flags);
6127 case IORING_OP_RECVMSG:
6128 ret = io_recvmsg(req, issue_flags);
6130 case IORING_OP_RECV:
6131 ret = io_recv(req, issue_flags);
6133 case IORING_OP_TIMEOUT:
6134 ret = io_timeout(req, issue_flags);
6136 case IORING_OP_TIMEOUT_REMOVE:
6137 ret = io_timeout_remove(req, issue_flags);
6139 case IORING_OP_ACCEPT:
6140 ret = io_accept(req, issue_flags);
6142 case IORING_OP_CONNECT:
6143 ret = io_connect(req, issue_flags);
6145 case IORING_OP_ASYNC_CANCEL:
6146 ret = io_async_cancel(req, issue_flags);
6148 case IORING_OP_FALLOCATE:
6149 ret = io_fallocate(req, issue_flags);
6151 case IORING_OP_OPENAT:
6152 ret = io_openat(req, issue_flags);
6154 case IORING_OP_CLOSE:
6155 ret = io_close(req, issue_flags);
6157 case IORING_OP_FILES_UPDATE:
6158 ret = io_files_update(req, issue_flags);
6160 case IORING_OP_STATX:
6161 ret = io_statx(req, issue_flags);
6163 case IORING_OP_FADVISE:
6164 ret = io_fadvise(req, issue_flags);
6166 case IORING_OP_MADVISE:
6167 ret = io_madvise(req, issue_flags);
6169 case IORING_OP_OPENAT2:
6170 ret = io_openat2(req, issue_flags);
6172 case IORING_OP_EPOLL_CTL:
6173 ret = io_epoll_ctl(req, issue_flags);
6175 case IORING_OP_SPLICE:
6176 ret = io_splice(req, issue_flags);
6178 case IORING_OP_PROVIDE_BUFFERS:
6179 ret = io_provide_buffers(req, issue_flags);
6181 case IORING_OP_REMOVE_BUFFERS:
6182 ret = io_remove_buffers(req, issue_flags);
6185 ret = io_tee(req, issue_flags);
6187 case IORING_OP_SHUTDOWN:
6188 ret = io_shutdown(req, issue_flags);
6190 case IORING_OP_RENAMEAT:
6191 ret = io_renameat(req, issue_flags);
6193 case IORING_OP_UNLINKAT:
6194 ret = io_unlinkat(req, issue_flags);
6202 revert_creds(creds);
6207 /* If the op doesn't have a file, we're not polling for it */
6208 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6209 const bool in_async = io_wq_current_is_worker();
6211 /* workqueue context doesn't hold uring_lock, grab it now */
6213 mutex_lock(&ctx->uring_lock);
6215 io_iopoll_req_issued(req, in_async);
6218 mutex_unlock(&ctx->uring_lock);
6224 static void io_wq_submit_work(struct io_wq_work *work)
6226 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6227 struct io_kiocb *timeout;
6230 timeout = io_prep_linked_timeout(req);
6232 io_queue_linked_timeout(timeout);
6234 if (work->flags & IO_WQ_WORK_CANCEL)
6239 ret = io_issue_sqe(req, 0);
6241 * We can get EAGAIN for polled IO even though we're
6242 * forcing a sync submission from here, since we can't
6243 * wait for request slots on the block side.
6251 /* avoid locking problems by failing it from a clean context */
6253 /* io-wq is going to take one down */
6255 io_req_task_queue_fail(req, ret);
6259 #define FFS_ASYNC_READ 0x1UL
6260 #define FFS_ASYNC_WRITE 0x2UL
6262 #define FFS_ISREG 0x4UL
6264 #define FFS_ISREG 0x0UL
6266 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6268 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
6271 struct io_fixed_file *table_l2;
6273 table_l2 = table->files[i >> IORING_FILE_TABLE_SHIFT];
6274 return &table_l2[i & IORING_FILE_TABLE_MASK];
6277 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6280 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
6282 return (struct file *) (slot->file_ptr & FFS_MASK);
6285 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6287 unsigned long file_ptr = (unsigned long) file;
6289 if (__io_file_supports_async(file, READ))
6290 file_ptr |= FFS_ASYNC_READ;
6291 if (__io_file_supports_async(file, WRITE))
6292 file_ptr |= FFS_ASYNC_WRITE;
6293 if (S_ISREG(file_inode(file)->i_mode))
6294 file_ptr |= FFS_ISREG;
6295 file_slot->file_ptr = file_ptr;
6298 static struct file *io_file_get(struct io_submit_state *state,
6299 struct io_kiocb *req, int fd, bool fixed)
6301 struct io_ring_ctx *ctx = req->ctx;
6305 unsigned long file_ptr;
6307 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6309 fd = array_index_nospec(fd, ctx->nr_user_files);
6310 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
6311 file = (struct file *) (file_ptr & FFS_MASK);
6312 file_ptr &= ~FFS_MASK;
6313 /* mask in overlapping REQ_F and FFS bits */
6314 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6315 io_req_set_rsrc_node(req);
6317 trace_io_uring_file_get(ctx, fd);
6318 file = __io_file_get(state, fd);
6320 /* we don't allow fixed io_uring files */
6321 if (file && unlikely(file->f_op == &io_uring_fops))
6322 io_req_track_inflight(req);
6328 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6330 struct io_timeout_data *data = container_of(timer,
6331 struct io_timeout_data, timer);
6332 struct io_kiocb *prev, *req = data->req;
6333 struct io_ring_ctx *ctx = req->ctx;
6334 unsigned long flags;
6336 spin_lock_irqsave(&ctx->completion_lock, flags);
6337 prev = req->timeout.head;
6338 req->timeout.head = NULL;
6341 * We don't expect the list to be empty, that will only happen if we
6342 * race with the completion of the linked work.
6344 if (prev && req_ref_inc_not_zero(prev))
6345 io_remove_next_linked(prev);
6348 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6351 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6352 io_put_req_deferred(prev, 1);
6354 io_req_complete_post(req, -ETIME, 0);
6356 io_put_req_deferred(req, 1);
6357 return HRTIMER_NORESTART;
6360 static void io_queue_linked_timeout(struct io_kiocb *req)
6362 struct io_ring_ctx *ctx = req->ctx;
6364 spin_lock_irq(&ctx->completion_lock);
6366 * If the back reference is NULL, then our linked request finished
6367 * before we got a chance to setup the timer
6369 if (req->timeout.head) {
6370 struct io_timeout_data *data = req->async_data;
6372 data->timer.function = io_link_timeout_fn;
6373 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6376 spin_unlock_irq(&ctx->completion_lock);
6377 /* drop submission reference */
6381 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6383 struct io_kiocb *nxt = req->link;
6385 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6386 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6389 nxt->timeout.head = req;
6390 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6391 req->flags |= REQ_F_LINK_TIMEOUT;
6395 static void __io_queue_sqe(struct io_kiocb *req)
6397 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6400 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6403 * We async punt it if the file wasn't marked NOWAIT, or if the file
6404 * doesn't support non-blocking read/write attempts
6407 /* drop submission reference */
6408 if (req->flags & REQ_F_COMPLETE_INLINE) {
6409 struct io_ring_ctx *ctx = req->ctx;
6410 struct io_comp_state *cs = &ctx->submit_state.comp;
6412 cs->reqs[cs->nr++] = req;
6413 if (cs->nr == ARRAY_SIZE(cs->reqs))
6414 io_submit_flush_completions(cs, ctx);
6418 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6419 if (!io_arm_poll_handler(req)) {
6421 * Queued up for async execution, worker will release
6422 * submit reference when the iocb is actually submitted.
6424 io_queue_async_work(req);
6427 io_req_complete_failed(req, ret);
6430 io_queue_linked_timeout(linked_timeout);
6433 static void io_queue_sqe(struct io_kiocb *req)
6437 ret = io_req_defer(req);
6439 if (ret != -EIOCBQUEUED) {
6441 io_req_complete_failed(req, ret);
6443 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6444 ret = io_req_prep_async(req);
6447 io_queue_async_work(req);
6449 __io_queue_sqe(req);
6454 * Check SQE restrictions (opcode and flags).
6456 * Returns 'true' if SQE is allowed, 'false' otherwise.
6458 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6459 struct io_kiocb *req,
6460 unsigned int sqe_flags)
6462 if (!ctx->restricted)
6465 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6468 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6469 ctx->restrictions.sqe_flags_required)
6472 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6473 ctx->restrictions.sqe_flags_required))
6479 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6480 const struct io_uring_sqe *sqe)
6482 struct io_submit_state *state;
6483 unsigned int sqe_flags;
6484 int personality, ret = 0;
6486 req->opcode = READ_ONCE(sqe->opcode);
6487 /* same numerical values with corresponding REQ_F_*, safe to copy */
6488 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6489 req->user_data = READ_ONCE(sqe->user_data);
6490 req->async_data = NULL;
6494 req->fixed_rsrc_refs = NULL;
6495 /* one is dropped after submission, the other at completion */
6496 atomic_set(&req->refs, 2);
6497 req->task = current;
6499 req->work.creds = NULL;
6501 /* enforce forwards compatibility on users */
6502 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6507 if (unlikely(req->opcode >= IORING_OP_LAST))
6510 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6513 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6514 !io_op_defs[req->opcode].buffer_select)
6517 personality = READ_ONCE(sqe->personality);
6519 req->work.creds = xa_load(&ctx->personalities, personality);
6520 if (!req->work.creds)
6522 get_cred(req->work.creds);
6524 state = &ctx->submit_state;
6527 * Plug now if we have more than 1 IO left after this, and the target
6528 * is potentially a read/write to block based storage.
6530 if (!state->plug_started && state->ios_left > 1 &&
6531 io_op_defs[req->opcode].plug) {
6532 blk_start_plug(&state->plug);
6533 state->plug_started = true;
6536 if (io_op_defs[req->opcode].needs_file) {
6537 bool fixed = req->flags & REQ_F_FIXED_FILE;
6539 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6540 if (unlikely(!req->file))
6548 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6549 const struct io_uring_sqe *sqe)
6551 struct io_submit_link *link = &ctx->submit_state.link;
6554 ret = io_init_req(ctx, req, sqe);
6555 if (unlikely(ret)) {
6558 /* fail even hard links since we don't submit */
6559 link->head->flags |= REQ_F_FAIL_LINK;
6560 io_req_complete_failed(link->head, -ECANCELED);
6563 io_req_complete_failed(req, ret);
6566 ret = io_req_prep(req, sqe);
6570 /* don't need @sqe from now on */
6571 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6572 true, ctx->flags & IORING_SETUP_SQPOLL);
6575 * If we already have a head request, queue this one for async
6576 * submittal once the head completes. If we don't have a head but
6577 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6578 * submitted sync once the chain is complete. If none of those
6579 * conditions are true (normal request), then just queue it.
6582 struct io_kiocb *head = link->head;
6585 * Taking sequential execution of a link, draining both sides
6586 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6587 * requests in the link. So, it drains the head and the
6588 * next after the link request. The last one is done via
6589 * drain_next flag to persist the effect across calls.
6591 if (req->flags & REQ_F_IO_DRAIN) {
6592 head->flags |= REQ_F_IO_DRAIN;
6593 ctx->drain_next = 1;
6595 ret = io_req_prep_async(req);
6598 trace_io_uring_link(ctx, req, head);
6599 link->last->link = req;
6602 /* last request of a link, enqueue the link */
6603 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6608 if (unlikely(ctx->drain_next)) {
6609 req->flags |= REQ_F_IO_DRAIN;
6610 ctx->drain_next = 0;
6612 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6624 * Batched submission is done, ensure local IO is flushed out.
6626 static void io_submit_state_end(struct io_submit_state *state,
6627 struct io_ring_ctx *ctx)
6629 if (state->link.head)
6630 io_queue_sqe(state->link.head);
6632 io_submit_flush_completions(&state->comp, ctx);
6633 if (state->plug_started)
6634 blk_finish_plug(&state->plug);
6635 io_state_file_put(state);
6639 * Start submission side cache.
6641 static void io_submit_state_start(struct io_submit_state *state,
6642 unsigned int max_ios)
6644 state->plug_started = false;
6645 state->ios_left = max_ios;
6646 /* set only head, no need to init link_last in advance */
6647 state->link.head = NULL;
6650 static void io_commit_sqring(struct io_ring_ctx *ctx)
6652 struct io_rings *rings = ctx->rings;
6655 * Ensure any loads from the SQEs are done at this point,
6656 * since once we write the new head, the application could
6657 * write new data to them.
6659 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6663 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6664 * that is mapped by userspace. This means that care needs to be taken to
6665 * ensure that reads are stable, as we cannot rely on userspace always
6666 * being a good citizen. If members of the sqe are validated and then later
6667 * used, it's important that those reads are done through READ_ONCE() to
6668 * prevent a re-load down the line.
6670 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6672 u32 *sq_array = ctx->sq_array;
6676 * The cached sq head (or cq tail) serves two purposes:
6678 * 1) allows us to batch the cost of updating the user visible
6680 * 2) allows the kernel side to track the head on its own, even
6681 * though the application is the one updating it.
6683 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6684 if (likely(head < ctx->sq_entries))
6685 return &ctx->sq_sqes[head];
6687 /* drop invalid entries */
6688 ctx->cached_sq_dropped++;
6689 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6693 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6697 /* make sure SQ entry isn't read before tail */
6698 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6700 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6703 percpu_counter_add(¤t->io_uring->inflight, nr);
6704 refcount_add(nr, ¤t->usage);
6705 io_submit_state_start(&ctx->submit_state, nr);
6707 while (submitted < nr) {
6708 const struct io_uring_sqe *sqe;
6709 struct io_kiocb *req;
6711 req = io_alloc_req(ctx);
6712 if (unlikely(!req)) {
6714 submitted = -EAGAIN;
6717 sqe = io_get_sqe(ctx);
6718 if (unlikely(!sqe)) {
6719 kmem_cache_free(req_cachep, req);
6722 /* will complete beyond this point, count as submitted */
6724 if (io_submit_sqe(ctx, req, sqe))
6728 if (unlikely(submitted != nr)) {
6729 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6730 struct io_uring_task *tctx = current->io_uring;
6731 int unused = nr - ref_used;
6733 percpu_ref_put_many(&ctx->refs, unused);
6734 percpu_counter_sub(&tctx->inflight, unused);
6735 put_task_struct_many(current, unused);
6738 io_submit_state_end(&ctx->submit_state, ctx);
6739 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6740 io_commit_sqring(ctx);
6745 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6747 /* Tell userspace we may need a wakeup call */
6748 spin_lock_irq(&ctx->completion_lock);
6749 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6750 spin_unlock_irq(&ctx->completion_lock);
6753 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6755 spin_lock_irq(&ctx->completion_lock);
6756 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6757 spin_unlock_irq(&ctx->completion_lock);
6760 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6762 unsigned int to_submit;
6765 to_submit = io_sqring_entries(ctx);
6766 /* if we're handling multiple rings, cap submit size for fairness */
6767 if (cap_entries && to_submit > 8)
6770 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6771 unsigned nr_events = 0;
6773 mutex_lock(&ctx->uring_lock);
6774 if (!list_empty(&ctx->iopoll_list))
6775 io_do_iopoll(ctx, &nr_events, 0);
6778 * Don't submit if refs are dying, good for io_uring_register(),
6779 * but also it is relied upon by io_ring_exit_work()
6781 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6782 !(ctx->flags & IORING_SETUP_R_DISABLED))
6783 ret = io_submit_sqes(ctx, to_submit);
6784 mutex_unlock(&ctx->uring_lock);
6787 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6788 wake_up(&ctx->sqo_sq_wait);
6793 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6795 struct io_ring_ctx *ctx;
6796 unsigned sq_thread_idle = 0;
6798 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6799 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6800 sqd->sq_thread_idle = sq_thread_idle;
6803 static int io_sq_thread(void *data)
6805 struct io_sq_data *sqd = data;
6806 struct io_ring_ctx *ctx;
6807 unsigned long timeout = 0;
6808 char buf[TASK_COMM_LEN];
6811 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6812 set_task_comm(current, buf);
6814 if (sqd->sq_cpu != -1)
6815 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6817 set_cpus_allowed_ptr(current, cpu_online_mask);
6818 current->flags |= PF_NO_SETAFFINITY;
6820 mutex_lock(&sqd->lock);
6821 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6823 bool cap_entries, sqt_spin, needs_sched;
6825 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6826 signal_pending(current)) {
6827 bool did_sig = false;
6829 mutex_unlock(&sqd->lock);
6830 if (signal_pending(current)) {
6831 struct ksignal ksig;
6833 did_sig = get_signal(&ksig);
6836 mutex_lock(&sqd->lock);
6840 io_run_task_work_head(&sqd->park_task_work);
6841 timeout = jiffies + sqd->sq_thread_idle;
6845 cap_entries = !list_is_singular(&sqd->ctx_list);
6846 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6847 const struct cred *creds = NULL;
6849 if (ctx->sq_creds != current_cred())
6850 creds = override_creds(ctx->sq_creds);
6851 ret = __io_sq_thread(ctx, cap_entries);
6853 revert_creds(creds);
6854 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6858 if (sqt_spin || !time_after(jiffies, timeout)) {
6862 timeout = jiffies + sqd->sq_thread_idle;
6866 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6867 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6868 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6869 io_ring_set_wakeup_flag(ctx);
6872 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6873 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6874 !list_empty_careful(&ctx->iopoll_list)) {
6875 needs_sched = false;
6878 if (io_sqring_entries(ctx)) {
6879 needs_sched = false;
6885 mutex_unlock(&sqd->lock);
6887 mutex_lock(&sqd->lock);
6889 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6890 io_ring_clear_wakeup_flag(ctx);
6893 finish_wait(&sqd->wait, &wait);
6894 io_run_task_work_head(&sqd->park_task_work);
6895 timeout = jiffies + sqd->sq_thread_idle;
6898 io_uring_cancel_sqpoll(sqd);
6900 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6901 io_ring_set_wakeup_flag(ctx);
6903 io_run_task_work_head(&sqd->park_task_work);
6904 mutex_unlock(&sqd->lock);
6906 complete(&sqd->exited);
6910 struct io_wait_queue {
6911 struct wait_queue_entry wq;
6912 struct io_ring_ctx *ctx;
6914 unsigned nr_timeouts;
6917 static inline bool io_should_wake(struct io_wait_queue *iowq)
6919 struct io_ring_ctx *ctx = iowq->ctx;
6922 * Wake up if we have enough events, or if a timeout occurred since we
6923 * started waiting. For timeouts, we always want to return to userspace,
6924 * regardless of event count.
6926 return io_cqring_events(ctx) >= iowq->to_wait ||
6927 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6930 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6931 int wake_flags, void *key)
6933 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6937 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6938 * the task, and the next invocation will do it.
6940 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6941 return autoremove_wake_function(curr, mode, wake_flags, key);
6945 static int io_run_task_work_sig(void)
6947 if (io_run_task_work())
6949 if (!signal_pending(current))
6951 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6952 return -ERESTARTSYS;
6956 /* when returns >0, the caller should retry */
6957 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6958 struct io_wait_queue *iowq,
6959 signed long *timeout)
6963 /* make sure we run task_work before checking for signals */
6964 ret = io_run_task_work_sig();
6965 if (ret || io_should_wake(iowq))
6967 /* let the caller flush overflows, retry */
6968 if (test_bit(0, &ctx->cq_check_overflow))
6971 *timeout = schedule_timeout(*timeout);
6972 return !*timeout ? -ETIME : 1;
6976 * Wait until events become available, if we don't already have some. The
6977 * application must reap them itself, as they reside on the shared cq ring.
6979 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6980 const sigset_t __user *sig, size_t sigsz,
6981 struct __kernel_timespec __user *uts)
6983 struct io_wait_queue iowq = {
6986 .func = io_wake_function,
6987 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6990 .to_wait = min_events,
6992 struct io_rings *rings = ctx->rings;
6993 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6997 io_cqring_overflow_flush(ctx, false);
6998 if (io_cqring_events(ctx) >= min_events)
7000 if (!io_run_task_work())
7005 #ifdef CONFIG_COMPAT
7006 if (in_compat_syscall())
7007 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7011 ret = set_user_sigmask(sig, sigsz);
7018 struct timespec64 ts;
7020 if (get_timespec64(&ts, uts))
7022 timeout = timespec64_to_jiffies(&ts);
7025 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7026 trace_io_uring_cqring_wait(ctx, min_events);
7028 /* if we can't even flush overflow, don't wait for more */
7029 if (!io_cqring_overflow_flush(ctx, false)) {
7033 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7034 TASK_INTERRUPTIBLE);
7035 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7036 finish_wait(&ctx->wait, &iowq.wq);
7040 restore_saved_sigmask_unless(ret == -EINTR);
7042 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7045 static void io_free_file_tables(struct io_file_table *table, unsigned nr_files)
7047 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7049 for (i = 0; i < nr_tables; i++)
7050 kfree(table->files[i]);
7051 kfree(table->files);
7052 table->files = NULL;
7055 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7057 spin_lock_bh(&ctx->rsrc_ref_lock);
7060 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7062 spin_unlock_bh(&ctx->rsrc_ref_lock);
7065 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7067 percpu_ref_exit(&ref_node->refs);
7071 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7072 struct io_rsrc_data *data_to_kill)
7074 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7075 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7078 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7080 rsrc_node->rsrc_data = data_to_kill;
7081 io_rsrc_ref_lock(ctx);
7082 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7083 io_rsrc_ref_unlock(ctx);
7085 atomic_inc(&data_to_kill->refs);
7086 percpu_ref_kill(&rsrc_node->refs);
7087 ctx->rsrc_node = NULL;
7090 if (!ctx->rsrc_node) {
7091 ctx->rsrc_node = ctx->rsrc_backup_node;
7092 ctx->rsrc_backup_node = NULL;
7096 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7098 if (ctx->rsrc_backup_node)
7100 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7101 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7104 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7108 /* As we may drop ->uring_lock, other task may have started quiesce */
7112 data->quiesce = true;
7114 ret = io_rsrc_node_switch_start(ctx);
7117 io_rsrc_node_switch(ctx, data);
7119 /* kill initial ref, already quiesced if zero */
7120 if (atomic_dec_and_test(&data->refs))
7122 flush_delayed_work(&ctx->rsrc_put_work);
7123 ret = wait_for_completion_interruptible(&data->done);
7127 atomic_inc(&data->refs);
7128 /* wait for all works potentially completing data->done */
7129 flush_delayed_work(&ctx->rsrc_put_work);
7130 reinit_completion(&data->done);
7132 mutex_unlock(&ctx->uring_lock);
7133 ret = io_run_task_work_sig();
7134 mutex_lock(&ctx->uring_lock);
7136 data->quiesce = false;
7141 static void io_rsrc_data_free(struct io_rsrc_data *data)
7147 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7148 rsrc_put_fn *do_put,
7151 struct io_rsrc_data *data;
7153 data = kzalloc(sizeof(*data), GFP_KERNEL);
7157 data->tags = kvcalloc(nr, sizeof(*data->tags), GFP_KERNEL);
7163 atomic_set(&data->refs, 1);
7165 data->do_put = do_put;
7166 init_completion(&data->done);
7170 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7172 #if defined(CONFIG_UNIX)
7173 if (ctx->ring_sock) {
7174 struct sock *sock = ctx->ring_sock->sk;
7175 struct sk_buff *skb;
7177 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7183 for (i = 0; i < ctx->nr_user_files; i++) {
7186 file = io_file_from_index(ctx, i);
7191 io_free_file_tables(&ctx->file_table, ctx->nr_user_files);
7192 io_rsrc_data_free(ctx->file_data);
7193 ctx->file_data = NULL;
7194 ctx->nr_user_files = 0;
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;
7274 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7276 struct io_ring_ctx *ctx_attach;
7277 struct io_sq_data *sqd;
7280 f = fdget(p->wq_fd);
7282 return ERR_PTR(-ENXIO);
7283 if (f.file->f_op != &io_uring_fops) {
7285 return ERR_PTR(-EINVAL);
7288 ctx_attach = f.file->private_data;
7289 sqd = ctx_attach->sq_data;
7292 return ERR_PTR(-EINVAL);
7294 if (sqd->task_tgid != current->tgid) {
7296 return ERR_PTR(-EPERM);
7299 refcount_inc(&sqd->refs);
7304 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7307 struct io_sq_data *sqd;
7310 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7311 sqd = io_attach_sq_data(p);
7316 /* fall through for EPERM case, setup new sqd/task */
7317 if (PTR_ERR(sqd) != -EPERM)
7321 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7323 return ERR_PTR(-ENOMEM);
7325 atomic_set(&sqd->park_pending, 0);
7326 refcount_set(&sqd->refs, 1);
7327 INIT_LIST_HEAD(&sqd->ctx_list);
7328 mutex_init(&sqd->lock);
7329 init_waitqueue_head(&sqd->wait);
7330 init_completion(&sqd->exited);
7334 #if defined(CONFIG_UNIX)
7336 * Ensure the UNIX gc is aware of our file set, so we are certain that
7337 * the io_uring can be safely unregistered on process exit, even if we have
7338 * loops in the file referencing.
7340 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7342 struct sock *sk = ctx->ring_sock->sk;
7343 struct scm_fp_list *fpl;
7344 struct sk_buff *skb;
7347 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7351 skb = alloc_skb(0, GFP_KERNEL);
7360 fpl->user = get_uid(current_user());
7361 for (i = 0; i < nr; i++) {
7362 struct file *file = io_file_from_index(ctx, i + offset);
7366 fpl->fp[nr_files] = get_file(file);
7367 unix_inflight(fpl->user, fpl->fp[nr_files]);
7372 fpl->max = SCM_MAX_FD;
7373 fpl->count = nr_files;
7374 UNIXCB(skb).fp = fpl;
7375 skb->destructor = unix_destruct_scm;
7376 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7377 skb_queue_head(&sk->sk_receive_queue, skb);
7379 for (i = 0; i < nr_files; i++)
7390 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7391 * causes regular reference counting to break down. We rely on the UNIX
7392 * garbage collection to take care of this problem for us.
7394 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7396 unsigned left, total;
7400 left = ctx->nr_user_files;
7402 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7404 ret = __io_sqe_files_scm(ctx, this_files, total);
7408 total += this_files;
7414 while (total < ctx->nr_user_files) {
7415 struct file *file = io_file_from_index(ctx, total);
7425 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7431 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
7433 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7435 table->files = kcalloc(nr_tables, sizeof(*table->files), GFP_KERNEL);
7439 for (i = 0; i < nr_tables; i++) {
7440 unsigned int this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7442 table->files[i] = kcalloc(this_files, sizeof(*table->files[i]),
7444 if (!table->files[i])
7446 nr_files -= this_files;
7452 io_free_file_tables(table, nr_tables * IORING_MAX_FILES_TABLE);
7456 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7458 struct file *file = prsrc->file;
7459 #if defined(CONFIG_UNIX)
7460 struct sock *sock = ctx->ring_sock->sk;
7461 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7462 struct sk_buff *skb;
7465 __skb_queue_head_init(&list);
7468 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7469 * remove this entry and rearrange the file array.
7471 skb = skb_dequeue(head);
7473 struct scm_fp_list *fp;
7475 fp = UNIXCB(skb).fp;
7476 for (i = 0; i < fp->count; i++) {
7479 if (fp->fp[i] != file)
7482 unix_notinflight(fp->user, fp->fp[i]);
7483 left = fp->count - 1 - i;
7485 memmove(&fp->fp[i], &fp->fp[i + 1],
7486 left * sizeof(struct file *));
7493 __skb_queue_tail(&list, skb);
7503 __skb_queue_tail(&list, skb);
7505 skb = skb_dequeue(head);
7508 if (skb_peek(&list)) {
7509 spin_lock_irq(&head->lock);
7510 while ((skb = __skb_dequeue(&list)) != NULL)
7511 __skb_queue_tail(head, skb);
7512 spin_unlock_irq(&head->lock);
7519 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7521 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7522 struct io_ring_ctx *ctx = rsrc_data->ctx;
7523 struct io_rsrc_put *prsrc, *tmp;
7525 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7526 list_del(&prsrc->list);
7529 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
7530 unsigned long flags;
7532 io_ring_submit_lock(ctx, lock_ring);
7533 spin_lock_irqsave(&ctx->completion_lock, flags);
7534 io_cqring_fill_event(ctx, prsrc->tag, 0, 0);
7535 io_commit_cqring(ctx);
7536 spin_unlock_irqrestore(&ctx->completion_lock, flags);
7537 io_cqring_ev_posted(ctx);
7538 io_ring_submit_unlock(ctx, lock_ring);
7541 rsrc_data->do_put(ctx, prsrc);
7545 io_rsrc_node_destroy(ref_node);
7546 if (atomic_dec_and_test(&rsrc_data->refs))
7547 complete(&rsrc_data->done);
7550 static void io_rsrc_put_work(struct work_struct *work)
7552 struct io_ring_ctx *ctx;
7553 struct llist_node *node;
7555 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7556 node = llist_del_all(&ctx->rsrc_put_llist);
7559 struct io_rsrc_node *ref_node;
7560 struct llist_node *next = node->next;
7562 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7563 __io_rsrc_put_work(ref_node);
7568 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7570 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7571 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
7572 bool first_add = false;
7574 io_rsrc_ref_lock(ctx);
7577 while (!list_empty(&ctx->rsrc_ref_list)) {
7578 node = list_first_entry(&ctx->rsrc_ref_list,
7579 struct io_rsrc_node, node);
7580 /* recycle ref nodes in order */
7583 list_del(&node->node);
7584 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7586 io_rsrc_ref_unlock(ctx);
7589 mod_delayed_work(system_wq, &ctx->rsrc_put_work, HZ);
7592 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7594 struct io_rsrc_node *ref_node;
7596 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7600 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7605 INIT_LIST_HEAD(&ref_node->node);
7606 INIT_LIST_HEAD(&ref_node->rsrc_list);
7607 ref_node->done = false;
7611 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7612 unsigned nr_args, u64 __user *tags)
7614 __s32 __user *fds = (__s32 __user *) arg;
7618 struct io_rsrc_data *file_data;
7624 if (nr_args > IORING_MAX_FIXED_FILES)
7626 ret = io_rsrc_node_switch_start(ctx);
7630 file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put, nr_args);
7633 ctx->file_data = file_data;
7635 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
7638 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7641 if ((tags && copy_from_user(&tag, &tags[i], sizeof(tag))) ||
7642 copy_from_user(&fd, &fds[i], sizeof(fd))) {
7646 /* allow sparse sets */
7656 if (unlikely(!file))
7660 * Don't allow io_uring instances to be registered. If UNIX
7661 * isn't enabled, then this causes a reference cycle and this
7662 * instance can never get freed. If UNIX is enabled we'll
7663 * handle it just fine, but there's still no point in allowing
7664 * a ring fd as it doesn't support regular read/write anyway.
7666 if (file->f_op == &io_uring_fops) {
7670 ctx->file_data->tags[i] = tag;
7671 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
7674 ret = io_sqe_files_scm(ctx);
7676 __io_sqe_files_unregister(ctx);
7680 io_rsrc_node_switch(ctx, NULL);
7683 for (i = 0; i < ctx->nr_user_files; i++) {
7684 file = io_file_from_index(ctx, i);
7688 io_free_file_tables(&ctx->file_table, nr_args);
7689 ctx->nr_user_files = 0;
7691 io_rsrc_data_free(ctx->file_data);
7692 ctx->file_data = NULL;
7696 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7699 #if defined(CONFIG_UNIX)
7700 struct sock *sock = ctx->ring_sock->sk;
7701 struct sk_buff_head *head = &sock->sk_receive_queue;
7702 struct sk_buff *skb;
7705 * See if we can merge this file into an existing skb SCM_RIGHTS
7706 * file set. If there's no room, fall back to allocating a new skb
7707 * and filling it in.
7709 spin_lock_irq(&head->lock);
7710 skb = skb_peek(head);
7712 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7714 if (fpl->count < SCM_MAX_FD) {
7715 __skb_unlink(skb, head);
7716 spin_unlock_irq(&head->lock);
7717 fpl->fp[fpl->count] = get_file(file);
7718 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7720 spin_lock_irq(&head->lock);
7721 __skb_queue_head(head, skb);
7726 spin_unlock_irq(&head->lock);
7733 return __io_sqe_files_scm(ctx, 1, index);
7739 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
7740 struct io_rsrc_node *node, void *rsrc)
7742 struct io_rsrc_put *prsrc;
7744 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7748 prsrc->tag = data->tags[idx];
7750 list_add(&prsrc->list, &node->rsrc_list);
7754 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7755 struct io_uring_rsrc_update2 *up,
7758 u64 __user *tags = u64_to_user_ptr(up->tags);
7759 __s32 __user *fds = u64_to_user_ptr(up->data);
7760 struct io_rsrc_data *data = ctx->file_data;
7761 struct io_fixed_file *file_slot;
7765 bool needs_switch = false;
7767 if (!ctx->file_data)
7769 if (up->offset + nr_args > ctx->nr_user_files)
7772 for (done = 0; done < nr_args; done++) {
7775 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
7776 copy_from_user(&fd, &fds[done], sizeof(fd))) {
7780 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
7784 if (fd == IORING_REGISTER_FILES_SKIP)
7787 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7788 file_slot = io_fixed_file_slot(&ctx->file_table, i);
7790 if (file_slot->file_ptr) {
7791 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7792 err = io_queue_rsrc_removal(data, up->offset + done,
7793 ctx->rsrc_node, file);
7796 file_slot->file_ptr = 0;
7797 needs_switch = true;
7806 * Don't allow io_uring instances to be registered. If
7807 * UNIX isn't enabled, then this causes a reference
7808 * cycle and this instance can never get freed. If UNIX
7809 * is enabled we'll handle it just fine, but there's
7810 * still no point in allowing a ring fd as it doesn't
7811 * support regular read/write anyway.
7813 if (file->f_op == &io_uring_fops) {
7818 data->tags[up->offset + done] = tag;
7819 io_fixed_file_set(file_slot, file);
7820 err = io_sqe_file_register(ctx, file, i);
7822 file_slot->file_ptr = 0;
7830 io_rsrc_node_switch(ctx, data);
7831 return done ? done : err;
7834 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7836 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7838 req = io_put_req_find_next(req);
7839 return req ? &req->work : NULL;
7842 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7843 struct task_struct *task)
7845 struct io_wq_hash *hash;
7846 struct io_wq_data data;
7847 unsigned int concurrency;
7849 hash = ctx->hash_map;
7851 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7853 return ERR_PTR(-ENOMEM);
7854 refcount_set(&hash->refs, 1);
7855 init_waitqueue_head(&hash->wait);
7856 ctx->hash_map = hash;
7861 data.free_work = io_free_work;
7862 data.do_work = io_wq_submit_work;
7864 /* Do QD, or 4 * CPUS, whatever is smallest */
7865 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7867 return io_wq_create(concurrency, &data);
7870 static int io_uring_alloc_task_context(struct task_struct *task,
7871 struct io_ring_ctx *ctx)
7873 struct io_uring_task *tctx;
7876 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7877 if (unlikely(!tctx))
7880 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7881 if (unlikely(ret)) {
7886 tctx->io_wq = io_init_wq_offload(ctx, task);
7887 if (IS_ERR(tctx->io_wq)) {
7888 ret = PTR_ERR(tctx->io_wq);
7889 percpu_counter_destroy(&tctx->inflight);
7895 init_waitqueue_head(&tctx->wait);
7897 atomic_set(&tctx->in_idle, 0);
7898 atomic_set(&tctx->inflight_tracked, 0);
7899 task->io_uring = tctx;
7900 spin_lock_init(&tctx->task_lock);
7901 INIT_WQ_LIST(&tctx->task_list);
7902 tctx->task_state = 0;
7903 init_task_work(&tctx->task_work, tctx_task_work);
7907 void __io_uring_free(struct task_struct *tsk)
7909 struct io_uring_task *tctx = tsk->io_uring;
7911 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7912 WARN_ON_ONCE(tctx->io_wq);
7914 percpu_counter_destroy(&tctx->inflight);
7916 tsk->io_uring = NULL;
7919 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7920 struct io_uring_params *p)
7924 /* Retain compatibility with failing for an invalid attach attempt */
7925 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7926 IORING_SETUP_ATTACH_WQ) {
7929 f = fdget(p->wq_fd);
7933 if (f.file->f_op != &io_uring_fops)
7936 if (ctx->flags & IORING_SETUP_SQPOLL) {
7937 struct task_struct *tsk;
7938 struct io_sq_data *sqd;
7941 sqd = io_get_sq_data(p, &attached);
7947 ctx->sq_creds = get_current_cred();
7949 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7950 if (!ctx->sq_thread_idle)
7951 ctx->sq_thread_idle = HZ;
7953 io_sq_thread_park(sqd);
7954 list_add(&ctx->sqd_list, &sqd->ctx_list);
7955 io_sqd_update_thread_idle(sqd);
7956 /* don't attach to a dying SQPOLL thread, would be racy */
7957 ret = (attached && !sqd->thread) ? -ENXIO : 0;
7958 io_sq_thread_unpark(sqd);
7965 if (p->flags & IORING_SETUP_SQ_AFF) {
7966 int cpu = p->sq_thread_cpu;
7969 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
7976 sqd->task_pid = current->pid;
7977 sqd->task_tgid = current->tgid;
7978 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7985 ret = io_uring_alloc_task_context(tsk, ctx);
7986 wake_up_new_task(tsk);
7989 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7990 /* Can't have SQ_AFF without SQPOLL */
7997 complete(&ctx->sq_data->exited);
7999 io_sq_thread_finish(ctx);
8003 static inline void __io_unaccount_mem(struct user_struct *user,
8004 unsigned long nr_pages)
8006 atomic_long_sub(nr_pages, &user->locked_vm);
8009 static inline int __io_account_mem(struct user_struct *user,
8010 unsigned long nr_pages)
8012 unsigned long page_limit, cur_pages, new_pages;
8014 /* Don't allow more pages than we can safely lock */
8015 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8018 cur_pages = atomic_long_read(&user->locked_vm);
8019 new_pages = cur_pages + nr_pages;
8020 if (new_pages > page_limit)
8022 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8023 new_pages) != cur_pages);
8028 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8031 __io_unaccount_mem(ctx->user, nr_pages);
8033 if (ctx->mm_account)
8034 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8037 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8042 ret = __io_account_mem(ctx->user, nr_pages);
8047 if (ctx->mm_account)
8048 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8053 static void io_mem_free(void *ptr)
8060 page = virt_to_head_page(ptr);
8061 if (put_page_testzero(page))
8062 free_compound_page(page);
8065 static void *io_mem_alloc(size_t size)
8067 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8068 __GFP_NORETRY | __GFP_ACCOUNT;
8070 return (void *) __get_free_pages(gfp_flags, get_order(size));
8073 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8076 struct io_rings *rings;
8077 size_t off, sq_array_size;
8079 off = struct_size(rings, cqes, cq_entries);
8080 if (off == SIZE_MAX)
8084 off = ALIGN(off, SMP_CACHE_BYTES);
8092 sq_array_size = array_size(sizeof(u32), sq_entries);
8093 if (sq_array_size == SIZE_MAX)
8096 if (check_add_overflow(off, sq_array_size, &off))
8102 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
8104 struct io_mapped_ubuf *imu = *slot;
8107 for (i = 0; i < imu->nr_bvecs; i++)
8108 unpin_user_page(imu->bvec[i].bv_page);
8109 if (imu->acct_pages)
8110 io_unaccount_mem(ctx, imu->acct_pages);
8115 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
8117 io_buffer_unmap(ctx, &prsrc->buf);
8121 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8125 for (i = 0; i < ctx->nr_user_bufs; i++)
8126 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
8127 kfree(ctx->user_bufs);
8128 kfree(ctx->buf_data);
8129 ctx->user_bufs = NULL;
8130 ctx->buf_data = NULL;
8131 ctx->nr_user_bufs = 0;
8134 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8141 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
8143 __io_sqe_buffers_unregister(ctx);
8147 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8148 void __user *arg, unsigned index)
8150 struct iovec __user *src;
8152 #ifdef CONFIG_COMPAT
8154 struct compat_iovec __user *ciovs;
8155 struct compat_iovec ciov;
8157 ciovs = (struct compat_iovec __user *) arg;
8158 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8161 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8162 dst->iov_len = ciov.iov_len;
8166 src = (struct iovec __user *) arg;
8167 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8173 * Not super efficient, but this is just a registration time. And we do cache
8174 * the last compound head, so generally we'll only do a full search if we don't
8177 * We check if the given compound head page has already been accounted, to
8178 * avoid double accounting it. This allows us to account the full size of the
8179 * page, not just the constituent pages of a huge page.
8181 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8182 int nr_pages, struct page *hpage)
8186 /* check current page array */
8187 for (i = 0; i < nr_pages; i++) {
8188 if (!PageCompound(pages[i]))
8190 if (compound_head(pages[i]) == hpage)
8194 /* check previously registered pages */
8195 for (i = 0; i < ctx->nr_user_bufs; i++) {
8196 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
8198 for (j = 0; j < imu->nr_bvecs; j++) {
8199 if (!PageCompound(imu->bvec[j].bv_page))
8201 if (compound_head(imu->bvec[j].bv_page) == hpage)
8209 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8210 int nr_pages, struct io_mapped_ubuf *imu,
8211 struct page **last_hpage)
8215 for (i = 0; i < nr_pages; i++) {
8216 if (!PageCompound(pages[i])) {
8221 hpage = compound_head(pages[i]);
8222 if (hpage == *last_hpage)
8224 *last_hpage = hpage;
8225 if (headpage_already_acct(ctx, pages, i, hpage))
8227 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8231 if (!imu->acct_pages)
8234 ret = io_account_mem(ctx, imu->acct_pages);
8236 imu->acct_pages = 0;
8240 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8241 struct io_mapped_ubuf **pimu,
8242 struct page **last_hpage)
8244 struct io_mapped_ubuf *imu = NULL;
8245 struct vm_area_struct **vmas = NULL;
8246 struct page **pages = NULL;
8247 unsigned long off, start, end, ubuf;
8249 int ret, pret, nr_pages, i;
8251 ubuf = (unsigned long) iov->iov_base;
8252 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8253 start = ubuf >> PAGE_SHIFT;
8254 nr_pages = end - start;
8259 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8263 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8268 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
8273 mmap_read_lock(current->mm);
8274 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8276 if (pret == nr_pages) {
8277 /* don't support file backed memory */
8278 for (i = 0; i < nr_pages; i++) {
8279 struct vm_area_struct *vma = vmas[i];
8282 !is_file_hugepages(vma->vm_file)) {
8288 ret = pret < 0 ? pret : -EFAULT;
8290 mmap_read_unlock(current->mm);
8293 * if we did partial map, or found file backed vmas,
8294 * release any pages we did get
8297 unpin_user_pages(pages, pret);
8301 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8303 unpin_user_pages(pages, pret);
8307 off = ubuf & ~PAGE_MASK;
8308 size = iov->iov_len;
8309 for (i = 0; i < nr_pages; i++) {
8312 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8313 imu->bvec[i].bv_page = pages[i];
8314 imu->bvec[i].bv_len = vec_len;
8315 imu->bvec[i].bv_offset = off;
8319 /* store original address for later verification */
8321 imu->ubuf_end = ubuf + iov->iov_len;
8322 imu->nr_bvecs = nr_pages;
8333 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8335 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
8336 return ctx->user_bufs ? 0 : -ENOMEM;
8339 static int io_buffer_validate(struct iovec *iov)
8341 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8344 * Don't impose further limits on the size and buffer
8345 * constraints here, we'll -EINVAL later when IO is
8346 * submitted if they are wrong.
8348 if (!iov->iov_base || !iov->iov_len)
8351 /* arbitrary limit, but we need something */
8352 if (iov->iov_len > SZ_1G)
8355 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8361 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8362 unsigned int nr_args, u64 __user *tags)
8364 struct page *last_hpage = NULL;
8365 struct io_rsrc_data *data;
8371 if (!nr_args || nr_args > UIO_MAXIOV)
8373 ret = io_rsrc_node_switch_start(ctx);
8376 data = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, nr_args);
8379 ret = io_buffers_map_alloc(ctx, nr_args);
8385 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
8388 if (tags && copy_from_user(&tag, &tags[i], sizeof(tag))) {
8392 ret = io_copy_iov(ctx, &iov, arg, i);
8395 ret = io_buffer_validate(&iov);
8399 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
8403 data->tags[i] = tag;
8406 WARN_ON_ONCE(ctx->buf_data);
8408 ctx->buf_data = data;
8410 __io_sqe_buffers_unregister(ctx);
8412 io_rsrc_node_switch(ctx, NULL);
8416 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
8417 struct io_uring_rsrc_update2 *up,
8418 unsigned int nr_args)
8420 u64 __user *tags = u64_to_user_ptr(up->tags);
8421 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
8422 struct page *last_hpage = NULL;
8423 bool needs_switch = false;
8429 if (up->offset + nr_args > ctx->nr_user_bufs)
8432 for (done = 0; done < nr_args; done++) {
8433 struct io_mapped_ubuf *imu;
8434 int offset = up->offset + done;
8437 err = io_copy_iov(ctx, &iov, iovs, done);
8440 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
8444 err = io_buffer_validate(&iov);
8447 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
8451 i = array_index_nospec(offset, ctx->nr_user_bufs);
8452 if (ctx->user_bufs[i]) {
8453 err = io_queue_rsrc_removal(ctx->buf_data, offset,
8454 ctx->rsrc_node, ctx->user_bufs[i]);
8455 if (unlikely(err)) {
8456 io_buffer_unmap(ctx, &imu);
8459 ctx->user_bufs[i] = NULL;
8460 needs_switch = true;
8463 ctx->user_bufs[i] = imu;
8464 ctx->buf_data->tags[offset] = tag;
8468 io_rsrc_node_switch(ctx, ctx->buf_data);
8469 return done ? done : err;
8472 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8474 __s32 __user *fds = arg;
8480 if (copy_from_user(&fd, fds, sizeof(*fds)))
8483 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8484 if (IS_ERR(ctx->cq_ev_fd)) {
8485 int ret = PTR_ERR(ctx->cq_ev_fd);
8486 ctx->cq_ev_fd = NULL;
8493 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8495 if (ctx->cq_ev_fd) {
8496 eventfd_ctx_put(ctx->cq_ev_fd);
8497 ctx->cq_ev_fd = NULL;
8504 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8506 struct io_buffer *buf;
8507 unsigned long index;
8509 xa_for_each(&ctx->io_buffers, index, buf)
8510 __io_remove_buffers(ctx, buf, index, -1U);
8513 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8515 struct io_kiocb *req, *nxt;
8517 list_for_each_entry_safe(req, nxt, list, compl.list) {
8518 if (tsk && req->task != tsk)
8520 list_del(&req->compl.list);
8521 kmem_cache_free(req_cachep, req);
8525 static void io_req_caches_free(struct io_ring_ctx *ctx)
8527 struct io_submit_state *submit_state = &ctx->submit_state;
8528 struct io_comp_state *cs = &ctx->submit_state.comp;
8530 mutex_lock(&ctx->uring_lock);
8532 if (submit_state->free_reqs) {
8533 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8534 submit_state->reqs);
8535 submit_state->free_reqs = 0;
8538 io_flush_cached_locked_reqs(ctx, cs);
8539 io_req_cache_free(&cs->free_list, NULL);
8540 mutex_unlock(&ctx->uring_lock);
8543 static bool io_wait_rsrc_data(struct io_rsrc_data *data)
8547 if (!atomic_dec_and_test(&data->refs))
8548 wait_for_completion(&data->done);
8552 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8554 io_sq_thread_finish(ctx);
8556 if (ctx->mm_account) {
8557 mmdrop(ctx->mm_account);
8558 ctx->mm_account = NULL;
8561 mutex_lock(&ctx->uring_lock);
8562 if (io_wait_rsrc_data(ctx->buf_data))
8563 __io_sqe_buffers_unregister(ctx);
8564 if (io_wait_rsrc_data(ctx->file_data))
8565 __io_sqe_files_unregister(ctx);
8567 __io_cqring_overflow_flush(ctx, true);
8568 mutex_unlock(&ctx->uring_lock);
8569 io_eventfd_unregister(ctx);
8570 io_destroy_buffers(ctx);
8572 put_cred(ctx->sq_creds);
8574 /* there are no registered resources left, nobody uses it */
8576 io_rsrc_node_destroy(ctx->rsrc_node);
8577 if (ctx->rsrc_backup_node)
8578 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8579 flush_delayed_work(&ctx->rsrc_put_work);
8581 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8582 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8584 #if defined(CONFIG_UNIX)
8585 if (ctx->ring_sock) {
8586 ctx->ring_sock->file = NULL; /* so that iput() is called */
8587 sock_release(ctx->ring_sock);
8591 io_mem_free(ctx->rings);
8592 io_mem_free(ctx->sq_sqes);
8594 percpu_ref_exit(&ctx->refs);
8595 free_uid(ctx->user);
8596 io_req_caches_free(ctx);
8598 io_wq_put_hash(ctx->hash_map);
8599 kfree(ctx->cancel_hash);
8603 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8605 struct io_ring_ctx *ctx = file->private_data;
8608 poll_wait(file, &ctx->cq_wait, wait);
8610 * synchronizes with barrier from wq_has_sleeper call in
8614 if (!io_sqring_full(ctx))
8615 mask |= EPOLLOUT | EPOLLWRNORM;
8618 * Don't flush cqring overflow list here, just do a simple check.
8619 * Otherwise there could possible be ABBA deadlock:
8622 * lock(&ctx->uring_lock);
8624 * lock(&ctx->uring_lock);
8627 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8628 * pushs them to do the flush.
8630 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8631 mask |= EPOLLIN | EPOLLRDNORM;
8636 static int io_uring_fasync(int fd, struct file *file, int on)
8638 struct io_ring_ctx *ctx = file->private_data;
8640 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8643 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8645 const struct cred *creds;
8647 creds = xa_erase(&ctx->personalities, id);
8656 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8658 return io_run_task_work_head(&ctx->exit_task_work);
8661 struct io_tctx_exit {
8662 struct callback_head task_work;
8663 struct completion completion;
8664 struct io_ring_ctx *ctx;
8667 static void io_tctx_exit_cb(struct callback_head *cb)
8669 struct io_uring_task *tctx = current->io_uring;
8670 struct io_tctx_exit *work;
8672 work = container_of(cb, struct io_tctx_exit, task_work);
8674 * When @in_idle, we're in cancellation and it's racy to remove the
8675 * node. It'll be removed by the end of cancellation, just ignore it.
8677 if (!atomic_read(&tctx->in_idle))
8678 io_uring_del_task_file((unsigned long)work->ctx);
8679 complete(&work->completion);
8682 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8684 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8686 return req->ctx == data;
8689 static void io_ring_exit_work(struct work_struct *work)
8691 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8692 unsigned long timeout = jiffies + HZ * 60 * 5;
8693 struct io_tctx_exit exit;
8694 struct io_tctx_node *node;
8698 * If we're doing polled IO and end up having requests being
8699 * submitted async (out-of-line), then completions can come in while
8700 * we're waiting for refs to drop. We need to reap these manually,
8701 * as nobody else will be looking for them.
8704 io_uring_try_cancel_requests(ctx, NULL, NULL);
8706 struct io_sq_data *sqd = ctx->sq_data;
8707 struct task_struct *tsk;
8709 io_sq_thread_park(sqd);
8711 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
8712 io_wq_cancel_cb(tsk->io_uring->io_wq,
8713 io_cancel_ctx_cb, ctx, true);
8714 io_sq_thread_unpark(sqd);
8717 WARN_ON_ONCE(time_after(jiffies, timeout));
8718 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8720 init_completion(&exit.completion);
8721 init_task_work(&exit.task_work, io_tctx_exit_cb);
8724 * Some may use context even when all refs and requests have been put,
8725 * and they are free to do so while still holding uring_lock or
8726 * completion_lock, see __io_req_task_submit(). Apart from other work,
8727 * this lock/unlock section also waits them to finish.
8729 mutex_lock(&ctx->uring_lock);
8730 while (!list_empty(&ctx->tctx_list)) {
8731 WARN_ON_ONCE(time_after(jiffies, timeout));
8733 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8735 /* don't spin on a single task if cancellation failed */
8736 list_rotate_left(&ctx->tctx_list);
8737 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8738 if (WARN_ON_ONCE(ret))
8740 wake_up_process(node->task);
8742 mutex_unlock(&ctx->uring_lock);
8743 wait_for_completion(&exit.completion);
8744 mutex_lock(&ctx->uring_lock);
8746 mutex_unlock(&ctx->uring_lock);
8747 spin_lock_irq(&ctx->completion_lock);
8748 spin_unlock_irq(&ctx->completion_lock);
8750 io_ring_ctx_free(ctx);
8753 /* Returns true if we found and killed one or more timeouts */
8754 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8755 struct files_struct *files)
8757 struct io_kiocb *req, *tmp;
8760 spin_lock_irq(&ctx->completion_lock);
8761 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8762 if (io_match_task(req, tsk, files)) {
8763 io_kill_timeout(req, -ECANCELED);
8768 io_commit_cqring(ctx);
8769 spin_unlock_irq(&ctx->completion_lock);
8771 io_cqring_ev_posted(ctx);
8772 return canceled != 0;
8775 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8777 unsigned long index;
8778 struct creds *creds;
8780 mutex_lock(&ctx->uring_lock);
8781 percpu_ref_kill(&ctx->refs);
8783 __io_cqring_overflow_flush(ctx, true);
8784 xa_for_each(&ctx->personalities, index, creds)
8785 io_unregister_personality(ctx, index);
8786 mutex_unlock(&ctx->uring_lock);
8788 io_kill_timeouts(ctx, NULL, NULL);
8789 io_poll_remove_all(ctx, NULL, NULL);
8791 /* if we failed setting up the ctx, we might not have any rings */
8792 io_iopoll_try_reap_events(ctx);
8794 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8796 * Use system_unbound_wq to avoid spawning tons of event kworkers
8797 * if we're exiting a ton of rings at the same time. It just adds
8798 * noise and overhead, there's no discernable change in runtime
8799 * over using system_wq.
8801 queue_work(system_unbound_wq, &ctx->exit_work);
8804 static int io_uring_release(struct inode *inode, struct file *file)
8806 struct io_ring_ctx *ctx = file->private_data;
8808 file->private_data = NULL;
8809 io_ring_ctx_wait_and_kill(ctx);
8813 struct io_task_cancel {
8814 struct task_struct *task;
8815 struct files_struct *files;
8818 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8820 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8821 struct io_task_cancel *cancel = data;
8824 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8825 unsigned long flags;
8826 struct io_ring_ctx *ctx = req->ctx;
8828 /* protect against races with linked timeouts */
8829 spin_lock_irqsave(&ctx->completion_lock, flags);
8830 ret = io_match_task(req, cancel->task, cancel->files);
8831 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8833 ret = io_match_task(req, cancel->task, cancel->files);
8838 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8839 struct task_struct *task,
8840 struct files_struct *files)
8842 struct io_defer_entry *de;
8845 spin_lock_irq(&ctx->completion_lock);
8846 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8847 if (io_match_task(de->req, task, files)) {
8848 list_cut_position(&list, &ctx->defer_list, &de->list);
8852 spin_unlock_irq(&ctx->completion_lock);
8853 if (list_empty(&list))
8856 while (!list_empty(&list)) {
8857 de = list_first_entry(&list, struct io_defer_entry, list);
8858 list_del_init(&de->list);
8859 io_req_complete_failed(de->req, -ECANCELED);
8865 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8867 struct io_tctx_node *node;
8868 enum io_wq_cancel cret;
8871 mutex_lock(&ctx->uring_lock);
8872 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8873 struct io_uring_task *tctx = node->task->io_uring;
8876 * io_wq will stay alive while we hold uring_lock, because it's
8877 * killed after ctx nodes, which requires to take the lock.
8879 if (!tctx || !tctx->io_wq)
8881 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8882 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8884 mutex_unlock(&ctx->uring_lock);
8889 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8890 struct task_struct *task,
8891 struct files_struct *files)
8893 struct io_task_cancel cancel = { .task = task, .files = files, };
8894 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8897 enum io_wq_cancel cret;
8901 ret |= io_uring_try_cancel_iowq(ctx);
8902 } else if (tctx && tctx->io_wq) {
8904 * Cancels requests of all rings, not only @ctx, but
8905 * it's fine as the task is in exit/exec.
8907 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8909 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8912 /* SQPOLL thread does its own polling */
8913 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8914 (ctx->sq_data && ctx->sq_data->thread == current)) {
8915 while (!list_empty_careful(&ctx->iopoll_list)) {
8916 io_iopoll_try_reap_events(ctx);
8921 ret |= io_cancel_defer_files(ctx, task, files);
8922 ret |= io_poll_remove_all(ctx, task, files);
8923 ret |= io_kill_timeouts(ctx, task, files);
8924 ret |= io_run_task_work();
8925 ret |= io_run_ctx_fallback(ctx);
8932 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8934 struct io_uring_task *tctx = current->io_uring;
8935 struct io_tctx_node *node;
8938 if (unlikely(!tctx)) {
8939 ret = io_uring_alloc_task_context(current, ctx);
8942 tctx = current->io_uring;
8944 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8945 node = kmalloc(sizeof(*node), GFP_KERNEL);
8949 node->task = current;
8951 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8958 mutex_lock(&ctx->uring_lock);
8959 list_add(&node->ctx_node, &ctx->tctx_list);
8960 mutex_unlock(&ctx->uring_lock);
8967 * Note that this task has used io_uring. We use it for cancelation purposes.
8969 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8971 struct io_uring_task *tctx = current->io_uring;
8973 if (likely(tctx && tctx->last == ctx))
8975 return __io_uring_add_task_file(ctx);
8979 * Remove this io_uring_file -> task mapping.
8981 static void io_uring_del_task_file(unsigned long index)
8983 struct io_uring_task *tctx = current->io_uring;
8984 struct io_tctx_node *node;
8988 node = xa_erase(&tctx->xa, index);
8992 WARN_ON_ONCE(current != node->task);
8993 WARN_ON_ONCE(list_empty(&node->ctx_node));
8995 mutex_lock(&node->ctx->uring_lock);
8996 list_del(&node->ctx_node);
8997 mutex_unlock(&node->ctx->uring_lock);
8999 if (tctx->last == node->ctx)
9004 static void io_uring_clean_tctx(struct io_uring_task *tctx)
9006 struct io_tctx_node *node;
9007 unsigned long index;
9009 xa_for_each(&tctx->xa, index, node)
9010 io_uring_del_task_file(index);
9012 io_wq_put_and_exit(tctx->io_wq);
9017 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
9020 return atomic_read(&tctx->inflight_tracked);
9021 return percpu_counter_sum(&tctx->inflight);
9024 static void io_uring_try_cancel(struct files_struct *files)
9026 struct io_uring_task *tctx = current->io_uring;
9027 struct io_tctx_node *node;
9028 unsigned long index;
9030 xa_for_each(&tctx->xa, index, node) {
9031 struct io_ring_ctx *ctx = node->ctx;
9033 /* sqpoll task will cancel all its requests */
9035 io_uring_try_cancel_requests(ctx, current, files);
9039 /* should only be called by SQPOLL task */
9040 static void io_uring_cancel_sqpoll(struct io_sq_data *sqd)
9042 struct io_uring_task *tctx = current->io_uring;
9043 struct io_ring_ctx *ctx;
9047 if (!current->io_uring)
9049 WARN_ON_ONCE(!sqd || sqd->thread != current);
9051 atomic_inc(&tctx->in_idle);
9053 /* read completions before cancelations */
9054 inflight = tctx_inflight(tctx, false);
9057 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
9058 io_uring_try_cancel_requests(ctx, current, NULL);
9060 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9062 * If we've seen completions, retry without waiting. This
9063 * avoids a race where a completion comes in before we did
9064 * prepare_to_wait().
9066 if (inflight == tctx_inflight(tctx, false))
9068 finish_wait(&tctx->wait, &wait);
9070 atomic_dec(&tctx->in_idle);
9074 * Find any io_uring fd that this task has registered or done IO on, and cancel
9077 void __io_uring_cancel(struct files_struct *files)
9079 struct io_uring_task *tctx = current->io_uring;
9083 /* make sure overflow events are dropped */
9084 atomic_inc(&tctx->in_idle);
9086 /* read completions before cancelations */
9087 inflight = tctx_inflight(tctx, !!files);
9090 io_uring_try_cancel(files);
9091 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9094 * If we've seen completions, retry without waiting. This
9095 * avoids a race where a completion comes in before we did
9096 * prepare_to_wait().
9098 if (inflight == tctx_inflight(tctx, !!files))
9100 finish_wait(&tctx->wait, &wait);
9102 atomic_dec(&tctx->in_idle);
9104 io_uring_clean_tctx(tctx);
9106 /* for exec all current's requests should be gone, kill tctx */
9107 __io_uring_free(current);
9111 static void *io_uring_validate_mmap_request(struct file *file,
9112 loff_t pgoff, size_t sz)
9114 struct io_ring_ctx *ctx = file->private_data;
9115 loff_t offset = pgoff << PAGE_SHIFT;
9120 case IORING_OFF_SQ_RING:
9121 case IORING_OFF_CQ_RING:
9124 case IORING_OFF_SQES:
9128 return ERR_PTR(-EINVAL);
9131 page = virt_to_head_page(ptr);
9132 if (sz > page_size(page))
9133 return ERR_PTR(-EINVAL);
9140 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9142 size_t sz = vma->vm_end - vma->vm_start;
9146 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9148 return PTR_ERR(ptr);
9150 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9151 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9154 #else /* !CONFIG_MMU */
9156 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9158 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9161 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9163 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9166 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9167 unsigned long addr, unsigned long len,
9168 unsigned long pgoff, unsigned long flags)
9172 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9174 return PTR_ERR(ptr);
9176 return (unsigned long) ptr;
9179 #endif /* !CONFIG_MMU */
9181 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9186 if (!io_sqring_full(ctx))
9188 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9190 if (!io_sqring_full(ctx))
9193 } while (!signal_pending(current));
9195 finish_wait(&ctx->sqo_sq_wait, &wait);
9199 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9200 struct __kernel_timespec __user **ts,
9201 const sigset_t __user **sig)
9203 struct io_uring_getevents_arg arg;
9206 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9207 * is just a pointer to the sigset_t.
9209 if (!(flags & IORING_ENTER_EXT_ARG)) {
9210 *sig = (const sigset_t __user *) argp;
9216 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9217 * timespec and sigset_t pointers if good.
9219 if (*argsz != sizeof(arg))
9221 if (copy_from_user(&arg, argp, sizeof(arg)))
9223 *sig = u64_to_user_ptr(arg.sigmask);
9224 *argsz = arg.sigmask_sz;
9225 *ts = u64_to_user_ptr(arg.ts);
9229 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9230 u32, min_complete, u32, flags, const void __user *, argp,
9233 struct io_ring_ctx *ctx;
9240 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9241 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9245 if (unlikely(!f.file))
9249 if (unlikely(f.file->f_op != &io_uring_fops))
9253 ctx = f.file->private_data;
9254 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9258 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9262 * For SQ polling, the thread will do all submissions and completions.
9263 * Just return the requested submit count, and wake the thread if
9267 if (ctx->flags & IORING_SETUP_SQPOLL) {
9268 io_cqring_overflow_flush(ctx, false);
9271 if (unlikely(ctx->sq_data->thread == NULL)) {
9274 if (flags & IORING_ENTER_SQ_WAKEUP)
9275 wake_up(&ctx->sq_data->wait);
9276 if (flags & IORING_ENTER_SQ_WAIT) {
9277 ret = io_sqpoll_wait_sq(ctx);
9281 submitted = to_submit;
9282 } else if (to_submit) {
9283 ret = io_uring_add_task_file(ctx);
9286 mutex_lock(&ctx->uring_lock);
9287 submitted = io_submit_sqes(ctx, to_submit);
9288 mutex_unlock(&ctx->uring_lock);
9290 if (submitted != to_submit)
9293 if (flags & IORING_ENTER_GETEVENTS) {
9294 const sigset_t __user *sig;
9295 struct __kernel_timespec __user *ts;
9297 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9301 min_complete = min(min_complete, ctx->cq_entries);
9304 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9305 * space applications don't need to do io completion events
9306 * polling again, they can rely on io_sq_thread to do polling
9307 * work, which can reduce cpu usage and uring_lock contention.
9309 if (ctx->flags & IORING_SETUP_IOPOLL &&
9310 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9311 ret = io_iopoll_check(ctx, min_complete);
9313 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9318 percpu_ref_put(&ctx->refs);
9321 return submitted ? submitted : ret;
9324 #ifdef CONFIG_PROC_FS
9325 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9326 const struct cred *cred)
9328 struct user_namespace *uns = seq_user_ns(m);
9329 struct group_info *gi;
9334 seq_printf(m, "%5d\n", id);
9335 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9336 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9337 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9338 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9339 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9340 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9341 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9342 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9343 seq_puts(m, "\n\tGroups:\t");
9344 gi = cred->group_info;
9345 for (g = 0; g < gi->ngroups; g++) {
9346 seq_put_decimal_ull(m, g ? " " : "",
9347 from_kgid_munged(uns, gi->gid[g]));
9349 seq_puts(m, "\n\tCapEff:\t");
9350 cap = cred->cap_effective;
9351 CAP_FOR_EACH_U32(__capi)
9352 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9357 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9359 struct io_sq_data *sq = NULL;
9364 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9365 * since fdinfo case grabs it in the opposite direction of normal use
9366 * cases. If we fail to get the lock, we just don't iterate any
9367 * structures that could be going away outside the io_uring mutex.
9369 has_lock = mutex_trylock(&ctx->uring_lock);
9371 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9377 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9378 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9379 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9380 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9381 struct file *f = io_file_from_index(ctx, i);
9384 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9386 seq_printf(m, "%5u: <none>\n", i);
9388 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9389 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9390 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
9391 unsigned int len = buf->ubuf_end - buf->ubuf;
9393 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9395 if (has_lock && !xa_empty(&ctx->personalities)) {
9396 unsigned long index;
9397 const struct cred *cred;
9399 seq_printf(m, "Personalities:\n");
9400 xa_for_each(&ctx->personalities, index, cred)
9401 io_uring_show_cred(m, index, cred);
9403 seq_printf(m, "PollList:\n");
9404 spin_lock_irq(&ctx->completion_lock);
9405 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9406 struct hlist_head *list = &ctx->cancel_hash[i];
9407 struct io_kiocb *req;
9409 hlist_for_each_entry(req, list, hash_node)
9410 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9411 req->task->task_works != NULL);
9413 spin_unlock_irq(&ctx->completion_lock);
9415 mutex_unlock(&ctx->uring_lock);
9418 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9420 struct io_ring_ctx *ctx = f->private_data;
9422 if (percpu_ref_tryget(&ctx->refs)) {
9423 __io_uring_show_fdinfo(ctx, m);
9424 percpu_ref_put(&ctx->refs);
9429 static const struct file_operations io_uring_fops = {
9430 .release = io_uring_release,
9431 .mmap = io_uring_mmap,
9433 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9434 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9436 .poll = io_uring_poll,
9437 .fasync = io_uring_fasync,
9438 #ifdef CONFIG_PROC_FS
9439 .show_fdinfo = io_uring_show_fdinfo,
9443 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9444 struct io_uring_params *p)
9446 struct io_rings *rings;
9447 size_t size, sq_array_offset;
9449 /* make sure these are sane, as we already accounted them */
9450 ctx->sq_entries = p->sq_entries;
9451 ctx->cq_entries = p->cq_entries;
9453 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9454 if (size == SIZE_MAX)
9457 rings = io_mem_alloc(size);
9462 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9463 rings->sq_ring_mask = p->sq_entries - 1;
9464 rings->cq_ring_mask = p->cq_entries - 1;
9465 rings->sq_ring_entries = p->sq_entries;
9466 rings->cq_ring_entries = p->cq_entries;
9467 ctx->sq_mask = rings->sq_ring_mask;
9468 ctx->cq_mask = rings->cq_ring_mask;
9470 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9471 if (size == SIZE_MAX) {
9472 io_mem_free(ctx->rings);
9477 ctx->sq_sqes = io_mem_alloc(size);
9478 if (!ctx->sq_sqes) {
9479 io_mem_free(ctx->rings);
9487 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9491 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9495 ret = io_uring_add_task_file(ctx);
9500 fd_install(fd, file);
9505 * Allocate an anonymous fd, this is what constitutes the application
9506 * visible backing of an io_uring instance. The application mmaps this
9507 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9508 * we have to tie this fd to a socket for file garbage collection purposes.
9510 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9513 #if defined(CONFIG_UNIX)
9516 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9519 return ERR_PTR(ret);
9522 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9523 O_RDWR | O_CLOEXEC);
9524 #if defined(CONFIG_UNIX)
9526 sock_release(ctx->ring_sock);
9527 ctx->ring_sock = NULL;
9529 ctx->ring_sock->file = file;
9535 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9536 struct io_uring_params __user *params)
9538 struct io_ring_ctx *ctx;
9544 if (entries > IORING_MAX_ENTRIES) {
9545 if (!(p->flags & IORING_SETUP_CLAMP))
9547 entries = IORING_MAX_ENTRIES;
9551 * Use twice as many entries for the CQ ring. It's possible for the
9552 * application to drive a higher depth than the size of the SQ ring,
9553 * since the sqes are only used at submission time. This allows for
9554 * some flexibility in overcommitting a bit. If the application has
9555 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9556 * of CQ ring entries manually.
9558 p->sq_entries = roundup_pow_of_two(entries);
9559 if (p->flags & IORING_SETUP_CQSIZE) {
9561 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9562 * to a power-of-two, if it isn't already. We do NOT impose
9563 * any cq vs sq ring sizing.
9567 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9568 if (!(p->flags & IORING_SETUP_CLAMP))
9570 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9572 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9573 if (p->cq_entries < p->sq_entries)
9576 p->cq_entries = 2 * p->sq_entries;
9579 ctx = io_ring_ctx_alloc(p);
9582 ctx->compat = in_compat_syscall();
9583 if (!capable(CAP_IPC_LOCK))
9584 ctx->user = get_uid(current_user());
9587 * This is just grabbed for accounting purposes. When a process exits,
9588 * the mm is exited and dropped before the files, hence we need to hang
9589 * on to this mm purely for the purposes of being able to unaccount
9590 * memory (locked/pinned vm). It's not used for anything else.
9592 mmgrab(current->mm);
9593 ctx->mm_account = current->mm;
9595 ret = io_allocate_scq_urings(ctx, p);
9599 ret = io_sq_offload_create(ctx, p);
9602 /* always set a rsrc node */
9603 io_rsrc_node_switch_start(ctx);
9604 io_rsrc_node_switch(ctx, NULL);
9606 memset(&p->sq_off, 0, sizeof(p->sq_off));
9607 p->sq_off.head = offsetof(struct io_rings, sq.head);
9608 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9609 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9610 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9611 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9612 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9613 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9615 memset(&p->cq_off, 0, sizeof(p->cq_off));
9616 p->cq_off.head = offsetof(struct io_rings, cq.head);
9617 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9618 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9619 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9620 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9621 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9622 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9624 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9625 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9626 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9627 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9628 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9630 if (copy_to_user(params, p, sizeof(*p))) {
9635 file = io_uring_get_file(ctx);
9637 ret = PTR_ERR(file);
9642 * Install ring fd as the very last thing, so we don't risk someone
9643 * having closed it before we finish setup
9645 ret = io_uring_install_fd(ctx, file);
9647 /* fput will clean it up */
9652 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9655 io_ring_ctx_wait_and_kill(ctx);
9660 * Sets up an aio uring context, and returns the fd. Applications asks for a
9661 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9662 * params structure passed in.
9664 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9666 struct io_uring_params p;
9669 if (copy_from_user(&p, params, sizeof(p)))
9671 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9676 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9677 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9678 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9679 IORING_SETUP_R_DISABLED))
9682 return io_uring_create(entries, &p, params);
9685 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9686 struct io_uring_params __user *, params)
9688 return io_uring_setup(entries, params);
9691 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9693 struct io_uring_probe *p;
9697 size = struct_size(p, ops, nr_args);
9698 if (size == SIZE_MAX)
9700 p = kzalloc(size, GFP_KERNEL);
9705 if (copy_from_user(p, arg, size))
9708 if (memchr_inv(p, 0, size))
9711 p->last_op = IORING_OP_LAST - 1;
9712 if (nr_args > IORING_OP_LAST)
9713 nr_args = IORING_OP_LAST;
9715 for (i = 0; i < nr_args; i++) {
9717 if (!io_op_defs[i].not_supported)
9718 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9723 if (copy_to_user(arg, p, size))
9730 static int io_register_personality(struct io_ring_ctx *ctx)
9732 const struct cred *creds;
9736 creds = get_current_cred();
9738 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9739 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9746 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9747 unsigned int nr_args)
9749 struct io_uring_restriction *res;
9753 /* Restrictions allowed only if rings started disabled */
9754 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9757 /* We allow only a single restrictions registration */
9758 if (ctx->restrictions.registered)
9761 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9764 size = array_size(nr_args, sizeof(*res));
9765 if (size == SIZE_MAX)
9768 res = memdup_user(arg, size);
9770 return PTR_ERR(res);
9774 for (i = 0; i < nr_args; i++) {
9775 switch (res[i].opcode) {
9776 case IORING_RESTRICTION_REGISTER_OP:
9777 if (res[i].register_op >= IORING_REGISTER_LAST) {
9782 __set_bit(res[i].register_op,
9783 ctx->restrictions.register_op);
9785 case IORING_RESTRICTION_SQE_OP:
9786 if (res[i].sqe_op >= IORING_OP_LAST) {
9791 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9793 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9794 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9796 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9797 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9806 /* Reset all restrictions if an error happened */
9808 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9810 ctx->restrictions.registered = true;
9816 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9818 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9821 if (ctx->restrictions.registered)
9822 ctx->restricted = 1;
9824 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9825 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9826 wake_up(&ctx->sq_data->wait);
9830 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
9831 struct io_uring_rsrc_update2 *up,
9839 if (check_add_overflow(up->offset, nr_args, &tmp))
9841 err = io_rsrc_node_switch_start(ctx);
9846 case IORING_RSRC_FILE:
9847 return __io_sqe_files_update(ctx, up, nr_args);
9848 case IORING_RSRC_BUFFER:
9849 return __io_sqe_buffers_update(ctx, up, nr_args);
9854 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
9857 struct io_uring_rsrc_update2 up;
9861 memset(&up, 0, sizeof(up));
9862 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
9864 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
9867 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
9870 struct io_uring_rsrc_update2 up;
9872 if (size != sizeof(up))
9874 if (copy_from_user(&up, arg, sizeof(up)))
9878 return __io_register_rsrc_update(ctx, up.type, &up, up.nr);
9881 static int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
9884 struct io_uring_rsrc_register rr;
9886 /* keep it extendible */
9887 if (size != sizeof(rr))
9890 memset(&rr, 0, sizeof(rr));
9891 if (copy_from_user(&rr, arg, size))
9897 case IORING_RSRC_FILE:
9898 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
9899 rr.nr, u64_to_user_ptr(rr.tags));
9900 case IORING_RSRC_BUFFER:
9901 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
9902 rr.nr, u64_to_user_ptr(rr.tags));
9907 static bool io_register_op_must_quiesce(int op)
9910 case IORING_REGISTER_BUFFERS:
9911 case IORING_UNREGISTER_BUFFERS:
9912 case IORING_REGISTER_FILES:
9913 case IORING_UNREGISTER_FILES:
9914 case IORING_REGISTER_FILES_UPDATE:
9915 case IORING_REGISTER_PROBE:
9916 case IORING_REGISTER_PERSONALITY:
9917 case IORING_UNREGISTER_PERSONALITY:
9918 case IORING_REGISTER_RSRC:
9919 case IORING_REGISTER_RSRC_UPDATE:
9926 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9927 void __user *arg, unsigned nr_args)
9928 __releases(ctx->uring_lock)
9929 __acquires(ctx->uring_lock)
9934 * We're inside the ring mutex, if the ref is already dying, then
9935 * someone else killed the ctx or is already going through
9936 * io_uring_register().
9938 if (percpu_ref_is_dying(&ctx->refs))
9941 if (ctx->restricted) {
9942 if (opcode >= IORING_REGISTER_LAST)
9944 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
9945 if (!test_bit(opcode, ctx->restrictions.register_op))
9949 if (io_register_op_must_quiesce(opcode)) {
9950 percpu_ref_kill(&ctx->refs);
9953 * Drop uring mutex before waiting for references to exit. If
9954 * another thread is currently inside io_uring_enter() it might
9955 * need to grab the uring_lock to make progress. If we hold it
9956 * here across the drain wait, then we can deadlock. It's safe
9957 * to drop the mutex here, since no new references will come in
9958 * after we've killed the percpu ref.
9960 mutex_unlock(&ctx->uring_lock);
9962 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9965 ret = io_run_task_work_sig();
9969 mutex_lock(&ctx->uring_lock);
9972 io_refs_resurrect(&ctx->refs, &ctx->ref_comp);
9978 case IORING_REGISTER_BUFFERS:
9979 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
9981 case IORING_UNREGISTER_BUFFERS:
9985 ret = io_sqe_buffers_unregister(ctx);
9987 case IORING_REGISTER_FILES:
9988 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
9990 case IORING_UNREGISTER_FILES:
9994 ret = io_sqe_files_unregister(ctx);
9996 case IORING_REGISTER_FILES_UPDATE:
9997 ret = io_register_files_update(ctx, arg, nr_args);
9999 case IORING_REGISTER_EVENTFD:
10000 case IORING_REGISTER_EVENTFD_ASYNC:
10004 ret = io_eventfd_register(ctx, arg);
10007 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
10008 ctx->eventfd_async = 1;
10010 ctx->eventfd_async = 0;
10012 case IORING_UNREGISTER_EVENTFD:
10014 if (arg || nr_args)
10016 ret = io_eventfd_unregister(ctx);
10018 case IORING_REGISTER_PROBE:
10020 if (!arg || nr_args > 256)
10022 ret = io_probe(ctx, arg, nr_args);
10024 case IORING_REGISTER_PERSONALITY:
10026 if (arg || nr_args)
10028 ret = io_register_personality(ctx);
10030 case IORING_UNREGISTER_PERSONALITY:
10034 ret = io_unregister_personality(ctx, nr_args);
10036 case IORING_REGISTER_ENABLE_RINGS:
10038 if (arg || nr_args)
10040 ret = io_register_enable_rings(ctx);
10042 case IORING_REGISTER_RESTRICTIONS:
10043 ret = io_register_restrictions(ctx, arg, nr_args);
10045 case IORING_REGISTER_RSRC:
10046 ret = io_register_rsrc(ctx, arg, nr_args);
10048 case IORING_REGISTER_RSRC_UPDATE:
10049 ret = io_register_rsrc_update(ctx, arg, nr_args);
10056 if (io_register_op_must_quiesce(opcode)) {
10057 /* bring the ctx back to life */
10058 percpu_ref_reinit(&ctx->refs);
10059 reinit_completion(&ctx->ref_comp);
10064 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
10065 void __user *, arg, unsigned int, nr_args)
10067 struct io_ring_ctx *ctx;
10076 if (f.file->f_op != &io_uring_fops)
10079 ctx = f.file->private_data;
10081 io_run_task_work();
10083 mutex_lock(&ctx->uring_lock);
10084 ret = __io_uring_register(ctx, opcode, arg, nr_args);
10085 mutex_unlock(&ctx->uring_lock);
10086 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
10087 ctx->cq_ev_fd != NULL, ret);
10093 static int __init io_uring_init(void)
10095 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
10096 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
10097 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
10100 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
10101 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
10102 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
10103 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
10104 BUILD_BUG_SQE_ELEM(1, __u8, flags);
10105 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
10106 BUILD_BUG_SQE_ELEM(4, __s32, fd);
10107 BUILD_BUG_SQE_ELEM(8, __u64, off);
10108 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
10109 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10110 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10111 BUILD_BUG_SQE_ELEM(24, __u32, len);
10112 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10113 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10114 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10115 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10116 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10117 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10118 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10119 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10120 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10121 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10122 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10123 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10124 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10125 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10126 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10127 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10128 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10129 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10130 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10132 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10133 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10134 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10138 __initcall(io_uring_init);