1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 #define IORING_FILE_TABLE_SHIFT 9
97 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
104 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 enum io_uring_cmd_flags {
191 IO_URING_F_NONBLOCK = 1,
192 IO_URING_F_COMPLETE_DEFER = 2,
195 struct io_mapped_ubuf {
198 struct bio_vec *bvec;
199 unsigned int nr_bvecs;
200 unsigned long acct_pages;
206 struct list_head list;
213 struct fixed_rsrc_table {
217 struct fixed_rsrc_ref_node {
218 struct percpu_ref refs;
219 struct list_head node;
220 struct list_head rsrc_list;
221 struct fixed_rsrc_data *rsrc_data;
222 void (*rsrc_put)(struct io_ring_ctx *ctx,
223 struct io_rsrc_put *prsrc);
224 struct llist_node llist;
228 struct fixed_rsrc_data {
229 struct fixed_rsrc_table *table;
230 struct io_ring_ctx *ctx;
232 struct fixed_rsrc_ref_node *node;
233 struct percpu_ref refs;
234 struct completion done;
239 struct list_head list;
245 struct io_restriction {
246 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
247 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
248 u8 sqe_flags_allowed;
249 u8 sqe_flags_required;
254 IO_SQ_THREAD_SHOULD_STOP = 0,
255 IO_SQ_THREAD_SHOULD_PARK,
260 atomic_t park_pending;
263 /* ctx's that are using this sqd */
264 struct list_head ctx_list;
266 struct task_struct *thread;
267 struct wait_queue_head wait;
269 unsigned sq_thread_idle;
275 struct completion exited;
276 struct callback_head *park_task_work;
279 #define IO_IOPOLL_BATCH 8
280 #define IO_COMPL_BATCH 32
281 #define IO_REQ_CACHE_SIZE 32
282 #define IO_REQ_ALLOC_BATCH 8
284 struct io_comp_state {
285 struct io_kiocb *reqs[IO_COMPL_BATCH];
287 unsigned int locked_free_nr;
288 /* inline/task_work completion list, under ->uring_lock */
289 struct list_head free_list;
290 /* IRQ completion list, under ->completion_lock */
291 struct list_head locked_free_list;
294 struct io_submit_link {
295 struct io_kiocb *head;
296 struct io_kiocb *last;
299 struct io_submit_state {
300 struct blk_plug plug;
301 struct io_submit_link link;
304 * io_kiocb alloc cache
306 void *reqs[IO_REQ_CACHE_SIZE];
307 unsigned int free_reqs;
312 * Batch completion logic
314 struct io_comp_state comp;
317 * File reference cache
321 unsigned int file_refs;
322 unsigned int ios_left;
327 struct percpu_ref refs;
328 } ____cacheline_aligned_in_smp;
332 unsigned int compat: 1;
333 unsigned int cq_overflow_flushed: 1;
334 unsigned int drain_next: 1;
335 unsigned int eventfd_async: 1;
336 unsigned int restricted: 1;
339 * Ring buffer of indices into array of io_uring_sqe, which is
340 * mmapped by the application using the IORING_OFF_SQES offset.
342 * This indirection could e.g. be used to assign fixed
343 * io_uring_sqe entries to operations and only submit them to
344 * the queue when needed.
346 * The kernel modifies neither the indices array nor the entries
350 unsigned cached_sq_head;
353 unsigned sq_thread_idle;
354 unsigned cached_sq_dropped;
355 unsigned cached_cq_overflow;
356 unsigned long sq_check_overflow;
358 /* hashed buffered write serialization */
359 struct io_wq_hash *hash_map;
361 struct list_head defer_list;
362 struct list_head timeout_list;
363 struct list_head cq_overflow_list;
365 struct io_uring_sqe *sq_sqes;
366 } ____cacheline_aligned_in_smp;
369 struct mutex uring_lock;
370 wait_queue_head_t wait;
371 } ____cacheline_aligned_in_smp;
373 struct io_submit_state submit_state;
375 struct io_rings *rings;
377 /* Only used for accounting purposes */
378 struct mm_struct *mm_account;
380 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
381 struct io_sq_data *sq_data; /* if using sq thread polling */
383 struct wait_queue_head sqo_sq_wait;
384 struct list_head sqd_list;
387 * If used, fixed file set. Writers must ensure that ->refs is dead,
388 * readers must ensure that ->refs is alive as long as the file* is
389 * used. Only updated through io_uring_register(2).
391 struct fixed_rsrc_data *file_data;
392 unsigned nr_user_files;
394 /* if used, fixed mapped user buffers */
395 unsigned nr_user_bufs;
396 struct io_mapped_ubuf *user_bufs;
398 struct user_struct *user;
400 struct completion ref_comp;
402 #if defined(CONFIG_UNIX)
403 struct socket *ring_sock;
406 struct xarray io_buffers;
408 struct xarray personalities;
412 unsigned cached_cq_tail;
415 atomic_t cq_timeouts;
416 unsigned cq_last_tm_flush;
417 unsigned long cq_check_overflow;
418 struct wait_queue_head cq_wait;
419 struct fasync_struct *cq_fasync;
420 struct eventfd_ctx *cq_ev_fd;
421 } ____cacheline_aligned_in_smp;
424 spinlock_t completion_lock;
427 * ->iopoll_list is protected by the ctx->uring_lock for
428 * io_uring instances that don't use IORING_SETUP_SQPOLL.
429 * For SQPOLL, only the single threaded io_sq_thread() will
430 * manipulate the list, hence no extra locking is needed there.
432 struct list_head iopoll_list;
433 struct hlist_head *cancel_hash;
434 unsigned cancel_hash_bits;
435 bool poll_multi_file;
437 spinlock_t inflight_lock;
438 struct list_head inflight_list;
439 } ____cacheline_aligned_in_smp;
441 struct delayed_work rsrc_put_work;
442 struct llist_head rsrc_put_llist;
443 struct list_head rsrc_ref_list;
444 spinlock_t rsrc_ref_lock;
445 struct fixed_rsrc_ref_node *rsrc_backup_node;
447 struct io_restriction restrictions;
450 struct callback_head *exit_task_work;
452 struct wait_queue_head hash_wait;
454 /* Keep this last, we don't need it for the fast path */
455 struct work_struct exit_work;
456 struct list_head tctx_list;
459 struct io_uring_task {
460 /* submission side */
462 struct wait_queue_head wait;
463 const struct io_ring_ctx *last;
465 struct percpu_counter inflight;
469 spinlock_t task_lock;
470 struct io_wq_work_list task_list;
471 unsigned long task_state;
472 struct callback_head task_work;
476 * First field must be the file pointer in all the
477 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
479 struct io_poll_iocb {
481 struct wait_queue_head *head;
485 struct wait_queue_entry wait;
488 struct io_poll_remove {
498 struct io_timeout_data {
499 struct io_kiocb *req;
500 struct hrtimer timer;
501 struct timespec64 ts;
502 enum hrtimer_mode mode;
507 struct sockaddr __user *addr;
508 int __user *addr_len;
510 unsigned long nofile;
530 struct list_head list;
531 /* head of the link, used by linked timeouts only */
532 struct io_kiocb *head;
535 struct io_timeout_rem {
540 struct timespec64 ts;
545 /* NOTE: kiocb has the file as the first member, so don't do it here */
553 struct sockaddr __user *addr;
560 struct user_msghdr __user *umsg;
566 struct io_buffer *kbuf;
572 struct filename *filename;
574 unsigned long nofile;
577 struct io_rsrc_update {
603 struct epoll_event event;
607 struct file *file_out;
608 struct file *file_in;
615 struct io_provide_buf {
629 const char __user *filename;
630 struct statx __user *buffer;
642 struct filename *oldpath;
643 struct filename *newpath;
651 struct filename *filename;
654 struct io_completion {
656 struct list_head list;
660 struct io_async_connect {
661 struct sockaddr_storage address;
664 struct io_async_msghdr {
665 struct iovec fast_iov[UIO_FASTIOV];
666 /* points to an allocated iov, if NULL we use fast_iov instead */
667 struct iovec *free_iov;
668 struct sockaddr __user *uaddr;
670 struct sockaddr_storage addr;
674 struct iovec fast_iov[UIO_FASTIOV];
675 const struct iovec *free_iovec;
676 struct iov_iter iter;
678 struct wait_page_queue wpq;
682 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
683 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
684 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
685 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
686 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
687 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
693 REQ_F_LINK_TIMEOUT_BIT,
694 REQ_F_NEED_CLEANUP_BIT,
696 REQ_F_BUFFER_SELECTED_BIT,
697 REQ_F_NO_FILE_TABLE_BIT,
698 REQ_F_LTIMEOUT_ACTIVE_BIT,
699 REQ_F_COMPLETE_INLINE_BIT,
701 /* keep async read/write and isreg together and in order */
702 REQ_F_ASYNC_READ_BIT,
703 REQ_F_ASYNC_WRITE_BIT,
706 /* not a real bit, just to check we're not overflowing the space */
712 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
713 /* drain existing IO first */
714 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
716 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
717 /* doesn't sever on completion < 0 */
718 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
720 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
721 /* IOSQE_BUFFER_SELECT */
722 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
724 /* fail rest of links */
725 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
726 /* on inflight list, should be cancelled and waited on exit reliably */
727 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
728 /* read/write uses file position */
729 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
730 /* must not punt to workers */
731 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
732 /* has or had linked timeout */
733 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
735 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
736 /* already went through poll handler */
737 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
738 /* buffer already selected */
739 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
740 /* doesn't need file table for this request */
741 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
742 /* linked timeout is active, i.e. prepared by link's head */
743 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
744 /* completion is deferred through io_comp_state */
745 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
746 /* caller should reissue async */
747 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
748 /* supports async reads */
749 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
750 /* supports async writes */
751 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
753 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
757 struct io_poll_iocb poll;
758 struct io_poll_iocb *double_poll;
761 struct io_task_work {
762 struct io_wq_work_node node;
763 task_work_func_t func;
767 * NOTE! Each of the iocb union members has the file pointer
768 * as the first entry in their struct definition. So you can
769 * access the file pointer through any of the sub-structs,
770 * or directly as just 'ki_filp' in this struct.
776 struct io_poll_iocb poll;
777 struct io_poll_remove poll_remove;
778 struct io_accept accept;
780 struct io_cancel cancel;
781 struct io_timeout timeout;
782 struct io_timeout_rem timeout_rem;
783 struct io_connect connect;
784 struct io_sr_msg sr_msg;
786 struct io_close close;
787 struct io_rsrc_update rsrc_update;
788 struct io_fadvise fadvise;
789 struct io_madvise madvise;
790 struct io_epoll epoll;
791 struct io_splice splice;
792 struct io_provide_buf pbuf;
793 struct io_statx statx;
794 struct io_shutdown shutdown;
795 struct io_rename rename;
796 struct io_unlink unlink;
797 /* use only after cleaning per-op data, see io_clean_op() */
798 struct io_completion compl;
801 /* opcode allocated if it needs to store data for async defer */
804 /* polled IO has completed */
810 struct io_ring_ctx *ctx;
813 struct task_struct *task;
816 struct io_kiocb *link;
817 struct percpu_ref *fixed_rsrc_refs;
820 * 1. used with ctx->iopoll_list with reads/writes
821 * 2. to track reqs with ->files (see io_op_def::file_table)
823 struct list_head inflight_entry;
825 struct io_task_work io_task_work;
826 struct callback_head task_work;
828 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
829 struct hlist_node hash_node;
830 struct async_poll *apoll;
831 struct io_wq_work work;
834 struct io_tctx_node {
835 struct list_head ctx_node;
836 struct task_struct *task;
837 struct io_ring_ctx *ctx;
840 struct io_defer_entry {
841 struct list_head list;
842 struct io_kiocb *req;
847 /* needs req->file assigned */
848 unsigned needs_file : 1;
849 /* hash wq insertion if file is a regular file */
850 unsigned hash_reg_file : 1;
851 /* unbound wq insertion if file is a non-regular file */
852 unsigned unbound_nonreg_file : 1;
853 /* opcode is not supported by this kernel */
854 unsigned not_supported : 1;
855 /* set if opcode supports polled "wait" */
857 unsigned pollout : 1;
858 /* op supports buffer selection */
859 unsigned buffer_select : 1;
860 /* do prep async if is going to be punted */
861 unsigned needs_async_setup : 1;
862 /* should block plug */
864 /* size of async data needed, if any */
865 unsigned short async_size;
868 static const struct io_op_def io_op_defs[] = {
869 [IORING_OP_NOP] = {},
870 [IORING_OP_READV] = {
872 .unbound_nonreg_file = 1,
875 .needs_async_setup = 1,
877 .async_size = sizeof(struct io_async_rw),
879 [IORING_OP_WRITEV] = {
882 .unbound_nonreg_file = 1,
884 .needs_async_setup = 1,
886 .async_size = sizeof(struct io_async_rw),
888 [IORING_OP_FSYNC] = {
891 [IORING_OP_READ_FIXED] = {
893 .unbound_nonreg_file = 1,
896 .async_size = sizeof(struct io_async_rw),
898 [IORING_OP_WRITE_FIXED] = {
901 .unbound_nonreg_file = 1,
904 .async_size = sizeof(struct io_async_rw),
906 [IORING_OP_POLL_ADD] = {
908 .unbound_nonreg_file = 1,
910 [IORING_OP_POLL_REMOVE] = {},
911 [IORING_OP_SYNC_FILE_RANGE] = {
914 [IORING_OP_SENDMSG] = {
916 .unbound_nonreg_file = 1,
918 .needs_async_setup = 1,
919 .async_size = sizeof(struct io_async_msghdr),
921 [IORING_OP_RECVMSG] = {
923 .unbound_nonreg_file = 1,
926 .needs_async_setup = 1,
927 .async_size = sizeof(struct io_async_msghdr),
929 [IORING_OP_TIMEOUT] = {
930 .async_size = sizeof(struct io_timeout_data),
932 [IORING_OP_TIMEOUT_REMOVE] = {
933 /* used by timeout updates' prep() */
935 [IORING_OP_ACCEPT] = {
937 .unbound_nonreg_file = 1,
940 [IORING_OP_ASYNC_CANCEL] = {},
941 [IORING_OP_LINK_TIMEOUT] = {
942 .async_size = sizeof(struct io_timeout_data),
944 [IORING_OP_CONNECT] = {
946 .unbound_nonreg_file = 1,
948 .needs_async_setup = 1,
949 .async_size = sizeof(struct io_async_connect),
951 [IORING_OP_FALLOCATE] = {
954 [IORING_OP_OPENAT] = {},
955 [IORING_OP_CLOSE] = {},
956 [IORING_OP_FILES_UPDATE] = {},
957 [IORING_OP_STATX] = {},
960 .unbound_nonreg_file = 1,
964 .async_size = sizeof(struct io_async_rw),
966 [IORING_OP_WRITE] = {
968 .unbound_nonreg_file = 1,
971 .async_size = sizeof(struct io_async_rw),
973 [IORING_OP_FADVISE] = {
976 [IORING_OP_MADVISE] = {},
979 .unbound_nonreg_file = 1,
984 .unbound_nonreg_file = 1,
988 [IORING_OP_OPENAT2] = {
990 [IORING_OP_EPOLL_CTL] = {
991 .unbound_nonreg_file = 1,
993 [IORING_OP_SPLICE] = {
996 .unbound_nonreg_file = 1,
998 [IORING_OP_PROVIDE_BUFFERS] = {},
999 [IORING_OP_REMOVE_BUFFERS] = {},
1003 .unbound_nonreg_file = 1,
1005 [IORING_OP_SHUTDOWN] = {
1008 [IORING_OP_RENAMEAT] = {},
1009 [IORING_OP_UNLINKAT] = {},
1012 static bool io_disarm_next(struct io_kiocb *req);
1013 static void io_uring_del_task_file(unsigned long index);
1014 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1015 struct task_struct *task,
1016 struct files_struct *files);
1017 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
1018 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
1019 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
1020 struct io_ring_ctx *ctx);
1021 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
1023 static bool io_rw_reissue(struct io_kiocb *req);
1024 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1025 static void io_put_req(struct io_kiocb *req);
1026 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1027 static void io_double_put_req(struct io_kiocb *req);
1028 static void io_dismantle_req(struct io_kiocb *req);
1029 static void io_put_task(struct task_struct *task, int nr);
1030 static void io_queue_next(struct io_kiocb *req);
1031 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1032 static void io_queue_linked_timeout(struct io_kiocb *req);
1033 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1034 struct io_uring_rsrc_update *ip,
1036 static void __io_clean_op(struct io_kiocb *req);
1037 static struct file *io_file_get(struct io_submit_state *state,
1038 struct io_kiocb *req, int fd, bool fixed);
1039 static void __io_queue_sqe(struct io_kiocb *req);
1040 static void io_rsrc_put_work(struct work_struct *work);
1042 static void io_req_task_queue(struct io_kiocb *req);
1043 static void io_submit_flush_completions(struct io_comp_state *cs,
1044 struct io_ring_ctx *ctx);
1045 static int io_req_prep_async(struct io_kiocb *req);
1047 static struct kmem_cache *req_cachep;
1049 static const struct file_operations io_uring_fops;
1051 struct sock *io_uring_get_socket(struct file *file)
1053 #if defined(CONFIG_UNIX)
1054 if (file->f_op == &io_uring_fops) {
1055 struct io_ring_ctx *ctx = file->private_data;
1057 return ctx->ring_sock->sk;
1062 EXPORT_SYMBOL(io_uring_get_socket);
1064 #define io_for_each_link(pos, head) \
1065 for (pos = (head); pos; pos = pos->link)
1067 static inline void io_clean_op(struct io_kiocb *req)
1069 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1073 static inline void io_set_resource_node(struct io_kiocb *req)
1075 struct io_ring_ctx *ctx = req->ctx;
1077 if (!req->fixed_rsrc_refs) {
1078 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1079 percpu_ref_get(req->fixed_rsrc_refs);
1083 static bool io_match_task(struct io_kiocb *head,
1084 struct task_struct *task,
1085 struct files_struct *files)
1087 struct io_kiocb *req;
1089 if (task && head->task != task) {
1090 /* in terms of cancelation, always match if req task is dead */
1091 if (head->task->flags & PF_EXITING)
1098 io_for_each_link(req, head) {
1099 if (req->flags & REQ_F_INFLIGHT)
1105 static inline void req_set_fail_links(struct io_kiocb *req)
1107 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1108 req->flags |= REQ_F_FAIL_LINK;
1111 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1113 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1115 complete(&ctx->ref_comp);
1118 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1120 return !req->timeout.off;
1123 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1125 struct io_ring_ctx *ctx;
1128 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1133 * Use 5 bits less than the max cq entries, that should give us around
1134 * 32 entries per hash list if totally full and uniformly spread.
1136 hash_bits = ilog2(p->cq_entries);
1140 ctx->cancel_hash_bits = hash_bits;
1141 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1143 if (!ctx->cancel_hash)
1145 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1147 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1148 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1151 ctx->flags = p->flags;
1152 init_waitqueue_head(&ctx->sqo_sq_wait);
1153 INIT_LIST_HEAD(&ctx->sqd_list);
1154 init_waitqueue_head(&ctx->cq_wait);
1155 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1156 init_completion(&ctx->ref_comp);
1157 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1158 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1159 mutex_init(&ctx->uring_lock);
1160 init_waitqueue_head(&ctx->wait);
1161 spin_lock_init(&ctx->completion_lock);
1162 INIT_LIST_HEAD(&ctx->iopoll_list);
1163 INIT_LIST_HEAD(&ctx->defer_list);
1164 INIT_LIST_HEAD(&ctx->timeout_list);
1165 spin_lock_init(&ctx->inflight_lock);
1166 INIT_LIST_HEAD(&ctx->inflight_list);
1167 spin_lock_init(&ctx->rsrc_ref_lock);
1168 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1169 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1170 init_llist_head(&ctx->rsrc_put_llist);
1171 INIT_LIST_HEAD(&ctx->tctx_list);
1172 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1173 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1176 kfree(ctx->cancel_hash);
1181 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1183 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1184 struct io_ring_ctx *ctx = req->ctx;
1186 return seq != ctx->cached_cq_tail
1187 + READ_ONCE(ctx->cached_cq_overflow);
1193 static void io_req_track_inflight(struct io_kiocb *req)
1195 struct io_ring_ctx *ctx = req->ctx;
1197 if (!(req->flags & REQ_F_INFLIGHT)) {
1198 req->flags |= REQ_F_INFLIGHT;
1200 spin_lock_irq(&ctx->inflight_lock);
1201 list_add(&req->inflight_entry, &ctx->inflight_list);
1202 spin_unlock_irq(&ctx->inflight_lock);
1206 static void io_prep_async_work(struct io_kiocb *req)
1208 const struct io_op_def *def = &io_op_defs[req->opcode];
1209 struct io_ring_ctx *ctx = req->ctx;
1211 if (!req->work.creds)
1212 req->work.creds = get_current_cred();
1214 if (req->flags & REQ_F_FORCE_ASYNC)
1215 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1217 if (req->flags & REQ_F_ISREG) {
1218 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1219 io_wq_hash_work(&req->work, file_inode(req->file));
1220 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1221 if (def->unbound_nonreg_file)
1222 req->work.flags |= IO_WQ_WORK_UNBOUND;
1226 static void io_prep_async_link(struct io_kiocb *req)
1228 struct io_kiocb *cur;
1230 io_for_each_link(cur, req)
1231 io_prep_async_work(cur);
1234 static void io_queue_async_work(struct io_kiocb *req)
1236 struct io_ring_ctx *ctx = req->ctx;
1237 struct io_kiocb *link = io_prep_linked_timeout(req);
1238 struct io_uring_task *tctx = req->task->io_uring;
1241 BUG_ON(!tctx->io_wq);
1243 /* init ->work of the whole link before punting */
1244 io_prep_async_link(req);
1245 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1246 &req->work, req->flags);
1247 io_wq_enqueue(tctx->io_wq, &req->work);
1249 io_queue_linked_timeout(link);
1252 static void io_kill_timeout(struct io_kiocb *req, int status)
1254 struct io_timeout_data *io = req->async_data;
1257 ret = hrtimer_try_to_cancel(&io->timer);
1259 atomic_set(&req->ctx->cq_timeouts,
1260 atomic_read(&req->ctx->cq_timeouts) + 1);
1261 list_del_init(&req->timeout.list);
1262 io_cqring_fill_event(req, status);
1263 io_put_req_deferred(req, 1);
1267 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1270 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1271 struct io_defer_entry, list);
1273 if (req_need_defer(de->req, de->seq))
1275 list_del_init(&de->list);
1276 io_req_task_queue(de->req);
1278 } while (!list_empty(&ctx->defer_list));
1281 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1285 if (list_empty(&ctx->timeout_list))
1288 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1291 u32 events_needed, events_got;
1292 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1293 struct io_kiocb, timeout.list);
1295 if (io_is_timeout_noseq(req))
1299 * Since seq can easily wrap around over time, subtract
1300 * the last seq at which timeouts were flushed before comparing.
1301 * Assuming not more than 2^31-1 events have happened since,
1302 * these subtractions won't have wrapped, so we can check if
1303 * target is in [last_seq, current_seq] by comparing the two.
1305 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1306 events_got = seq - ctx->cq_last_tm_flush;
1307 if (events_got < events_needed)
1310 list_del_init(&req->timeout.list);
1311 io_kill_timeout(req, 0);
1312 } while (!list_empty(&ctx->timeout_list));
1314 ctx->cq_last_tm_flush = seq;
1317 static void io_commit_cqring(struct io_ring_ctx *ctx)
1319 io_flush_timeouts(ctx);
1321 /* order cqe stores with ring update */
1322 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1324 if (unlikely(!list_empty(&ctx->defer_list)))
1325 __io_queue_deferred(ctx);
1328 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1330 struct io_rings *r = ctx->rings;
1332 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1335 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1337 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1340 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1342 struct io_rings *rings = ctx->rings;
1346 * writes to the cq entry need to come after reading head; the
1347 * control dependency is enough as we're using WRITE_ONCE to
1350 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1353 tail = ctx->cached_cq_tail++;
1354 return &rings->cqes[tail & ctx->cq_mask];
1357 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1361 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1363 if (!ctx->eventfd_async)
1365 return io_wq_current_is_worker();
1368 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1370 /* see waitqueue_active() comment */
1373 if (waitqueue_active(&ctx->wait))
1374 wake_up(&ctx->wait);
1375 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1376 wake_up(&ctx->sq_data->wait);
1377 if (io_should_trigger_evfd(ctx))
1378 eventfd_signal(ctx->cq_ev_fd, 1);
1379 if (waitqueue_active(&ctx->cq_wait)) {
1380 wake_up_interruptible(&ctx->cq_wait);
1381 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1385 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1387 /* see waitqueue_active() comment */
1390 if (ctx->flags & IORING_SETUP_SQPOLL) {
1391 if (waitqueue_active(&ctx->wait))
1392 wake_up(&ctx->wait);
1394 if (io_should_trigger_evfd(ctx))
1395 eventfd_signal(ctx->cq_ev_fd, 1);
1396 if (waitqueue_active(&ctx->cq_wait)) {
1397 wake_up_interruptible(&ctx->cq_wait);
1398 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1402 /* Returns true if there are no backlogged entries after the flush */
1403 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1404 struct task_struct *tsk,
1405 struct files_struct *files)
1407 struct io_rings *rings = ctx->rings;
1408 struct io_kiocb *req, *tmp;
1409 struct io_uring_cqe *cqe;
1410 unsigned long flags;
1411 bool all_flushed, posted;
1414 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1418 spin_lock_irqsave(&ctx->completion_lock, flags);
1419 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1420 if (!io_match_task(req, tsk, files))
1423 cqe = io_get_cqring(ctx);
1427 list_move(&req->compl.list, &list);
1429 WRITE_ONCE(cqe->user_data, req->user_data);
1430 WRITE_ONCE(cqe->res, req->result);
1431 WRITE_ONCE(cqe->flags, req->compl.cflags);
1433 ctx->cached_cq_overflow++;
1434 WRITE_ONCE(ctx->rings->cq_overflow,
1435 ctx->cached_cq_overflow);
1440 all_flushed = list_empty(&ctx->cq_overflow_list);
1442 clear_bit(0, &ctx->sq_check_overflow);
1443 clear_bit(0, &ctx->cq_check_overflow);
1444 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1448 io_commit_cqring(ctx);
1449 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1451 io_cqring_ev_posted(ctx);
1453 while (!list_empty(&list)) {
1454 req = list_first_entry(&list, struct io_kiocb, compl.list);
1455 list_del(&req->compl.list);
1462 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1463 struct task_struct *tsk,
1464 struct files_struct *files)
1468 if (test_bit(0, &ctx->cq_check_overflow)) {
1469 /* iopoll syncs against uring_lock, not completion_lock */
1470 if (ctx->flags & IORING_SETUP_IOPOLL)
1471 mutex_lock(&ctx->uring_lock);
1472 ret = __io_cqring_overflow_flush(ctx, force, tsk, files);
1473 if (ctx->flags & IORING_SETUP_IOPOLL)
1474 mutex_unlock(&ctx->uring_lock);
1481 * Shamelessly stolen from the mm implementation of page reference checking,
1482 * see commit f958d7b528b1 for details.
1484 #define req_ref_zero_or_close_to_overflow(req) \
1485 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1487 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1489 return atomic_inc_not_zero(&req->refs);
1492 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1494 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1495 return atomic_sub_and_test(refs, &req->refs);
1498 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1500 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1501 return atomic_dec_and_test(&req->refs);
1504 static inline void req_ref_put(struct io_kiocb *req)
1506 WARN_ON_ONCE(req_ref_put_and_test(req));
1509 static inline void req_ref_get(struct io_kiocb *req)
1511 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1512 atomic_inc(&req->refs);
1515 static void __io_cqring_fill_event(struct io_kiocb *req, long res,
1516 unsigned int cflags)
1518 struct io_ring_ctx *ctx = req->ctx;
1519 struct io_uring_cqe *cqe;
1521 trace_io_uring_complete(ctx, req->user_data, res);
1524 * If we can't get a cq entry, userspace overflowed the
1525 * submission (by quite a lot). Increment the overflow count in
1528 cqe = io_get_cqring(ctx);
1530 WRITE_ONCE(cqe->user_data, req->user_data);
1531 WRITE_ONCE(cqe->res, res);
1532 WRITE_ONCE(cqe->flags, cflags);
1533 } else if (ctx->cq_overflow_flushed ||
1534 atomic_read(&req->task->io_uring->in_idle)) {
1536 * If we're in ring overflow flush mode, or in task cancel mode,
1537 * then we cannot store the request for later flushing, we need
1538 * to drop it on the floor.
1540 ctx->cached_cq_overflow++;
1541 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1543 if (list_empty(&ctx->cq_overflow_list)) {
1544 set_bit(0, &ctx->sq_check_overflow);
1545 set_bit(0, &ctx->cq_check_overflow);
1546 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1550 req->compl.cflags = cflags;
1552 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1556 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1558 __io_cqring_fill_event(req, res, 0);
1561 static void io_req_complete_post(struct io_kiocb *req, long res,
1562 unsigned int cflags)
1564 struct io_ring_ctx *ctx = req->ctx;
1565 unsigned long flags;
1567 spin_lock_irqsave(&ctx->completion_lock, flags);
1568 __io_cqring_fill_event(req, res, cflags);
1570 * If we're the last reference to this request, add to our locked
1573 if (req_ref_put_and_test(req)) {
1574 struct io_comp_state *cs = &ctx->submit_state.comp;
1576 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1577 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1578 io_disarm_next(req);
1580 io_req_task_queue(req->link);
1584 io_dismantle_req(req);
1585 io_put_task(req->task, 1);
1586 list_add(&req->compl.list, &cs->locked_free_list);
1587 cs->locked_free_nr++;
1589 if (!percpu_ref_tryget(&ctx->refs))
1592 io_commit_cqring(ctx);
1593 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1596 io_cqring_ev_posted(ctx);
1597 percpu_ref_put(&ctx->refs);
1601 static void io_req_complete_state(struct io_kiocb *req, long res,
1602 unsigned int cflags)
1606 req->compl.cflags = cflags;
1607 req->flags |= REQ_F_COMPLETE_INLINE;
1610 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1611 long res, unsigned cflags)
1613 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1614 io_req_complete_state(req, res, cflags);
1616 io_req_complete_post(req, res, cflags);
1619 static inline void io_req_complete(struct io_kiocb *req, long res)
1621 __io_req_complete(req, 0, res, 0);
1624 static void io_req_complete_failed(struct io_kiocb *req, long res)
1626 req_set_fail_links(req);
1628 io_req_complete_post(req, res, 0);
1631 /* Returns true IFF there are requests in the cache */
1632 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1634 struct io_submit_state *state = &ctx->submit_state;
1635 struct io_comp_state *cs = &state->comp;
1639 * If we have more than a batch's worth of requests in our IRQ side
1640 * locked cache, grab the lock and move them over to our submission
1643 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1644 spin_lock_irq(&ctx->completion_lock);
1645 list_splice_init(&cs->locked_free_list, &cs->free_list);
1646 cs->locked_free_nr = 0;
1647 spin_unlock_irq(&ctx->completion_lock);
1650 nr = state->free_reqs;
1651 while (!list_empty(&cs->free_list)) {
1652 struct io_kiocb *req = list_first_entry(&cs->free_list,
1653 struct io_kiocb, compl.list);
1655 list_del(&req->compl.list);
1656 state->reqs[nr++] = req;
1657 if (nr == ARRAY_SIZE(state->reqs))
1661 state->free_reqs = nr;
1665 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1667 struct io_submit_state *state = &ctx->submit_state;
1669 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1671 if (!state->free_reqs) {
1672 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1675 if (io_flush_cached_reqs(ctx))
1678 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1682 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1683 * retry single alloc to be on the safe side.
1685 if (unlikely(ret <= 0)) {
1686 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1687 if (!state->reqs[0])
1691 state->free_reqs = ret;
1695 return state->reqs[state->free_reqs];
1698 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1705 static void io_dismantle_req(struct io_kiocb *req)
1709 if (req->async_data)
1710 kfree(req->async_data);
1712 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1713 if (req->fixed_rsrc_refs)
1714 percpu_ref_put(req->fixed_rsrc_refs);
1715 if (req->work.creds) {
1716 put_cred(req->work.creds);
1717 req->work.creds = NULL;
1720 if (req->flags & REQ_F_INFLIGHT) {
1721 struct io_ring_ctx *ctx = req->ctx;
1722 unsigned long flags;
1724 spin_lock_irqsave(&ctx->inflight_lock, flags);
1725 list_del(&req->inflight_entry);
1726 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1727 req->flags &= ~REQ_F_INFLIGHT;
1731 /* must to be called somewhat shortly after putting a request */
1732 static inline void io_put_task(struct task_struct *task, int nr)
1734 struct io_uring_task *tctx = task->io_uring;
1736 percpu_counter_sub(&tctx->inflight, nr);
1737 if (unlikely(atomic_read(&tctx->in_idle)))
1738 wake_up(&tctx->wait);
1739 put_task_struct_many(task, nr);
1742 static void __io_free_req(struct io_kiocb *req)
1744 struct io_ring_ctx *ctx = req->ctx;
1746 io_dismantle_req(req);
1747 io_put_task(req->task, 1);
1749 kmem_cache_free(req_cachep, req);
1750 percpu_ref_put(&ctx->refs);
1753 static inline void io_remove_next_linked(struct io_kiocb *req)
1755 struct io_kiocb *nxt = req->link;
1757 req->link = nxt->link;
1761 static bool io_kill_linked_timeout(struct io_kiocb *req)
1762 __must_hold(&req->ctx->completion_lock)
1764 struct io_kiocb *link = req->link;
1765 bool cancelled = false;
1768 * Can happen if a linked timeout fired and link had been like
1769 * req -> link t-out -> link t-out [-> ...]
1771 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1772 struct io_timeout_data *io = link->async_data;
1775 io_remove_next_linked(req);
1776 link->timeout.head = NULL;
1777 ret = hrtimer_try_to_cancel(&io->timer);
1779 io_cqring_fill_event(link, -ECANCELED);
1780 io_put_req_deferred(link, 1);
1784 req->flags &= ~REQ_F_LINK_TIMEOUT;
1788 static void io_fail_links(struct io_kiocb *req)
1789 __must_hold(&req->ctx->completion_lock)
1791 struct io_kiocb *nxt, *link = req->link;
1798 trace_io_uring_fail_link(req, link);
1799 io_cqring_fill_event(link, -ECANCELED);
1800 io_put_req_deferred(link, 2);
1805 static bool io_disarm_next(struct io_kiocb *req)
1806 __must_hold(&req->ctx->completion_lock)
1808 bool posted = false;
1810 if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1811 posted = io_kill_linked_timeout(req);
1812 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
1813 posted |= (req->link != NULL);
1819 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1821 struct io_kiocb *nxt;
1824 * If LINK is set, we have dependent requests in this chain. If we
1825 * didn't fail this request, queue the first one up, moving any other
1826 * dependencies to the next request. In case of failure, fail the rest
1829 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK)) {
1830 struct io_ring_ctx *ctx = req->ctx;
1831 unsigned long flags;
1834 spin_lock_irqsave(&ctx->completion_lock, flags);
1835 posted = io_disarm_next(req);
1837 io_commit_cqring(req->ctx);
1838 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1840 io_cqring_ev_posted(ctx);
1847 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1849 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1851 return __io_req_find_next(req);
1854 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1858 if (ctx->submit_state.comp.nr) {
1859 mutex_lock(&ctx->uring_lock);
1860 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1861 mutex_unlock(&ctx->uring_lock);
1863 percpu_ref_put(&ctx->refs);
1866 static bool __tctx_task_work(struct io_uring_task *tctx)
1868 struct io_ring_ctx *ctx = NULL;
1869 struct io_wq_work_list list;
1870 struct io_wq_work_node *node;
1872 if (wq_list_empty(&tctx->task_list))
1875 spin_lock_irq(&tctx->task_lock);
1876 list = tctx->task_list;
1877 INIT_WQ_LIST(&tctx->task_list);
1878 spin_unlock_irq(&tctx->task_lock);
1882 struct io_wq_work_node *next = node->next;
1883 struct io_kiocb *req;
1885 req = container_of(node, struct io_kiocb, io_task_work.node);
1886 if (req->ctx != ctx) {
1887 ctx_flush_and_put(ctx);
1889 percpu_ref_get(&ctx->refs);
1892 req->task_work.func(&req->task_work);
1896 ctx_flush_and_put(ctx);
1897 return list.first != NULL;
1900 static void tctx_task_work(struct callback_head *cb)
1902 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1904 clear_bit(0, &tctx->task_state);
1906 while (__tctx_task_work(tctx))
1910 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1911 enum task_work_notify_mode notify)
1913 struct io_uring_task *tctx = tsk->io_uring;
1914 struct io_wq_work_node *node, *prev;
1915 unsigned long flags;
1918 WARN_ON_ONCE(!tctx);
1920 spin_lock_irqsave(&tctx->task_lock, flags);
1921 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1922 spin_unlock_irqrestore(&tctx->task_lock, flags);
1924 /* task_work already pending, we're done */
1925 if (test_bit(0, &tctx->task_state) ||
1926 test_and_set_bit(0, &tctx->task_state))
1929 if (!task_work_add(tsk, &tctx->task_work, notify))
1933 * Slow path - we failed, find and delete work. if the work is not
1934 * in the list, it got run and we're fine.
1937 spin_lock_irqsave(&tctx->task_lock, flags);
1938 wq_list_for_each(node, prev, &tctx->task_list) {
1939 if (&req->io_task_work.node == node) {
1940 wq_list_del(&tctx->task_list, node, prev);
1945 spin_unlock_irqrestore(&tctx->task_lock, flags);
1946 clear_bit(0, &tctx->task_state);
1950 static int io_req_task_work_add(struct io_kiocb *req)
1952 struct task_struct *tsk = req->task;
1953 struct io_ring_ctx *ctx = req->ctx;
1954 enum task_work_notify_mode notify;
1957 if (tsk->flags & PF_EXITING)
1961 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1962 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1963 * processing task_work. There's no reliable way to tell if TWA_RESUME
1967 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1968 notify = TWA_SIGNAL;
1970 ret = io_task_work_add(tsk, req, notify);
1972 wake_up_process(tsk);
1977 static bool io_run_task_work_head(struct callback_head **work_head)
1979 struct callback_head *work, *next;
1980 bool executed = false;
1983 work = xchg(work_head, NULL);
1999 static void io_task_work_add_head(struct callback_head **work_head,
2000 struct callback_head *task_work)
2002 struct callback_head *head;
2005 head = READ_ONCE(*work_head);
2006 task_work->next = head;
2007 } while (cmpxchg(work_head, head, task_work) != head);
2010 static void io_req_task_work_add_fallback(struct io_kiocb *req,
2011 task_work_func_t cb)
2013 init_task_work(&req->task_work, cb);
2014 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2017 static void __io_req_task_cancel(struct io_kiocb *req, int error)
2019 struct io_ring_ctx *ctx = req->ctx;
2021 spin_lock_irq(&ctx->completion_lock);
2022 io_cqring_fill_event(req, error);
2023 io_commit_cqring(ctx);
2024 spin_unlock_irq(&ctx->completion_lock);
2026 io_cqring_ev_posted(ctx);
2027 req_set_fail_links(req);
2028 io_double_put_req(req);
2031 static void io_req_task_cancel(struct callback_head *cb)
2033 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2034 struct io_ring_ctx *ctx = req->ctx;
2036 /* ctx is guaranteed to stay alive while we hold uring_lock */
2037 mutex_lock(&ctx->uring_lock);
2038 __io_req_task_cancel(req, req->result);
2039 mutex_unlock(&ctx->uring_lock);
2042 static void __io_req_task_submit(struct io_kiocb *req)
2044 struct io_ring_ctx *ctx = req->ctx;
2046 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2047 mutex_lock(&ctx->uring_lock);
2048 if (!(current->flags & PF_EXITING) && !current->in_execve)
2049 __io_queue_sqe(req);
2051 __io_req_task_cancel(req, -EFAULT);
2052 mutex_unlock(&ctx->uring_lock);
2055 static void io_req_task_submit(struct callback_head *cb)
2057 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2059 __io_req_task_submit(req);
2062 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2065 req->task_work.func = io_req_task_cancel;
2067 if (unlikely(io_req_task_work_add(req)))
2068 io_req_task_work_add_fallback(req, io_req_task_cancel);
2071 static void io_req_task_queue(struct io_kiocb *req)
2073 req->task_work.func = io_req_task_submit;
2075 if (unlikely(io_req_task_work_add(req)))
2076 io_req_task_queue_fail(req, -ECANCELED);
2079 static inline void io_queue_next(struct io_kiocb *req)
2081 struct io_kiocb *nxt = io_req_find_next(req);
2084 io_req_task_queue(nxt);
2087 static void io_free_req(struct io_kiocb *req)
2094 struct task_struct *task;
2099 static inline void io_init_req_batch(struct req_batch *rb)
2106 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2107 struct req_batch *rb)
2110 io_put_task(rb->task, rb->task_refs);
2112 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2115 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2116 struct io_submit_state *state)
2119 io_dismantle_req(req);
2121 if (req->task != rb->task) {
2123 io_put_task(rb->task, rb->task_refs);
2124 rb->task = req->task;
2130 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2131 state->reqs[state->free_reqs++] = req;
2133 list_add(&req->compl.list, &state->comp.free_list);
2136 static void io_submit_flush_completions(struct io_comp_state *cs,
2137 struct io_ring_ctx *ctx)
2140 struct io_kiocb *req;
2141 struct req_batch rb;
2143 io_init_req_batch(&rb);
2144 spin_lock_irq(&ctx->completion_lock);
2145 for (i = 0; i < nr; i++) {
2147 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2149 io_commit_cqring(ctx);
2150 spin_unlock_irq(&ctx->completion_lock);
2152 io_cqring_ev_posted(ctx);
2153 for (i = 0; i < nr; i++) {
2156 /* submission and completion refs */
2157 if (req_ref_sub_and_test(req, 2))
2158 io_req_free_batch(&rb, req, &ctx->submit_state);
2161 io_req_free_batch_finish(ctx, &rb);
2166 * Drop reference to request, return next in chain (if there is one) if this
2167 * was the last reference to this request.
2169 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2171 struct io_kiocb *nxt = NULL;
2173 if (req_ref_put_and_test(req)) {
2174 nxt = io_req_find_next(req);
2180 static void io_put_req(struct io_kiocb *req)
2182 if (req_ref_put_and_test(req))
2186 static void io_put_req_deferred_cb(struct callback_head *cb)
2188 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2193 static void io_free_req_deferred(struct io_kiocb *req)
2197 req->task_work.func = io_put_req_deferred_cb;
2198 ret = io_req_task_work_add(req);
2200 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2203 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2205 if (req_ref_sub_and_test(req, refs))
2206 io_free_req_deferred(req);
2209 static void io_double_put_req(struct io_kiocb *req)
2211 /* drop both submit and complete references */
2212 if (req_ref_sub_and_test(req, 2))
2216 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2218 /* See comment at the top of this file */
2220 return __io_cqring_events(ctx);
2223 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2225 struct io_rings *rings = ctx->rings;
2227 /* make sure SQ entry isn't read before tail */
2228 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2231 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2233 unsigned int cflags;
2235 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2236 cflags |= IORING_CQE_F_BUFFER;
2237 req->flags &= ~REQ_F_BUFFER_SELECTED;
2242 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2244 struct io_buffer *kbuf;
2246 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2247 return io_put_kbuf(req, kbuf);
2250 static inline bool io_run_task_work(void)
2253 * Not safe to run on exiting task, and the task_work handling will
2254 * not add work to such a task.
2256 if (unlikely(current->flags & PF_EXITING))
2258 if (current->task_works) {
2259 __set_current_state(TASK_RUNNING);
2268 * Find and free completed poll iocbs
2270 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2271 struct list_head *done)
2273 struct req_batch rb;
2274 struct io_kiocb *req;
2276 /* order with ->result store in io_complete_rw_iopoll() */
2279 io_init_req_batch(&rb);
2280 while (!list_empty(done)) {
2283 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2284 list_del(&req->inflight_entry);
2286 if (READ_ONCE(req->result) == -EAGAIN) {
2287 req->iopoll_completed = 0;
2288 if (io_rw_reissue(req))
2292 if (req->flags & REQ_F_BUFFER_SELECTED)
2293 cflags = io_put_rw_kbuf(req);
2295 __io_cqring_fill_event(req, req->result, cflags);
2298 if (req_ref_put_and_test(req))
2299 io_req_free_batch(&rb, req, &ctx->submit_state);
2302 io_commit_cqring(ctx);
2303 io_cqring_ev_posted_iopoll(ctx);
2304 io_req_free_batch_finish(ctx, &rb);
2307 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2310 struct io_kiocb *req, *tmp;
2316 * Only spin for completions if we don't have multiple devices hanging
2317 * off our complete list, and we're under the requested amount.
2319 spin = !ctx->poll_multi_file && *nr_events < min;
2322 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2323 struct kiocb *kiocb = &req->rw.kiocb;
2326 * Move completed and retryable entries to our local lists.
2327 * If we find a request that requires polling, break out
2328 * and complete those lists first, if we have entries there.
2330 if (READ_ONCE(req->iopoll_completed)) {
2331 list_move_tail(&req->inflight_entry, &done);
2334 if (!list_empty(&done))
2337 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2341 /* iopoll may have completed current req */
2342 if (READ_ONCE(req->iopoll_completed))
2343 list_move_tail(&req->inflight_entry, &done);
2350 if (!list_empty(&done))
2351 io_iopoll_complete(ctx, nr_events, &done);
2357 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2358 * non-spinning poll check - we'll still enter the driver poll loop, but only
2359 * as a non-spinning completion check.
2361 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2364 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2367 ret = io_do_iopoll(ctx, nr_events, min);
2370 if (*nr_events >= min)
2378 * We can't just wait for polled events to come to us, we have to actively
2379 * find and complete them.
2381 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2383 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2386 mutex_lock(&ctx->uring_lock);
2387 while (!list_empty(&ctx->iopoll_list)) {
2388 unsigned int nr_events = 0;
2390 io_do_iopoll(ctx, &nr_events, 0);
2392 /* let it sleep and repeat later if can't complete a request */
2396 * Ensure we allow local-to-the-cpu processing to take place,
2397 * in this case we need to ensure that we reap all events.
2398 * Also let task_work, etc. to progress by releasing the mutex
2400 if (need_resched()) {
2401 mutex_unlock(&ctx->uring_lock);
2403 mutex_lock(&ctx->uring_lock);
2406 mutex_unlock(&ctx->uring_lock);
2409 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2411 unsigned int nr_events = 0;
2412 int iters = 0, ret = 0;
2415 * We disallow the app entering submit/complete with polling, but we
2416 * still need to lock the ring to prevent racing with polled issue
2417 * that got punted to a workqueue.
2419 mutex_lock(&ctx->uring_lock);
2422 * Don't enter poll loop if we already have events pending.
2423 * If we do, we can potentially be spinning for commands that
2424 * already triggered a CQE (eg in error).
2426 if (test_bit(0, &ctx->cq_check_overflow))
2427 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2428 if (io_cqring_events(ctx))
2432 * If a submit got punted to a workqueue, we can have the
2433 * application entering polling for a command before it gets
2434 * issued. That app will hold the uring_lock for the duration
2435 * of the poll right here, so we need to take a breather every
2436 * now and then to ensure that the issue has a chance to add
2437 * the poll to the issued list. Otherwise we can spin here
2438 * forever, while the workqueue is stuck trying to acquire the
2441 if (!(++iters & 7)) {
2442 mutex_unlock(&ctx->uring_lock);
2444 mutex_lock(&ctx->uring_lock);
2447 ret = io_iopoll_getevents(ctx, &nr_events, min);
2451 } while (min && !nr_events && !need_resched());
2453 mutex_unlock(&ctx->uring_lock);
2457 static void kiocb_end_write(struct io_kiocb *req)
2460 * Tell lockdep we inherited freeze protection from submission
2463 if (req->flags & REQ_F_ISREG) {
2464 struct inode *inode = file_inode(req->file);
2466 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2468 file_end_write(req->file);
2472 static bool io_resubmit_prep(struct io_kiocb *req)
2474 /* either already prepared or successfully done */
2475 return req->async_data || !io_req_prep_async(req);
2478 static bool io_rw_should_reissue(struct io_kiocb *req)
2480 umode_t mode = file_inode(req->file)->i_mode;
2481 struct io_ring_ctx *ctx = req->ctx;
2483 if (!S_ISBLK(mode) && !S_ISREG(mode))
2485 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2486 !(ctx->flags & IORING_SETUP_IOPOLL)))
2489 * If ref is dying, we might be running poll reap from the exit work.
2490 * Don't attempt to reissue from that path, just let it fail with
2493 if (percpu_ref_is_dying(&ctx->refs))
2498 static bool io_rw_should_reissue(struct io_kiocb *req)
2504 static bool io_rw_reissue(struct io_kiocb *req)
2507 if (!io_rw_should_reissue(req))
2510 lockdep_assert_held(&req->ctx->uring_lock);
2512 if (io_resubmit_prep(req)) {
2514 io_queue_async_work(req);
2517 req_set_fail_links(req);
2522 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2523 unsigned int issue_flags)
2527 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2528 kiocb_end_write(req);
2529 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_should_reissue(req)) {
2530 req->flags |= REQ_F_REISSUE;
2533 if (res != req->result)
2534 req_set_fail_links(req);
2535 if (req->flags & REQ_F_BUFFER_SELECTED)
2536 cflags = io_put_rw_kbuf(req);
2537 __io_req_complete(req, issue_flags, res, cflags);
2540 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2542 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2544 __io_complete_rw(req, res, res2, 0);
2547 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2549 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2552 /* Rewind iter, if we have one. iopoll path resubmits as usual */
2553 if (res == -EAGAIN && io_rw_should_reissue(req)) {
2554 struct io_async_rw *rw = req->async_data;
2557 iov_iter_revert(&rw->iter,
2558 req->result - iov_iter_count(&rw->iter));
2559 else if (!io_resubmit_prep(req))
2564 if (kiocb->ki_flags & IOCB_WRITE)
2565 kiocb_end_write(req);
2567 if (res != -EAGAIN && res != req->result)
2568 req_set_fail_links(req);
2570 WRITE_ONCE(req->result, res);
2571 /* order with io_iopoll_complete() checking ->result */
2573 WRITE_ONCE(req->iopoll_completed, 1);
2577 * After the iocb has been issued, it's safe to be found on the poll list.
2578 * Adding the kiocb to the list AFTER submission ensures that we don't
2579 * find it from a io_iopoll_getevents() thread before the issuer is done
2580 * accessing the kiocb cookie.
2582 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2584 struct io_ring_ctx *ctx = req->ctx;
2587 * Track whether we have multiple files in our lists. This will impact
2588 * how we do polling eventually, not spinning if we're on potentially
2589 * different devices.
2591 if (list_empty(&ctx->iopoll_list)) {
2592 ctx->poll_multi_file = false;
2593 } else if (!ctx->poll_multi_file) {
2594 struct io_kiocb *list_req;
2596 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2598 if (list_req->file != req->file)
2599 ctx->poll_multi_file = true;
2603 * For fast devices, IO may have already completed. If it has, add
2604 * it to the front so we find it first.
2606 if (READ_ONCE(req->iopoll_completed))
2607 list_add(&req->inflight_entry, &ctx->iopoll_list);
2609 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2612 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2613 * task context or in io worker task context. If current task context is
2614 * sq thread, we don't need to check whether should wake up sq thread.
2616 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2617 wq_has_sleeper(&ctx->sq_data->wait))
2618 wake_up(&ctx->sq_data->wait);
2621 static inline void io_state_file_put(struct io_submit_state *state)
2623 if (state->file_refs) {
2624 fput_many(state->file, state->file_refs);
2625 state->file_refs = 0;
2630 * Get as many references to a file as we have IOs left in this submission,
2631 * assuming most submissions are for one file, or at least that each file
2632 * has more than one submission.
2634 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2639 if (state->file_refs) {
2640 if (state->fd == fd) {
2644 io_state_file_put(state);
2646 state->file = fget_many(fd, state->ios_left);
2647 if (unlikely(!state->file))
2651 state->file_refs = state->ios_left - 1;
2655 static bool io_bdev_nowait(struct block_device *bdev)
2657 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2661 * If we tracked the file through the SCM inflight mechanism, we could support
2662 * any file. For now, just ensure that anything potentially problematic is done
2665 static bool __io_file_supports_async(struct file *file, int rw)
2667 umode_t mode = file_inode(file)->i_mode;
2669 if (S_ISBLK(mode)) {
2670 if (IS_ENABLED(CONFIG_BLOCK) &&
2671 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2675 if (S_ISCHR(mode) || S_ISSOCK(mode))
2677 if (S_ISREG(mode)) {
2678 if (IS_ENABLED(CONFIG_BLOCK) &&
2679 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2680 file->f_op != &io_uring_fops)
2685 /* any ->read/write should understand O_NONBLOCK */
2686 if (file->f_flags & O_NONBLOCK)
2689 if (!(file->f_mode & FMODE_NOWAIT))
2693 return file->f_op->read_iter != NULL;
2695 return file->f_op->write_iter != NULL;
2698 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2700 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2702 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2705 return __io_file_supports_async(req->file, rw);
2708 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2710 struct io_ring_ctx *ctx = req->ctx;
2711 struct kiocb *kiocb = &req->rw.kiocb;
2712 struct file *file = req->file;
2716 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2717 req->flags |= REQ_F_ISREG;
2719 kiocb->ki_pos = READ_ONCE(sqe->off);
2720 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2721 req->flags |= REQ_F_CUR_POS;
2722 kiocb->ki_pos = file->f_pos;
2724 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2725 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2726 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2730 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2731 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2732 req->flags |= REQ_F_NOWAIT;
2734 ioprio = READ_ONCE(sqe->ioprio);
2736 ret = ioprio_check_cap(ioprio);
2740 kiocb->ki_ioprio = ioprio;
2742 kiocb->ki_ioprio = get_current_ioprio();
2744 if (ctx->flags & IORING_SETUP_IOPOLL) {
2745 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2746 !kiocb->ki_filp->f_op->iopoll)
2749 kiocb->ki_flags |= IOCB_HIPRI;
2750 kiocb->ki_complete = io_complete_rw_iopoll;
2751 req->iopoll_completed = 0;
2753 if (kiocb->ki_flags & IOCB_HIPRI)
2755 kiocb->ki_complete = io_complete_rw;
2758 req->rw.addr = READ_ONCE(sqe->addr);
2759 req->rw.len = READ_ONCE(sqe->len);
2760 req->buf_index = READ_ONCE(sqe->buf_index);
2764 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2770 case -ERESTARTNOINTR:
2771 case -ERESTARTNOHAND:
2772 case -ERESTART_RESTARTBLOCK:
2774 * We can't just restart the syscall, since previously
2775 * submitted sqes may already be in progress. Just fail this
2781 kiocb->ki_complete(kiocb, ret, 0);
2785 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2786 unsigned int issue_flags)
2788 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2789 struct io_async_rw *io = req->async_data;
2790 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2792 /* add previously done IO, if any */
2793 if (io && io->bytes_done > 0) {
2795 ret = io->bytes_done;
2797 ret += io->bytes_done;
2800 if (req->flags & REQ_F_CUR_POS)
2801 req->file->f_pos = kiocb->ki_pos;
2802 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2803 __io_complete_rw(req, ret, 0, issue_flags);
2805 io_rw_done(kiocb, ret);
2807 if (check_reissue && req->flags & REQ_F_REISSUE) {
2808 req->flags &= ~REQ_F_REISSUE;
2809 if (!io_rw_reissue(req)) {
2812 req_set_fail_links(req);
2813 if (req->flags & REQ_F_BUFFER_SELECTED)
2814 cflags = io_put_rw_kbuf(req);
2815 __io_req_complete(req, issue_flags, ret, cflags);
2820 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2822 struct io_ring_ctx *ctx = req->ctx;
2823 size_t len = req->rw.len;
2824 struct io_mapped_ubuf *imu;
2825 u16 index, buf_index = req->buf_index;
2829 if (unlikely(buf_index >= ctx->nr_user_bufs))
2831 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2832 imu = &ctx->user_bufs[index];
2833 buf_addr = req->rw.addr;
2836 if (buf_addr + len < buf_addr)
2838 /* not inside the mapped region */
2839 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2843 * May not be a start of buffer, set size appropriately
2844 * and advance us to the beginning.
2846 offset = buf_addr - imu->ubuf;
2847 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2851 * Don't use iov_iter_advance() here, as it's really slow for
2852 * using the latter parts of a big fixed buffer - it iterates
2853 * over each segment manually. We can cheat a bit here, because
2856 * 1) it's a BVEC iter, we set it up
2857 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2858 * first and last bvec
2860 * So just find our index, and adjust the iterator afterwards.
2861 * If the offset is within the first bvec (or the whole first
2862 * bvec, just use iov_iter_advance(). This makes it easier
2863 * since we can just skip the first segment, which may not
2864 * be PAGE_SIZE aligned.
2866 const struct bio_vec *bvec = imu->bvec;
2868 if (offset <= bvec->bv_len) {
2869 iov_iter_advance(iter, offset);
2871 unsigned long seg_skip;
2873 /* skip first vec */
2874 offset -= bvec->bv_len;
2875 seg_skip = 1 + (offset >> PAGE_SHIFT);
2877 iter->bvec = bvec + seg_skip;
2878 iter->nr_segs -= seg_skip;
2879 iter->count -= bvec->bv_len + offset;
2880 iter->iov_offset = offset & ~PAGE_MASK;
2887 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2890 mutex_unlock(&ctx->uring_lock);
2893 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2896 * "Normal" inline submissions always hold the uring_lock, since we
2897 * grab it from the system call. Same is true for the SQPOLL offload.
2898 * The only exception is when we've detached the request and issue it
2899 * from an async worker thread, grab the lock for that case.
2902 mutex_lock(&ctx->uring_lock);
2905 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2906 int bgid, struct io_buffer *kbuf,
2909 struct io_buffer *head;
2911 if (req->flags & REQ_F_BUFFER_SELECTED)
2914 io_ring_submit_lock(req->ctx, needs_lock);
2916 lockdep_assert_held(&req->ctx->uring_lock);
2918 head = xa_load(&req->ctx->io_buffers, bgid);
2920 if (!list_empty(&head->list)) {
2921 kbuf = list_last_entry(&head->list, struct io_buffer,
2923 list_del(&kbuf->list);
2926 xa_erase(&req->ctx->io_buffers, bgid);
2928 if (*len > kbuf->len)
2931 kbuf = ERR_PTR(-ENOBUFS);
2934 io_ring_submit_unlock(req->ctx, needs_lock);
2939 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2942 struct io_buffer *kbuf;
2945 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2946 bgid = req->buf_index;
2947 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2950 req->rw.addr = (u64) (unsigned long) kbuf;
2951 req->flags |= REQ_F_BUFFER_SELECTED;
2952 return u64_to_user_ptr(kbuf->addr);
2955 #ifdef CONFIG_COMPAT
2956 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2959 struct compat_iovec __user *uiov;
2960 compat_ssize_t clen;
2964 uiov = u64_to_user_ptr(req->rw.addr);
2965 if (!access_ok(uiov, sizeof(*uiov)))
2967 if (__get_user(clen, &uiov->iov_len))
2973 buf = io_rw_buffer_select(req, &len, needs_lock);
2975 return PTR_ERR(buf);
2976 iov[0].iov_base = buf;
2977 iov[0].iov_len = (compat_size_t) len;
2982 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2985 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2989 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2992 len = iov[0].iov_len;
2995 buf = io_rw_buffer_select(req, &len, needs_lock);
2997 return PTR_ERR(buf);
2998 iov[0].iov_base = buf;
2999 iov[0].iov_len = len;
3003 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3006 if (req->flags & REQ_F_BUFFER_SELECTED) {
3007 struct io_buffer *kbuf;
3009 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
3010 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3011 iov[0].iov_len = kbuf->len;
3014 if (req->rw.len != 1)
3017 #ifdef CONFIG_COMPAT
3018 if (req->ctx->compat)
3019 return io_compat_import(req, iov, needs_lock);
3022 return __io_iov_buffer_select(req, iov, needs_lock);
3025 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
3026 struct iov_iter *iter, bool needs_lock)
3028 void __user *buf = u64_to_user_ptr(req->rw.addr);
3029 size_t sqe_len = req->rw.len;
3030 u8 opcode = req->opcode;
3033 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3035 return io_import_fixed(req, rw, iter);
3038 /* buffer index only valid with fixed read/write, or buffer select */
3039 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
3042 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3043 if (req->flags & REQ_F_BUFFER_SELECT) {
3044 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
3046 return PTR_ERR(buf);
3047 req->rw.len = sqe_len;
3050 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3055 if (req->flags & REQ_F_BUFFER_SELECT) {
3056 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3058 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3063 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3067 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3069 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3073 * For files that don't have ->read_iter() and ->write_iter(), handle them
3074 * by looping over ->read() or ->write() manually.
3076 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3078 struct kiocb *kiocb = &req->rw.kiocb;
3079 struct file *file = req->file;
3083 * Don't support polled IO through this interface, and we can't
3084 * support non-blocking either. For the latter, this just causes
3085 * the kiocb to be handled from an async context.
3087 if (kiocb->ki_flags & IOCB_HIPRI)
3089 if (kiocb->ki_flags & IOCB_NOWAIT)
3092 while (iov_iter_count(iter)) {
3096 if (!iov_iter_is_bvec(iter)) {
3097 iovec = iov_iter_iovec(iter);
3099 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3100 iovec.iov_len = req->rw.len;
3104 nr = file->f_op->read(file, iovec.iov_base,
3105 iovec.iov_len, io_kiocb_ppos(kiocb));
3107 nr = file->f_op->write(file, iovec.iov_base,
3108 iovec.iov_len, io_kiocb_ppos(kiocb));
3117 if (nr != iovec.iov_len)
3121 iov_iter_advance(iter, nr);
3127 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3128 const struct iovec *fast_iov, struct iov_iter *iter)
3130 struct io_async_rw *rw = req->async_data;
3132 memcpy(&rw->iter, iter, sizeof(*iter));
3133 rw->free_iovec = iovec;
3135 /* can only be fixed buffers, no need to do anything */
3136 if (iov_iter_is_bvec(iter))
3139 unsigned iov_off = 0;
3141 rw->iter.iov = rw->fast_iov;
3142 if (iter->iov != fast_iov) {
3143 iov_off = iter->iov - fast_iov;
3144 rw->iter.iov += iov_off;
3146 if (rw->fast_iov != fast_iov)
3147 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3148 sizeof(struct iovec) * iter->nr_segs);
3150 req->flags |= REQ_F_NEED_CLEANUP;
3154 static inline int io_alloc_async_data(struct io_kiocb *req)
3156 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3157 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3158 return req->async_data == NULL;
3161 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3162 const struct iovec *fast_iov,
3163 struct iov_iter *iter, bool force)
3165 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3167 if (!req->async_data) {
3168 if (io_alloc_async_data(req)) {
3173 io_req_map_rw(req, iovec, fast_iov, iter);
3178 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3180 struct io_async_rw *iorw = req->async_data;
3181 struct iovec *iov = iorw->fast_iov;
3184 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3185 if (unlikely(ret < 0))
3188 iorw->bytes_done = 0;
3189 iorw->free_iovec = iov;
3191 req->flags |= REQ_F_NEED_CLEANUP;
3195 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3197 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3199 return io_prep_rw(req, sqe);
3203 * This is our waitqueue callback handler, registered through lock_page_async()
3204 * when we initially tried to do the IO with the iocb armed our waitqueue.
3205 * This gets called when the page is unlocked, and we generally expect that to
3206 * happen when the page IO is completed and the page is now uptodate. This will
3207 * queue a task_work based retry of the operation, attempting to copy the data
3208 * again. If the latter fails because the page was NOT uptodate, then we will
3209 * do a thread based blocking retry of the operation. That's the unexpected
3212 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3213 int sync, void *arg)
3215 struct wait_page_queue *wpq;
3216 struct io_kiocb *req = wait->private;
3217 struct wait_page_key *key = arg;
3219 wpq = container_of(wait, struct wait_page_queue, wait);
3221 if (!wake_page_match(wpq, key))
3224 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3225 list_del_init(&wait->entry);
3227 /* submit ref gets dropped, acquire a new one */
3229 io_req_task_queue(req);
3234 * This controls whether a given IO request should be armed for async page
3235 * based retry. If we return false here, the request is handed to the async
3236 * worker threads for retry. If we're doing buffered reads on a regular file,
3237 * we prepare a private wait_page_queue entry and retry the operation. This
3238 * will either succeed because the page is now uptodate and unlocked, or it
3239 * will register a callback when the page is unlocked at IO completion. Through
3240 * that callback, io_uring uses task_work to setup a retry of the operation.
3241 * That retry will attempt the buffered read again. The retry will generally
3242 * succeed, or in rare cases where it fails, we then fall back to using the
3243 * async worker threads for a blocking retry.
3245 static bool io_rw_should_retry(struct io_kiocb *req)
3247 struct io_async_rw *rw = req->async_data;
3248 struct wait_page_queue *wait = &rw->wpq;
3249 struct kiocb *kiocb = &req->rw.kiocb;
3251 /* never retry for NOWAIT, we just complete with -EAGAIN */
3252 if (req->flags & REQ_F_NOWAIT)
3255 /* Only for buffered IO */
3256 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3260 * just use poll if we can, and don't attempt if the fs doesn't
3261 * support callback based unlocks
3263 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3266 wait->wait.func = io_async_buf_func;
3267 wait->wait.private = req;
3268 wait->wait.flags = 0;
3269 INIT_LIST_HEAD(&wait->wait.entry);
3270 kiocb->ki_flags |= IOCB_WAITQ;
3271 kiocb->ki_flags &= ~IOCB_NOWAIT;
3272 kiocb->ki_waitq = wait;
3276 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3278 if (req->file->f_op->read_iter)
3279 return call_read_iter(req->file, &req->rw.kiocb, iter);
3280 else if (req->file->f_op->read)
3281 return loop_rw_iter(READ, req, iter);
3286 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3288 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3289 struct kiocb *kiocb = &req->rw.kiocb;
3290 struct iov_iter __iter, *iter = &__iter;
3291 struct io_async_rw *rw = req->async_data;
3292 ssize_t io_size, ret, ret2;
3293 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3299 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3303 io_size = iov_iter_count(iter);
3304 req->result = io_size;
3306 /* Ensure we clear previously set non-block flag */
3307 if (!force_nonblock)
3308 kiocb->ki_flags &= ~IOCB_NOWAIT;
3310 kiocb->ki_flags |= IOCB_NOWAIT;
3312 /* If the file doesn't support async, just async punt */
3313 if (force_nonblock && !io_file_supports_async(req, READ)) {
3314 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3315 return ret ?: -EAGAIN;
3318 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3319 if (unlikely(ret)) {
3324 ret = io_iter_do_read(req, iter);
3326 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3327 req->flags &= ~REQ_F_REISSUE;
3328 /* IOPOLL retry should happen for io-wq threads */
3329 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3331 /* no retry on NONBLOCK nor RWF_NOWAIT */
3332 if (req->flags & REQ_F_NOWAIT)
3334 /* some cases will consume bytes even on error returns */
3335 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3337 } else if (ret == -EIOCBQUEUED) {
3339 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3340 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3341 /* read all, failed, already did sync or don't want to retry */
3345 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3350 rw = req->async_data;
3351 /* now use our persistent iterator, if we aren't already */
3356 rw->bytes_done += ret;
3357 /* if we can retry, do so with the callbacks armed */
3358 if (!io_rw_should_retry(req)) {
3359 kiocb->ki_flags &= ~IOCB_WAITQ;
3364 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3365 * we get -EIOCBQUEUED, then we'll get a notification when the
3366 * desired page gets unlocked. We can also get a partial read
3367 * here, and if we do, then just retry at the new offset.
3369 ret = io_iter_do_read(req, iter);
3370 if (ret == -EIOCBQUEUED)
3372 /* we got some bytes, but not all. retry. */
3373 kiocb->ki_flags &= ~IOCB_WAITQ;
3374 } while (ret > 0 && ret < io_size);
3376 kiocb_done(kiocb, ret, issue_flags);
3378 /* it's faster to check here then delegate to kfree */
3384 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3386 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3388 return io_prep_rw(req, sqe);
3391 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3393 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3394 struct kiocb *kiocb = &req->rw.kiocb;
3395 struct iov_iter __iter, *iter = &__iter;
3396 struct io_async_rw *rw = req->async_data;
3397 ssize_t ret, ret2, io_size;
3398 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3404 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3408 io_size = iov_iter_count(iter);
3409 req->result = io_size;
3411 /* Ensure we clear previously set non-block flag */
3412 if (!force_nonblock)
3413 kiocb->ki_flags &= ~IOCB_NOWAIT;
3415 kiocb->ki_flags |= IOCB_NOWAIT;
3417 /* If the file doesn't support async, just async punt */
3418 if (force_nonblock && !io_file_supports_async(req, WRITE))
3421 /* file path doesn't support NOWAIT for non-direct_IO */
3422 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3423 (req->flags & REQ_F_ISREG))
3426 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3431 * Open-code file_start_write here to grab freeze protection,
3432 * which will be released by another thread in
3433 * io_complete_rw(). Fool lockdep by telling it the lock got
3434 * released so that it doesn't complain about the held lock when
3435 * we return to userspace.
3437 if (req->flags & REQ_F_ISREG) {
3438 sb_start_write(file_inode(req->file)->i_sb);
3439 __sb_writers_release(file_inode(req->file)->i_sb,
3442 kiocb->ki_flags |= IOCB_WRITE;
3444 if (req->file->f_op->write_iter)
3445 ret2 = call_write_iter(req->file, kiocb, iter);
3446 else if (req->file->f_op->write)
3447 ret2 = loop_rw_iter(WRITE, req, iter);
3451 if (req->flags & REQ_F_REISSUE) {
3452 req->flags &= ~REQ_F_REISSUE;
3457 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3458 * retry them without IOCB_NOWAIT.
3460 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3462 /* no retry on NONBLOCK nor RWF_NOWAIT */
3463 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3465 if (!force_nonblock || ret2 != -EAGAIN) {
3466 /* IOPOLL retry should happen for io-wq threads */
3467 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3470 kiocb_done(kiocb, ret2, issue_flags);
3473 /* some cases will consume bytes even on error returns */
3474 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3475 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3476 return ret ?: -EAGAIN;
3479 /* it's reportedly faster than delegating the null check to kfree() */
3485 static int io_renameat_prep(struct io_kiocb *req,
3486 const struct io_uring_sqe *sqe)
3488 struct io_rename *ren = &req->rename;
3489 const char __user *oldf, *newf;
3491 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3494 ren->old_dfd = READ_ONCE(sqe->fd);
3495 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3496 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3497 ren->new_dfd = READ_ONCE(sqe->len);
3498 ren->flags = READ_ONCE(sqe->rename_flags);
3500 ren->oldpath = getname(oldf);
3501 if (IS_ERR(ren->oldpath))
3502 return PTR_ERR(ren->oldpath);
3504 ren->newpath = getname(newf);
3505 if (IS_ERR(ren->newpath)) {
3506 putname(ren->oldpath);
3507 return PTR_ERR(ren->newpath);
3510 req->flags |= REQ_F_NEED_CLEANUP;
3514 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3516 struct io_rename *ren = &req->rename;
3519 if (issue_flags & IO_URING_F_NONBLOCK)
3522 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3523 ren->newpath, ren->flags);
3525 req->flags &= ~REQ_F_NEED_CLEANUP;
3527 req_set_fail_links(req);
3528 io_req_complete(req, ret);
3532 static int io_unlinkat_prep(struct io_kiocb *req,
3533 const struct io_uring_sqe *sqe)
3535 struct io_unlink *un = &req->unlink;
3536 const char __user *fname;
3538 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3541 un->dfd = READ_ONCE(sqe->fd);
3543 un->flags = READ_ONCE(sqe->unlink_flags);
3544 if (un->flags & ~AT_REMOVEDIR)
3547 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3548 un->filename = getname(fname);
3549 if (IS_ERR(un->filename))
3550 return PTR_ERR(un->filename);
3552 req->flags |= REQ_F_NEED_CLEANUP;
3556 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3558 struct io_unlink *un = &req->unlink;
3561 if (issue_flags & IO_URING_F_NONBLOCK)
3564 if (un->flags & AT_REMOVEDIR)
3565 ret = do_rmdir(un->dfd, un->filename);
3567 ret = do_unlinkat(un->dfd, un->filename);
3569 req->flags &= ~REQ_F_NEED_CLEANUP;
3571 req_set_fail_links(req);
3572 io_req_complete(req, ret);
3576 static int io_shutdown_prep(struct io_kiocb *req,
3577 const struct io_uring_sqe *sqe)
3579 #if defined(CONFIG_NET)
3580 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3582 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3586 req->shutdown.how = READ_ONCE(sqe->len);
3593 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3595 #if defined(CONFIG_NET)
3596 struct socket *sock;
3599 if (issue_flags & IO_URING_F_NONBLOCK)
3602 sock = sock_from_file(req->file);
3603 if (unlikely(!sock))
3606 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3608 req_set_fail_links(req);
3609 io_req_complete(req, ret);
3616 static int __io_splice_prep(struct io_kiocb *req,
3617 const struct io_uring_sqe *sqe)
3619 struct io_splice* sp = &req->splice;
3620 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3622 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3626 sp->len = READ_ONCE(sqe->len);
3627 sp->flags = READ_ONCE(sqe->splice_flags);
3629 if (unlikely(sp->flags & ~valid_flags))
3632 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3633 (sp->flags & SPLICE_F_FD_IN_FIXED));
3636 req->flags |= REQ_F_NEED_CLEANUP;
3638 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3640 * Splice operation will be punted aync, and here need to
3641 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3643 req->work.flags |= IO_WQ_WORK_UNBOUND;
3649 static int io_tee_prep(struct io_kiocb *req,
3650 const struct io_uring_sqe *sqe)
3652 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3654 return __io_splice_prep(req, sqe);
3657 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3659 struct io_splice *sp = &req->splice;
3660 struct file *in = sp->file_in;
3661 struct file *out = sp->file_out;
3662 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3665 if (issue_flags & IO_URING_F_NONBLOCK)
3668 ret = do_tee(in, out, sp->len, flags);
3670 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3671 req->flags &= ~REQ_F_NEED_CLEANUP;
3674 req_set_fail_links(req);
3675 io_req_complete(req, ret);
3679 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3681 struct io_splice* sp = &req->splice;
3683 sp->off_in = READ_ONCE(sqe->splice_off_in);
3684 sp->off_out = READ_ONCE(sqe->off);
3685 return __io_splice_prep(req, sqe);
3688 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3690 struct io_splice *sp = &req->splice;
3691 struct file *in = sp->file_in;
3692 struct file *out = sp->file_out;
3693 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3694 loff_t *poff_in, *poff_out;
3697 if (issue_flags & IO_URING_F_NONBLOCK)
3700 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3701 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3704 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3706 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3707 req->flags &= ~REQ_F_NEED_CLEANUP;
3710 req_set_fail_links(req);
3711 io_req_complete(req, ret);
3716 * IORING_OP_NOP just posts a completion event, nothing else.
3718 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3720 struct io_ring_ctx *ctx = req->ctx;
3722 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3725 __io_req_complete(req, issue_flags, 0, 0);
3729 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3731 struct io_ring_ctx *ctx = req->ctx;
3736 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3738 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3741 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3742 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3745 req->sync.off = READ_ONCE(sqe->off);
3746 req->sync.len = READ_ONCE(sqe->len);
3750 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3752 loff_t end = req->sync.off + req->sync.len;
3755 /* fsync always requires a blocking context */
3756 if (issue_flags & IO_URING_F_NONBLOCK)
3759 ret = vfs_fsync_range(req->file, req->sync.off,
3760 end > 0 ? end : LLONG_MAX,
3761 req->sync.flags & IORING_FSYNC_DATASYNC);
3763 req_set_fail_links(req);
3764 io_req_complete(req, ret);
3768 static int io_fallocate_prep(struct io_kiocb *req,
3769 const struct io_uring_sqe *sqe)
3771 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3773 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3776 req->sync.off = READ_ONCE(sqe->off);
3777 req->sync.len = READ_ONCE(sqe->addr);
3778 req->sync.mode = READ_ONCE(sqe->len);
3782 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3786 /* fallocate always requiring blocking context */
3787 if (issue_flags & IO_URING_F_NONBLOCK)
3789 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3792 req_set_fail_links(req);
3793 io_req_complete(req, ret);
3797 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3799 const char __user *fname;
3802 if (unlikely(sqe->ioprio || sqe->buf_index))
3804 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3807 /* open.how should be already initialised */
3808 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3809 req->open.how.flags |= O_LARGEFILE;
3811 req->open.dfd = READ_ONCE(sqe->fd);
3812 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3813 req->open.filename = getname(fname);
3814 if (IS_ERR(req->open.filename)) {
3815 ret = PTR_ERR(req->open.filename);
3816 req->open.filename = NULL;
3819 req->open.nofile = rlimit(RLIMIT_NOFILE);
3820 req->flags |= REQ_F_NEED_CLEANUP;
3824 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3828 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3830 mode = READ_ONCE(sqe->len);
3831 flags = READ_ONCE(sqe->open_flags);
3832 req->open.how = build_open_how(flags, mode);
3833 return __io_openat_prep(req, sqe);
3836 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3838 struct open_how __user *how;
3842 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3844 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3845 len = READ_ONCE(sqe->len);
3846 if (len < OPEN_HOW_SIZE_VER0)
3849 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3854 return __io_openat_prep(req, sqe);
3857 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3859 struct open_flags op;
3862 bool resolve_nonblock;
3865 ret = build_open_flags(&req->open.how, &op);
3868 nonblock_set = op.open_flag & O_NONBLOCK;
3869 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3870 if (issue_flags & IO_URING_F_NONBLOCK) {
3872 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3873 * it'll always -EAGAIN
3875 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3877 op.lookup_flags |= LOOKUP_CACHED;
3878 op.open_flag |= O_NONBLOCK;
3881 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3885 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3886 /* only retry if RESOLVE_CACHED wasn't already set by application */
3887 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3888 file == ERR_PTR(-EAGAIN)) {
3890 * We could hang on to this 'fd', but seems like marginal
3891 * gain for something that is now known to be a slower path.
3892 * So just put it, and we'll get a new one when we retry.
3900 ret = PTR_ERR(file);
3902 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3903 file->f_flags &= ~O_NONBLOCK;
3904 fsnotify_open(file);
3905 fd_install(ret, file);
3908 putname(req->open.filename);
3909 req->flags &= ~REQ_F_NEED_CLEANUP;
3911 req_set_fail_links(req);
3912 io_req_complete(req, ret);
3916 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3918 return io_openat2(req, issue_flags);
3921 static int io_remove_buffers_prep(struct io_kiocb *req,
3922 const struct io_uring_sqe *sqe)
3924 struct io_provide_buf *p = &req->pbuf;
3927 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3930 tmp = READ_ONCE(sqe->fd);
3931 if (!tmp || tmp > USHRT_MAX)
3934 memset(p, 0, sizeof(*p));
3936 p->bgid = READ_ONCE(sqe->buf_group);
3940 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3941 int bgid, unsigned nbufs)
3945 /* shouldn't happen */
3949 /* the head kbuf is the list itself */
3950 while (!list_empty(&buf->list)) {
3951 struct io_buffer *nxt;
3953 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3954 list_del(&nxt->list);
3961 xa_erase(&ctx->io_buffers, bgid);
3966 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3968 struct io_provide_buf *p = &req->pbuf;
3969 struct io_ring_ctx *ctx = req->ctx;
3970 struct io_buffer *head;
3972 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3974 io_ring_submit_lock(ctx, !force_nonblock);
3976 lockdep_assert_held(&ctx->uring_lock);
3979 head = xa_load(&ctx->io_buffers, p->bgid);
3981 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3983 req_set_fail_links(req);
3985 /* complete before unlock, IOPOLL may need the lock */
3986 __io_req_complete(req, issue_flags, ret, 0);
3987 io_ring_submit_unlock(ctx, !force_nonblock);
3991 static int io_provide_buffers_prep(struct io_kiocb *req,
3992 const struct io_uring_sqe *sqe)
3995 struct io_provide_buf *p = &req->pbuf;
3998 if (sqe->ioprio || sqe->rw_flags)
4001 tmp = READ_ONCE(sqe->fd);
4002 if (!tmp || tmp > USHRT_MAX)
4005 p->addr = READ_ONCE(sqe->addr);
4006 p->len = READ_ONCE(sqe->len);
4008 size = (unsigned long)p->len * p->nbufs;
4009 if (!access_ok(u64_to_user_ptr(p->addr), size))
4012 p->bgid = READ_ONCE(sqe->buf_group);
4013 tmp = READ_ONCE(sqe->off);
4014 if (tmp > USHRT_MAX)
4020 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
4022 struct io_buffer *buf;
4023 u64 addr = pbuf->addr;
4024 int i, bid = pbuf->bid;
4026 for (i = 0; i < pbuf->nbufs; i++) {
4027 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
4032 buf->len = pbuf->len;
4037 INIT_LIST_HEAD(&buf->list);
4040 list_add_tail(&buf->list, &(*head)->list);
4044 return i ? i : -ENOMEM;
4047 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4049 struct io_provide_buf *p = &req->pbuf;
4050 struct io_ring_ctx *ctx = req->ctx;
4051 struct io_buffer *head, *list;
4053 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4055 io_ring_submit_lock(ctx, !force_nonblock);
4057 lockdep_assert_held(&ctx->uring_lock);
4059 list = head = xa_load(&ctx->io_buffers, p->bgid);
4061 ret = io_add_buffers(p, &head);
4062 if (ret >= 0 && !list) {
4063 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4065 __io_remove_buffers(ctx, head, p->bgid, -1U);
4068 req_set_fail_links(req);
4069 /* complete before unlock, IOPOLL may need the lock */
4070 __io_req_complete(req, issue_flags, ret, 0);
4071 io_ring_submit_unlock(ctx, !force_nonblock);
4075 static int io_epoll_ctl_prep(struct io_kiocb *req,
4076 const struct io_uring_sqe *sqe)
4078 #if defined(CONFIG_EPOLL)
4079 if (sqe->ioprio || sqe->buf_index)
4081 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4084 req->epoll.epfd = READ_ONCE(sqe->fd);
4085 req->epoll.op = READ_ONCE(sqe->len);
4086 req->epoll.fd = READ_ONCE(sqe->off);
4088 if (ep_op_has_event(req->epoll.op)) {
4089 struct epoll_event __user *ev;
4091 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4092 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4102 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4104 #if defined(CONFIG_EPOLL)
4105 struct io_epoll *ie = &req->epoll;
4107 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4109 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4110 if (force_nonblock && ret == -EAGAIN)
4114 req_set_fail_links(req);
4115 __io_req_complete(req, issue_flags, ret, 0);
4122 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4124 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4125 if (sqe->ioprio || sqe->buf_index || sqe->off)
4127 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4130 req->madvise.addr = READ_ONCE(sqe->addr);
4131 req->madvise.len = READ_ONCE(sqe->len);
4132 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4139 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4141 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4142 struct io_madvise *ma = &req->madvise;
4145 if (issue_flags & IO_URING_F_NONBLOCK)
4148 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4150 req_set_fail_links(req);
4151 io_req_complete(req, ret);
4158 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4160 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4162 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4165 req->fadvise.offset = READ_ONCE(sqe->off);
4166 req->fadvise.len = READ_ONCE(sqe->len);
4167 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4171 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4173 struct io_fadvise *fa = &req->fadvise;
4176 if (issue_flags & IO_URING_F_NONBLOCK) {
4177 switch (fa->advice) {
4178 case POSIX_FADV_NORMAL:
4179 case POSIX_FADV_RANDOM:
4180 case POSIX_FADV_SEQUENTIAL:
4187 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4189 req_set_fail_links(req);
4190 io_req_complete(req, ret);
4194 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4196 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4198 if (sqe->ioprio || sqe->buf_index)
4200 if (req->flags & REQ_F_FIXED_FILE)
4203 req->statx.dfd = READ_ONCE(sqe->fd);
4204 req->statx.mask = READ_ONCE(sqe->len);
4205 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4206 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4207 req->statx.flags = READ_ONCE(sqe->statx_flags);
4212 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4214 struct io_statx *ctx = &req->statx;
4217 if (issue_flags & IO_URING_F_NONBLOCK) {
4218 /* only need file table for an actual valid fd */
4219 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4220 req->flags |= REQ_F_NO_FILE_TABLE;
4224 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4228 req_set_fail_links(req);
4229 io_req_complete(req, ret);
4233 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4235 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4237 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4238 sqe->rw_flags || sqe->buf_index)
4240 if (req->flags & REQ_F_FIXED_FILE)
4243 req->close.fd = READ_ONCE(sqe->fd);
4247 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4249 struct files_struct *files = current->files;
4250 struct io_close *close = &req->close;
4251 struct fdtable *fdt;
4257 spin_lock(&files->file_lock);
4258 fdt = files_fdtable(files);
4259 if (close->fd >= fdt->max_fds) {
4260 spin_unlock(&files->file_lock);
4263 file = fdt->fd[close->fd];
4265 spin_unlock(&files->file_lock);
4269 if (file->f_op == &io_uring_fops) {
4270 spin_unlock(&files->file_lock);
4275 /* if the file has a flush method, be safe and punt to async */
4276 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4277 spin_unlock(&files->file_lock);
4281 ret = __close_fd_get_file(close->fd, &file);
4282 spin_unlock(&files->file_lock);
4289 /* No ->flush() or already async, safely close from here */
4290 ret = filp_close(file, current->files);
4293 req_set_fail_links(req);
4296 __io_req_complete(req, issue_flags, ret, 0);
4300 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4302 struct io_ring_ctx *ctx = req->ctx;
4304 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4306 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4309 req->sync.off = READ_ONCE(sqe->off);
4310 req->sync.len = READ_ONCE(sqe->len);
4311 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4315 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4319 /* sync_file_range always requires a blocking context */
4320 if (issue_flags & IO_URING_F_NONBLOCK)
4323 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4326 req_set_fail_links(req);
4327 io_req_complete(req, ret);
4331 #if defined(CONFIG_NET)
4332 static int io_setup_async_msg(struct io_kiocb *req,
4333 struct io_async_msghdr *kmsg)
4335 struct io_async_msghdr *async_msg = req->async_data;
4339 if (io_alloc_async_data(req)) {
4340 kfree(kmsg->free_iov);
4343 async_msg = req->async_data;
4344 req->flags |= REQ_F_NEED_CLEANUP;
4345 memcpy(async_msg, kmsg, sizeof(*kmsg));
4346 async_msg->msg.msg_name = &async_msg->addr;
4347 /* if were using fast_iov, set it to the new one */
4348 if (!async_msg->free_iov)
4349 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4354 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4355 struct io_async_msghdr *iomsg)
4357 iomsg->msg.msg_name = &iomsg->addr;
4358 iomsg->free_iov = iomsg->fast_iov;
4359 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4360 req->sr_msg.msg_flags, &iomsg->free_iov);
4363 static int io_sendmsg_prep_async(struct io_kiocb *req)
4367 ret = io_sendmsg_copy_hdr(req, req->async_data);
4369 req->flags |= REQ_F_NEED_CLEANUP;
4373 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4375 struct io_sr_msg *sr = &req->sr_msg;
4377 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4380 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4381 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4382 sr->len = READ_ONCE(sqe->len);
4384 #ifdef CONFIG_COMPAT
4385 if (req->ctx->compat)
4386 sr->msg_flags |= MSG_CMSG_COMPAT;
4391 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4393 struct io_async_msghdr iomsg, *kmsg;
4394 struct socket *sock;
4399 sock = sock_from_file(req->file);
4400 if (unlikely(!sock))
4403 kmsg = req->async_data;
4405 ret = io_sendmsg_copy_hdr(req, &iomsg);
4411 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4412 if (flags & MSG_DONTWAIT)
4413 req->flags |= REQ_F_NOWAIT;
4414 else if (issue_flags & IO_URING_F_NONBLOCK)
4415 flags |= MSG_DONTWAIT;
4417 if (flags & MSG_WAITALL)
4418 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4420 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4421 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4422 return io_setup_async_msg(req, kmsg);
4423 if (ret == -ERESTARTSYS)
4426 /* fast path, check for non-NULL to avoid function call */
4428 kfree(kmsg->free_iov);
4429 req->flags &= ~REQ_F_NEED_CLEANUP;
4431 req_set_fail_links(req);
4432 __io_req_complete(req, issue_flags, ret, 0);
4436 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4438 struct io_sr_msg *sr = &req->sr_msg;
4441 struct socket *sock;
4446 sock = sock_from_file(req->file);
4447 if (unlikely(!sock))
4450 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4454 msg.msg_name = NULL;
4455 msg.msg_control = NULL;
4456 msg.msg_controllen = 0;
4457 msg.msg_namelen = 0;
4459 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4460 if (flags & MSG_DONTWAIT)
4461 req->flags |= REQ_F_NOWAIT;
4462 else if (issue_flags & IO_URING_F_NONBLOCK)
4463 flags |= MSG_DONTWAIT;
4465 if (flags & MSG_WAITALL)
4466 min_ret = iov_iter_count(&msg.msg_iter);
4468 msg.msg_flags = flags;
4469 ret = sock_sendmsg(sock, &msg);
4470 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4472 if (ret == -ERESTARTSYS)
4476 req_set_fail_links(req);
4477 __io_req_complete(req, issue_flags, ret, 0);
4481 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4482 struct io_async_msghdr *iomsg)
4484 struct io_sr_msg *sr = &req->sr_msg;
4485 struct iovec __user *uiov;
4489 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4490 &iomsg->uaddr, &uiov, &iov_len);
4494 if (req->flags & REQ_F_BUFFER_SELECT) {
4497 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4499 sr->len = iomsg->fast_iov[0].iov_len;
4500 iomsg->free_iov = NULL;
4502 iomsg->free_iov = iomsg->fast_iov;
4503 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4504 &iomsg->free_iov, &iomsg->msg.msg_iter,
4513 #ifdef CONFIG_COMPAT
4514 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4515 struct io_async_msghdr *iomsg)
4517 struct compat_msghdr __user *msg_compat;
4518 struct io_sr_msg *sr = &req->sr_msg;
4519 struct compat_iovec __user *uiov;
4524 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4525 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4530 uiov = compat_ptr(ptr);
4531 if (req->flags & REQ_F_BUFFER_SELECT) {
4532 compat_ssize_t clen;
4536 if (!access_ok(uiov, sizeof(*uiov)))
4538 if (__get_user(clen, &uiov->iov_len))
4543 iomsg->free_iov = NULL;
4545 iomsg->free_iov = iomsg->fast_iov;
4546 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4547 UIO_FASTIOV, &iomsg->free_iov,
4548 &iomsg->msg.msg_iter, true);
4557 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4558 struct io_async_msghdr *iomsg)
4560 iomsg->msg.msg_name = &iomsg->addr;
4562 #ifdef CONFIG_COMPAT
4563 if (req->ctx->compat)
4564 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4567 return __io_recvmsg_copy_hdr(req, iomsg);
4570 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4573 struct io_sr_msg *sr = &req->sr_msg;
4574 struct io_buffer *kbuf;
4576 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4581 req->flags |= REQ_F_BUFFER_SELECTED;
4585 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4587 return io_put_kbuf(req, req->sr_msg.kbuf);
4590 static int io_recvmsg_prep_async(struct io_kiocb *req)
4594 ret = io_recvmsg_copy_hdr(req, req->async_data);
4596 req->flags |= REQ_F_NEED_CLEANUP;
4600 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4602 struct io_sr_msg *sr = &req->sr_msg;
4604 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4607 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4608 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4609 sr->len = READ_ONCE(sqe->len);
4610 sr->bgid = READ_ONCE(sqe->buf_group);
4612 #ifdef CONFIG_COMPAT
4613 if (req->ctx->compat)
4614 sr->msg_flags |= MSG_CMSG_COMPAT;
4619 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4621 struct io_async_msghdr iomsg, *kmsg;
4622 struct socket *sock;
4623 struct io_buffer *kbuf;
4626 int ret, cflags = 0;
4627 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4629 sock = sock_from_file(req->file);
4630 if (unlikely(!sock))
4633 kmsg = req->async_data;
4635 ret = io_recvmsg_copy_hdr(req, &iomsg);
4641 if (req->flags & REQ_F_BUFFER_SELECT) {
4642 kbuf = io_recv_buffer_select(req, !force_nonblock);
4644 return PTR_ERR(kbuf);
4645 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4646 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4647 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4648 1, req->sr_msg.len);
4651 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4652 if (flags & MSG_DONTWAIT)
4653 req->flags |= REQ_F_NOWAIT;
4654 else if (force_nonblock)
4655 flags |= MSG_DONTWAIT;
4657 if (flags & MSG_WAITALL)
4658 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4660 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4661 kmsg->uaddr, flags);
4662 if (force_nonblock && ret == -EAGAIN)
4663 return io_setup_async_msg(req, kmsg);
4664 if (ret == -ERESTARTSYS)
4667 if (req->flags & REQ_F_BUFFER_SELECTED)
4668 cflags = io_put_recv_kbuf(req);
4669 /* fast path, check for non-NULL to avoid function call */
4671 kfree(kmsg->free_iov);
4672 req->flags &= ~REQ_F_NEED_CLEANUP;
4673 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4674 req_set_fail_links(req);
4675 __io_req_complete(req, issue_flags, ret, cflags);
4679 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4681 struct io_buffer *kbuf;
4682 struct io_sr_msg *sr = &req->sr_msg;
4684 void __user *buf = sr->buf;
4685 struct socket *sock;
4689 int ret, cflags = 0;
4690 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4692 sock = sock_from_file(req->file);
4693 if (unlikely(!sock))
4696 if (req->flags & REQ_F_BUFFER_SELECT) {
4697 kbuf = io_recv_buffer_select(req, !force_nonblock);
4699 return PTR_ERR(kbuf);
4700 buf = u64_to_user_ptr(kbuf->addr);
4703 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4707 msg.msg_name = NULL;
4708 msg.msg_control = NULL;
4709 msg.msg_controllen = 0;
4710 msg.msg_namelen = 0;
4711 msg.msg_iocb = NULL;
4714 flags = req->sr_msg.msg_flags | MSG_NOSIGNAL;
4715 if (flags & MSG_DONTWAIT)
4716 req->flags |= REQ_F_NOWAIT;
4717 else if (force_nonblock)
4718 flags |= MSG_DONTWAIT;
4720 if (flags & MSG_WAITALL)
4721 min_ret = iov_iter_count(&msg.msg_iter);
4723 ret = sock_recvmsg(sock, &msg, flags);
4724 if (force_nonblock && ret == -EAGAIN)
4726 if (ret == -ERESTARTSYS)
4729 if (req->flags & REQ_F_BUFFER_SELECTED)
4730 cflags = io_put_recv_kbuf(req);
4731 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4732 req_set_fail_links(req);
4733 __io_req_complete(req, issue_flags, ret, cflags);
4737 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4739 struct io_accept *accept = &req->accept;
4741 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4743 if (sqe->ioprio || sqe->len || sqe->buf_index)
4746 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4747 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4748 accept->flags = READ_ONCE(sqe->accept_flags);
4749 accept->nofile = rlimit(RLIMIT_NOFILE);
4753 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4755 struct io_accept *accept = &req->accept;
4756 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4757 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4760 if (req->file->f_flags & O_NONBLOCK)
4761 req->flags |= REQ_F_NOWAIT;
4763 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4764 accept->addr_len, accept->flags,
4766 if (ret == -EAGAIN && force_nonblock)
4769 if (ret == -ERESTARTSYS)
4771 req_set_fail_links(req);
4773 __io_req_complete(req, issue_flags, ret, 0);
4777 static int io_connect_prep_async(struct io_kiocb *req)
4779 struct io_async_connect *io = req->async_data;
4780 struct io_connect *conn = &req->connect;
4782 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4785 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4787 struct io_connect *conn = &req->connect;
4789 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4791 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4794 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4795 conn->addr_len = READ_ONCE(sqe->addr2);
4799 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4801 struct io_async_connect __io, *io;
4802 unsigned file_flags;
4804 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4806 if (req->async_data) {
4807 io = req->async_data;
4809 ret = move_addr_to_kernel(req->connect.addr,
4810 req->connect.addr_len,
4817 file_flags = force_nonblock ? O_NONBLOCK : 0;
4819 ret = __sys_connect_file(req->file, &io->address,
4820 req->connect.addr_len, file_flags);
4821 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4822 if (req->async_data)
4824 if (io_alloc_async_data(req)) {
4828 memcpy(req->async_data, &__io, sizeof(__io));
4831 if (ret == -ERESTARTSYS)
4835 req_set_fail_links(req);
4836 __io_req_complete(req, issue_flags, ret, 0);
4839 #else /* !CONFIG_NET */
4840 #define IO_NETOP_FN(op) \
4841 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4843 return -EOPNOTSUPP; \
4846 #define IO_NETOP_PREP(op) \
4848 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4850 return -EOPNOTSUPP; \
4853 #define IO_NETOP_PREP_ASYNC(op) \
4855 static int io_##op##_prep_async(struct io_kiocb *req) \
4857 return -EOPNOTSUPP; \
4860 IO_NETOP_PREP_ASYNC(sendmsg);
4861 IO_NETOP_PREP_ASYNC(recvmsg);
4862 IO_NETOP_PREP_ASYNC(connect);
4863 IO_NETOP_PREP(accept);
4866 #endif /* CONFIG_NET */
4868 struct io_poll_table {
4869 struct poll_table_struct pt;
4870 struct io_kiocb *req;
4874 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4875 __poll_t mask, task_work_func_t func)
4879 /* for instances that support it check for an event match first: */
4880 if (mask && !(mask & poll->events))
4883 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4885 list_del_init(&poll->wait.entry);
4888 req->task_work.func = func;
4891 * If this fails, then the task is exiting. When a task exits, the
4892 * work gets canceled, so just cancel this request as well instead
4893 * of executing it. We can't safely execute it anyway, as we may not
4894 * have the needed state needed for it anyway.
4896 ret = io_req_task_work_add(req);
4897 if (unlikely(ret)) {
4898 WRITE_ONCE(poll->canceled, true);
4899 io_req_task_work_add_fallback(req, func);
4904 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4905 __acquires(&req->ctx->completion_lock)
4907 struct io_ring_ctx *ctx = req->ctx;
4909 if (!req->result && !READ_ONCE(poll->canceled)) {
4910 struct poll_table_struct pt = { ._key = poll->events };
4912 req->result = vfs_poll(req->file, &pt) & poll->events;
4915 spin_lock_irq(&ctx->completion_lock);
4916 if (!req->result && !READ_ONCE(poll->canceled)) {
4917 add_wait_queue(poll->head, &poll->wait);
4924 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4926 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4927 if (req->opcode == IORING_OP_POLL_ADD)
4928 return req->async_data;
4929 return req->apoll->double_poll;
4932 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4934 if (req->opcode == IORING_OP_POLL_ADD)
4936 return &req->apoll->poll;
4939 static void io_poll_remove_double(struct io_kiocb *req)
4941 struct io_poll_iocb *poll = io_poll_get_double(req);
4943 lockdep_assert_held(&req->ctx->completion_lock);
4945 if (poll && poll->head) {
4946 struct wait_queue_head *head = poll->head;
4948 spin_lock(&head->lock);
4949 list_del_init(&poll->wait.entry);
4950 if (poll->wait.private)
4953 spin_unlock(&head->lock);
4957 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4959 struct io_ring_ctx *ctx = req->ctx;
4961 if (!error && req->poll.canceled)
4964 io_poll_remove_double(req);
4965 req->poll.done = true;
4966 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4967 io_commit_cqring(ctx);
4970 static void io_poll_task_func(struct callback_head *cb)
4972 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4973 struct io_ring_ctx *ctx = req->ctx;
4974 struct io_kiocb *nxt;
4976 if (io_poll_rewait(req, &req->poll)) {
4977 spin_unlock_irq(&ctx->completion_lock);
4979 hash_del(&req->hash_node);
4980 io_poll_complete(req, req->result, 0);
4981 spin_unlock_irq(&ctx->completion_lock);
4983 nxt = io_put_req_find_next(req);
4984 io_cqring_ev_posted(ctx);
4986 __io_req_task_submit(nxt);
4990 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4991 int sync, void *key)
4993 struct io_kiocb *req = wait->private;
4994 struct io_poll_iocb *poll = io_poll_get_single(req);
4995 __poll_t mask = key_to_poll(key);
4997 /* for instances that support it check for an event match first: */
4998 if (mask && !(mask & poll->events))
5001 list_del_init(&wait->entry);
5003 if (poll && poll->head) {
5006 spin_lock(&poll->head->lock);
5007 done = list_empty(&poll->wait.entry);
5009 list_del_init(&poll->wait.entry);
5010 /* make sure double remove sees this as being gone */
5011 wait->private = NULL;
5012 spin_unlock(&poll->head->lock);
5014 /* use wait func handler, so it matches the rq type */
5015 poll->wait.func(&poll->wait, mode, sync, key);
5022 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5023 wait_queue_func_t wake_func)
5027 poll->canceled = false;
5028 poll->events = events;
5029 INIT_LIST_HEAD(&poll->wait.entry);
5030 init_waitqueue_func_entry(&poll->wait, wake_func);
5033 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
5034 struct wait_queue_head *head,
5035 struct io_poll_iocb **poll_ptr)
5037 struct io_kiocb *req = pt->req;
5040 * If poll->head is already set, it's because the file being polled
5041 * uses multiple waitqueues for poll handling (eg one for read, one
5042 * for write). Setup a separate io_poll_iocb if this happens.
5044 if (unlikely(poll->head)) {
5045 struct io_poll_iocb *poll_one = poll;
5047 /* already have a 2nd entry, fail a third attempt */
5049 pt->error = -EINVAL;
5052 /* double add on the same waitqueue head, ignore */
5053 if (poll->head == head)
5055 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5057 pt->error = -ENOMEM;
5060 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5062 poll->wait.private = req;
5069 if (poll->events & EPOLLEXCLUSIVE)
5070 add_wait_queue_exclusive(head, &poll->wait);
5072 add_wait_queue(head, &poll->wait);
5075 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5076 struct poll_table_struct *p)
5078 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5079 struct async_poll *apoll = pt->req->apoll;
5081 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5084 static void io_async_task_func(struct callback_head *cb)
5086 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5087 struct async_poll *apoll = req->apoll;
5088 struct io_ring_ctx *ctx = req->ctx;
5090 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5092 if (io_poll_rewait(req, &apoll->poll)) {
5093 spin_unlock_irq(&ctx->completion_lock);
5097 /* If req is still hashed, it cannot have been canceled. Don't check. */
5098 if (hash_hashed(&req->hash_node))
5099 hash_del(&req->hash_node);
5101 io_poll_remove_double(req);
5102 spin_unlock_irq(&ctx->completion_lock);
5104 if (!READ_ONCE(apoll->poll.canceled))
5105 __io_req_task_submit(req);
5107 __io_req_task_cancel(req, -ECANCELED);
5109 kfree(apoll->double_poll);
5113 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5116 struct io_kiocb *req = wait->private;
5117 struct io_poll_iocb *poll = &req->apoll->poll;
5119 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5122 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5125 static void io_poll_req_insert(struct io_kiocb *req)
5127 struct io_ring_ctx *ctx = req->ctx;
5128 struct hlist_head *list;
5130 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5131 hlist_add_head(&req->hash_node, list);
5134 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5135 struct io_poll_iocb *poll,
5136 struct io_poll_table *ipt, __poll_t mask,
5137 wait_queue_func_t wake_func)
5138 __acquires(&ctx->completion_lock)
5140 struct io_ring_ctx *ctx = req->ctx;
5141 bool cancel = false;
5143 INIT_HLIST_NODE(&req->hash_node);
5144 io_init_poll_iocb(poll, mask, wake_func);
5145 poll->file = req->file;
5146 poll->wait.private = req;
5148 ipt->pt._key = mask;
5150 ipt->error = -EINVAL;
5152 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5154 spin_lock_irq(&ctx->completion_lock);
5155 if (likely(poll->head)) {
5156 spin_lock(&poll->head->lock);
5157 if (unlikely(list_empty(&poll->wait.entry))) {
5163 if (mask || ipt->error)
5164 list_del_init(&poll->wait.entry);
5166 WRITE_ONCE(poll->canceled, true);
5167 else if (!poll->done) /* actually waiting for an event */
5168 io_poll_req_insert(req);
5169 spin_unlock(&poll->head->lock);
5175 static bool io_arm_poll_handler(struct io_kiocb *req)
5177 const struct io_op_def *def = &io_op_defs[req->opcode];
5178 struct io_ring_ctx *ctx = req->ctx;
5179 struct async_poll *apoll;
5180 struct io_poll_table ipt;
5184 if (!req->file || !file_can_poll(req->file))
5186 if (req->flags & REQ_F_POLLED)
5190 else if (def->pollout)
5194 /* if we can't nonblock try, then no point in arming a poll handler */
5195 if (!io_file_supports_async(req, rw))
5198 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5199 if (unlikely(!apoll))
5201 apoll->double_poll = NULL;
5203 req->flags |= REQ_F_POLLED;
5208 mask |= POLLIN | POLLRDNORM;
5210 mask |= POLLOUT | POLLWRNORM;
5212 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5213 if ((req->opcode == IORING_OP_RECVMSG) &&
5214 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5217 mask |= POLLERR | POLLPRI;
5219 ipt.pt._qproc = io_async_queue_proc;
5221 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5223 if (ret || ipt.error) {
5224 io_poll_remove_double(req);
5225 spin_unlock_irq(&ctx->completion_lock);
5226 kfree(apoll->double_poll);
5230 spin_unlock_irq(&ctx->completion_lock);
5231 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5232 apoll->poll.events);
5236 static bool __io_poll_remove_one(struct io_kiocb *req,
5237 struct io_poll_iocb *poll)
5239 bool do_complete = false;
5241 spin_lock(&poll->head->lock);
5242 WRITE_ONCE(poll->canceled, true);
5243 if (!list_empty(&poll->wait.entry)) {
5244 list_del_init(&poll->wait.entry);
5247 spin_unlock(&poll->head->lock);
5248 hash_del(&req->hash_node);
5252 static bool io_poll_remove_one(struct io_kiocb *req)
5256 io_poll_remove_double(req);
5258 if (req->opcode == IORING_OP_POLL_ADD) {
5259 do_complete = __io_poll_remove_one(req, &req->poll);
5261 struct async_poll *apoll = req->apoll;
5263 /* non-poll requests have submit ref still */
5264 do_complete = __io_poll_remove_one(req, &apoll->poll);
5267 kfree(apoll->double_poll);
5273 io_cqring_fill_event(req, -ECANCELED);
5274 io_commit_cqring(req->ctx);
5275 req_set_fail_links(req);
5276 io_put_req_deferred(req, 1);
5283 * Returns true if we found and killed one or more poll requests
5285 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5286 struct files_struct *files)
5288 struct hlist_node *tmp;
5289 struct io_kiocb *req;
5292 spin_lock_irq(&ctx->completion_lock);
5293 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5294 struct hlist_head *list;
5296 list = &ctx->cancel_hash[i];
5297 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5298 if (io_match_task(req, tsk, files))
5299 posted += io_poll_remove_one(req);
5302 spin_unlock_irq(&ctx->completion_lock);
5305 io_cqring_ev_posted(ctx);
5310 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5312 struct hlist_head *list;
5313 struct io_kiocb *req;
5315 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5316 hlist_for_each_entry(req, list, hash_node) {
5317 if (sqe_addr != req->user_data)
5319 if (io_poll_remove_one(req))
5327 static int io_poll_remove_prep(struct io_kiocb *req,
5328 const struct io_uring_sqe *sqe)
5330 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5332 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5336 req->poll_remove.addr = READ_ONCE(sqe->addr);
5341 * Find a running poll command that matches one specified in sqe->addr,
5342 * and remove it if found.
5344 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5346 struct io_ring_ctx *ctx = req->ctx;
5349 spin_lock_irq(&ctx->completion_lock);
5350 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5351 spin_unlock_irq(&ctx->completion_lock);
5354 req_set_fail_links(req);
5355 io_req_complete(req, ret);
5359 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5362 struct io_kiocb *req = wait->private;
5363 struct io_poll_iocb *poll = &req->poll;
5365 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5368 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5369 struct poll_table_struct *p)
5371 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5373 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5376 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5378 struct io_poll_iocb *poll = &req->poll;
5381 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5383 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5386 events = READ_ONCE(sqe->poll32_events);
5388 events = swahw32(events);
5390 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5391 (events & EPOLLEXCLUSIVE);
5395 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5397 struct io_poll_iocb *poll = &req->poll;
5398 struct io_ring_ctx *ctx = req->ctx;
5399 struct io_poll_table ipt;
5402 ipt.pt._qproc = io_poll_queue_proc;
5404 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5407 if (mask) { /* no async, we'd stolen it */
5409 io_poll_complete(req, mask, 0);
5411 spin_unlock_irq(&ctx->completion_lock);
5414 io_cqring_ev_posted(ctx);
5420 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5422 struct io_timeout_data *data = container_of(timer,
5423 struct io_timeout_data, timer);
5424 struct io_kiocb *req = data->req;
5425 struct io_ring_ctx *ctx = req->ctx;
5426 unsigned long flags;
5428 spin_lock_irqsave(&ctx->completion_lock, flags);
5429 list_del_init(&req->timeout.list);
5430 atomic_set(&req->ctx->cq_timeouts,
5431 atomic_read(&req->ctx->cq_timeouts) + 1);
5433 io_cqring_fill_event(req, -ETIME);
5434 io_commit_cqring(ctx);
5435 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5437 io_cqring_ev_posted(ctx);
5438 req_set_fail_links(req);
5440 return HRTIMER_NORESTART;
5443 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5446 struct io_timeout_data *io;
5447 struct io_kiocb *req;
5450 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5451 if (user_data == req->user_data) {
5458 return ERR_PTR(ret);
5460 io = req->async_data;
5461 ret = hrtimer_try_to_cancel(&io->timer);
5463 return ERR_PTR(-EALREADY);
5464 list_del_init(&req->timeout.list);
5468 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5470 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5473 return PTR_ERR(req);
5475 req_set_fail_links(req);
5476 io_cqring_fill_event(req, -ECANCELED);
5477 io_put_req_deferred(req, 1);
5481 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5482 struct timespec64 *ts, enum hrtimer_mode mode)
5484 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5485 struct io_timeout_data *data;
5488 return PTR_ERR(req);
5490 req->timeout.off = 0; /* noseq */
5491 data = req->async_data;
5492 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5493 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5494 data->timer.function = io_timeout_fn;
5495 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5499 static int io_timeout_remove_prep(struct io_kiocb *req,
5500 const struct io_uring_sqe *sqe)
5502 struct io_timeout_rem *tr = &req->timeout_rem;
5504 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5506 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5508 if (sqe->ioprio || sqe->buf_index || sqe->len)
5511 tr->addr = READ_ONCE(sqe->addr);
5512 tr->flags = READ_ONCE(sqe->timeout_flags);
5513 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5514 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5516 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5518 } else if (tr->flags) {
5519 /* timeout removal doesn't support flags */
5526 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5528 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5533 * Remove or update an existing timeout command
5535 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5537 struct io_timeout_rem *tr = &req->timeout_rem;
5538 struct io_ring_ctx *ctx = req->ctx;
5541 spin_lock_irq(&ctx->completion_lock);
5542 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5543 ret = io_timeout_cancel(ctx, tr->addr);
5545 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5546 io_translate_timeout_mode(tr->flags));
5548 io_cqring_fill_event(req, ret);
5549 io_commit_cqring(ctx);
5550 spin_unlock_irq(&ctx->completion_lock);
5551 io_cqring_ev_posted(ctx);
5553 req_set_fail_links(req);
5558 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5559 bool is_timeout_link)
5561 struct io_timeout_data *data;
5563 u32 off = READ_ONCE(sqe->off);
5565 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5567 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5569 if (off && is_timeout_link)
5571 flags = READ_ONCE(sqe->timeout_flags);
5572 if (flags & ~IORING_TIMEOUT_ABS)
5575 req->timeout.off = off;
5577 if (!req->async_data && io_alloc_async_data(req))
5580 data = req->async_data;
5583 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5586 data->mode = io_translate_timeout_mode(flags);
5587 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5588 if (is_timeout_link)
5589 io_req_track_inflight(req);
5593 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5595 struct io_ring_ctx *ctx = req->ctx;
5596 struct io_timeout_data *data = req->async_data;
5597 struct list_head *entry;
5598 u32 tail, off = req->timeout.off;
5600 spin_lock_irq(&ctx->completion_lock);
5603 * sqe->off holds how many events that need to occur for this
5604 * timeout event to be satisfied. If it isn't set, then this is
5605 * a pure timeout request, sequence isn't used.
5607 if (io_is_timeout_noseq(req)) {
5608 entry = ctx->timeout_list.prev;
5612 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5613 req->timeout.target_seq = tail + off;
5615 /* Update the last seq here in case io_flush_timeouts() hasn't.
5616 * This is safe because ->completion_lock is held, and submissions
5617 * and completions are never mixed in the same ->completion_lock section.
5619 ctx->cq_last_tm_flush = tail;
5622 * Insertion sort, ensuring the first entry in the list is always
5623 * the one we need first.
5625 list_for_each_prev(entry, &ctx->timeout_list) {
5626 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5629 if (io_is_timeout_noseq(nxt))
5631 /* nxt.seq is behind @tail, otherwise would've been completed */
5632 if (off >= nxt->timeout.target_seq - tail)
5636 list_add(&req->timeout.list, entry);
5637 data->timer.function = io_timeout_fn;
5638 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5639 spin_unlock_irq(&ctx->completion_lock);
5643 struct io_cancel_data {
5644 struct io_ring_ctx *ctx;
5648 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5650 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5651 struct io_cancel_data *cd = data;
5653 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5656 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5657 struct io_ring_ctx *ctx)
5659 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5660 enum io_wq_cancel cancel_ret;
5663 if (!tctx || !tctx->io_wq)
5666 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5667 switch (cancel_ret) {
5668 case IO_WQ_CANCEL_OK:
5671 case IO_WQ_CANCEL_RUNNING:
5674 case IO_WQ_CANCEL_NOTFOUND:
5682 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5683 struct io_kiocb *req, __u64 sqe_addr,
5686 unsigned long flags;
5689 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5690 if (ret != -ENOENT) {
5691 spin_lock_irqsave(&ctx->completion_lock, flags);
5695 spin_lock_irqsave(&ctx->completion_lock, flags);
5696 ret = io_timeout_cancel(ctx, sqe_addr);
5699 ret = io_poll_cancel(ctx, sqe_addr);
5703 io_cqring_fill_event(req, ret);
5704 io_commit_cqring(ctx);
5705 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5706 io_cqring_ev_posted(ctx);
5709 req_set_fail_links(req);
5713 static int io_async_cancel_prep(struct io_kiocb *req,
5714 const struct io_uring_sqe *sqe)
5716 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5718 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5720 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5723 req->cancel.addr = READ_ONCE(sqe->addr);
5727 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5729 struct io_ring_ctx *ctx = req->ctx;
5730 u64 sqe_addr = req->cancel.addr;
5731 struct io_tctx_node *node;
5734 /* tasks should wait for their io-wq threads, so safe w/o sync */
5735 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5736 spin_lock_irq(&ctx->completion_lock);
5739 ret = io_timeout_cancel(ctx, sqe_addr);
5742 ret = io_poll_cancel(ctx, sqe_addr);
5745 spin_unlock_irq(&ctx->completion_lock);
5747 /* slow path, try all io-wq's */
5748 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5750 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5751 struct io_uring_task *tctx = node->task->io_uring;
5753 if (!tctx || !tctx->io_wq)
5755 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5759 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5761 spin_lock_irq(&ctx->completion_lock);
5763 io_cqring_fill_event(req, ret);
5764 io_commit_cqring(ctx);
5765 spin_unlock_irq(&ctx->completion_lock);
5766 io_cqring_ev_posted(ctx);
5769 req_set_fail_links(req);
5774 static int io_rsrc_update_prep(struct io_kiocb *req,
5775 const struct io_uring_sqe *sqe)
5777 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5779 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5781 if (sqe->ioprio || sqe->rw_flags)
5784 req->rsrc_update.offset = READ_ONCE(sqe->off);
5785 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5786 if (!req->rsrc_update.nr_args)
5788 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5792 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5794 struct io_ring_ctx *ctx = req->ctx;
5795 struct io_uring_rsrc_update up;
5798 if (issue_flags & IO_URING_F_NONBLOCK)
5801 up.offset = req->rsrc_update.offset;
5802 up.data = req->rsrc_update.arg;
5804 mutex_lock(&ctx->uring_lock);
5805 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5806 mutex_unlock(&ctx->uring_lock);
5809 req_set_fail_links(req);
5810 __io_req_complete(req, issue_flags, ret, 0);
5814 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5816 switch (req->opcode) {
5819 case IORING_OP_READV:
5820 case IORING_OP_READ_FIXED:
5821 case IORING_OP_READ:
5822 return io_read_prep(req, sqe);
5823 case IORING_OP_WRITEV:
5824 case IORING_OP_WRITE_FIXED:
5825 case IORING_OP_WRITE:
5826 return io_write_prep(req, sqe);
5827 case IORING_OP_POLL_ADD:
5828 return io_poll_add_prep(req, sqe);
5829 case IORING_OP_POLL_REMOVE:
5830 return io_poll_remove_prep(req, sqe);
5831 case IORING_OP_FSYNC:
5832 return io_fsync_prep(req, sqe);
5833 case IORING_OP_SYNC_FILE_RANGE:
5834 return io_sfr_prep(req, sqe);
5835 case IORING_OP_SENDMSG:
5836 case IORING_OP_SEND:
5837 return io_sendmsg_prep(req, sqe);
5838 case IORING_OP_RECVMSG:
5839 case IORING_OP_RECV:
5840 return io_recvmsg_prep(req, sqe);
5841 case IORING_OP_CONNECT:
5842 return io_connect_prep(req, sqe);
5843 case IORING_OP_TIMEOUT:
5844 return io_timeout_prep(req, sqe, false);
5845 case IORING_OP_TIMEOUT_REMOVE:
5846 return io_timeout_remove_prep(req, sqe);
5847 case IORING_OP_ASYNC_CANCEL:
5848 return io_async_cancel_prep(req, sqe);
5849 case IORING_OP_LINK_TIMEOUT:
5850 return io_timeout_prep(req, sqe, true);
5851 case IORING_OP_ACCEPT:
5852 return io_accept_prep(req, sqe);
5853 case IORING_OP_FALLOCATE:
5854 return io_fallocate_prep(req, sqe);
5855 case IORING_OP_OPENAT:
5856 return io_openat_prep(req, sqe);
5857 case IORING_OP_CLOSE:
5858 return io_close_prep(req, sqe);
5859 case IORING_OP_FILES_UPDATE:
5860 return io_rsrc_update_prep(req, sqe);
5861 case IORING_OP_STATX:
5862 return io_statx_prep(req, sqe);
5863 case IORING_OP_FADVISE:
5864 return io_fadvise_prep(req, sqe);
5865 case IORING_OP_MADVISE:
5866 return io_madvise_prep(req, sqe);
5867 case IORING_OP_OPENAT2:
5868 return io_openat2_prep(req, sqe);
5869 case IORING_OP_EPOLL_CTL:
5870 return io_epoll_ctl_prep(req, sqe);
5871 case IORING_OP_SPLICE:
5872 return io_splice_prep(req, sqe);
5873 case IORING_OP_PROVIDE_BUFFERS:
5874 return io_provide_buffers_prep(req, sqe);
5875 case IORING_OP_REMOVE_BUFFERS:
5876 return io_remove_buffers_prep(req, sqe);
5878 return io_tee_prep(req, sqe);
5879 case IORING_OP_SHUTDOWN:
5880 return io_shutdown_prep(req, sqe);
5881 case IORING_OP_RENAMEAT:
5882 return io_renameat_prep(req, sqe);
5883 case IORING_OP_UNLINKAT:
5884 return io_unlinkat_prep(req, sqe);
5887 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5892 static int io_req_prep_async(struct io_kiocb *req)
5894 if (!io_op_defs[req->opcode].needs_async_setup)
5896 if (WARN_ON_ONCE(req->async_data))
5898 if (io_alloc_async_data(req))
5901 switch (req->opcode) {
5902 case IORING_OP_READV:
5903 return io_rw_prep_async(req, READ);
5904 case IORING_OP_WRITEV:
5905 return io_rw_prep_async(req, WRITE);
5906 case IORING_OP_SENDMSG:
5907 return io_sendmsg_prep_async(req);
5908 case IORING_OP_RECVMSG:
5909 return io_recvmsg_prep_async(req);
5910 case IORING_OP_CONNECT:
5911 return io_connect_prep_async(req);
5913 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5918 static u32 io_get_sequence(struct io_kiocb *req)
5920 struct io_kiocb *pos;
5921 struct io_ring_ctx *ctx = req->ctx;
5922 u32 total_submitted, nr_reqs = 0;
5924 io_for_each_link(pos, req)
5927 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5928 return total_submitted - nr_reqs;
5931 static int io_req_defer(struct io_kiocb *req)
5933 struct io_ring_ctx *ctx = req->ctx;
5934 struct io_defer_entry *de;
5938 /* Still need defer if there is pending req in defer list. */
5939 if (likely(list_empty_careful(&ctx->defer_list) &&
5940 !(req->flags & REQ_F_IO_DRAIN)))
5943 seq = io_get_sequence(req);
5944 /* Still a chance to pass the sequence check */
5945 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5948 ret = io_req_prep_async(req);
5951 io_prep_async_link(req);
5952 de = kmalloc(sizeof(*de), GFP_KERNEL);
5956 spin_lock_irq(&ctx->completion_lock);
5957 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5958 spin_unlock_irq(&ctx->completion_lock);
5960 io_queue_async_work(req);
5961 return -EIOCBQUEUED;
5964 trace_io_uring_defer(ctx, req, req->user_data);
5967 list_add_tail(&de->list, &ctx->defer_list);
5968 spin_unlock_irq(&ctx->completion_lock);
5969 return -EIOCBQUEUED;
5972 static void __io_clean_op(struct io_kiocb *req)
5974 if (req->flags & REQ_F_BUFFER_SELECTED) {
5975 switch (req->opcode) {
5976 case IORING_OP_READV:
5977 case IORING_OP_READ_FIXED:
5978 case IORING_OP_READ:
5979 kfree((void *)(unsigned long)req->rw.addr);
5981 case IORING_OP_RECVMSG:
5982 case IORING_OP_RECV:
5983 kfree(req->sr_msg.kbuf);
5986 req->flags &= ~REQ_F_BUFFER_SELECTED;
5989 if (req->flags & REQ_F_NEED_CLEANUP) {
5990 switch (req->opcode) {
5991 case IORING_OP_READV:
5992 case IORING_OP_READ_FIXED:
5993 case IORING_OP_READ:
5994 case IORING_OP_WRITEV:
5995 case IORING_OP_WRITE_FIXED:
5996 case IORING_OP_WRITE: {
5997 struct io_async_rw *io = req->async_data;
5999 kfree(io->free_iovec);
6002 case IORING_OP_RECVMSG:
6003 case IORING_OP_SENDMSG: {
6004 struct io_async_msghdr *io = req->async_data;
6006 kfree(io->free_iov);
6009 case IORING_OP_SPLICE:
6011 io_put_file(req, req->splice.file_in,
6012 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
6014 case IORING_OP_OPENAT:
6015 case IORING_OP_OPENAT2:
6016 if (req->open.filename)
6017 putname(req->open.filename);
6019 case IORING_OP_RENAMEAT:
6020 putname(req->rename.oldpath);
6021 putname(req->rename.newpath);
6023 case IORING_OP_UNLINKAT:
6024 putname(req->unlink.filename);
6027 req->flags &= ~REQ_F_NEED_CLEANUP;
6031 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6033 struct io_ring_ctx *ctx = req->ctx;
6034 const struct cred *creds = NULL;
6037 if (req->work.creds && req->work.creds != current_cred())
6038 creds = override_creds(req->work.creds);
6040 switch (req->opcode) {
6042 ret = io_nop(req, issue_flags);
6044 case IORING_OP_READV:
6045 case IORING_OP_READ_FIXED:
6046 case IORING_OP_READ:
6047 ret = io_read(req, issue_flags);
6049 case IORING_OP_WRITEV:
6050 case IORING_OP_WRITE_FIXED:
6051 case IORING_OP_WRITE:
6052 ret = io_write(req, issue_flags);
6054 case IORING_OP_FSYNC:
6055 ret = io_fsync(req, issue_flags);
6057 case IORING_OP_POLL_ADD:
6058 ret = io_poll_add(req, issue_flags);
6060 case IORING_OP_POLL_REMOVE:
6061 ret = io_poll_remove(req, issue_flags);
6063 case IORING_OP_SYNC_FILE_RANGE:
6064 ret = io_sync_file_range(req, issue_flags);
6066 case IORING_OP_SENDMSG:
6067 ret = io_sendmsg(req, issue_flags);
6069 case IORING_OP_SEND:
6070 ret = io_send(req, issue_flags);
6072 case IORING_OP_RECVMSG:
6073 ret = io_recvmsg(req, issue_flags);
6075 case IORING_OP_RECV:
6076 ret = io_recv(req, issue_flags);
6078 case IORING_OP_TIMEOUT:
6079 ret = io_timeout(req, issue_flags);
6081 case IORING_OP_TIMEOUT_REMOVE:
6082 ret = io_timeout_remove(req, issue_flags);
6084 case IORING_OP_ACCEPT:
6085 ret = io_accept(req, issue_flags);
6087 case IORING_OP_CONNECT:
6088 ret = io_connect(req, issue_flags);
6090 case IORING_OP_ASYNC_CANCEL:
6091 ret = io_async_cancel(req, issue_flags);
6093 case IORING_OP_FALLOCATE:
6094 ret = io_fallocate(req, issue_flags);
6096 case IORING_OP_OPENAT:
6097 ret = io_openat(req, issue_flags);
6099 case IORING_OP_CLOSE:
6100 ret = io_close(req, issue_flags);
6102 case IORING_OP_FILES_UPDATE:
6103 ret = io_files_update(req, issue_flags);
6105 case IORING_OP_STATX:
6106 ret = io_statx(req, issue_flags);
6108 case IORING_OP_FADVISE:
6109 ret = io_fadvise(req, issue_flags);
6111 case IORING_OP_MADVISE:
6112 ret = io_madvise(req, issue_flags);
6114 case IORING_OP_OPENAT2:
6115 ret = io_openat2(req, issue_flags);
6117 case IORING_OP_EPOLL_CTL:
6118 ret = io_epoll_ctl(req, issue_flags);
6120 case IORING_OP_SPLICE:
6121 ret = io_splice(req, issue_flags);
6123 case IORING_OP_PROVIDE_BUFFERS:
6124 ret = io_provide_buffers(req, issue_flags);
6126 case IORING_OP_REMOVE_BUFFERS:
6127 ret = io_remove_buffers(req, issue_flags);
6130 ret = io_tee(req, issue_flags);
6132 case IORING_OP_SHUTDOWN:
6133 ret = io_shutdown(req, issue_flags);
6135 case IORING_OP_RENAMEAT:
6136 ret = io_renameat(req, issue_flags);
6138 case IORING_OP_UNLINKAT:
6139 ret = io_unlinkat(req, issue_flags);
6147 revert_creds(creds);
6152 /* If the op doesn't have a file, we're not polling for it */
6153 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6154 const bool in_async = io_wq_current_is_worker();
6156 /* workqueue context doesn't hold uring_lock, grab it now */
6158 mutex_lock(&ctx->uring_lock);
6160 io_iopoll_req_issued(req, in_async);
6163 mutex_unlock(&ctx->uring_lock);
6169 static void io_wq_submit_work(struct io_wq_work *work)
6171 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6172 struct io_kiocb *timeout;
6175 timeout = io_prep_linked_timeout(req);
6177 io_queue_linked_timeout(timeout);
6179 if (work->flags & IO_WQ_WORK_CANCEL)
6184 ret = io_issue_sqe(req, 0);
6186 * We can get EAGAIN for polled IO even though we're
6187 * forcing a sync submission from here, since we can't
6188 * wait for request slots on the block side.
6196 /* avoid locking problems by failing it from a clean context */
6198 /* io-wq is going to take one down */
6200 io_req_task_queue_fail(req, ret);
6204 #define FFS_ASYNC_READ 0x1UL
6205 #define FFS_ASYNC_WRITE 0x2UL
6207 #define FFS_ISREG 0x4UL
6209 #define FFS_ISREG 0x0UL
6211 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6213 static inline struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
6216 struct fixed_rsrc_table *table;
6218 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6219 return &table->files[i & IORING_FILE_TABLE_MASK];
6222 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6225 struct file **file_slot = io_fixed_file_slot(ctx->file_data, index);
6227 return (struct file *) ((unsigned long) *file_slot & FFS_MASK);
6230 static struct file *io_file_get(struct io_submit_state *state,
6231 struct io_kiocb *req, int fd, bool fixed)
6233 struct io_ring_ctx *ctx = req->ctx;
6237 unsigned long file_ptr;
6239 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6241 fd = array_index_nospec(fd, ctx->nr_user_files);
6242 file_ptr = (unsigned long) *io_fixed_file_slot(ctx->file_data, fd);
6243 file = (struct file *) (file_ptr & FFS_MASK);
6244 file_ptr &= ~FFS_MASK;
6245 /* mask in overlapping REQ_F and FFS bits */
6246 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6247 io_set_resource_node(req);
6249 trace_io_uring_file_get(ctx, fd);
6250 file = __io_file_get(state, fd);
6252 /* we don't allow fixed io_uring files */
6253 if (file && unlikely(file->f_op == &io_uring_fops))
6254 io_req_track_inflight(req);
6260 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6262 struct io_timeout_data *data = container_of(timer,
6263 struct io_timeout_data, timer);
6264 struct io_kiocb *prev, *req = data->req;
6265 struct io_ring_ctx *ctx = req->ctx;
6266 unsigned long flags;
6268 spin_lock_irqsave(&ctx->completion_lock, flags);
6269 prev = req->timeout.head;
6270 req->timeout.head = NULL;
6273 * We don't expect the list to be empty, that will only happen if we
6274 * race with the completion of the linked work.
6276 if (prev && req_ref_inc_not_zero(prev))
6277 io_remove_next_linked(prev);
6280 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6283 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6284 io_put_req_deferred(prev, 1);
6286 io_req_complete_post(req, -ETIME, 0);
6287 io_put_req_deferred(req, 1);
6289 return HRTIMER_NORESTART;
6292 static void io_queue_linked_timeout(struct io_kiocb *req)
6294 struct io_ring_ctx *ctx = req->ctx;
6296 spin_lock_irq(&ctx->completion_lock);
6298 * If the back reference is NULL, then our linked request finished
6299 * before we got a chance to setup the timer
6301 if (req->timeout.head) {
6302 struct io_timeout_data *data = req->async_data;
6304 data->timer.function = io_link_timeout_fn;
6305 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6308 spin_unlock_irq(&ctx->completion_lock);
6309 /* drop submission reference */
6313 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6315 struct io_kiocb *nxt = req->link;
6317 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6318 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6321 nxt->timeout.head = req;
6322 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6323 req->flags |= REQ_F_LINK_TIMEOUT;
6327 static void __io_queue_sqe(struct io_kiocb *req)
6329 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6332 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6335 * We async punt it if the file wasn't marked NOWAIT, or if the file
6336 * doesn't support non-blocking read/write attempts
6339 /* drop submission reference */
6340 if (req->flags & REQ_F_COMPLETE_INLINE) {
6341 struct io_ring_ctx *ctx = req->ctx;
6342 struct io_comp_state *cs = &ctx->submit_state.comp;
6344 cs->reqs[cs->nr++] = req;
6345 if (cs->nr == ARRAY_SIZE(cs->reqs))
6346 io_submit_flush_completions(cs, ctx);
6350 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6351 if (!io_arm_poll_handler(req)) {
6353 * Queued up for async execution, worker will release
6354 * submit reference when the iocb is actually submitted.
6356 io_queue_async_work(req);
6359 io_req_complete_failed(req, ret);
6362 io_queue_linked_timeout(linked_timeout);
6365 static void io_queue_sqe(struct io_kiocb *req)
6369 ret = io_req_defer(req);
6371 if (ret != -EIOCBQUEUED) {
6373 io_req_complete_failed(req, ret);
6375 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6376 ret = io_req_prep_async(req);
6379 io_queue_async_work(req);
6381 __io_queue_sqe(req);
6386 * Check SQE restrictions (opcode and flags).
6388 * Returns 'true' if SQE is allowed, 'false' otherwise.
6390 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6391 struct io_kiocb *req,
6392 unsigned int sqe_flags)
6394 if (!ctx->restricted)
6397 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6400 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6401 ctx->restrictions.sqe_flags_required)
6404 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6405 ctx->restrictions.sqe_flags_required))
6411 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6412 const struct io_uring_sqe *sqe)
6414 struct io_submit_state *state;
6415 unsigned int sqe_flags;
6416 int personality, ret = 0;
6418 req->opcode = READ_ONCE(sqe->opcode);
6419 /* same numerical values with corresponding REQ_F_*, safe to copy */
6420 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6421 req->user_data = READ_ONCE(sqe->user_data);
6422 req->async_data = NULL;
6426 req->fixed_rsrc_refs = NULL;
6427 /* one is dropped after submission, the other at completion */
6428 atomic_set(&req->refs, 2);
6429 req->task = current;
6431 req->work.list.next = NULL;
6432 req->work.creds = NULL;
6433 req->work.flags = 0;
6435 /* enforce forwards compatibility on users */
6436 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6441 if (unlikely(req->opcode >= IORING_OP_LAST))
6444 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6447 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6448 !io_op_defs[req->opcode].buffer_select)
6451 personality = READ_ONCE(sqe->personality);
6453 req->work.creds = xa_load(&ctx->personalities, personality);
6454 if (!req->work.creds)
6456 get_cred(req->work.creds);
6458 state = &ctx->submit_state;
6461 * Plug now if we have more than 1 IO left after this, and the target
6462 * is potentially a read/write to block based storage.
6464 if (!state->plug_started && state->ios_left > 1 &&
6465 io_op_defs[req->opcode].plug) {
6466 blk_start_plug(&state->plug);
6467 state->plug_started = true;
6470 if (io_op_defs[req->opcode].needs_file) {
6471 bool fixed = req->flags & REQ_F_FIXED_FILE;
6473 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6474 if (unlikely(!req->file))
6482 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6483 const struct io_uring_sqe *sqe)
6485 struct io_submit_link *link = &ctx->submit_state.link;
6488 ret = io_init_req(ctx, req, sqe);
6489 if (unlikely(ret)) {
6492 /* fail even hard links since we don't submit */
6493 link->head->flags |= REQ_F_FAIL_LINK;
6494 io_req_complete_failed(link->head, -ECANCELED);
6497 io_req_complete_failed(req, ret);
6500 ret = io_req_prep(req, sqe);
6504 /* don't need @sqe from now on */
6505 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6506 true, ctx->flags & IORING_SETUP_SQPOLL);
6509 * If we already have a head request, queue this one for async
6510 * submittal once the head completes. If we don't have a head but
6511 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6512 * submitted sync once the chain is complete. If none of those
6513 * conditions are true (normal request), then just queue it.
6516 struct io_kiocb *head = link->head;
6519 * Taking sequential execution of a link, draining both sides
6520 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6521 * requests in the link. So, it drains the head and the
6522 * next after the link request. The last one is done via
6523 * drain_next flag to persist the effect across calls.
6525 if (req->flags & REQ_F_IO_DRAIN) {
6526 head->flags |= REQ_F_IO_DRAIN;
6527 ctx->drain_next = 1;
6529 ret = io_req_prep_async(req);
6532 trace_io_uring_link(ctx, req, head);
6533 link->last->link = req;
6536 /* last request of a link, enqueue the link */
6537 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6542 if (unlikely(ctx->drain_next)) {
6543 req->flags |= REQ_F_IO_DRAIN;
6544 ctx->drain_next = 0;
6546 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6558 * Batched submission is done, ensure local IO is flushed out.
6560 static void io_submit_state_end(struct io_submit_state *state,
6561 struct io_ring_ctx *ctx)
6563 if (state->link.head)
6564 io_queue_sqe(state->link.head);
6566 io_submit_flush_completions(&state->comp, ctx);
6567 if (state->plug_started)
6568 blk_finish_plug(&state->plug);
6569 io_state_file_put(state);
6573 * Start submission side cache.
6575 static void io_submit_state_start(struct io_submit_state *state,
6576 unsigned int max_ios)
6578 state->plug_started = false;
6579 state->ios_left = max_ios;
6580 /* set only head, no need to init link_last in advance */
6581 state->link.head = NULL;
6584 static void io_commit_sqring(struct io_ring_ctx *ctx)
6586 struct io_rings *rings = ctx->rings;
6589 * Ensure any loads from the SQEs are done at this point,
6590 * since once we write the new head, the application could
6591 * write new data to them.
6593 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6597 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6598 * that is mapped by userspace. This means that care needs to be taken to
6599 * ensure that reads are stable, as we cannot rely on userspace always
6600 * being a good citizen. If members of the sqe are validated and then later
6601 * used, it's important that those reads are done through READ_ONCE() to
6602 * prevent a re-load down the line.
6604 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6606 u32 *sq_array = ctx->sq_array;
6610 * The cached sq head (or cq tail) serves two purposes:
6612 * 1) allows us to batch the cost of updating the user visible
6614 * 2) allows the kernel side to track the head on its own, even
6615 * though the application is the one updating it.
6617 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6618 if (likely(head < ctx->sq_entries))
6619 return &ctx->sq_sqes[head];
6621 /* drop invalid entries */
6622 ctx->cached_sq_dropped++;
6623 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6627 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6631 /* if we have a backlog and couldn't flush it all, return BUSY */
6632 if (test_bit(0, &ctx->sq_check_overflow)) {
6633 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6637 /* make sure SQ entry isn't read before tail */
6638 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6640 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6643 percpu_counter_add(¤t->io_uring->inflight, nr);
6644 refcount_add(nr, ¤t->usage);
6645 io_submit_state_start(&ctx->submit_state, nr);
6647 while (submitted < nr) {
6648 const struct io_uring_sqe *sqe;
6649 struct io_kiocb *req;
6651 req = io_alloc_req(ctx);
6652 if (unlikely(!req)) {
6654 submitted = -EAGAIN;
6657 sqe = io_get_sqe(ctx);
6658 if (unlikely(!sqe)) {
6659 kmem_cache_free(req_cachep, req);
6662 /* will complete beyond this point, count as submitted */
6664 if (io_submit_sqe(ctx, req, sqe))
6668 if (unlikely(submitted != nr)) {
6669 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6670 struct io_uring_task *tctx = current->io_uring;
6671 int unused = nr - ref_used;
6673 percpu_ref_put_many(&ctx->refs, unused);
6674 percpu_counter_sub(&tctx->inflight, unused);
6675 put_task_struct_many(current, unused);
6678 io_submit_state_end(&ctx->submit_state, ctx);
6679 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6680 io_commit_sqring(ctx);
6685 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6687 /* Tell userspace we may need a wakeup call */
6688 spin_lock_irq(&ctx->completion_lock);
6689 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6690 spin_unlock_irq(&ctx->completion_lock);
6693 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6695 spin_lock_irq(&ctx->completion_lock);
6696 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6697 spin_unlock_irq(&ctx->completion_lock);
6700 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6702 unsigned int to_submit;
6705 to_submit = io_sqring_entries(ctx);
6706 /* if we're handling multiple rings, cap submit size for fairness */
6707 if (cap_entries && to_submit > 8)
6710 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6711 unsigned nr_events = 0;
6713 mutex_lock(&ctx->uring_lock);
6714 if (!list_empty(&ctx->iopoll_list))
6715 io_do_iopoll(ctx, &nr_events, 0);
6717 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6718 !(ctx->flags & IORING_SETUP_R_DISABLED))
6719 ret = io_submit_sqes(ctx, to_submit);
6720 mutex_unlock(&ctx->uring_lock);
6723 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6724 wake_up(&ctx->sqo_sq_wait);
6729 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6731 struct io_ring_ctx *ctx;
6732 unsigned sq_thread_idle = 0;
6734 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6735 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6736 sqd->sq_thread_idle = sq_thread_idle;
6739 static int io_sq_thread(void *data)
6741 struct io_sq_data *sqd = data;
6742 struct io_ring_ctx *ctx;
6743 unsigned long timeout = 0;
6744 char buf[TASK_COMM_LEN];
6747 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6748 set_task_comm(current, buf);
6749 current->pf_io_worker = NULL;
6751 if (sqd->sq_cpu != -1)
6752 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6754 set_cpus_allowed_ptr(current, cpu_online_mask);
6755 current->flags |= PF_NO_SETAFFINITY;
6757 mutex_lock(&sqd->lock);
6758 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6760 bool cap_entries, sqt_spin, needs_sched;
6762 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6763 signal_pending(current)) {
6764 bool did_sig = false;
6766 mutex_unlock(&sqd->lock);
6767 if (signal_pending(current)) {
6768 struct ksignal ksig;
6770 did_sig = get_signal(&ksig);
6773 mutex_lock(&sqd->lock);
6777 io_run_task_work_head(&sqd->park_task_work);
6778 timeout = jiffies + sqd->sq_thread_idle;
6782 cap_entries = !list_is_singular(&sqd->ctx_list);
6783 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6784 const struct cred *creds = NULL;
6786 if (ctx->sq_creds != current_cred())
6787 creds = override_creds(ctx->sq_creds);
6788 ret = __io_sq_thread(ctx, cap_entries);
6790 revert_creds(creds);
6791 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6795 if (sqt_spin || !time_after(jiffies, timeout)) {
6799 timeout = jiffies + sqd->sq_thread_idle;
6804 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6805 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6806 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6807 !list_empty_careful(&ctx->iopoll_list)) {
6808 needs_sched = false;
6811 if (io_sqring_entries(ctx)) {
6812 needs_sched = false;
6817 if (needs_sched && !test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6818 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6819 io_ring_set_wakeup_flag(ctx);
6821 mutex_unlock(&sqd->lock);
6823 mutex_lock(&sqd->lock);
6824 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6825 io_ring_clear_wakeup_flag(ctx);
6828 finish_wait(&sqd->wait, &wait);
6829 io_run_task_work_head(&sqd->park_task_work);
6830 timeout = jiffies + sqd->sq_thread_idle;
6833 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6834 io_uring_cancel_sqpoll(ctx);
6836 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6837 io_ring_set_wakeup_flag(ctx);
6838 mutex_unlock(&sqd->lock);
6841 io_run_task_work_head(&sqd->park_task_work);
6842 complete(&sqd->exited);
6846 struct io_wait_queue {
6847 struct wait_queue_entry wq;
6848 struct io_ring_ctx *ctx;
6850 unsigned nr_timeouts;
6853 static inline bool io_should_wake(struct io_wait_queue *iowq)
6855 struct io_ring_ctx *ctx = iowq->ctx;
6858 * Wake up if we have enough events, or if a timeout occurred since we
6859 * started waiting. For timeouts, we always want to return to userspace,
6860 * regardless of event count.
6862 return io_cqring_events(ctx) >= iowq->to_wait ||
6863 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6866 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6867 int wake_flags, void *key)
6869 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6873 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6874 * the task, and the next invocation will do it.
6876 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6877 return autoremove_wake_function(curr, mode, wake_flags, key);
6881 static int io_run_task_work_sig(void)
6883 if (io_run_task_work())
6885 if (!signal_pending(current))
6887 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6888 return -ERESTARTSYS;
6892 /* when returns >0, the caller should retry */
6893 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6894 struct io_wait_queue *iowq,
6895 signed long *timeout)
6899 /* make sure we run task_work before checking for signals */
6900 ret = io_run_task_work_sig();
6901 if (ret || io_should_wake(iowq))
6903 /* let the caller flush overflows, retry */
6904 if (test_bit(0, &ctx->cq_check_overflow))
6907 *timeout = schedule_timeout(*timeout);
6908 return !*timeout ? -ETIME : 1;
6912 * Wait until events become available, if we don't already have some. The
6913 * application must reap them itself, as they reside on the shared cq ring.
6915 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6916 const sigset_t __user *sig, size_t sigsz,
6917 struct __kernel_timespec __user *uts)
6919 struct io_wait_queue iowq = {
6922 .func = io_wake_function,
6923 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6926 .to_wait = min_events,
6928 struct io_rings *rings = ctx->rings;
6929 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6933 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6934 if (io_cqring_events(ctx) >= min_events)
6936 if (!io_run_task_work())
6941 #ifdef CONFIG_COMPAT
6942 if (in_compat_syscall())
6943 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6947 ret = set_user_sigmask(sig, sigsz);
6954 struct timespec64 ts;
6956 if (get_timespec64(&ts, uts))
6958 timeout = timespec64_to_jiffies(&ts);
6961 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6962 trace_io_uring_cqring_wait(ctx, min_events);
6964 /* if we can't even flush overflow, don't wait for more */
6965 if (!io_cqring_overflow_flush(ctx, false, NULL, NULL)) {
6969 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6970 TASK_INTERRUPTIBLE);
6971 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
6972 finish_wait(&ctx->wait, &iowq.wq);
6976 restore_saved_sigmask_unless(ret == -EINTR);
6978 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6981 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6983 #if defined(CONFIG_UNIX)
6984 if (ctx->ring_sock) {
6985 struct sock *sock = ctx->ring_sock->sk;
6986 struct sk_buff *skb;
6988 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6994 for (i = 0; i < ctx->nr_user_files; i++) {
6997 file = io_file_from_index(ctx, i);
7004 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7006 struct fixed_rsrc_data *data;
7008 data = container_of(ref, struct fixed_rsrc_data, refs);
7009 complete(&data->done);
7012 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7014 spin_lock_bh(&ctx->rsrc_ref_lock);
7017 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7019 spin_unlock_bh(&ctx->rsrc_ref_lock);
7022 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
7023 struct fixed_rsrc_data *rsrc_data,
7024 struct fixed_rsrc_ref_node *ref_node)
7026 io_rsrc_ref_lock(ctx);
7027 rsrc_data->node = ref_node;
7028 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
7029 io_rsrc_ref_unlock(ctx);
7030 percpu_ref_get(&rsrc_data->refs);
7033 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
7035 struct fixed_rsrc_ref_node *ref_node = NULL;
7037 io_rsrc_ref_lock(ctx);
7038 ref_node = data->node;
7040 io_rsrc_ref_unlock(ctx);
7042 percpu_ref_kill(&ref_node->refs);
7045 static int io_rsrc_refnode_prealloc(struct io_ring_ctx *ctx)
7047 if (ctx->rsrc_backup_node)
7049 ctx->rsrc_backup_node = alloc_fixed_rsrc_ref_node(ctx);
7050 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7053 static struct fixed_rsrc_ref_node *
7054 io_rsrc_refnode_get(struct io_ring_ctx *ctx,
7055 struct fixed_rsrc_data *rsrc_data,
7056 void (*rsrc_put)(struct io_ring_ctx *ctx,
7057 struct io_rsrc_put *prsrc))
7059 struct fixed_rsrc_ref_node *node = ctx->rsrc_backup_node;
7061 WARN_ON_ONCE(!node);
7063 ctx->rsrc_backup_node = NULL;
7064 node->rsrc_data = rsrc_data;
7065 node->rsrc_put = rsrc_put;
7069 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
7070 struct io_ring_ctx *ctx,
7071 void (*rsrc_put)(struct io_ring_ctx *ctx,
7072 struct io_rsrc_put *prsrc))
7074 struct fixed_rsrc_ref_node *node;
7080 data->quiesce = true;
7082 ret = io_rsrc_refnode_prealloc(ctx);
7085 io_sqe_rsrc_kill_node(ctx, data);
7086 percpu_ref_kill(&data->refs);
7087 flush_delayed_work(&ctx->rsrc_put_work);
7089 ret = wait_for_completion_interruptible(&data->done);
7093 percpu_ref_resurrect(&data->refs);
7094 node = io_rsrc_refnode_get(ctx, data, rsrc_put);
7095 io_sqe_rsrc_set_node(ctx, data, node);
7096 reinit_completion(&data->done);
7098 mutex_unlock(&ctx->uring_lock);
7099 ret = io_run_task_work_sig();
7100 mutex_lock(&ctx->uring_lock);
7102 data->quiesce = false;
7107 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7109 struct fixed_rsrc_data *data;
7111 data = kzalloc(sizeof(*data), GFP_KERNEL);
7115 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7116 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7121 init_completion(&data->done);
7125 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7127 percpu_ref_exit(&data->refs);
7132 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7134 struct fixed_rsrc_data *data = ctx->file_data;
7135 unsigned nr_tables, i;
7139 * percpu_ref_is_dying() is to stop parallel files unregister
7140 * Since we possibly drop uring lock later in this function to
7143 if (!data || percpu_ref_is_dying(&data->refs))
7145 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7149 __io_sqe_files_unregister(ctx);
7150 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7151 for (i = 0; i < nr_tables; i++)
7152 kfree(data->table[i].files);
7153 free_fixed_rsrc_data(data);
7154 ctx->file_data = NULL;
7155 ctx->nr_user_files = 0;
7159 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7160 __releases(&sqd->lock)
7162 WARN_ON_ONCE(sqd->thread == current);
7165 * Do the dance but not conditional clear_bit() because it'd race with
7166 * other threads incrementing park_pending and setting the bit.
7168 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7169 if (atomic_dec_return(&sqd->park_pending))
7170 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7171 mutex_unlock(&sqd->lock);
7174 static void io_sq_thread_park(struct io_sq_data *sqd)
7175 __acquires(&sqd->lock)
7177 WARN_ON_ONCE(sqd->thread == current);
7179 atomic_inc(&sqd->park_pending);
7180 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7181 mutex_lock(&sqd->lock);
7183 wake_up_process(sqd->thread);
7186 static void io_sq_thread_stop(struct io_sq_data *sqd)
7188 WARN_ON_ONCE(sqd->thread == current);
7190 mutex_lock(&sqd->lock);
7191 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7193 wake_up_process(sqd->thread);
7194 mutex_unlock(&sqd->lock);
7195 wait_for_completion(&sqd->exited);
7198 static void io_put_sq_data(struct io_sq_data *sqd)
7200 if (refcount_dec_and_test(&sqd->refs)) {
7201 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7203 io_sq_thread_stop(sqd);
7208 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7210 struct io_sq_data *sqd = ctx->sq_data;
7213 io_sq_thread_park(sqd);
7214 list_del_init(&ctx->sqd_list);
7215 io_sqd_update_thread_idle(sqd);
7216 io_sq_thread_unpark(sqd);
7218 io_put_sq_data(sqd);
7219 ctx->sq_data = NULL;
7221 put_cred(ctx->sq_creds);
7225 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7227 struct io_ring_ctx *ctx_attach;
7228 struct io_sq_data *sqd;
7231 f = fdget(p->wq_fd);
7233 return ERR_PTR(-ENXIO);
7234 if (f.file->f_op != &io_uring_fops) {
7236 return ERR_PTR(-EINVAL);
7239 ctx_attach = f.file->private_data;
7240 sqd = ctx_attach->sq_data;
7243 return ERR_PTR(-EINVAL);
7245 if (sqd->task_tgid != current->tgid) {
7247 return ERR_PTR(-EPERM);
7250 refcount_inc(&sqd->refs);
7255 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7258 struct io_sq_data *sqd;
7261 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7262 sqd = io_attach_sq_data(p);
7267 /* fall through for EPERM case, setup new sqd/task */
7268 if (PTR_ERR(sqd) != -EPERM)
7272 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7274 return ERR_PTR(-ENOMEM);
7276 atomic_set(&sqd->park_pending, 0);
7277 refcount_set(&sqd->refs, 1);
7278 INIT_LIST_HEAD(&sqd->ctx_list);
7279 mutex_init(&sqd->lock);
7280 init_waitqueue_head(&sqd->wait);
7281 init_completion(&sqd->exited);
7285 #if defined(CONFIG_UNIX)
7287 * Ensure the UNIX gc is aware of our file set, so we are certain that
7288 * the io_uring can be safely unregistered on process exit, even if we have
7289 * loops in the file referencing.
7291 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7293 struct sock *sk = ctx->ring_sock->sk;
7294 struct scm_fp_list *fpl;
7295 struct sk_buff *skb;
7298 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7302 skb = alloc_skb(0, GFP_KERNEL);
7311 fpl->user = get_uid(current_user());
7312 for (i = 0; i < nr; i++) {
7313 struct file *file = io_file_from_index(ctx, i + offset);
7317 fpl->fp[nr_files] = get_file(file);
7318 unix_inflight(fpl->user, fpl->fp[nr_files]);
7323 fpl->max = SCM_MAX_FD;
7324 fpl->count = nr_files;
7325 UNIXCB(skb).fp = fpl;
7326 skb->destructor = unix_destruct_scm;
7327 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7328 skb_queue_head(&sk->sk_receive_queue, skb);
7330 for (i = 0; i < nr_files; i++)
7341 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7342 * causes regular reference counting to break down. We rely on the UNIX
7343 * garbage collection to take care of this problem for us.
7345 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7347 unsigned left, total;
7351 left = ctx->nr_user_files;
7353 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7355 ret = __io_sqe_files_scm(ctx, this_files, total);
7359 total += this_files;
7365 while (total < ctx->nr_user_files) {
7366 struct file *file = io_file_from_index(ctx, total);
7376 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7382 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7383 unsigned nr_tables, unsigned nr_files)
7387 for (i = 0; i < nr_tables; i++) {
7388 struct fixed_rsrc_table *table = &file_data->table[i];
7389 unsigned this_files;
7391 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7392 table->files = kcalloc(this_files, sizeof(struct file *),
7396 nr_files -= this_files;
7402 for (i = 0; i < nr_tables; i++) {
7403 struct fixed_rsrc_table *table = &file_data->table[i];
7404 kfree(table->files);
7409 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7411 struct file *file = prsrc->file;
7412 #if defined(CONFIG_UNIX)
7413 struct sock *sock = ctx->ring_sock->sk;
7414 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7415 struct sk_buff *skb;
7418 __skb_queue_head_init(&list);
7421 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7422 * remove this entry and rearrange the file array.
7424 skb = skb_dequeue(head);
7426 struct scm_fp_list *fp;
7428 fp = UNIXCB(skb).fp;
7429 for (i = 0; i < fp->count; i++) {
7432 if (fp->fp[i] != file)
7435 unix_notinflight(fp->user, fp->fp[i]);
7436 left = fp->count - 1 - i;
7438 memmove(&fp->fp[i], &fp->fp[i + 1],
7439 left * sizeof(struct file *));
7446 __skb_queue_tail(&list, skb);
7456 __skb_queue_tail(&list, skb);
7458 skb = skb_dequeue(head);
7461 if (skb_peek(&list)) {
7462 spin_lock_irq(&head->lock);
7463 while ((skb = __skb_dequeue(&list)) != NULL)
7464 __skb_queue_tail(head, skb);
7465 spin_unlock_irq(&head->lock);
7472 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7474 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7475 struct io_ring_ctx *ctx = rsrc_data->ctx;
7476 struct io_rsrc_put *prsrc, *tmp;
7478 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7479 list_del(&prsrc->list);
7480 ref_node->rsrc_put(ctx, prsrc);
7484 percpu_ref_exit(&ref_node->refs);
7486 percpu_ref_put(&rsrc_data->refs);
7489 static void io_rsrc_put_work(struct work_struct *work)
7491 struct io_ring_ctx *ctx;
7492 struct llist_node *node;
7494 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7495 node = llist_del_all(&ctx->rsrc_put_llist);
7498 struct fixed_rsrc_ref_node *ref_node;
7499 struct llist_node *next = node->next;
7501 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7502 __io_rsrc_put_work(ref_node);
7507 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7509 struct fixed_rsrc_ref_node *ref_node;
7510 struct fixed_rsrc_data *data;
7511 struct io_ring_ctx *ctx;
7512 bool first_add = false;
7515 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7516 data = ref_node->rsrc_data;
7519 io_rsrc_ref_lock(ctx);
7520 ref_node->done = true;
7522 while (!list_empty(&ctx->rsrc_ref_list)) {
7523 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7524 struct fixed_rsrc_ref_node, node);
7525 /* recycle ref nodes in order */
7526 if (!ref_node->done)
7528 list_del(&ref_node->node);
7529 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7531 io_rsrc_ref_unlock(ctx);
7533 if (percpu_ref_is_dying(&data->refs))
7537 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7539 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7542 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7543 struct io_ring_ctx *ctx)
7545 struct fixed_rsrc_ref_node *ref_node;
7547 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7551 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7556 INIT_LIST_HEAD(&ref_node->node);
7557 INIT_LIST_HEAD(&ref_node->rsrc_list);
7558 ref_node->done = false;
7562 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7563 struct fixed_rsrc_ref_node *ref_node)
7565 ref_node->rsrc_data = ctx->file_data;
7566 ref_node->rsrc_put = io_ring_file_put;
7569 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7571 percpu_ref_exit(&ref_node->refs);
7576 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7579 __s32 __user *fds = (__s32 __user *) arg;
7580 unsigned nr_tables, i;
7582 int fd, ret = -ENOMEM;
7583 struct fixed_rsrc_ref_node *ref_node;
7584 struct fixed_rsrc_data *file_data;
7590 if (nr_args > IORING_MAX_FIXED_FILES)
7593 file_data = alloc_fixed_rsrc_data(ctx);
7596 ctx->file_data = file_data;
7598 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7599 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7601 if (!file_data->table)
7604 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7607 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7608 unsigned long file_ptr;
7610 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7614 /* allow sparse sets */
7624 * Don't allow io_uring instances to be registered. If UNIX
7625 * isn't enabled, then this causes a reference cycle and this
7626 * instance can never get freed. If UNIX is enabled we'll
7627 * handle it just fine, but there's still no point in allowing
7628 * a ring fd as it doesn't support regular read/write anyway.
7630 if (file->f_op == &io_uring_fops) {
7634 file_ptr = (unsigned long) file;
7635 if (__io_file_supports_async(file, READ))
7636 file_ptr |= FFS_ASYNC_READ;
7637 if (__io_file_supports_async(file, WRITE))
7638 file_ptr |= FFS_ASYNC_WRITE;
7639 if (S_ISREG(file_inode(file)->i_mode))
7640 file_ptr |= FFS_ISREG;
7641 *io_fixed_file_slot(file_data, i) = (struct file *) file_ptr;
7644 ret = io_sqe_files_scm(ctx);
7646 io_sqe_files_unregister(ctx);
7650 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7652 io_sqe_files_unregister(ctx);
7655 init_fixed_file_ref_node(ctx, ref_node);
7657 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7660 for (i = 0; i < ctx->nr_user_files; i++) {
7661 file = io_file_from_index(ctx, i);
7665 for (i = 0; i < nr_tables; i++)
7666 kfree(file_data->table[i].files);
7667 ctx->nr_user_files = 0;
7669 free_fixed_rsrc_data(ctx->file_data);
7670 ctx->file_data = NULL;
7674 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7677 #if defined(CONFIG_UNIX)
7678 struct sock *sock = ctx->ring_sock->sk;
7679 struct sk_buff_head *head = &sock->sk_receive_queue;
7680 struct sk_buff *skb;
7683 * See if we can merge this file into an existing skb SCM_RIGHTS
7684 * file set. If there's no room, fall back to allocating a new skb
7685 * and filling it in.
7687 spin_lock_irq(&head->lock);
7688 skb = skb_peek(head);
7690 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7692 if (fpl->count < SCM_MAX_FD) {
7693 __skb_unlink(skb, head);
7694 spin_unlock_irq(&head->lock);
7695 fpl->fp[fpl->count] = get_file(file);
7696 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7698 spin_lock_irq(&head->lock);
7699 __skb_queue_head(head, skb);
7704 spin_unlock_irq(&head->lock);
7711 return __io_sqe_files_scm(ctx, 1, index);
7717 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7719 struct io_rsrc_put *prsrc;
7720 struct fixed_rsrc_ref_node *ref_node = data->node;
7722 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7727 list_add(&prsrc->list, &ref_node->rsrc_list);
7732 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7735 return io_queue_rsrc_removal(data, (void *)file);
7738 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7739 struct io_uring_rsrc_update *up,
7742 struct fixed_rsrc_data *data = ctx->file_data;
7743 struct fixed_rsrc_ref_node *ref_node;
7744 struct file *file, **file_slot;
7748 bool needs_switch = false;
7750 if (check_add_overflow(up->offset, nr_args, &done))
7752 if (done > ctx->nr_user_files)
7754 err = io_rsrc_refnode_prealloc(ctx);
7758 fds = u64_to_user_ptr(up->data);
7759 for (done = 0; done < nr_args; done++) {
7761 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7765 if (fd == IORING_REGISTER_FILES_SKIP)
7768 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7769 file_slot = io_fixed_file_slot(ctx->file_data, i);
7772 file = (struct file *) ((unsigned long) *file_slot & FFS_MASK);
7773 err = io_queue_file_removal(data, file);
7777 needs_switch = true;
7786 * Don't allow io_uring instances to be registered. If
7787 * UNIX isn't enabled, then this causes a reference
7788 * cycle and this instance can never get freed. If UNIX
7789 * is enabled we'll handle it just fine, but there's
7790 * still no point in allowing a ring fd as it doesn't
7791 * support regular read/write anyway.
7793 if (file->f_op == &io_uring_fops) {
7799 err = io_sqe_file_register(ctx, file, i);
7809 percpu_ref_kill(&data->node->refs);
7810 ref_node = io_rsrc_refnode_get(ctx, data, io_ring_file_put);
7811 io_sqe_rsrc_set_node(ctx, data, ref_node);
7813 return done ? done : err;
7816 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7819 struct io_uring_rsrc_update up;
7821 if (!ctx->file_data)
7825 if (copy_from_user(&up, arg, sizeof(up)))
7830 return __io_sqe_files_update(ctx, &up, nr_args);
7833 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7835 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7837 req = io_put_req_find_next(req);
7838 return req ? &req->work : NULL;
7841 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7843 struct io_wq_hash *hash;
7844 struct io_wq_data data;
7845 unsigned int concurrency;
7847 hash = ctx->hash_map;
7849 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7851 return ERR_PTR(-ENOMEM);
7852 refcount_set(&hash->refs, 1);
7853 init_waitqueue_head(&hash->wait);
7854 ctx->hash_map = hash;
7858 data.free_work = io_free_work;
7859 data.do_work = io_wq_submit_work;
7861 /* Do QD, or 4 * CPUS, whatever is smallest */
7862 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7864 return io_wq_create(concurrency, &data);
7867 static int io_uring_alloc_task_context(struct task_struct *task,
7868 struct io_ring_ctx *ctx)
7870 struct io_uring_task *tctx;
7873 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7874 if (unlikely(!tctx))
7877 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7878 if (unlikely(ret)) {
7883 tctx->io_wq = io_init_wq_offload(ctx);
7884 if (IS_ERR(tctx->io_wq)) {
7885 ret = PTR_ERR(tctx->io_wq);
7886 percpu_counter_destroy(&tctx->inflight);
7892 init_waitqueue_head(&tctx->wait);
7894 atomic_set(&tctx->in_idle, 0);
7895 task->io_uring = tctx;
7896 spin_lock_init(&tctx->task_lock);
7897 INIT_WQ_LIST(&tctx->task_list);
7898 tctx->task_state = 0;
7899 init_task_work(&tctx->task_work, tctx_task_work);
7903 void __io_uring_free(struct task_struct *tsk)
7905 struct io_uring_task *tctx = tsk->io_uring;
7907 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7908 WARN_ON_ONCE(tctx->io_wq);
7910 percpu_counter_destroy(&tctx->inflight);
7912 tsk->io_uring = NULL;
7915 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7916 struct io_uring_params *p)
7920 /* Retain compatibility with failing for an invalid attach attempt */
7921 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7922 IORING_SETUP_ATTACH_WQ) {
7925 f = fdget(p->wq_fd);
7928 if (f.file->f_op != &io_uring_fops) {
7934 if (ctx->flags & IORING_SETUP_SQPOLL) {
7935 struct task_struct *tsk;
7936 struct io_sq_data *sqd;
7940 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7943 sqd = io_get_sq_data(p, &attached);
7949 ctx->sq_creds = get_current_cred();
7951 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7952 if (!ctx->sq_thread_idle)
7953 ctx->sq_thread_idle = HZ;
7956 io_sq_thread_park(sqd);
7957 list_add(&ctx->sqd_list, &sqd->ctx_list);
7958 io_sqd_update_thread_idle(sqd);
7959 /* don't attach to a dying SQPOLL thread, would be racy */
7960 if (attached && !sqd->thread)
7962 io_sq_thread_unpark(sqd);
7969 if (p->flags & IORING_SETUP_SQ_AFF) {
7970 int cpu = p->sq_thread_cpu;
7973 if (cpu >= nr_cpu_ids)
7975 if (!cpu_online(cpu))
7983 sqd->task_pid = current->pid;
7984 sqd->task_tgid = current->tgid;
7985 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7992 ret = io_uring_alloc_task_context(tsk, ctx);
7993 wake_up_new_task(tsk);
7996 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7997 /* Can't have SQ_AFF without SQPOLL */
8004 io_sq_thread_finish(ctx);
8007 complete(&ctx->sq_data->exited);
8011 static inline void __io_unaccount_mem(struct user_struct *user,
8012 unsigned long nr_pages)
8014 atomic_long_sub(nr_pages, &user->locked_vm);
8017 static inline int __io_account_mem(struct user_struct *user,
8018 unsigned long nr_pages)
8020 unsigned long page_limit, cur_pages, new_pages;
8022 /* Don't allow more pages than we can safely lock */
8023 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8026 cur_pages = atomic_long_read(&user->locked_vm);
8027 new_pages = cur_pages + nr_pages;
8028 if (new_pages > page_limit)
8030 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8031 new_pages) != cur_pages);
8036 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8039 __io_unaccount_mem(ctx->user, nr_pages);
8041 if (ctx->mm_account)
8042 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8045 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8050 ret = __io_account_mem(ctx->user, nr_pages);
8055 if (ctx->mm_account)
8056 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8061 static void io_mem_free(void *ptr)
8068 page = virt_to_head_page(ptr);
8069 if (put_page_testzero(page))
8070 free_compound_page(page);
8073 static void *io_mem_alloc(size_t size)
8075 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8076 __GFP_NORETRY | __GFP_ACCOUNT;
8078 return (void *) __get_free_pages(gfp_flags, get_order(size));
8081 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8084 struct io_rings *rings;
8085 size_t off, sq_array_size;
8087 off = struct_size(rings, cqes, cq_entries);
8088 if (off == SIZE_MAX)
8092 off = ALIGN(off, SMP_CACHE_BYTES);
8100 sq_array_size = array_size(sizeof(u32), sq_entries);
8101 if (sq_array_size == SIZE_MAX)
8104 if (check_add_overflow(off, sq_array_size, &off))
8110 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8114 if (!ctx->user_bufs)
8117 for (i = 0; i < ctx->nr_user_bufs; i++) {
8118 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8120 for (j = 0; j < imu->nr_bvecs; j++)
8121 unpin_user_page(imu->bvec[j].bv_page);
8123 if (imu->acct_pages)
8124 io_unaccount_mem(ctx, imu->acct_pages);
8129 kfree(ctx->user_bufs);
8130 ctx->user_bufs = NULL;
8131 ctx->nr_user_bufs = 0;
8135 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8136 void __user *arg, unsigned index)
8138 struct iovec __user *src;
8140 #ifdef CONFIG_COMPAT
8142 struct compat_iovec __user *ciovs;
8143 struct compat_iovec ciov;
8145 ciovs = (struct compat_iovec __user *) arg;
8146 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8149 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8150 dst->iov_len = ciov.iov_len;
8154 src = (struct iovec __user *) arg;
8155 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8161 * Not super efficient, but this is just a registration time. And we do cache
8162 * the last compound head, so generally we'll only do a full search if we don't
8165 * We check if the given compound head page has already been accounted, to
8166 * avoid double accounting it. This allows us to account the full size of the
8167 * page, not just the constituent pages of a huge page.
8169 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8170 int nr_pages, struct page *hpage)
8174 /* check current page array */
8175 for (i = 0; i < nr_pages; i++) {
8176 if (!PageCompound(pages[i]))
8178 if (compound_head(pages[i]) == hpage)
8182 /* check previously registered pages */
8183 for (i = 0; i < ctx->nr_user_bufs; i++) {
8184 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8186 for (j = 0; j < imu->nr_bvecs; j++) {
8187 if (!PageCompound(imu->bvec[j].bv_page))
8189 if (compound_head(imu->bvec[j].bv_page) == hpage)
8197 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8198 int nr_pages, struct io_mapped_ubuf *imu,
8199 struct page **last_hpage)
8203 for (i = 0; i < nr_pages; i++) {
8204 if (!PageCompound(pages[i])) {
8209 hpage = compound_head(pages[i]);
8210 if (hpage == *last_hpage)
8212 *last_hpage = hpage;
8213 if (headpage_already_acct(ctx, pages, i, hpage))
8215 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8219 if (!imu->acct_pages)
8222 ret = io_account_mem(ctx, imu->acct_pages);
8224 imu->acct_pages = 0;
8228 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8229 struct io_mapped_ubuf *imu,
8230 struct page **last_hpage)
8232 struct vm_area_struct **vmas = NULL;
8233 struct page **pages = NULL;
8234 unsigned long off, start, end, ubuf;
8236 int ret, pret, nr_pages, i;
8238 ubuf = (unsigned long) iov->iov_base;
8239 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8240 start = ubuf >> PAGE_SHIFT;
8241 nr_pages = end - start;
8245 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8249 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8254 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8260 mmap_read_lock(current->mm);
8261 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8263 if (pret == nr_pages) {
8264 /* don't support file backed memory */
8265 for (i = 0; i < nr_pages; i++) {
8266 struct vm_area_struct *vma = vmas[i];
8269 !is_file_hugepages(vma->vm_file)) {
8275 ret = pret < 0 ? pret : -EFAULT;
8277 mmap_read_unlock(current->mm);
8280 * if we did partial map, or found file backed vmas,
8281 * release any pages we did get
8284 unpin_user_pages(pages, pret);
8289 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8291 unpin_user_pages(pages, pret);
8296 off = ubuf & ~PAGE_MASK;
8297 size = iov->iov_len;
8298 for (i = 0; i < nr_pages; i++) {
8301 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8302 imu->bvec[i].bv_page = pages[i];
8303 imu->bvec[i].bv_len = vec_len;
8304 imu->bvec[i].bv_offset = off;
8308 /* store original address for later verification */
8310 imu->len = iov->iov_len;
8311 imu->nr_bvecs = nr_pages;
8319 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8323 if (!nr_args || nr_args > UIO_MAXIOV)
8326 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8328 if (!ctx->user_bufs)
8334 static int io_buffer_validate(struct iovec *iov)
8337 * Don't impose further limits on the size and buffer
8338 * constraints here, we'll -EINVAL later when IO is
8339 * submitted if they are wrong.
8341 if (!iov->iov_base || !iov->iov_len)
8344 /* arbitrary limit, but we need something */
8345 if (iov->iov_len > SZ_1G)
8351 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8352 unsigned int nr_args)
8356 struct page *last_hpage = NULL;
8358 ret = io_buffers_map_alloc(ctx, nr_args);
8362 for (i = 0; i < nr_args; i++) {
8363 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8365 ret = io_copy_iov(ctx, &iov, arg, i);
8369 ret = io_buffer_validate(&iov);
8373 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8377 ctx->nr_user_bufs++;
8381 io_sqe_buffers_unregister(ctx);
8386 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8388 __s32 __user *fds = arg;
8394 if (copy_from_user(&fd, fds, sizeof(*fds)))
8397 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8398 if (IS_ERR(ctx->cq_ev_fd)) {
8399 int ret = PTR_ERR(ctx->cq_ev_fd);
8400 ctx->cq_ev_fd = NULL;
8407 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8409 if (ctx->cq_ev_fd) {
8410 eventfd_ctx_put(ctx->cq_ev_fd);
8411 ctx->cq_ev_fd = NULL;
8418 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8420 struct io_buffer *buf;
8421 unsigned long index;
8423 xa_for_each(&ctx->io_buffers, index, buf)
8424 __io_remove_buffers(ctx, buf, index, -1U);
8427 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8429 struct io_kiocb *req, *nxt;
8431 list_for_each_entry_safe(req, nxt, list, compl.list) {
8432 if (tsk && req->task != tsk)
8434 list_del(&req->compl.list);
8435 kmem_cache_free(req_cachep, req);
8439 static void io_req_caches_free(struct io_ring_ctx *ctx)
8441 struct io_submit_state *submit_state = &ctx->submit_state;
8442 struct io_comp_state *cs = &ctx->submit_state.comp;
8444 mutex_lock(&ctx->uring_lock);
8446 if (submit_state->free_reqs) {
8447 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8448 submit_state->reqs);
8449 submit_state->free_reqs = 0;
8452 spin_lock_irq(&ctx->completion_lock);
8453 list_splice_init(&cs->locked_free_list, &cs->free_list);
8454 cs->locked_free_nr = 0;
8455 spin_unlock_irq(&ctx->completion_lock);
8457 io_req_cache_free(&cs->free_list, NULL);
8459 mutex_unlock(&ctx->uring_lock);
8462 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8465 * Some may use context even when all refs and requests have been put,
8466 * and they are free to do so while still holding uring_lock or
8467 * completion_lock, see __io_req_task_submit(). Wait for them to finish.
8469 mutex_lock(&ctx->uring_lock);
8470 mutex_unlock(&ctx->uring_lock);
8471 spin_lock_irq(&ctx->completion_lock);
8472 spin_unlock_irq(&ctx->completion_lock);
8474 io_sq_thread_finish(ctx);
8475 io_sqe_buffers_unregister(ctx);
8477 if (ctx->mm_account) {
8478 mmdrop(ctx->mm_account);
8479 ctx->mm_account = NULL;
8482 mutex_lock(&ctx->uring_lock);
8483 io_sqe_files_unregister(ctx);
8484 mutex_unlock(&ctx->uring_lock);
8485 io_eventfd_unregister(ctx);
8486 io_destroy_buffers(ctx);
8488 if (ctx->rsrc_backup_node)
8489 destroy_fixed_rsrc_ref_node(ctx->rsrc_backup_node);
8491 #if defined(CONFIG_UNIX)
8492 if (ctx->ring_sock) {
8493 ctx->ring_sock->file = NULL; /* so that iput() is called */
8494 sock_release(ctx->ring_sock);
8498 io_mem_free(ctx->rings);
8499 io_mem_free(ctx->sq_sqes);
8501 percpu_ref_exit(&ctx->refs);
8502 free_uid(ctx->user);
8503 io_req_caches_free(ctx);
8505 io_wq_put_hash(ctx->hash_map);
8506 kfree(ctx->cancel_hash);
8510 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8512 struct io_ring_ctx *ctx = file->private_data;
8515 poll_wait(file, &ctx->cq_wait, wait);
8517 * synchronizes with barrier from wq_has_sleeper call in
8521 if (!io_sqring_full(ctx))
8522 mask |= EPOLLOUT | EPOLLWRNORM;
8525 * Don't flush cqring overflow list here, just do a simple check.
8526 * Otherwise there could possible be ABBA deadlock:
8529 * lock(&ctx->uring_lock);
8531 * lock(&ctx->uring_lock);
8534 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8535 * pushs them to do the flush.
8537 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8538 mask |= EPOLLIN | EPOLLRDNORM;
8543 static int io_uring_fasync(int fd, struct file *file, int on)
8545 struct io_ring_ctx *ctx = file->private_data;
8547 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8550 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8552 const struct cred *creds;
8554 creds = xa_erase(&ctx->personalities, id);
8563 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8565 return io_run_task_work_head(&ctx->exit_task_work);
8568 struct io_tctx_exit {
8569 struct callback_head task_work;
8570 struct completion completion;
8571 struct io_ring_ctx *ctx;
8574 static void io_tctx_exit_cb(struct callback_head *cb)
8576 struct io_uring_task *tctx = current->io_uring;
8577 struct io_tctx_exit *work;
8579 work = container_of(cb, struct io_tctx_exit, task_work);
8581 * When @in_idle, we're in cancellation and it's racy to remove the
8582 * node. It'll be removed by the end of cancellation, just ignore it.
8584 if (!atomic_read(&tctx->in_idle))
8585 io_uring_del_task_file((unsigned long)work->ctx);
8586 complete(&work->completion);
8589 static void io_ring_exit_work(struct work_struct *work)
8591 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8592 unsigned long timeout = jiffies + HZ * 60 * 5;
8593 struct io_tctx_exit exit;
8594 struct io_tctx_node *node;
8597 /* prevent SQPOLL from submitting new requests */
8599 io_sq_thread_park(ctx->sq_data);
8600 list_del_init(&ctx->sqd_list);
8601 io_sqd_update_thread_idle(ctx->sq_data);
8602 io_sq_thread_unpark(ctx->sq_data);
8606 * If we're doing polled IO and end up having requests being
8607 * submitted async (out-of-line), then completions can come in while
8608 * we're waiting for refs to drop. We need to reap these manually,
8609 * as nobody else will be looking for them.
8612 io_uring_try_cancel_requests(ctx, NULL, NULL);
8614 WARN_ON_ONCE(time_after(jiffies, timeout));
8615 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8617 mutex_lock(&ctx->uring_lock);
8618 while (!list_empty(&ctx->tctx_list)) {
8619 WARN_ON_ONCE(time_after(jiffies, timeout));
8621 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8624 init_completion(&exit.completion);
8625 init_task_work(&exit.task_work, io_tctx_exit_cb);
8626 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8627 if (WARN_ON_ONCE(ret))
8629 wake_up_process(node->task);
8631 mutex_unlock(&ctx->uring_lock);
8632 wait_for_completion(&exit.completion);
8634 mutex_lock(&ctx->uring_lock);
8636 mutex_unlock(&ctx->uring_lock);
8638 io_ring_ctx_free(ctx);
8641 /* Returns true if we found and killed one or more timeouts */
8642 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8643 struct files_struct *files)
8645 struct io_kiocb *req, *tmp;
8648 spin_lock_irq(&ctx->completion_lock);
8649 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8650 if (io_match_task(req, tsk, files)) {
8651 io_kill_timeout(req, -ECANCELED);
8656 io_commit_cqring(ctx);
8657 spin_unlock_irq(&ctx->completion_lock);
8659 io_cqring_ev_posted(ctx);
8660 return canceled != 0;
8663 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8665 unsigned long index;
8666 struct creds *creds;
8668 mutex_lock(&ctx->uring_lock);
8669 percpu_ref_kill(&ctx->refs);
8670 /* if force is set, the ring is going away. always drop after that */
8671 ctx->cq_overflow_flushed = 1;
8673 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8674 xa_for_each(&ctx->personalities, index, creds)
8675 io_unregister_personality(ctx, index);
8676 mutex_unlock(&ctx->uring_lock);
8678 io_kill_timeouts(ctx, NULL, NULL);
8679 io_poll_remove_all(ctx, NULL, NULL);
8681 /* if we failed setting up the ctx, we might not have any rings */
8682 io_iopoll_try_reap_events(ctx);
8684 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8686 * Use system_unbound_wq to avoid spawning tons of event kworkers
8687 * if we're exiting a ton of rings at the same time. It just adds
8688 * noise and overhead, there's no discernable change in runtime
8689 * over using system_wq.
8691 queue_work(system_unbound_wq, &ctx->exit_work);
8694 static int io_uring_release(struct inode *inode, struct file *file)
8696 struct io_ring_ctx *ctx = file->private_data;
8698 file->private_data = NULL;
8699 io_ring_ctx_wait_and_kill(ctx);
8703 struct io_task_cancel {
8704 struct task_struct *task;
8705 struct files_struct *files;
8708 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8710 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8711 struct io_task_cancel *cancel = data;
8714 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8715 unsigned long flags;
8716 struct io_ring_ctx *ctx = req->ctx;
8718 /* protect against races with linked timeouts */
8719 spin_lock_irqsave(&ctx->completion_lock, flags);
8720 ret = io_match_task(req, cancel->task, cancel->files);
8721 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8723 ret = io_match_task(req, cancel->task, cancel->files);
8728 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8729 struct task_struct *task,
8730 struct files_struct *files)
8732 struct io_defer_entry *de;
8735 spin_lock_irq(&ctx->completion_lock);
8736 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8737 if (io_match_task(de->req, task, files)) {
8738 list_cut_position(&list, &ctx->defer_list, &de->list);
8742 spin_unlock_irq(&ctx->completion_lock);
8743 if (list_empty(&list))
8746 while (!list_empty(&list)) {
8747 de = list_first_entry(&list, struct io_defer_entry, list);
8748 list_del_init(&de->list);
8749 io_req_complete_failed(de->req, -ECANCELED);
8755 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8757 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8759 return req->ctx == data;
8762 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8764 struct io_tctx_node *node;
8765 enum io_wq_cancel cret;
8768 mutex_lock(&ctx->uring_lock);
8769 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8770 struct io_uring_task *tctx = node->task->io_uring;
8773 * io_wq will stay alive while we hold uring_lock, because it's
8774 * killed after ctx nodes, which requires to take the lock.
8776 if (!tctx || !tctx->io_wq)
8778 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8779 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8781 mutex_unlock(&ctx->uring_lock);
8786 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8787 struct task_struct *task,
8788 struct files_struct *files)
8790 struct io_task_cancel cancel = { .task = task, .files = files, };
8791 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8794 enum io_wq_cancel cret;
8798 ret |= io_uring_try_cancel_iowq(ctx);
8799 } else if (tctx && tctx->io_wq) {
8801 * Cancels requests of all rings, not only @ctx, but
8802 * it's fine as the task is in exit/exec.
8804 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8806 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8809 /* SQPOLL thread does its own polling */
8810 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8811 (ctx->sq_data && ctx->sq_data->thread == current)) {
8812 while (!list_empty_careful(&ctx->iopoll_list)) {
8813 io_iopoll_try_reap_events(ctx);
8818 ret |= io_cancel_defer_files(ctx, task, files);
8819 ret |= io_poll_remove_all(ctx, task, files);
8820 ret |= io_kill_timeouts(ctx, task, files);
8821 ret |= io_run_task_work();
8822 ret |= io_run_ctx_fallback(ctx);
8823 io_cqring_overflow_flush(ctx, true, task, files);
8830 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8831 struct task_struct *task,
8832 struct files_struct *files)
8834 struct io_kiocb *req;
8837 spin_lock_irq(&ctx->inflight_lock);
8838 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8839 cnt += io_match_task(req, task, files);
8840 spin_unlock_irq(&ctx->inflight_lock);
8844 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8845 struct task_struct *task,
8846 struct files_struct *files)
8848 while (!list_empty_careful(&ctx->inflight_list)) {
8852 inflight = io_uring_count_inflight(ctx, task, files);
8856 io_uring_try_cancel_requests(ctx, task, files);
8858 prepare_to_wait(&task->io_uring->wait, &wait,
8859 TASK_UNINTERRUPTIBLE);
8860 if (inflight == io_uring_count_inflight(ctx, task, files))
8862 finish_wait(&task->io_uring->wait, &wait);
8866 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8868 struct io_uring_task *tctx = current->io_uring;
8869 struct io_tctx_node *node;
8872 if (unlikely(!tctx)) {
8873 ret = io_uring_alloc_task_context(current, ctx);
8876 tctx = current->io_uring;
8878 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8879 node = kmalloc(sizeof(*node), GFP_KERNEL);
8883 node->task = current;
8885 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8892 mutex_lock(&ctx->uring_lock);
8893 list_add(&node->ctx_node, &ctx->tctx_list);
8894 mutex_unlock(&ctx->uring_lock);
8901 * Note that this task has used io_uring. We use it for cancelation purposes.
8903 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8905 struct io_uring_task *tctx = current->io_uring;
8907 if (likely(tctx && tctx->last == ctx))
8909 return __io_uring_add_task_file(ctx);
8913 * Remove this io_uring_file -> task mapping.
8915 static void io_uring_del_task_file(unsigned long index)
8917 struct io_uring_task *tctx = current->io_uring;
8918 struct io_tctx_node *node;
8922 node = xa_erase(&tctx->xa, index);
8926 WARN_ON_ONCE(current != node->task);
8927 WARN_ON_ONCE(list_empty(&node->ctx_node));
8929 mutex_lock(&node->ctx->uring_lock);
8930 list_del(&node->ctx_node);
8931 mutex_unlock(&node->ctx->uring_lock);
8933 if (tctx->last == node->ctx)
8938 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8940 struct io_tctx_node *node;
8941 unsigned long index;
8943 xa_for_each(&tctx->xa, index, node)
8944 io_uring_del_task_file(index);
8946 io_wq_put_and_exit(tctx->io_wq);
8951 static s64 tctx_inflight(struct io_uring_task *tctx)
8953 return percpu_counter_sum(&tctx->inflight);
8956 static void io_sqpoll_cancel_cb(struct callback_head *cb)
8958 struct io_tctx_exit *work = container_of(cb, struct io_tctx_exit, task_work);
8959 struct io_ring_ctx *ctx = work->ctx;
8960 struct io_sq_data *sqd = ctx->sq_data;
8963 io_uring_cancel_sqpoll(ctx);
8964 complete(&work->completion);
8967 static void io_sqpoll_cancel_sync(struct io_ring_ctx *ctx)
8969 struct io_sq_data *sqd = ctx->sq_data;
8970 struct io_tctx_exit work = { .ctx = ctx, };
8971 struct task_struct *task;
8973 io_sq_thread_park(sqd);
8974 list_del_init(&ctx->sqd_list);
8975 io_sqd_update_thread_idle(sqd);
8978 init_completion(&work.completion);
8979 init_task_work(&work.task_work, io_sqpoll_cancel_cb);
8980 io_task_work_add_head(&sqd->park_task_work, &work.task_work);
8981 wake_up_process(task);
8983 io_sq_thread_unpark(sqd);
8986 wait_for_completion(&work.completion);
8989 void __io_uring_files_cancel(struct files_struct *files)
8991 struct io_uring_task *tctx = current->io_uring;
8992 struct io_tctx_node *node;
8993 unsigned long index;
8995 /* make sure overflow events are dropped */
8996 atomic_inc(&tctx->in_idle);
8997 xa_for_each(&tctx->xa, index, node) {
8998 struct io_ring_ctx *ctx = node->ctx;
9001 io_sqpoll_cancel_sync(ctx);
9004 io_uring_cancel_files(ctx, current, files);
9006 io_uring_try_cancel_requests(ctx, current, NULL);
9008 atomic_dec(&tctx->in_idle);
9011 io_uring_clean_tctx(tctx);
9014 /* should only be called by SQPOLL task */
9015 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
9017 struct io_sq_data *sqd = ctx->sq_data;
9018 struct io_uring_task *tctx = current->io_uring;
9022 WARN_ON_ONCE(!sqd || ctx->sq_data->thread != current);
9024 atomic_inc(&tctx->in_idle);
9026 /* read completions before cancelations */
9027 inflight = tctx_inflight(tctx);
9030 io_uring_try_cancel_requests(ctx, current, NULL);
9032 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9034 * If we've seen completions, retry without waiting. This
9035 * avoids a race where a completion comes in before we did
9036 * prepare_to_wait().
9038 if (inflight == tctx_inflight(tctx))
9040 finish_wait(&tctx->wait, &wait);
9042 atomic_dec(&tctx->in_idle);
9046 * Find any io_uring fd that this task has registered or done IO on, and cancel
9049 void __io_uring_task_cancel(void)
9051 struct io_uring_task *tctx = current->io_uring;
9055 /* make sure overflow events are dropped */
9056 atomic_inc(&tctx->in_idle);
9057 __io_uring_files_cancel(NULL);
9060 /* read completions before cancelations */
9061 inflight = tctx_inflight(tctx);
9064 __io_uring_files_cancel(NULL);
9066 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9069 * If we've seen completions, retry without waiting. This
9070 * avoids a race where a completion comes in before we did
9071 * prepare_to_wait().
9073 if (inflight == tctx_inflight(tctx))
9075 finish_wait(&tctx->wait, &wait);
9078 atomic_dec(&tctx->in_idle);
9080 io_uring_clean_tctx(tctx);
9081 /* all current's requests should be gone, we can kill tctx */
9082 __io_uring_free(current);
9085 static void *io_uring_validate_mmap_request(struct file *file,
9086 loff_t pgoff, size_t sz)
9088 struct io_ring_ctx *ctx = file->private_data;
9089 loff_t offset = pgoff << PAGE_SHIFT;
9094 case IORING_OFF_SQ_RING:
9095 case IORING_OFF_CQ_RING:
9098 case IORING_OFF_SQES:
9102 return ERR_PTR(-EINVAL);
9105 page = virt_to_head_page(ptr);
9106 if (sz > page_size(page))
9107 return ERR_PTR(-EINVAL);
9114 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9116 size_t sz = vma->vm_end - vma->vm_start;
9120 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9122 return PTR_ERR(ptr);
9124 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9125 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9128 #else /* !CONFIG_MMU */
9130 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9132 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9135 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9137 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9140 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9141 unsigned long addr, unsigned long len,
9142 unsigned long pgoff, unsigned long flags)
9146 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9148 return PTR_ERR(ptr);
9150 return (unsigned long) ptr;
9153 #endif /* !CONFIG_MMU */
9155 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9160 if (!io_sqring_full(ctx))
9162 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9164 if (!io_sqring_full(ctx))
9167 } while (!signal_pending(current));
9169 finish_wait(&ctx->sqo_sq_wait, &wait);
9173 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9174 struct __kernel_timespec __user **ts,
9175 const sigset_t __user **sig)
9177 struct io_uring_getevents_arg arg;
9180 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9181 * is just a pointer to the sigset_t.
9183 if (!(flags & IORING_ENTER_EXT_ARG)) {
9184 *sig = (const sigset_t __user *) argp;
9190 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9191 * timespec and sigset_t pointers if good.
9193 if (*argsz != sizeof(arg))
9195 if (copy_from_user(&arg, argp, sizeof(arg)))
9197 *sig = u64_to_user_ptr(arg.sigmask);
9198 *argsz = arg.sigmask_sz;
9199 *ts = u64_to_user_ptr(arg.ts);
9203 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9204 u32, min_complete, u32, flags, const void __user *, argp,
9207 struct io_ring_ctx *ctx;
9214 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9215 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9219 if (unlikely(!f.file))
9223 if (unlikely(f.file->f_op != &io_uring_fops))
9227 ctx = f.file->private_data;
9228 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9232 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9236 * For SQ polling, the thread will do all submissions and completions.
9237 * Just return the requested submit count, and wake the thread if
9241 if (ctx->flags & IORING_SETUP_SQPOLL) {
9242 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9245 if (unlikely(ctx->sq_data->thread == NULL)) {
9248 if (flags & IORING_ENTER_SQ_WAKEUP)
9249 wake_up(&ctx->sq_data->wait);
9250 if (flags & IORING_ENTER_SQ_WAIT) {
9251 ret = io_sqpoll_wait_sq(ctx);
9255 submitted = to_submit;
9256 } else if (to_submit) {
9257 ret = io_uring_add_task_file(ctx);
9260 mutex_lock(&ctx->uring_lock);
9261 submitted = io_submit_sqes(ctx, to_submit);
9262 mutex_unlock(&ctx->uring_lock);
9264 if (submitted != to_submit)
9267 if (flags & IORING_ENTER_GETEVENTS) {
9268 const sigset_t __user *sig;
9269 struct __kernel_timespec __user *ts;
9271 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9275 min_complete = min(min_complete, ctx->cq_entries);
9278 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9279 * space applications don't need to do io completion events
9280 * polling again, they can rely on io_sq_thread to do polling
9281 * work, which can reduce cpu usage and uring_lock contention.
9283 if (ctx->flags & IORING_SETUP_IOPOLL &&
9284 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9285 ret = io_iopoll_check(ctx, min_complete);
9287 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9292 percpu_ref_put(&ctx->refs);
9295 return submitted ? submitted : ret;
9298 #ifdef CONFIG_PROC_FS
9299 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9300 const struct cred *cred)
9302 struct user_namespace *uns = seq_user_ns(m);
9303 struct group_info *gi;
9308 seq_printf(m, "%5d\n", id);
9309 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9310 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9311 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9312 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9313 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9314 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9315 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9316 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9317 seq_puts(m, "\n\tGroups:\t");
9318 gi = cred->group_info;
9319 for (g = 0; g < gi->ngroups; g++) {
9320 seq_put_decimal_ull(m, g ? " " : "",
9321 from_kgid_munged(uns, gi->gid[g]));
9323 seq_puts(m, "\n\tCapEff:\t");
9324 cap = cred->cap_effective;
9325 CAP_FOR_EACH_U32(__capi)
9326 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9331 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9333 struct io_sq_data *sq = NULL;
9338 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9339 * since fdinfo case grabs it in the opposite direction of normal use
9340 * cases. If we fail to get the lock, we just don't iterate any
9341 * structures that could be going away outside the io_uring mutex.
9343 has_lock = mutex_trylock(&ctx->uring_lock);
9345 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9351 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9352 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9353 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9354 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9355 struct file *f = io_file_from_index(ctx, i);
9358 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9360 seq_printf(m, "%5u: <none>\n", i);
9362 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9363 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9364 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9366 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9367 (unsigned int) buf->len);
9369 if (has_lock && !xa_empty(&ctx->personalities)) {
9370 unsigned long index;
9371 const struct cred *cred;
9373 seq_printf(m, "Personalities:\n");
9374 xa_for_each(&ctx->personalities, index, cred)
9375 io_uring_show_cred(m, index, cred);
9377 seq_printf(m, "PollList:\n");
9378 spin_lock_irq(&ctx->completion_lock);
9379 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9380 struct hlist_head *list = &ctx->cancel_hash[i];
9381 struct io_kiocb *req;
9383 hlist_for_each_entry(req, list, hash_node)
9384 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9385 req->task->task_works != NULL);
9387 spin_unlock_irq(&ctx->completion_lock);
9389 mutex_unlock(&ctx->uring_lock);
9392 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9394 struct io_ring_ctx *ctx = f->private_data;
9396 if (percpu_ref_tryget(&ctx->refs)) {
9397 __io_uring_show_fdinfo(ctx, m);
9398 percpu_ref_put(&ctx->refs);
9403 static const struct file_operations io_uring_fops = {
9404 .release = io_uring_release,
9405 .mmap = io_uring_mmap,
9407 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9408 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9410 .poll = io_uring_poll,
9411 .fasync = io_uring_fasync,
9412 #ifdef CONFIG_PROC_FS
9413 .show_fdinfo = io_uring_show_fdinfo,
9417 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9418 struct io_uring_params *p)
9420 struct io_rings *rings;
9421 size_t size, sq_array_offset;
9423 /* make sure these are sane, as we already accounted them */
9424 ctx->sq_entries = p->sq_entries;
9425 ctx->cq_entries = p->cq_entries;
9427 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9428 if (size == SIZE_MAX)
9431 rings = io_mem_alloc(size);
9436 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9437 rings->sq_ring_mask = p->sq_entries - 1;
9438 rings->cq_ring_mask = p->cq_entries - 1;
9439 rings->sq_ring_entries = p->sq_entries;
9440 rings->cq_ring_entries = p->cq_entries;
9441 ctx->sq_mask = rings->sq_ring_mask;
9442 ctx->cq_mask = rings->cq_ring_mask;
9444 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9445 if (size == SIZE_MAX) {
9446 io_mem_free(ctx->rings);
9451 ctx->sq_sqes = io_mem_alloc(size);
9452 if (!ctx->sq_sqes) {
9453 io_mem_free(ctx->rings);
9461 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9465 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9469 ret = io_uring_add_task_file(ctx);
9474 fd_install(fd, file);
9479 * Allocate an anonymous fd, this is what constitutes the application
9480 * visible backing of an io_uring instance. The application mmaps this
9481 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9482 * we have to tie this fd to a socket for file garbage collection purposes.
9484 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9487 #if defined(CONFIG_UNIX)
9490 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9493 return ERR_PTR(ret);
9496 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9497 O_RDWR | O_CLOEXEC);
9498 #if defined(CONFIG_UNIX)
9500 sock_release(ctx->ring_sock);
9501 ctx->ring_sock = NULL;
9503 ctx->ring_sock->file = file;
9509 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9510 struct io_uring_params __user *params)
9512 struct io_ring_ctx *ctx;
9518 if (entries > IORING_MAX_ENTRIES) {
9519 if (!(p->flags & IORING_SETUP_CLAMP))
9521 entries = IORING_MAX_ENTRIES;
9525 * Use twice as many entries for the CQ ring. It's possible for the
9526 * application to drive a higher depth than the size of the SQ ring,
9527 * since the sqes are only used at submission time. This allows for
9528 * some flexibility in overcommitting a bit. If the application has
9529 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9530 * of CQ ring entries manually.
9532 p->sq_entries = roundup_pow_of_two(entries);
9533 if (p->flags & IORING_SETUP_CQSIZE) {
9535 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9536 * to a power-of-two, if it isn't already. We do NOT impose
9537 * any cq vs sq ring sizing.
9541 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9542 if (!(p->flags & IORING_SETUP_CLAMP))
9544 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9546 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9547 if (p->cq_entries < p->sq_entries)
9550 p->cq_entries = 2 * p->sq_entries;
9553 ctx = io_ring_ctx_alloc(p);
9556 ctx->compat = in_compat_syscall();
9557 if (!capable(CAP_IPC_LOCK))
9558 ctx->user = get_uid(current_user());
9561 * This is just grabbed for accounting purposes. When a process exits,
9562 * the mm is exited and dropped before the files, hence we need to hang
9563 * on to this mm purely for the purposes of being able to unaccount
9564 * memory (locked/pinned vm). It's not used for anything else.
9566 mmgrab(current->mm);
9567 ctx->mm_account = current->mm;
9569 ret = io_allocate_scq_urings(ctx, p);
9573 ret = io_sq_offload_create(ctx, p);
9577 memset(&p->sq_off, 0, sizeof(p->sq_off));
9578 p->sq_off.head = offsetof(struct io_rings, sq.head);
9579 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9580 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9581 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9582 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9583 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9584 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9586 memset(&p->cq_off, 0, sizeof(p->cq_off));
9587 p->cq_off.head = offsetof(struct io_rings, cq.head);
9588 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9589 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9590 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9591 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9592 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9593 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9595 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9596 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9597 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9598 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9599 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9601 if (copy_to_user(params, p, sizeof(*p))) {
9606 file = io_uring_get_file(ctx);
9608 ret = PTR_ERR(file);
9613 * Install ring fd as the very last thing, so we don't risk someone
9614 * having closed it before we finish setup
9616 ret = io_uring_install_fd(ctx, file);
9618 /* fput will clean it up */
9623 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9626 io_ring_ctx_wait_and_kill(ctx);
9631 * Sets up an aio uring context, and returns the fd. Applications asks for a
9632 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9633 * params structure passed in.
9635 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9637 struct io_uring_params p;
9640 if (copy_from_user(&p, params, sizeof(p)))
9642 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9647 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9648 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9649 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9650 IORING_SETUP_R_DISABLED))
9653 return io_uring_create(entries, &p, params);
9656 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9657 struct io_uring_params __user *, params)
9659 return io_uring_setup(entries, params);
9662 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9664 struct io_uring_probe *p;
9668 size = struct_size(p, ops, nr_args);
9669 if (size == SIZE_MAX)
9671 p = kzalloc(size, GFP_KERNEL);
9676 if (copy_from_user(p, arg, size))
9679 if (memchr_inv(p, 0, size))
9682 p->last_op = IORING_OP_LAST - 1;
9683 if (nr_args > IORING_OP_LAST)
9684 nr_args = IORING_OP_LAST;
9686 for (i = 0; i < nr_args; i++) {
9688 if (!io_op_defs[i].not_supported)
9689 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9694 if (copy_to_user(arg, p, size))
9701 static int io_register_personality(struct io_ring_ctx *ctx)
9703 const struct cred *creds;
9707 creds = get_current_cred();
9709 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9710 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9717 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9718 unsigned int nr_args)
9720 struct io_uring_restriction *res;
9724 /* Restrictions allowed only if rings started disabled */
9725 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9728 /* We allow only a single restrictions registration */
9729 if (ctx->restrictions.registered)
9732 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9735 size = array_size(nr_args, sizeof(*res));
9736 if (size == SIZE_MAX)
9739 res = memdup_user(arg, size);
9741 return PTR_ERR(res);
9745 for (i = 0; i < nr_args; i++) {
9746 switch (res[i].opcode) {
9747 case IORING_RESTRICTION_REGISTER_OP:
9748 if (res[i].register_op >= IORING_REGISTER_LAST) {
9753 __set_bit(res[i].register_op,
9754 ctx->restrictions.register_op);
9756 case IORING_RESTRICTION_SQE_OP:
9757 if (res[i].sqe_op >= IORING_OP_LAST) {
9762 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9764 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9765 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9767 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9768 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9777 /* Reset all restrictions if an error happened */
9779 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9781 ctx->restrictions.registered = true;
9787 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9789 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9792 if (ctx->restrictions.registered)
9793 ctx->restricted = 1;
9795 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9796 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9797 wake_up(&ctx->sq_data->wait);
9801 static bool io_register_op_must_quiesce(int op)
9804 case IORING_UNREGISTER_FILES:
9805 case IORING_REGISTER_FILES_UPDATE:
9806 case IORING_REGISTER_PROBE:
9807 case IORING_REGISTER_PERSONALITY:
9808 case IORING_UNREGISTER_PERSONALITY:
9815 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9816 void __user *arg, unsigned nr_args)
9817 __releases(ctx->uring_lock)
9818 __acquires(ctx->uring_lock)
9823 * We're inside the ring mutex, if the ref is already dying, then
9824 * someone else killed the ctx or is already going through
9825 * io_uring_register().
9827 if (percpu_ref_is_dying(&ctx->refs))
9830 if (io_register_op_must_quiesce(opcode)) {
9831 percpu_ref_kill(&ctx->refs);
9834 * Drop uring mutex before waiting for references to exit. If
9835 * another thread is currently inside io_uring_enter() it might
9836 * need to grab the uring_lock to make progress. If we hold it
9837 * here across the drain wait, then we can deadlock. It's safe
9838 * to drop the mutex here, since no new references will come in
9839 * after we've killed the percpu ref.
9841 mutex_unlock(&ctx->uring_lock);
9843 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9846 ret = io_run_task_work_sig();
9851 mutex_lock(&ctx->uring_lock);
9854 percpu_ref_resurrect(&ctx->refs);
9859 if (ctx->restricted) {
9860 if (opcode >= IORING_REGISTER_LAST) {
9865 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9872 case IORING_REGISTER_BUFFERS:
9873 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9875 case IORING_UNREGISTER_BUFFERS:
9879 ret = io_sqe_buffers_unregister(ctx);
9881 case IORING_REGISTER_FILES:
9882 ret = io_sqe_files_register(ctx, arg, nr_args);
9884 case IORING_UNREGISTER_FILES:
9888 ret = io_sqe_files_unregister(ctx);
9890 case IORING_REGISTER_FILES_UPDATE:
9891 ret = io_sqe_files_update(ctx, arg, nr_args);
9893 case IORING_REGISTER_EVENTFD:
9894 case IORING_REGISTER_EVENTFD_ASYNC:
9898 ret = io_eventfd_register(ctx, arg);
9901 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9902 ctx->eventfd_async = 1;
9904 ctx->eventfd_async = 0;
9906 case IORING_UNREGISTER_EVENTFD:
9910 ret = io_eventfd_unregister(ctx);
9912 case IORING_REGISTER_PROBE:
9914 if (!arg || nr_args > 256)
9916 ret = io_probe(ctx, arg, nr_args);
9918 case IORING_REGISTER_PERSONALITY:
9922 ret = io_register_personality(ctx);
9924 case IORING_UNREGISTER_PERSONALITY:
9928 ret = io_unregister_personality(ctx, nr_args);
9930 case IORING_REGISTER_ENABLE_RINGS:
9934 ret = io_register_enable_rings(ctx);
9936 case IORING_REGISTER_RESTRICTIONS:
9937 ret = io_register_restrictions(ctx, arg, nr_args);
9945 if (io_register_op_must_quiesce(opcode)) {
9946 /* bring the ctx back to life */
9947 percpu_ref_reinit(&ctx->refs);
9949 reinit_completion(&ctx->ref_comp);
9954 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9955 void __user *, arg, unsigned int, nr_args)
9957 struct io_ring_ctx *ctx;
9966 if (f.file->f_op != &io_uring_fops)
9969 ctx = f.file->private_data;
9973 mutex_lock(&ctx->uring_lock);
9974 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9975 mutex_unlock(&ctx->uring_lock);
9976 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9977 ctx->cq_ev_fd != NULL, ret);
9983 static int __init io_uring_init(void)
9985 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9986 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9987 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9990 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9991 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9992 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9993 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9994 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9995 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9996 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9997 BUILD_BUG_SQE_ELEM(8, __u64, off);
9998 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9999 BUILD_BUG_SQE_ELEM(16, __u64, addr);
10000 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
10001 BUILD_BUG_SQE_ELEM(24, __u32, len);
10002 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
10003 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
10004 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
10005 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
10006 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
10007 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
10008 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
10009 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
10010 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
10011 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
10012 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
10013 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
10014 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
10015 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
10016 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
10017 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
10018 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
10019 BUILD_BUG_SQE_ELEM(42, __u16, personality);
10020 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
10022 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
10023 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
10024 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
10028 __initcall(io_uring_init);