1 // SPDX-License-Identifier: GPL-2.0
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
30 * Also see the examples in the liburing library:
32 * git://git.kernel.dk/liburing
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
52 #include <linux/sched/signal.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blkdev.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
64 #include <net/af_unix.h>
66 #include <linux/anon_inodes.h>
67 #include <linux/sched/mm.h>
68 #include <linux/uaccess.h>
69 #include <linux/nospec.h>
70 #include <linux/sizes.h>
71 #include <linux/hugetlb.h>
72 #include <linux/highmem.h>
73 #include <linux/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/io_uring.h>
85 #include <uapi/linux/io_uring.h>
90 #define IORING_MAX_ENTRIES 32768
91 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
94 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 #define IORING_FILE_TABLE_SHIFT 9
97 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
98 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
99 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
100 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
103 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
104 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
108 u32 head ____cacheline_aligned_in_smp;
109 u32 tail ____cacheline_aligned_in_smp;
113 * This data is shared with the application through the mmap at offsets
114 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
116 * The offsets to the member fields are published through struct
117 * io_sqring_offsets when calling io_uring_setup.
121 * Head and tail offsets into the ring; the offsets need to be
122 * masked to get valid indices.
124 * The kernel controls head of the sq ring and the tail of the cq ring,
125 * and the application controls tail of the sq ring and the head of the
128 struct io_uring sq, cq;
130 * Bitmasks to apply to head and tail offsets (constant, equals
133 u32 sq_ring_mask, cq_ring_mask;
134 /* Ring sizes (constant, power of 2) */
135 u32 sq_ring_entries, cq_ring_entries;
137 * Number of invalid entries dropped by the kernel due to
138 * invalid index stored in array
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
144 * After a new SQ head value was read by the application this
145 * counter includes all submissions that were dropped reaching
146 * the new SQ head (and possibly more).
152 * Written by the kernel, shouldn't be modified by the
155 * The application needs a full memory barrier before checking
156 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
162 * Written by the application, shouldn't be modified by the
167 * Number of completion events lost because the queue was full;
168 * this should be avoided by the application by making sure
169 * there are not more requests pending than there is space in
170 * the completion queue.
172 * Written by the kernel, shouldn't be modified by the
173 * application (i.e. get number of "new events" by comparing to
176 * As completion events come in out of order this counter is not
177 * ordered with any other data.
181 * Ring buffer of completion events.
183 * The kernel writes completion events fresh every time they are
184 * produced, so the application is allowed to modify pending
187 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
190 enum io_uring_cmd_flags {
191 IO_URING_F_NONBLOCK = 1,
192 IO_URING_F_COMPLETE_DEFER = 2,
195 struct io_mapped_ubuf {
198 struct bio_vec *bvec;
199 unsigned int nr_bvecs;
200 unsigned long acct_pages;
205 struct io_overflow_cqe {
206 struct io_uring_cqe cqe;
207 struct list_head list;
210 struct io_fixed_file {
211 /* file * with additional FFS_* flags */
212 unsigned long file_ptr;
216 struct list_head list;
223 struct fixed_rsrc_table {
224 struct io_fixed_file *files;
227 struct io_rsrc_node {
228 struct percpu_ref refs;
229 struct list_head node;
230 struct list_head rsrc_list;
231 struct io_rsrc_data *rsrc_data;
232 struct llist_node llist;
236 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
238 struct io_rsrc_data {
239 struct fixed_rsrc_table *table;
240 struct io_ring_ctx *ctx;
243 struct percpu_ref refs;
244 struct completion done;
249 struct list_head list;
255 struct io_restriction {
256 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
257 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
258 u8 sqe_flags_allowed;
259 u8 sqe_flags_required;
264 IO_SQ_THREAD_SHOULD_STOP = 0,
265 IO_SQ_THREAD_SHOULD_PARK,
270 atomic_t park_pending;
273 /* ctx's that are using this sqd */
274 struct list_head ctx_list;
276 struct task_struct *thread;
277 struct wait_queue_head wait;
279 unsigned sq_thread_idle;
285 struct completion exited;
286 struct callback_head *park_task_work;
289 #define IO_IOPOLL_BATCH 8
290 #define IO_COMPL_BATCH 32
291 #define IO_REQ_CACHE_SIZE 32
292 #define IO_REQ_ALLOC_BATCH 8
294 struct io_comp_state {
295 struct io_kiocb *reqs[IO_COMPL_BATCH];
297 unsigned int locked_free_nr;
298 /* inline/task_work completion list, under ->uring_lock */
299 struct list_head free_list;
300 /* IRQ completion list, under ->completion_lock */
301 struct list_head locked_free_list;
304 struct io_submit_link {
305 struct io_kiocb *head;
306 struct io_kiocb *last;
309 struct io_submit_state {
310 struct blk_plug plug;
311 struct io_submit_link link;
314 * io_kiocb alloc cache
316 void *reqs[IO_REQ_CACHE_SIZE];
317 unsigned int free_reqs;
322 * Batch completion logic
324 struct io_comp_state comp;
327 * File reference cache
331 unsigned int file_refs;
332 unsigned int ios_left;
337 struct percpu_ref refs;
338 } ____cacheline_aligned_in_smp;
342 unsigned int compat: 1;
343 unsigned int drain_next: 1;
344 unsigned int eventfd_async: 1;
345 unsigned int restricted: 1;
348 * Ring buffer of indices into array of io_uring_sqe, which is
349 * mmapped by the application using the IORING_OFF_SQES offset.
351 * This indirection could e.g. be used to assign fixed
352 * io_uring_sqe entries to operations and only submit them to
353 * the queue when needed.
355 * The kernel modifies neither the indices array nor the entries
359 unsigned cached_sq_head;
362 unsigned sq_thread_idle;
363 unsigned cached_sq_dropped;
364 unsigned cached_cq_overflow;
365 unsigned long sq_check_overflow;
367 /* hashed buffered write serialization */
368 struct io_wq_hash *hash_map;
370 struct list_head defer_list;
371 struct list_head timeout_list;
372 struct list_head cq_overflow_list;
374 struct io_uring_sqe *sq_sqes;
375 } ____cacheline_aligned_in_smp;
378 struct mutex uring_lock;
379 wait_queue_head_t wait;
380 } ____cacheline_aligned_in_smp;
382 struct io_submit_state submit_state;
384 struct io_rings *rings;
386 /* Only used for accounting purposes */
387 struct mm_struct *mm_account;
389 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
396 * If used, fixed file set. Writers must ensure that ->refs is dead,
397 * readers must ensure that ->refs is alive as long as the file* is
398 * used. Only updated through io_uring_register(2).
400 struct io_rsrc_data *file_data;
401 unsigned nr_user_files;
403 /* if used, fixed mapped user buffers */
404 unsigned nr_user_bufs;
405 struct io_mapped_ubuf *user_bufs;
407 struct user_struct *user;
409 struct completion ref_comp;
411 #if defined(CONFIG_UNIX)
412 struct socket *ring_sock;
415 struct xarray io_buffers;
417 struct xarray personalities;
421 unsigned cached_cq_tail;
424 atomic_t cq_timeouts;
425 unsigned cq_last_tm_flush;
426 unsigned long cq_check_overflow;
427 struct wait_queue_head cq_wait;
428 struct fasync_struct *cq_fasync;
429 struct eventfd_ctx *cq_ev_fd;
430 } ____cacheline_aligned_in_smp;
433 spinlock_t completion_lock;
436 * ->iopoll_list is protected by the ctx->uring_lock for
437 * io_uring instances that don't use IORING_SETUP_SQPOLL.
438 * For SQPOLL, only the single threaded io_sq_thread() will
439 * manipulate the list, hence no extra locking is needed there.
441 struct list_head iopoll_list;
442 struct hlist_head *cancel_hash;
443 unsigned cancel_hash_bits;
444 bool poll_multi_file;
445 } ____cacheline_aligned_in_smp;
447 struct delayed_work rsrc_put_work;
448 struct llist_head rsrc_put_llist;
449 struct list_head rsrc_ref_list;
450 spinlock_t rsrc_ref_lock;
451 struct io_rsrc_node *rsrc_node;
452 struct io_rsrc_node *rsrc_backup_node;
454 struct io_restriction restrictions;
457 struct callback_head *exit_task_work;
459 /* Keep this last, we don't need it for the fast path */
460 struct work_struct exit_work;
461 struct list_head tctx_list;
464 struct io_uring_task {
465 /* submission side */
467 struct wait_queue_head wait;
468 const struct io_ring_ctx *last;
470 struct percpu_counter inflight;
471 atomic_t inflight_tracked;
474 spinlock_t task_lock;
475 struct io_wq_work_list task_list;
476 unsigned long task_state;
477 struct callback_head task_work;
481 * First field must be the file pointer in all the
482 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
484 struct io_poll_iocb {
486 struct wait_queue_head *head;
491 bool update_user_data;
493 struct wait_queue_entry wait;
501 struct io_poll_remove {
511 struct io_timeout_data {
512 struct io_kiocb *req;
513 struct hrtimer timer;
514 struct timespec64 ts;
515 enum hrtimer_mode mode;
520 struct sockaddr __user *addr;
521 int __user *addr_len;
523 unsigned long nofile;
543 struct list_head list;
544 /* head of the link, used by linked timeouts only */
545 struct io_kiocb *head;
548 struct io_timeout_rem {
553 struct timespec64 ts;
558 /* NOTE: kiocb has the file as the first member, so don't do it here */
566 struct sockaddr __user *addr;
573 struct compat_msghdr __user *umsg_compat;
574 struct user_msghdr __user *umsg;
580 struct io_buffer *kbuf;
586 struct filename *filename;
588 unsigned long nofile;
591 struct io_rsrc_update {
617 struct epoll_event event;
621 struct file *file_out;
622 struct file *file_in;
629 struct io_provide_buf {
643 const char __user *filename;
644 struct statx __user *buffer;
656 struct filename *oldpath;
657 struct filename *newpath;
665 struct filename *filename;
668 struct io_completion {
670 struct list_head list;
674 struct io_async_connect {
675 struct sockaddr_storage address;
678 struct io_async_msghdr {
679 struct iovec fast_iov[UIO_FASTIOV];
680 /* points to an allocated iov, if NULL we use fast_iov instead */
681 struct iovec *free_iov;
682 struct sockaddr __user *uaddr;
684 struct sockaddr_storage addr;
688 struct iovec fast_iov[UIO_FASTIOV];
689 const struct iovec *free_iovec;
690 struct iov_iter iter;
692 struct wait_page_queue wpq;
696 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
697 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
698 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
699 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
700 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
701 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
707 REQ_F_LINK_TIMEOUT_BIT,
708 REQ_F_NEED_CLEANUP_BIT,
710 REQ_F_BUFFER_SELECTED_BIT,
711 REQ_F_LTIMEOUT_ACTIVE_BIT,
712 REQ_F_COMPLETE_INLINE_BIT,
714 REQ_F_DONT_REISSUE_BIT,
715 /* keep async read/write and isreg together and in order */
716 REQ_F_ASYNC_READ_BIT,
717 REQ_F_ASYNC_WRITE_BIT,
720 /* not a real bit, just to check we're not overflowing the space */
726 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
727 /* drain existing IO first */
728 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
730 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
731 /* doesn't sever on completion < 0 */
732 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
734 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
735 /* IOSQE_BUFFER_SELECT */
736 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
738 /* fail rest of links */
739 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
740 /* on inflight list, should be cancelled and waited on exit reliably */
741 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
742 /* read/write uses file position */
743 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
744 /* must not punt to workers */
745 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
746 /* has or had linked timeout */
747 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
749 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
750 /* already went through poll handler */
751 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
752 /* buffer already selected */
753 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
754 /* linked timeout is active, i.e. prepared by link's head */
755 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
756 /* completion is deferred through io_comp_state */
757 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
758 /* caller should reissue async */
759 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
760 /* don't attempt request reissue, see io_rw_reissue() */
761 REQ_F_DONT_REISSUE = BIT(REQ_F_DONT_REISSUE_BIT),
762 /* supports async reads */
763 REQ_F_ASYNC_READ = BIT(REQ_F_ASYNC_READ_BIT),
764 /* supports async writes */
765 REQ_F_ASYNC_WRITE = BIT(REQ_F_ASYNC_WRITE_BIT),
767 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
771 struct io_poll_iocb poll;
772 struct io_poll_iocb *double_poll;
775 struct io_task_work {
776 struct io_wq_work_node node;
777 task_work_func_t func;
781 * NOTE! Each of the iocb union members has the file pointer
782 * as the first entry in their struct definition. So you can
783 * access the file pointer through any of the sub-structs,
784 * or directly as just 'ki_filp' in this struct.
790 struct io_poll_iocb poll;
791 struct io_poll_remove poll_remove;
792 struct io_accept accept;
794 struct io_cancel cancel;
795 struct io_timeout timeout;
796 struct io_timeout_rem timeout_rem;
797 struct io_connect connect;
798 struct io_sr_msg sr_msg;
800 struct io_close close;
801 struct io_rsrc_update rsrc_update;
802 struct io_fadvise fadvise;
803 struct io_madvise madvise;
804 struct io_epoll epoll;
805 struct io_splice splice;
806 struct io_provide_buf pbuf;
807 struct io_statx statx;
808 struct io_shutdown shutdown;
809 struct io_rename rename;
810 struct io_unlink unlink;
811 /* use only after cleaning per-op data, see io_clean_op() */
812 struct io_completion compl;
815 /* opcode allocated if it needs to store data for async defer */
818 /* polled IO has completed */
824 struct io_ring_ctx *ctx;
827 struct task_struct *task;
830 struct io_kiocb *link;
831 struct percpu_ref *fixed_rsrc_refs;
833 /* used with ctx->iopoll_list with reads/writes */
834 struct list_head inflight_entry;
836 struct io_task_work io_task_work;
837 struct callback_head task_work;
839 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
840 struct hlist_node hash_node;
841 struct async_poll *apoll;
842 struct io_wq_work work;
845 struct io_tctx_node {
846 struct list_head ctx_node;
847 struct task_struct *task;
848 struct io_ring_ctx *ctx;
851 struct io_defer_entry {
852 struct list_head list;
853 struct io_kiocb *req;
858 /* needs req->file assigned */
859 unsigned needs_file : 1;
860 /* hash wq insertion if file is a regular file */
861 unsigned hash_reg_file : 1;
862 /* unbound wq insertion if file is a non-regular file */
863 unsigned unbound_nonreg_file : 1;
864 /* opcode is not supported by this kernel */
865 unsigned not_supported : 1;
866 /* set if opcode supports polled "wait" */
868 unsigned pollout : 1;
869 /* op supports buffer selection */
870 unsigned buffer_select : 1;
871 /* do prep async if is going to be punted */
872 unsigned needs_async_setup : 1;
873 /* should block plug */
875 /* size of async data needed, if any */
876 unsigned short async_size;
879 static const struct io_op_def io_op_defs[] = {
880 [IORING_OP_NOP] = {},
881 [IORING_OP_READV] = {
883 .unbound_nonreg_file = 1,
886 .needs_async_setup = 1,
888 .async_size = sizeof(struct io_async_rw),
890 [IORING_OP_WRITEV] = {
893 .unbound_nonreg_file = 1,
895 .needs_async_setup = 1,
897 .async_size = sizeof(struct io_async_rw),
899 [IORING_OP_FSYNC] = {
902 [IORING_OP_READ_FIXED] = {
904 .unbound_nonreg_file = 1,
907 .async_size = sizeof(struct io_async_rw),
909 [IORING_OP_WRITE_FIXED] = {
912 .unbound_nonreg_file = 1,
915 .async_size = sizeof(struct io_async_rw),
917 [IORING_OP_POLL_ADD] = {
919 .unbound_nonreg_file = 1,
921 [IORING_OP_POLL_REMOVE] = {},
922 [IORING_OP_SYNC_FILE_RANGE] = {
925 [IORING_OP_SENDMSG] = {
927 .unbound_nonreg_file = 1,
929 .needs_async_setup = 1,
930 .async_size = sizeof(struct io_async_msghdr),
932 [IORING_OP_RECVMSG] = {
934 .unbound_nonreg_file = 1,
937 .needs_async_setup = 1,
938 .async_size = sizeof(struct io_async_msghdr),
940 [IORING_OP_TIMEOUT] = {
941 .async_size = sizeof(struct io_timeout_data),
943 [IORING_OP_TIMEOUT_REMOVE] = {
944 /* used by timeout updates' prep() */
946 [IORING_OP_ACCEPT] = {
948 .unbound_nonreg_file = 1,
951 [IORING_OP_ASYNC_CANCEL] = {},
952 [IORING_OP_LINK_TIMEOUT] = {
953 .async_size = sizeof(struct io_timeout_data),
955 [IORING_OP_CONNECT] = {
957 .unbound_nonreg_file = 1,
959 .needs_async_setup = 1,
960 .async_size = sizeof(struct io_async_connect),
962 [IORING_OP_FALLOCATE] = {
965 [IORING_OP_OPENAT] = {},
966 [IORING_OP_CLOSE] = {},
967 [IORING_OP_FILES_UPDATE] = {},
968 [IORING_OP_STATX] = {},
971 .unbound_nonreg_file = 1,
975 .async_size = sizeof(struct io_async_rw),
977 [IORING_OP_WRITE] = {
979 .unbound_nonreg_file = 1,
982 .async_size = sizeof(struct io_async_rw),
984 [IORING_OP_FADVISE] = {
987 [IORING_OP_MADVISE] = {},
990 .unbound_nonreg_file = 1,
995 .unbound_nonreg_file = 1,
999 [IORING_OP_OPENAT2] = {
1001 [IORING_OP_EPOLL_CTL] = {
1002 .unbound_nonreg_file = 1,
1004 [IORING_OP_SPLICE] = {
1007 .unbound_nonreg_file = 1,
1009 [IORING_OP_PROVIDE_BUFFERS] = {},
1010 [IORING_OP_REMOVE_BUFFERS] = {},
1014 .unbound_nonreg_file = 1,
1016 [IORING_OP_SHUTDOWN] = {
1019 [IORING_OP_RENAMEAT] = {},
1020 [IORING_OP_UNLINKAT] = {},
1023 static bool io_disarm_next(struct io_kiocb *req);
1024 static void io_uring_del_task_file(unsigned long index);
1025 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1026 struct task_struct *task,
1027 struct files_struct *files);
1028 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
1029 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx);
1031 static bool io_cqring_fill_event(struct io_kiocb *req, long res, unsigned cflags);
1032 static void io_put_req(struct io_kiocb *req);
1033 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1034 static void io_dismantle_req(struct io_kiocb *req);
1035 static void io_put_task(struct task_struct *task, int nr);
1036 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1037 static void io_queue_linked_timeout(struct io_kiocb *req);
1038 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1039 struct io_uring_rsrc_update *ip,
1041 static void io_clean_op(struct io_kiocb *req);
1042 static struct file *io_file_get(struct io_submit_state *state,
1043 struct io_kiocb *req, int fd, bool fixed);
1044 static void __io_queue_sqe(struct io_kiocb *req);
1045 static void io_rsrc_put_work(struct work_struct *work);
1047 static void io_req_task_queue(struct io_kiocb *req);
1048 static void io_submit_flush_completions(struct io_comp_state *cs,
1049 struct io_ring_ctx *ctx);
1050 static bool io_poll_remove_waitqs(struct io_kiocb *req);
1051 static int io_req_prep_async(struct io_kiocb *req);
1053 static struct kmem_cache *req_cachep;
1055 static const struct file_operations io_uring_fops;
1057 struct sock *io_uring_get_socket(struct file *file)
1059 #if defined(CONFIG_UNIX)
1060 if (file->f_op == &io_uring_fops) {
1061 struct io_ring_ctx *ctx = file->private_data;
1063 return ctx->ring_sock->sk;
1068 EXPORT_SYMBOL(io_uring_get_socket);
1070 #define io_for_each_link(pos, head) \
1071 for (pos = (head); pos; pos = pos->link)
1073 static inline void io_req_set_rsrc_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->rsrc_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)
1094 io_for_each_link(req, head) {
1095 if (req->flags & REQ_F_INFLIGHT)
1101 static inline void req_set_fail_links(struct io_kiocb *req)
1103 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1104 req->flags |= REQ_F_FAIL_LINK;
1107 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1109 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1111 complete(&ctx->ref_comp);
1114 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1116 return !req->timeout.off;
1119 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1121 struct io_ring_ctx *ctx;
1124 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1129 * Use 5 bits less than the max cq entries, that should give us around
1130 * 32 entries per hash list if totally full and uniformly spread.
1132 hash_bits = ilog2(p->cq_entries);
1136 ctx->cancel_hash_bits = hash_bits;
1137 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1139 if (!ctx->cancel_hash)
1141 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1143 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1144 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1147 ctx->flags = p->flags;
1148 init_waitqueue_head(&ctx->sqo_sq_wait);
1149 INIT_LIST_HEAD(&ctx->sqd_list);
1150 init_waitqueue_head(&ctx->cq_wait);
1151 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1152 init_completion(&ctx->ref_comp);
1153 xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1154 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1155 mutex_init(&ctx->uring_lock);
1156 init_waitqueue_head(&ctx->wait);
1157 spin_lock_init(&ctx->completion_lock);
1158 INIT_LIST_HEAD(&ctx->iopoll_list);
1159 INIT_LIST_HEAD(&ctx->defer_list);
1160 INIT_LIST_HEAD(&ctx->timeout_list);
1161 spin_lock_init(&ctx->rsrc_ref_lock);
1162 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1163 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1164 init_llist_head(&ctx->rsrc_put_llist);
1165 INIT_LIST_HEAD(&ctx->tctx_list);
1166 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1167 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1170 kfree(ctx->cancel_hash);
1175 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1177 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1178 struct io_ring_ctx *ctx = req->ctx;
1180 return seq != ctx->cached_cq_tail
1181 + READ_ONCE(ctx->cached_cq_overflow);
1187 static void io_req_track_inflight(struct io_kiocb *req)
1189 if (!(req->flags & REQ_F_INFLIGHT)) {
1190 req->flags |= REQ_F_INFLIGHT;
1191 atomic_inc(¤t->io_uring->inflight_tracked);
1195 static void io_prep_async_work(struct io_kiocb *req)
1197 const struct io_op_def *def = &io_op_defs[req->opcode];
1198 struct io_ring_ctx *ctx = req->ctx;
1200 if (!req->work.creds)
1201 req->work.creds = get_current_cred();
1203 req->work.list.next = NULL;
1204 req->work.flags = 0;
1205 if (req->flags & REQ_F_FORCE_ASYNC)
1206 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1208 if (req->flags & REQ_F_ISREG) {
1209 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1210 io_wq_hash_work(&req->work, file_inode(req->file));
1211 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1212 if (def->unbound_nonreg_file)
1213 req->work.flags |= IO_WQ_WORK_UNBOUND;
1216 switch (req->opcode) {
1217 case IORING_OP_SPLICE:
1219 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1220 req->work.flags |= IO_WQ_WORK_UNBOUND;
1225 static void io_prep_async_link(struct io_kiocb *req)
1227 struct io_kiocb *cur;
1229 io_for_each_link(cur, req)
1230 io_prep_async_work(cur);
1233 static void io_queue_async_work(struct io_kiocb *req)
1235 struct io_ring_ctx *ctx = req->ctx;
1236 struct io_kiocb *link = io_prep_linked_timeout(req);
1237 struct io_uring_task *tctx = req->task->io_uring;
1240 BUG_ON(!tctx->io_wq);
1242 /* init ->work of the whole link before punting */
1243 io_prep_async_link(req);
1244 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1245 &req->work, req->flags);
1246 io_wq_enqueue(tctx->io_wq, &req->work);
1248 io_queue_linked_timeout(link);
1251 static void io_kill_timeout(struct io_kiocb *req, int status)
1253 struct io_timeout_data *io = req->async_data;
1256 ret = hrtimer_try_to_cancel(&io->timer);
1258 atomic_set(&req->ctx->cq_timeouts,
1259 atomic_read(&req->ctx->cq_timeouts) + 1);
1260 list_del_init(&req->timeout.list);
1261 io_cqring_fill_event(req, status, 0);
1262 io_put_req_deferred(req, 1);
1266 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1269 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1270 struct io_defer_entry, list);
1272 if (req_need_defer(de->req, de->seq))
1274 list_del_init(&de->list);
1275 io_req_task_queue(de->req);
1277 } while (!list_empty(&ctx->defer_list));
1280 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1284 if (list_empty(&ctx->timeout_list))
1287 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1290 u32 events_needed, events_got;
1291 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1292 struct io_kiocb, timeout.list);
1294 if (io_is_timeout_noseq(req))
1298 * Since seq can easily wrap around over time, subtract
1299 * the last seq at which timeouts were flushed before comparing.
1300 * Assuming not more than 2^31-1 events have happened since,
1301 * these subtractions won't have wrapped, so we can check if
1302 * target is in [last_seq, current_seq] by comparing the two.
1304 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1305 events_got = seq - ctx->cq_last_tm_flush;
1306 if (events_got < events_needed)
1309 list_del_init(&req->timeout.list);
1310 io_kill_timeout(req, 0);
1311 } while (!list_empty(&ctx->timeout_list));
1313 ctx->cq_last_tm_flush = seq;
1316 static void io_commit_cqring(struct io_ring_ctx *ctx)
1318 io_flush_timeouts(ctx);
1320 /* order cqe stores with ring update */
1321 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1323 if (unlikely(!list_empty(&ctx->defer_list)))
1324 __io_queue_deferred(ctx);
1327 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1329 struct io_rings *r = ctx->rings;
1331 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1334 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1336 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1339 static inline struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1341 struct io_rings *rings = ctx->rings;
1345 * writes to the cq entry need to come after reading head; the
1346 * control dependency is enough as we're using WRITE_ONCE to
1349 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1352 tail = ctx->cached_cq_tail++;
1353 return &rings->cqes[tail & ctx->cq_mask];
1356 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1358 if (likely(!ctx->cq_ev_fd))
1360 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1362 return !ctx->eventfd_async || io_wq_current_is_worker();
1365 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1367 /* see waitqueue_active() comment */
1370 if (waitqueue_active(&ctx->wait))
1371 wake_up(&ctx->wait);
1372 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1373 wake_up(&ctx->sq_data->wait);
1374 if (io_should_trigger_evfd(ctx))
1375 eventfd_signal(ctx->cq_ev_fd, 1);
1376 if (waitqueue_active(&ctx->cq_wait)) {
1377 wake_up_interruptible(&ctx->cq_wait);
1378 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1382 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1384 /* see waitqueue_active() comment */
1387 if (ctx->flags & IORING_SETUP_SQPOLL) {
1388 if (waitqueue_active(&ctx->wait))
1389 wake_up(&ctx->wait);
1391 if (io_should_trigger_evfd(ctx))
1392 eventfd_signal(ctx->cq_ev_fd, 1);
1393 if (waitqueue_active(&ctx->cq_wait)) {
1394 wake_up_interruptible(&ctx->cq_wait);
1395 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1399 /* Returns true if there are no backlogged entries after the flush */
1400 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1402 struct io_rings *rings = ctx->rings;
1403 unsigned long flags;
1404 bool all_flushed, posted;
1406 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1410 spin_lock_irqsave(&ctx->completion_lock, flags);
1411 while (!list_empty(&ctx->cq_overflow_list)) {
1412 struct io_uring_cqe *cqe = io_get_cqring(ctx);
1413 struct io_overflow_cqe *ocqe;
1417 ocqe = list_first_entry(&ctx->cq_overflow_list,
1418 struct io_overflow_cqe, list);
1420 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1422 WRITE_ONCE(ctx->rings->cq_overflow,
1423 ++ctx->cached_cq_overflow);
1425 list_del(&ocqe->list);
1429 all_flushed = list_empty(&ctx->cq_overflow_list);
1431 clear_bit(0, &ctx->sq_check_overflow);
1432 clear_bit(0, &ctx->cq_check_overflow);
1433 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1437 io_commit_cqring(ctx);
1438 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1440 io_cqring_ev_posted(ctx);
1444 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1448 if (test_bit(0, &ctx->cq_check_overflow)) {
1449 /* iopoll syncs against uring_lock, not completion_lock */
1450 if (ctx->flags & IORING_SETUP_IOPOLL)
1451 mutex_lock(&ctx->uring_lock);
1452 ret = __io_cqring_overflow_flush(ctx, force);
1453 if (ctx->flags & IORING_SETUP_IOPOLL)
1454 mutex_unlock(&ctx->uring_lock);
1461 * Shamelessly stolen from the mm implementation of page reference checking,
1462 * see commit f958d7b528b1 for details.
1464 #define req_ref_zero_or_close_to_overflow(req) \
1465 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1467 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1469 return atomic_inc_not_zero(&req->refs);
1472 static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1474 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1475 return atomic_sub_and_test(refs, &req->refs);
1478 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1480 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1481 return atomic_dec_and_test(&req->refs);
1484 static inline void req_ref_put(struct io_kiocb *req)
1486 WARN_ON_ONCE(req_ref_put_and_test(req));
1489 static inline void req_ref_get(struct io_kiocb *req)
1491 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1492 atomic_inc(&req->refs);
1495 static bool io_cqring_event_overflow(struct io_kiocb *req, long res,
1496 unsigned int cflags)
1498 struct io_ring_ctx *ctx = req->ctx;
1500 if (!atomic_read(&req->task->io_uring->in_idle)) {
1501 struct io_overflow_cqe *ocqe;
1503 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1506 if (list_empty(&ctx->cq_overflow_list)) {
1507 set_bit(0, &ctx->sq_check_overflow);
1508 set_bit(0, &ctx->cq_check_overflow);
1509 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1511 ocqe->cqe.user_data = req->user_data;
1512 ocqe->cqe.res = res;
1513 ocqe->cqe.flags = cflags;
1514 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1519 * If we're in ring overflow flush mode, or in task cancel mode,
1520 * or cannot allocate an overflow entry, then we need to drop it
1523 WRITE_ONCE(ctx->rings->cq_overflow, ++ctx->cached_cq_overflow);
1527 static inline bool __io_cqring_fill_event(struct io_kiocb *req, long res,
1528 unsigned int cflags)
1530 struct io_ring_ctx *ctx = req->ctx;
1531 struct io_uring_cqe *cqe;
1533 trace_io_uring_complete(ctx, req->user_data, res, cflags);
1536 * If we can't get a cq entry, userspace overflowed the
1537 * submission (by quite a lot). Increment the overflow count in
1540 cqe = io_get_cqring(ctx);
1542 WRITE_ONCE(cqe->user_data, req->user_data);
1543 WRITE_ONCE(cqe->res, res);
1544 WRITE_ONCE(cqe->flags, cflags);
1547 return io_cqring_event_overflow(req, res, cflags);
1550 /* not as hot to bloat with inlining */
1551 static noinline bool io_cqring_fill_event(struct io_kiocb *req, long res,
1552 unsigned int cflags)
1554 return __io_cqring_fill_event(req, res, cflags);
1557 static void io_req_complete_post(struct io_kiocb *req, long res,
1558 unsigned int cflags)
1560 struct io_ring_ctx *ctx = req->ctx;
1561 unsigned long flags;
1563 spin_lock_irqsave(&ctx->completion_lock, flags);
1564 __io_cqring_fill_event(req, res, cflags);
1566 * If we're the last reference to this request, add to our locked
1569 if (req_ref_put_and_test(req)) {
1570 struct io_comp_state *cs = &ctx->submit_state.comp;
1572 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1573 if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL_LINK))
1574 io_disarm_next(req);
1576 io_req_task_queue(req->link);
1580 io_dismantle_req(req);
1581 io_put_task(req->task, 1);
1582 list_add(&req->compl.list, &cs->locked_free_list);
1583 cs->locked_free_nr++;
1585 if (!percpu_ref_tryget(&ctx->refs))
1588 io_commit_cqring(ctx);
1589 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1592 io_cqring_ev_posted(ctx);
1593 percpu_ref_put(&ctx->refs);
1597 static void io_req_complete_state(struct io_kiocb *req, long res,
1598 unsigned int cflags)
1600 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1603 req->compl.cflags = cflags;
1604 req->flags |= REQ_F_COMPLETE_INLINE;
1607 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1608 long res, unsigned cflags)
1610 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1611 io_req_complete_state(req, res, cflags);
1613 io_req_complete_post(req, res, cflags);
1616 static inline void io_req_complete(struct io_kiocb *req, long res)
1618 __io_req_complete(req, 0, res, 0);
1621 static void io_req_complete_failed(struct io_kiocb *req, long res)
1623 req_set_fail_links(req);
1625 io_req_complete_post(req, res, 0);
1628 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1629 struct io_comp_state *cs)
1631 spin_lock_irq(&ctx->completion_lock);
1632 list_splice_init(&cs->locked_free_list, &cs->free_list);
1633 cs->locked_free_nr = 0;
1634 spin_unlock_irq(&ctx->completion_lock);
1637 /* Returns true IFF there are requests in the cache */
1638 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1640 struct io_submit_state *state = &ctx->submit_state;
1641 struct io_comp_state *cs = &state->comp;
1645 * If we have more than a batch's worth of requests in our IRQ side
1646 * locked cache, grab the lock and move them over to our submission
1649 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH)
1650 io_flush_cached_locked_reqs(ctx, cs);
1652 nr = state->free_reqs;
1653 while (!list_empty(&cs->free_list)) {
1654 struct io_kiocb *req = list_first_entry(&cs->free_list,
1655 struct io_kiocb, compl.list);
1657 list_del(&req->compl.list);
1658 state->reqs[nr++] = req;
1659 if (nr == ARRAY_SIZE(state->reqs))
1663 state->free_reqs = nr;
1667 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1669 struct io_submit_state *state = &ctx->submit_state;
1671 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1673 if (!state->free_reqs) {
1674 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1677 if (io_flush_cached_reqs(ctx))
1680 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1684 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1685 * retry single alloc to be on the safe side.
1687 if (unlikely(ret <= 0)) {
1688 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1689 if (!state->reqs[0])
1693 state->free_reqs = ret;
1697 return state->reqs[state->free_reqs];
1700 static inline void io_put_file(struct file *file)
1706 static void io_dismantle_req(struct io_kiocb *req)
1708 unsigned int flags = req->flags;
1710 if (!(flags & REQ_F_FIXED_FILE))
1711 io_put_file(req->file);
1712 if (flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED |
1716 if (req->flags & REQ_F_INFLIGHT) {
1717 struct io_uring_task *tctx = req->task->io_uring;
1719 atomic_dec(&tctx->inflight_tracked);
1720 req->flags &= ~REQ_F_INFLIGHT;
1723 if (req->fixed_rsrc_refs)
1724 percpu_ref_put(req->fixed_rsrc_refs);
1725 if (req->async_data)
1726 kfree(req->async_data);
1727 if (req->work.creds) {
1728 put_cred(req->work.creds);
1729 req->work.creds = NULL;
1733 /* must to be called somewhat shortly after putting a request */
1734 static inline void io_put_task(struct task_struct *task, int nr)
1736 struct io_uring_task *tctx = task->io_uring;
1738 percpu_counter_sub(&tctx->inflight, nr);
1739 if (unlikely(atomic_read(&tctx->in_idle)))
1740 wake_up(&tctx->wait);
1741 put_task_struct_many(task, nr);
1744 static void __io_free_req(struct io_kiocb *req)
1746 struct io_ring_ctx *ctx = req->ctx;
1748 io_dismantle_req(req);
1749 io_put_task(req->task, 1);
1751 kmem_cache_free(req_cachep, req);
1752 percpu_ref_put(&ctx->refs);
1755 static inline void io_remove_next_linked(struct io_kiocb *req)
1757 struct io_kiocb *nxt = req->link;
1759 req->link = nxt->link;
1763 static bool io_kill_linked_timeout(struct io_kiocb *req)
1764 __must_hold(&req->ctx->completion_lock)
1766 struct io_kiocb *link = req->link;
1769 * Can happen if a linked timeout fired and link had been like
1770 * req -> link t-out -> link t-out [-> ...]
1772 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1773 struct io_timeout_data *io = link->async_data;
1776 io_remove_next_linked(req);
1777 link->timeout.head = NULL;
1778 ret = hrtimer_try_to_cancel(&io->timer);
1780 io_cqring_fill_event(link, -ECANCELED, 0);
1781 io_put_req_deferred(link, 1);
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, 0);
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_req_task_work_add(struct io_kiocb *req)
1912 struct task_struct *tsk = req->task;
1913 struct io_uring_task *tctx = tsk->io_uring;
1914 enum task_work_notify_mode notify;
1915 struct io_wq_work_node *node, *prev;
1916 unsigned long flags;
1919 if (unlikely(tsk->flags & PF_EXITING))
1922 WARN_ON_ONCE(!tctx);
1924 spin_lock_irqsave(&tctx->task_lock, flags);
1925 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1926 spin_unlock_irqrestore(&tctx->task_lock, flags);
1928 /* task_work already pending, we're done */
1929 if (test_bit(0, &tctx->task_state) ||
1930 test_and_set_bit(0, &tctx->task_state))
1934 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1935 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1936 * processing task_work. There's no reliable way to tell if TWA_RESUME
1939 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
1941 if (!task_work_add(tsk, &tctx->task_work, notify)) {
1942 wake_up_process(tsk);
1947 * Slow path - we failed, find and delete work. if the work is not
1948 * in the list, it got run and we're fine.
1950 spin_lock_irqsave(&tctx->task_lock, flags);
1951 wq_list_for_each(node, prev, &tctx->task_list) {
1952 if (&req->io_task_work.node == node) {
1953 wq_list_del(&tctx->task_list, node, prev);
1958 spin_unlock_irqrestore(&tctx->task_lock, flags);
1959 clear_bit(0, &tctx->task_state);
1963 static bool io_run_task_work_head(struct callback_head **work_head)
1965 struct callback_head *work, *next;
1966 bool executed = false;
1969 work = xchg(work_head, NULL);
1985 static void io_task_work_add_head(struct callback_head **work_head,
1986 struct callback_head *task_work)
1988 struct callback_head *head;
1991 head = READ_ONCE(*work_head);
1992 task_work->next = head;
1993 } while (cmpxchg(work_head, head, task_work) != head);
1996 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1997 task_work_func_t cb)
1999 init_task_work(&req->task_work, cb);
2000 io_task_work_add_head(&req->ctx->exit_task_work, &req->task_work);
2003 static void io_req_task_cancel(struct callback_head *cb)
2005 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2006 struct io_ring_ctx *ctx = req->ctx;
2008 /* ctx is guaranteed to stay alive while we hold uring_lock */
2009 mutex_lock(&ctx->uring_lock);
2010 io_req_complete_failed(req, req->result);
2011 mutex_unlock(&ctx->uring_lock);
2014 static void __io_req_task_submit(struct io_kiocb *req)
2016 struct io_ring_ctx *ctx = req->ctx;
2018 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2019 mutex_lock(&ctx->uring_lock);
2020 if (!(current->flags & PF_EXITING) && !current->in_execve)
2021 __io_queue_sqe(req);
2023 io_req_complete_failed(req, -EFAULT);
2024 mutex_unlock(&ctx->uring_lock);
2027 static void io_req_task_submit(struct callback_head *cb)
2029 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2031 __io_req_task_submit(req);
2034 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2037 req->task_work.func = io_req_task_cancel;
2039 if (unlikely(io_req_task_work_add(req)))
2040 io_req_task_work_add_fallback(req, io_req_task_cancel);
2043 static void io_req_task_queue(struct io_kiocb *req)
2045 req->task_work.func = io_req_task_submit;
2047 if (unlikely(io_req_task_work_add(req)))
2048 io_req_task_queue_fail(req, -ECANCELED);
2051 static inline void io_queue_next(struct io_kiocb *req)
2053 struct io_kiocb *nxt = io_req_find_next(req);
2056 io_req_task_queue(nxt);
2059 static void io_free_req(struct io_kiocb *req)
2066 struct task_struct *task;
2071 static inline void io_init_req_batch(struct req_batch *rb)
2078 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2079 struct req_batch *rb)
2082 io_put_task(rb->task, rb->task_refs);
2084 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2087 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2088 struct io_submit_state *state)
2091 io_dismantle_req(req);
2093 if (req->task != rb->task) {
2095 io_put_task(rb->task, rb->task_refs);
2096 rb->task = req->task;
2102 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2103 state->reqs[state->free_reqs++] = req;
2105 list_add(&req->compl.list, &state->comp.free_list);
2108 static void io_submit_flush_completions(struct io_comp_state *cs,
2109 struct io_ring_ctx *ctx)
2112 struct io_kiocb *req;
2113 struct req_batch rb;
2115 io_init_req_batch(&rb);
2116 spin_lock_irq(&ctx->completion_lock);
2117 for (i = 0; i < nr; i++) {
2119 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2121 io_commit_cqring(ctx);
2122 spin_unlock_irq(&ctx->completion_lock);
2124 io_cqring_ev_posted(ctx);
2125 for (i = 0; i < nr; i++) {
2128 /* submission and completion refs */
2129 if (req_ref_sub_and_test(req, 2))
2130 io_req_free_batch(&rb, req, &ctx->submit_state);
2133 io_req_free_batch_finish(ctx, &rb);
2138 * Drop reference to request, return next in chain (if there is one) if this
2139 * was the last reference to this request.
2141 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2143 struct io_kiocb *nxt = NULL;
2145 if (req_ref_put_and_test(req)) {
2146 nxt = io_req_find_next(req);
2152 static inline void io_put_req(struct io_kiocb *req)
2154 if (req_ref_put_and_test(req))
2158 static void io_put_req_deferred_cb(struct callback_head *cb)
2160 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2165 static void io_free_req_deferred(struct io_kiocb *req)
2167 req->task_work.func = io_put_req_deferred_cb;
2168 if (unlikely(io_req_task_work_add(req)))
2169 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2172 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2174 if (req_ref_sub_and_test(req, refs))
2175 io_free_req_deferred(req);
2178 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2180 /* See comment at the top of this file */
2182 return __io_cqring_events(ctx);
2185 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2187 struct io_rings *rings = ctx->rings;
2189 /* make sure SQ entry isn't read before tail */
2190 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2193 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2195 unsigned int cflags;
2197 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2198 cflags |= IORING_CQE_F_BUFFER;
2199 req->flags &= ~REQ_F_BUFFER_SELECTED;
2204 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2206 struct io_buffer *kbuf;
2208 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2209 return io_put_kbuf(req, kbuf);
2212 static inline bool io_run_task_work(void)
2215 * Not safe to run on exiting task, and the task_work handling will
2216 * not add work to such a task.
2218 if (unlikely(current->flags & PF_EXITING))
2220 if (current->task_works) {
2221 __set_current_state(TASK_RUNNING);
2230 * Find and free completed poll iocbs
2232 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2233 struct list_head *done)
2235 struct req_batch rb;
2236 struct io_kiocb *req;
2238 /* order with ->result store in io_complete_rw_iopoll() */
2241 io_init_req_batch(&rb);
2242 while (!list_empty(done)) {
2245 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2246 list_del(&req->inflight_entry);
2248 if (READ_ONCE(req->result) == -EAGAIN &&
2249 !(req->flags & REQ_F_DONT_REISSUE)) {
2250 req->iopoll_completed = 0;
2252 io_queue_async_work(req);
2256 if (req->flags & REQ_F_BUFFER_SELECTED)
2257 cflags = io_put_rw_kbuf(req);
2259 __io_cqring_fill_event(req, req->result, cflags);
2262 if (req_ref_put_and_test(req))
2263 io_req_free_batch(&rb, req, &ctx->submit_state);
2266 io_commit_cqring(ctx);
2267 io_cqring_ev_posted_iopoll(ctx);
2268 io_req_free_batch_finish(ctx, &rb);
2271 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2274 struct io_kiocb *req, *tmp;
2280 * Only spin for completions if we don't have multiple devices hanging
2281 * off our complete list, and we're under the requested amount.
2283 spin = !ctx->poll_multi_file && *nr_events < min;
2286 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2287 struct kiocb *kiocb = &req->rw.kiocb;
2290 * Move completed and retryable entries to our local lists.
2291 * If we find a request that requires polling, break out
2292 * and complete those lists first, if we have entries there.
2294 if (READ_ONCE(req->iopoll_completed)) {
2295 list_move_tail(&req->inflight_entry, &done);
2298 if (!list_empty(&done))
2301 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2305 /* iopoll may have completed current req */
2306 if (READ_ONCE(req->iopoll_completed))
2307 list_move_tail(&req->inflight_entry, &done);
2314 if (!list_empty(&done))
2315 io_iopoll_complete(ctx, nr_events, &done);
2321 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2322 * non-spinning poll check - we'll still enter the driver poll loop, but only
2323 * as a non-spinning completion check.
2325 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2328 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2331 ret = io_do_iopoll(ctx, nr_events, min);
2334 if (*nr_events >= min)
2342 * We can't just wait for polled events to come to us, we have to actively
2343 * find and complete them.
2345 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2347 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2350 mutex_lock(&ctx->uring_lock);
2351 while (!list_empty(&ctx->iopoll_list)) {
2352 unsigned int nr_events = 0;
2354 io_do_iopoll(ctx, &nr_events, 0);
2356 /* let it sleep and repeat later if can't complete a request */
2360 * Ensure we allow local-to-the-cpu processing to take place,
2361 * in this case we need to ensure that we reap all events.
2362 * Also let task_work, etc. to progress by releasing the mutex
2364 if (need_resched()) {
2365 mutex_unlock(&ctx->uring_lock);
2367 mutex_lock(&ctx->uring_lock);
2370 mutex_unlock(&ctx->uring_lock);
2373 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2375 unsigned int nr_events = 0;
2376 int iters = 0, ret = 0;
2379 * We disallow the app entering submit/complete with polling, but we
2380 * still need to lock the ring to prevent racing with polled issue
2381 * that got punted to a workqueue.
2383 mutex_lock(&ctx->uring_lock);
2386 * Don't enter poll loop if we already have events pending.
2387 * If we do, we can potentially be spinning for commands that
2388 * already triggered a CQE (eg in error).
2390 if (test_bit(0, &ctx->cq_check_overflow))
2391 __io_cqring_overflow_flush(ctx, false);
2392 if (io_cqring_events(ctx))
2396 * If a submit got punted to a workqueue, we can have the
2397 * application entering polling for a command before it gets
2398 * issued. That app will hold the uring_lock for the duration
2399 * of the poll right here, so we need to take a breather every
2400 * now and then to ensure that the issue has a chance to add
2401 * the poll to the issued list. Otherwise we can spin here
2402 * forever, while the workqueue is stuck trying to acquire the
2405 if (!(++iters & 7)) {
2406 mutex_unlock(&ctx->uring_lock);
2408 mutex_lock(&ctx->uring_lock);
2411 ret = io_iopoll_getevents(ctx, &nr_events, min);
2415 } while (min && !nr_events && !need_resched());
2417 mutex_unlock(&ctx->uring_lock);
2421 static void kiocb_end_write(struct io_kiocb *req)
2424 * Tell lockdep we inherited freeze protection from submission
2427 if (req->flags & REQ_F_ISREG) {
2428 struct super_block *sb = file_inode(req->file)->i_sb;
2430 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2436 static bool io_resubmit_prep(struct io_kiocb *req)
2438 struct io_async_rw *rw = req->async_data;
2441 return !io_req_prep_async(req);
2442 /* may have left rw->iter inconsistent on -EIOCBQUEUED */
2443 iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2447 static bool io_rw_should_reissue(struct io_kiocb *req)
2449 umode_t mode = file_inode(req->file)->i_mode;
2450 struct io_ring_ctx *ctx = req->ctx;
2452 if (!S_ISBLK(mode) && !S_ISREG(mode))
2454 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2455 !(ctx->flags & IORING_SETUP_IOPOLL)))
2458 * If ref is dying, we might be running poll reap from the exit work.
2459 * Don't attempt to reissue from that path, just let it fail with
2462 if (percpu_ref_is_dying(&ctx->refs))
2467 static bool io_resubmit_prep(struct io_kiocb *req)
2471 static bool io_rw_should_reissue(struct io_kiocb *req)
2477 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2478 unsigned int issue_flags)
2482 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2483 kiocb_end_write(req);
2484 if (res != req->result) {
2485 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2486 io_rw_should_reissue(req)) {
2487 req->flags |= REQ_F_REISSUE;
2490 req_set_fail_links(req);
2492 if (req->flags & REQ_F_BUFFER_SELECTED)
2493 cflags = io_put_rw_kbuf(req);
2494 __io_req_complete(req, issue_flags, res, cflags);
2497 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2499 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2501 __io_complete_rw(req, res, res2, 0);
2504 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2506 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2508 if (kiocb->ki_flags & IOCB_WRITE)
2509 kiocb_end_write(req);
2510 if (unlikely(res != req->result)) {
2511 if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2512 io_resubmit_prep(req))) {
2513 req_set_fail_links(req);
2514 req->flags |= REQ_F_DONT_REISSUE;
2518 WRITE_ONCE(req->result, res);
2519 /* order with io_iopoll_complete() checking ->result */
2521 WRITE_ONCE(req->iopoll_completed, 1);
2525 * After the iocb has been issued, it's safe to be found on the poll list.
2526 * Adding the kiocb to the list AFTER submission ensures that we don't
2527 * find it from a io_iopoll_getevents() thread before the issuer is done
2528 * accessing the kiocb cookie.
2530 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2532 struct io_ring_ctx *ctx = req->ctx;
2535 * Track whether we have multiple files in our lists. This will impact
2536 * how we do polling eventually, not spinning if we're on potentially
2537 * different devices.
2539 if (list_empty(&ctx->iopoll_list)) {
2540 ctx->poll_multi_file = false;
2541 } else if (!ctx->poll_multi_file) {
2542 struct io_kiocb *list_req;
2544 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2546 if (list_req->file != req->file)
2547 ctx->poll_multi_file = true;
2551 * For fast devices, IO may have already completed. If it has, add
2552 * it to the front so we find it first.
2554 if (READ_ONCE(req->iopoll_completed))
2555 list_add(&req->inflight_entry, &ctx->iopoll_list);
2557 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2560 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2561 * task context or in io worker task context. If current task context is
2562 * sq thread, we don't need to check whether should wake up sq thread.
2564 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2565 wq_has_sleeper(&ctx->sq_data->wait))
2566 wake_up(&ctx->sq_data->wait);
2569 static inline void io_state_file_put(struct io_submit_state *state)
2571 if (state->file_refs) {
2572 fput_many(state->file, state->file_refs);
2573 state->file_refs = 0;
2578 * Get as many references to a file as we have IOs left in this submission,
2579 * assuming most submissions are for one file, or at least that each file
2580 * has more than one submission.
2582 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2587 if (state->file_refs) {
2588 if (state->fd == fd) {
2592 io_state_file_put(state);
2594 state->file = fget_many(fd, state->ios_left);
2595 if (unlikely(!state->file))
2599 state->file_refs = state->ios_left - 1;
2603 static bool io_bdev_nowait(struct block_device *bdev)
2605 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2609 * If we tracked the file through the SCM inflight mechanism, we could support
2610 * any file. For now, just ensure that anything potentially problematic is done
2613 static bool __io_file_supports_async(struct file *file, int rw)
2615 umode_t mode = file_inode(file)->i_mode;
2617 if (S_ISBLK(mode)) {
2618 if (IS_ENABLED(CONFIG_BLOCK) &&
2619 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2623 if (S_ISCHR(mode) || S_ISSOCK(mode))
2625 if (S_ISREG(mode)) {
2626 if (IS_ENABLED(CONFIG_BLOCK) &&
2627 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2628 file->f_op != &io_uring_fops)
2633 /* any ->read/write should understand O_NONBLOCK */
2634 if (file->f_flags & O_NONBLOCK)
2637 if (!(file->f_mode & FMODE_NOWAIT))
2641 return file->f_op->read_iter != NULL;
2643 return file->f_op->write_iter != NULL;
2646 static bool io_file_supports_async(struct io_kiocb *req, int rw)
2648 if (rw == READ && (req->flags & REQ_F_ASYNC_READ))
2650 else if (rw == WRITE && (req->flags & REQ_F_ASYNC_WRITE))
2653 return __io_file_supports_async(req->file, rw);
2656 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2658 struct io_ring_ctx *ctx = req->ctx;
2659 struct kiocb *kiocb = &req->rw.kiocb;
2660 struct file *file = req->file;
2664 if (!(req->flags & REQ_F_ISREG) && S_ISREG(file_inode(file)->i_mode))
2665 req->flags |= REQ_F_ISREG;
2667 kiocb->ki_pos = READ_ONCE(sqe->off);
2668 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2669 req->flags |= REQ_F_CUR_POS;
2670 kiocb->ki_pos = file->f_pos;
2672 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2673 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2674 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2678 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2679 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2680 req->flags |= REQ_F_NOWAIT;
2682 ioprio = READ_ONCE(sqe->ioprio);
2684 ret = ioprio_check_cap(ioprio);
2688 kiocb->ki_ioprio = ioprio;
2690 kiocb->ki_ioprio = get_current_ioprio();
2692 if (ctx->flags & IORING_SETUP_IOPOLL) {
2693 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2694 !kiocb->ki_filp->f_op->iopoll)
2697 kiocb->ki_flags |= IOCB_HIPRI;
2698 kiocb->ki_complete = io_complete_rw_iopoll;
2699 req->iopoll_completed = 0;
2701 if (kiocb->ki_flags & IOCB_HIPRI)
2703 kiocb->ki_complete = io_complete_rw;
2706 req->rw.addr = READ_ONCE(sqe->addr);
2707 req->rw.len = READ_ONCE(sqe->len);
2708 req->buf_index = READ_ONCE(sqe->buf_index);
2712 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2718 case -ERESTARTNOINTR:
2719 case -ERESTARTNOHAND:
2720 case -ERESTART_RESTARTBLOCK:
2722 * We can't just restart the syscall, since previously
2723 * submitted sqes may already be in progress. Just fail this
2729 kiocb->ki_complete(kiocb, ret, 0);
2733 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2734 unsigned int issue_flags)
2736 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2737 struct io_async_rw *io = req->async_data;
2738 bool check_reissue = kiocb->ki_complete == io_complete_rw;
2740 /* add previously done IO, if any */
2741 if (io && io->bytes_done > 0) {
2743 ret = io->bytes_done;
2745 ret += io->bytes_done;
2748 if (req->flags & REQ_F_CUR_POS)
2749 req->file->f_pos = kiocb->ki_pos;
2750 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2751 __io_complete_rw(req, ret, 0, issue_flags);
2753 io_rw_done(kiocb, ret);
2755 if (check_reissue && req->flags & REQ_F_REISSUE) {
2756 req->flags &= ~REQ_F_REISSUE;
2757 if (!io_resubmit_prep(req)) {
2759 io_queue_async_work(req);
2763 req_set_fail_links(req);
2764 if (req->flags & REQ_F_BUFFER_SELECTED)
2765 cflags = io_put_rw_kbuf(req);
2766 __io_req_complete(req, issue_flags, ret, cflags);
2771 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2773 struct io_ring_ctx *ctx = req->ctx;
2774 size_t len = req->rw.len;
2775 struct io_mapped_ubuf *imu;
2776 u16 index, buf_index = req->buf_index;
2777 u64 buf_end, buf_addr = req->rw.addr;
2780 if (unlikely(buf_index >= ctx->nr_user_bufs))
2782 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2783 imu = &ctx->user_bufs[index];
2784 buf_addr = req->rw.addr;
2786 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2788 /* not inside the mapped region */
2789 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2793 * May not be a start of buffer, set size appropriately
2794 * and advance us to the beginning.
2796 offset = buf_addr - imu->ubuf;
2797 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2801 * Don't use iov_iter_advance() here, as it's really slow for
2802 * using the latter parts of a big fixed buffer - it iterates
2803 * over each segment manually. We can cheat a bit here, because
2806 * 1) it's a BVEC iter, we set it up
2807 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2808 * first and last bvec
2810 * So just find our index, and adjust the iterator afterwards.
2811 * If the offset is within the first bvec (or the whole first
2812 * bvec, just use iov_iter_advance(). This makes it easier
2813 * since we can just skip the first segment, which may not
2814 * be PAGE_SIZE aligned.
2816 const struct bio_vec *bvec = imu->bvec;
2818 if (offset <= bvec->bv_len) {
2819 iov_iter_advance(iter, offset);
2821 unsigned long seg_skip;
2823 /* skip first vec */
2824 offset -= bvec->bv_len;
2825 seg_skip = 1 + (offset >> PAGE_SHIFT);
2827 iter->bvec = bvec + seg_skip;
2828 iter->nr_segs -= seg_skip;
2829 iter->count -= bvec->bv_len + offset;
2830 iter->iov_offset = offset & ~PAGE_MASK;
2837 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2840 mutex_unlock(&ctx->uring_lock);
2843 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2846 * "Normal" inline submissions always hold the uring_lock, since we
2847 * grab it from the system call. Same is true for the SQPOLL offload.
2848 * The only exception is when we've detached the request and issue it
2849 * from an async worker thread, grab the lock for that case.
2852 mutex_lock(&ctx->uring_lock);
2855 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2856 int bgid, struct io_buffer *kbuf,
2859 struct io_buffer *head;
2861 if (req->flags & REQ_F_BUFFER_SELECTED)
2864 io_ring_submit_lock(req->ctx, needs_lock);
2866 lockdep_assert_held(&req->ctx->uring_lock);
2868 head = xa_load(&req->ctx->io_buffers, bgid);
2870 if (!list_empty(&head->list)) {
2871 kbuf = list_last_entry(&head->list, struct io_buffer,
2873 list_del(&kbuf->list);
2876 xa_erase(&req->ctx->io_buffers, bgid);
2878 if (*len > kbuf->len)
2881 kbuf = ERR_PTR(-ENOBUFS);
2884 io_ring_submit_unlock(req->ctx, needs_lock);
2889 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2892 struct io_buffer *kbuf;
2895 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2896 bgid = req->buf_index;
2897 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2900 req->rw.addr = (u64) (unsigned long) kbuf;
2901 req->flags |= REQ_F_BUFFER_SELECTED;
2902 return u64_to_user_ptr(kbuf->addr);
2905 #ifdef CONFIG_COMPAT
2906 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2909 struct compat_iovec __user *uiov;
2910 compat_ssize_t clen;
2914 uiov = u64_to_user_ptr(req->rw.addr);
2915 if (!access_ok(uiov, sizeof(*uiov)))
2917 if (__get_user(clen, &uiov->iov_len))
2923 buf = io_rw_buffer_select(req, &len, needs_lock);
2925 return PTR_ERR(buf);
2926 iov[0].iov_base = buf;
2927 iov[0].iov_len = (compat_size_t) len;
2932 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2935 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2939 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2942 len = iov[0].iov_len;
2945 buf = io_rw_buffer_select(req, &len, needs_lock);
2947 return PTR_ERR(buf);
2948 iov[0].iov_base = buf;
2949 iov[0].iov_len = len;
2953 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2956 if (req->flags & REQ_F_BUFFER_SELECTED) {
2957 struct io_buffer *kbuf;
2959 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2960 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2961 iov[0].iov_len = kbuf->len;
2964 if (req->rw.len != 1)
2967 #ifdef CONFIG_COMPAT
2968 if (req->ctx->compat)
2969 return io_compat_import(req, iov, needs_lock);
2972 return __io_iov_buffer_select(req, iov, needs_lock);
2975 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2976 struct iov_iter *iter, bool needs_lock)
2978 void __user *buf = u64_to_user_ptr(req->rw.addr);
2979 size_t sqe_len = req->rw.len;
2980 u8 opcode = req->opcode;
2983 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2985 return io_import_fixed(req, rw, iter);
2988 /* buffer index only valid with fixed read/write, or buffer select */
2989 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2992 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2993 if (req->flags & REQ_F_BUFFER_SELECT) {
2994 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2996 return PTR_ERR(buf);
2997 req->rw.len = sqe_len;
3000 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3005 if (req->flags & REQ_F_BUFFER_SELECT) {
3006 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3008 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3013 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3017 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3019 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3023 * For files that don't have ->read_iter() and ->write_iter(), handle them
3024 * by looping over ->read() or ->write() manually.
3026 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3028 struct kiocb *kiocb = &req->rw.kiocb;
3029 struct file *file = req->file;
3033 * Don't support polled IO through this interface, and we can't
3034 * support non-blocking either. For the latter, this just causes
3035 * the kiocb to be handled from an async context.
3037 if (kiocb->ki_flags & IOCB_HIPRI)
3039 if (kiocb->ki_flags & IOCB_NOWAIT)
3042 while (iov_iter_count(iter)) {
3046 if (!iov_iter_is_bvec(iter)) {
3047 iovec = iov_iter_iovec(iter);
3049 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3050 iovec.iov_len = req->rw.len;
3054 nr = file->f_op->read(file, iovec.iov_base,
3055 iovec.iov_len, io_kiocb_ppos(kiocb));
3057 nr = file->f_op->write(file, iovec.iov_base,
3058 iovec.iov_len, io_kiocb_ppos(kiocb));
3067 if (nr != iovec.iov_len)
3071 iov_iter_advance(iter, nr);
3077 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3078 const struct iovec *fast_iov, struct iov_iter *iter)
3080 struct io_async_rw *rw = req->async_data;
3082 memcpy(&rw->iter, iter, sizeof(*iter));
3083 rw->free_iovec = iovec;
3085 /* can only be fixed buffers, no need to do anything */
3086 if (iov_iter_is_bvec(iter))
3089 unsigned iov_off = 0;
3091 rw->iter.iov = rw->fast_iov;
3092 if (iter->iov != fast_iov) {
3093 iov_off = iter->iov - fast_iov;
3094 rw->iter.iov += iov_off;
3096 if (rw->fast_iov != fast_iov)
3097 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3098 sizeof(struct iovec) * iter->nr_segs);
3100 req->flags |= REQ_F_NEED_CLEANUP;
3104 static inline int io_alloc_async_data(struct io_kiocb *req)
3106 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3107 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3108 return req->async_data == NULL;
3111 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3112 const struct iovec *fast_iov,
3113 struct iov_iter *iter, bool force)
3115 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3117 if (!req->async_data) {
3118 if (io_alloc_async_data(req)) {
3123 io_req_map_rw(req, iovec, fast_iov, iter);
3128 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3130 struct io_async_rw *iorw = req->async_data;
3131 struct iovec *iov = iorw->fast_iov;
3134 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3135 if (unlikely(ret < 0))
3138 iorw->bytes_done = 0;
3139 iorw->free_iovec = iov;
3141 req->flags |= REQ_F_NEED_CLEANUP;
3145 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3147 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3149 return io_prep_rw(req, sqe);
3153 * This is our waitqueue callback handler, registered through lock_page_async()
3154 * when we initially tried to do the IO with the iocb armed our waitqueue.
3155 * This gets called when the page is unlocked, and we generally expect that to
3156 * happen when the page IO is completed and the page is now uptodate. This will
3157 * queue a task_work based retry of the operation, attempting to copy the data
3158 * again. If the latter fails because the page was NOT uptodate, then we will
3159 * do a thread based blocking retry of the operation. That's the unexpected
3162 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3163 int sync, void *arg)
3165 struct wait_page_queue *wpq;
3166 struct io_kiocb *req = wait->private;
3167 struct wait_page_key *key = arg;
3169 wpq = container_of(wait, struct wait_page_queue, wait);
3171 if (!wake_page_match(wpq, key))
3174 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3175 list_del_init(&wait->entry);
3177 /* submit ref gets dropped, acquire a new one */
3179 io_req_task_queue(req);
3184 * This controls whether a given IO request should be armed for async page
3185 * based retry. If we return false here, the request is handed to the async
3186 * worker threads for retry. If we're doing buffered reads on a regular file,
3187 * we prepare a private wait_page_queue entry and retry the operation. This
3188 * will either succeed because the page is now uptodate and unlocked, or it
3189 * will register a callback when the page is unlocked at IO completion. Through
3190 * that callback, io_uring uses task_work to setup a retry of the operation.
3191 * That retry will attempt the buffered read again. The retry will generally
3192 * succeed, or in rare cases where it fails, we then fall back to using the
3193 * async worker threads for a blocking retry.
3195 static bool io_rw_should_retry(struct io_kiocb *req)
3197 struct io_async_rw *rw = req->async_data;
3198 struct wait_page_queue *wait = &rw->wpq;
3199 struct kiocb *kiocb = &req->rw.kiocb;
3201 /* never retry for NOWAIT, we just complete with -EAGAIN */
3202 if (req->flags & REQ_F_NOWAIT)
3205 /* Only for buffered IO */
3206 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3210 * just use poll if we can, and don't attempt if the fs doesn't
3211 * support callback based unlocks
3213 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3216 wait->wait.func = io_async_buf_func;
3217 wait->wait.private = req;
3218 wait->wait.flags = 0;
3219 INIT_LIST_HEAD(&wait->wait.entry);
3220 kiocb->ki_flags |= IOCB_WAITQ;
3221 kiocb->ki_flags &= ~IOCB_NOWAIT;
3222 kiocb->ki_waitq = wait;
3226 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3228 if (req->file->f_op->read_iter)
3229 return call_read_iter(req->file, &req->rw.kiocb, iter);
3230 else if (req->file->f_op->read)
3231 return loop_rw_iter(READ, req, iter);
3236 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3238 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3239 struct kiocb *kiocb = &req->rw.kiocb;
3240 struct iov_iter __iter, *iter = &__iter;
3241 struct io_async_rw *rw = req->async_data;
3242 ssize_t io_size, ret, ret2;
3243 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3249 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3253 io_size = iov_iter_count(iter);
3254 req->result = io_size;
3256 /* Ensure we clear previously set non-block flag */
3257 if (!force_nonblock)
3258 kiocb->ki_flags &= ~IOCB_NOWAIT;
3260 kiocb->ki_flags |= IOCB_NOWAIT;
3262 /* If the file doesn't support async, just async punt */
3263 if (force_nonblock && !io_file_supports_async(req, READ)) {
3264 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3265 return ret ?: -EAGAIN;
3268 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3269 if (unlikely(ret)) {
3274 ret = io_iter_do_read(req, iter);
3276 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3277 req->flags &= ~REQ_F_REISSUE;
3278 /* IOPOLL retry should happen for io-wq threads */
3279 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3281 /* no retry on NONBLOCK nor RWF_NOWAIT */
3282 if (req->flags & REQ_F_NOWAIT)
3284 /* some cases will consume bytes even on error returns */
3285 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3287 } else if (ret == -EIOCBQUEUED) {
3289 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3290 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3291 /* read all, failed, already did sync or don't want to retry */
3295 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3300 rw = req->async_data;
3301 /* now use our persistent iterator, if we aren't already */
3306 rw->bytes_done += ret;
3307 /* if we can retry, do so with the callbacks armed */
3308 if (!io_rw_should_retry(req)) {
3309 kiocb->ki_flags &= ~IOCB_WAITQ;
3314 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3315 * we get -EIOCBQUEUED, then we'll get a notification when the
3316 * desired page gets unlocked. We can also get a partial read
3317 * here, and if we do, then just retry at the new offset.
3319 ret = io_iter_do_read(req, iter);
3320 if (ret == -EIOCBQUEUED)
3322 /* we got some bytes, but not all. retry. */
3323 kiocb->ki_flags &= ~IOCB_WAITQ;
3324 } while (ret > 0 && ret < io_size);
3326 kiocb_done(kiocb, ret, issue_flags);
3328 /* it's faster to check here then delegate to kfree */
3334 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3336 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3338 return io_prep_rw(req, sqe);
3341 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3343 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3344 struct kiocb *kiocb = &req->rw.kiocb;
3345 struct iov_iter __iter, *iter = &__iter;
3346 struct io_async_rw *rw = req->async_data;
3347 ssize_t ret, ret2, io_size;
3348 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3354 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3358 io_size = iov_iter_count(iter);
3359 req->result = io_size;
3361 /* Ensure we clear previously set non-block flag */
3362 if (!force_nonblock)
3363 kiocb->ki_flags &= ~IOCB_NOWAIT;
3365 kiocb->ki_flags |= IOCB_NOWAIT;
3367 /* If the file doesn't support async, just async punt */
3368 if (force_nonblock && !io_file_supports_async(req, WRITE))
3371 /* file path doesn't support NOWAIT for non-direct_IO */
3372 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3373 (req->flags & REQ_F_ISREG))
3376 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3381 * Open-code file_start_write here to grab freeze protection,
3382 * which will be released by another thread in
3383 * io_complete_rw(). Fool lockdep by telling it the lock got
3384 * released so that it doesn't complain about the held lock when
3385 * we return to userspace.
3387 if (req->flags & REQ_F_ISREG) {
3388 sb_start_write(file_inode(req->file)->i_sb);
3389 __sb_writers_release(file_inode(req->file)->i_sb,
3392 kiocb->ki_flags |= IOCB_WRITE;
3394 if (req->file->f_op->write_iter)
3395 ret2 = call_write_iter(req->file, kiocb, iter);
3396 else if (req->file->f_op->write)
3397 ret2 = loop_rw_iter(WRITE, req, iter);
3401 if (req->flags & REQ_F_REISSUE) {
3402 req->flags &= ~REQ_F_REISSUE;
3407 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3408 * retry them without IOCB_NOWAIT.
3410 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3412 /* no retry on NONBLOCK nor RWF_NOWAIT */
3413 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3415 if (!force_nonblock || ret2 != -EAGAIN) {
3416 /* IOPOLL retry should happen for io-wq threads */
3417 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3420 kiocb_done(kiocb, ret2, issue_flags);
3423 /* some cases will consume bytes even on error returns */
3424 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3425 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3426 return ret ?: -EAGAIN;
3429 /* it's reportedly faster than delegating the null check to kfree() */
3435 static int io_renameat_prep(struct io_kiocb *req,
3436 const struct io_uring_sqe *sqe)
3438 struct io_rename *ren = &req->rename;
3439 const char __user *oldf, *newf;
3441 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3444 ren->old_dfd = READ_ONCE(sqe->fd);
3445 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3446 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3447 ren->new_dfd = READ_ONCE(sqe->len);
3448 ren->flags = READ_ONCE(sqe->rename_flags);
3450 ren->oldpath = getname(oldf);
3451 if (IS_ERR(ren->oldpath))
3452 return PTR_ERR(ren->oldpath);
3454 ren->newpath = getname(newf);
3455 if (IS_ERR(ren->newpath)) {
3456 putname(ren->oldpath);
3457 return PTR_ERR(ren->newpath);
3460 req->flags |= REQ_F_NEED_CLEANUP;
3464 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3466 struct io_rename *ren = &req->rename;
3469 if (issue_flags & IO_URING_F_NONBLOCK)
3472 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3473 ren->newpath, ren->flags);
3475 req->flags &= ~REQ_F_NEED_CLEANUP;
3477 req_set_fail_links(req);
3478 io_req_complete(req, ret);
3482 static int io_unlinkat_prep(struct io_kiocb *req,
3483 const struct io_uring_sqe *sqe)
3485 struct io_unlink *un = &req->unlink;
3486 const char __user *fname;
3488 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3491 un->dfd = READ_ONCE(sqe->fd);
3493 un->flags = READ_ONCE(sqe->unlink_flags);
3494 if (un->flags & ~AT_REMOVEDIR)
3497 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3498 un->filename = getname(fname);
3499 if (IS_ERR(un->filename))
3500 return PTR_ERR(un->filename);
3502 req->flags |= REQ_F_NEED_CLEANUP;
3506 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3508 struct io_unlink *un = &req->unlink;
3511 if (issue_flags & IO_URING_F_NONBLOCK)
3514 if (un->flags & AT_REMOVEDIR)
3515 ret = do_rmdir(un->dfd, un->filename);
3517 ret = do_unlinkat(un->dfd, un->filename);
3519 req->flags &= ~REQ_F_NEED_CLEANUP;
3521 req_set_fail_links(req);
3522 io_req_complete(req, ret);
3526 static int io_shutdown_prep(struct io_kiocb *req,
3527 const struct io_uring_sqe *sqe)
3529 #if defined(CONFIG_NET)
3530 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3532 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3536 req->shutdown.how = READ_ONCE(sqe->len);
3543 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3545 #if defined(CONFIG_NET)
3546 struct socket *sock;
3549 if (issue_flags & IO_URING_F_NONBLOCK)
3552 sock = sock_from_file(req->file);
3553 if (unlikely(!sock))
3556 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3558 req_set_fail_links(req);
3559 io_req_complete(req, ret);
3566 static int __io_splice_prep(struct io_kiocb *req,
3567 const struct io_uring_sqe *sqe)
3569 struct io_splice* sp = &req->splice;
3570 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3572 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3576 sp->len = READ_ONCE(sqe->len);
3577 sp->flags = READ_ONCE(sqe->splice_flags);
3579 if (unlikely(sp->flags & ~valid_flags))
3582 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3583 (sp->flags & SPLICE_F_FD_IN_FIXED));
3586 req->flags |= REQ_F_NEED_CLEANUP;
3590 static int io_tee_prep(struct io_kiocb *req,
3591 const struct io_uring_sqe *sqe)
3593 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3595 return __io_splice_prep(req, sqe);
3598 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3600 struct io_splice *sp = &req->splice;
3601 struct file *in = sp->file_in;
3602 struct file *out = sp->file_out;
3603 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3606 if (issue_flags & IO_URING_F_NONBLOCK)
3609 ret = do_tee(in, out, sp->len, flags);
3611 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3613 req->flags &= ~REQ_F_NEED_CLEANUP;
3616 req_set_fail_links(req);
3617 io_req_complete(req, ret);
3621 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3623 struct io_splice* sp = &req->splice;
3625 sp->off_in = READ_ONCE(sqe->splice_off_in);
3626 sp->off_out = READ_ONCE(sqe->off);
3627 return __io_splice_prep(req, sqe);
3630 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3632 struct io_splice *sp = &req->splice;
3633 struct file *in = sp->file_in;
3634 struct file *out = sp->file_out;
3635 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3636 loff_t *poff_in, *poff_out;
3639 if (issue_flags & IO_URING_F_NONBLOCK)
3642 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3643 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3646 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3648 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3650 req->flags &= ~REQ_F_NEED_CLEANUP;
3653 req_set_fail_links(req);
3654 io_req_complete(req, ret);
3659 * IORING_OP_NOP just posts a completion event, nothing else.
3661 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3663 struct io_ring_ctx *ctx = req->ctx;
3665 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3668 __io_req_complete(req, issue_flags, 0, 0);
3672 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3674 struct io_ring_ctx *ctx = req->ctx;
3679 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3681 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3684 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3685 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3688 req->sync.off = READ_ONCE(sqe->off);
3689 req->sync.len = READ_ONCE(sqe->len);
3693 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3695 loff_t end = req->sync.off + req->sync.len;
3698 /* fsync always requires a blocking context */
3699 if (issue_flags & IO_URING_F_NONBLOCK)
3702 ret = vfs_fsync_range(req->file, req->sync.off,
3703 end > 0 ? end : LLONG_MAX,
3704 req->sync.flags & IORING_FSYNC_DATASYNC);
3706 req_set_fail_links(req);
3707 io_req_complete(req, ret);
3711 static int io_fallocate_prep(struct io_kiocb *req,
3712 const struct io_uring_sqe *sqe)
3714 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3716 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3719 req->sync.off = READ_ONCE(sqe->off);
3720 req->sync.len = READ_ONCE(sqe->addr);
3721 req->sync.mode = READ_ONCE(sqe->len);
3725 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3729 /* fallocate always requiring blocking context */
3730 if (issue_flags & IO_URING_F_NONBLOCK)
3732 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3735 req_set_fail_links(req);
3736 io_req_complete(req, ret);
3740 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3742 const char __user *fname;
3745 if (unlikely(sqe->ioprio || sqe->buf_index))
3747 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3750 /* open.how should be already initialised */
3751 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3752 req->open.how.flags |= O_LARGEFILE;
3754 req->open.dfd = READ_ONCE(sqe->fd);
3755 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3756 req->open.filename = getname(fname);
3757 if (IS_ERR(req->open.filename)) {
3758 ret = PTR_ERR(req->open.filename);
3759 req->open.filename = NULL;
3762 req->open.nofile = rlimit(RLIMIT_NOFILE);
3763 req->flags |= REQ_F_NEED_CLEANUP;
3767 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3771 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3773 mode = READ_ONCE(sqe->len);
3774 flags = READ_ONCE(sqe->open_flags);
3775 req->open.how = build_open_how(flags, mode);
3776 return __io_openat_prep(req, sqe);
3779 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3781 struct open_how __user *how;
3785 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3787 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3788 len = READ_ONCE(sqe->len);
3789 if (len < OPEN_HOW_SIZE_VER0)
3792 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3797 return __io_openat_prep(req, sqe);
3800 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3802 struct open_flags op;
3805 bool resolve_nonblock;
3808 ret = build_open_flags(&req->open.how, &op);
3811 nonblock_set = op.open_flag & O_NONBLOCK;
3812 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3813 if (issue_flags & IO_URING_F_NONBLOCK) {
3815 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3816 * it'll always -EAGAIN
3818 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3820 op.lookup_flags |= LOOKUP_CACHED;
3821 op.open_flag |= O_NONBLOCK;
3824 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3828 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3829 /* only retry if RESOLVE_CACHED wasn't already set by application */
3830 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3831 file == ERR_PTR(-EAGAIN)) {
3833 * We could hang on to this 'fd', but seems like marginal
3834 * gain for something that is now known to be a slower path.
3835 * So just put it, and we'll get a new one when we retry.
3843 ret = PTR_ERR(file);
3845 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3846 file->f_flags &= ~O_NONBLOCK;
3847 fsnotify_open(file);
3848 fd_install(ret, file);
3851 putname(req->open.filename);
3852 req->flags &= ~REQ_F_NEED_CLEANUP;
3854 req_set_fail_links(req);
3855 __io_req_complete(req, issue_flags, ret, 0);
3859 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3861 return io_openat2(req, issue_flags);
3864 static int io_remove_buffers_prep(struct io_kiocb *req,
3865 const struct io_uring_sqe *sqe)
3867 struct io_provide_buf *p = &req->pbuf;
3870 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3873 tmp = READ_ONCE(sqe->fd);
3874 if (!tmp || tmp > USHRT_MAX)
3877 memset(p, 0, sizeof(*p));
3879 p->bgid = READ_ONCE(sqe->buf_group);
3883 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3884 int bgid, unsigned nbufs)
3888 /* shouldn't happen */
3892 /* the head kbuf is the list itself */
3893 while (!list_empty(&buf->list)) {
3894 struct io_buffer *nxt;
3896 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3897 list_del(&nxt->list);
3904 xa_erase(&ctx->io_buffers, bgid);
3909 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3911 struct io_provide_buf *p = &req->pbuf;
3912 struct io_ring_ctx *ctx = req->ctx;
3913 struct io_buffer *head;
3915 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3917 io_ring_submit_lock(ctx, !force_nonblock);
3919 lockdep_assert_held(&ctx->uring_lock);
3922 head = xa_load(&ctx->io_buffers, p->bgid);
3924 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3926 req_set_fail_links(req);
3928 /* complete before unlock, IOPOLL may need the lock */
3929 __io_req_complete(req, issue_flags, ret, 0);
3930 io_ring_submit_unlock(ctx, !force_nonblock);
3934 static int io_provide_buffers_prep(struct io_kiocb *req,
3935 const struct io_uring_sqe *sqe)
3938 struct io_provide_buf *p = &req->pbuf;
3941 if (sqe->ioprio || sqe->rw_flags)
3944 tmp = READ_ONCE(sqe->fd);
3945 if (!tmp || tmp > USHRT_MAX)
3948 p->addr = READ_ONCE(sqe->addr);
3949 p->len = READ_ONCE(sqe->len);
3951 size = (unsigned long)p->len * p->nbufs;
3952 if (!access_ok(u64_to_user_ptr(p->addr), size))
3955 p->bgid = READ_ONCE(sqe->buf_group);
3956 tmp = READ_ONCE(sqe->off);
3957 if (tmp > USHRT_MAX)
3963 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3965 struct io_buffer *buf;
3966 u64 addr = pbuf->addr;
3967 int i, bid = pbuf->bid;
3969 for (i = 0; i < pbuf->nbufs; i++) {
3970 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3975 buf->len = pbuf->len;
3980 INIT_LIST_HEAD(&buf->list);
3983 list_add_tail(&buf->list, &(*head)->list);
3987 return i ? i : -ENOMEM;
3990 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3992 struct io_provide_buf *p = &req->pbuf;
3993 struct io_ring_ctx *ctx = req->ctx;
3994 struct io_buffer *head, *list;
3996 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3998 io_ring_submit_lock(ctx, !force_nonblock);
4000 lockdep_assert_held(&ctx->uring_lock);
4002 list = head = xa_load(&ctx->io_buffers, p->bgid);
4004 ret = io_add_buffers(p, &head);
4005 if (ret >= 0 && !list) {
4006 ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4008 __io_remove_buffers(ctx, head, p->bgid, -1U);
4011 req_set_fail_links(req);
4012 /* complete before unlock, IOPOLL may need the lock */
4013 __io_req_complete(req, issue_flags, ret, 0);
4014 io_ring_submit_unlock(ctx, !force_nonblock);
4018 static int io_epoll_ctl_prep(struct io_kiocb *req,
4019 const struct io_uring_sqe *sqe)
4021 #if defined(CONFIG_EPOLL)
4022 if (sqe->ioprio || sqe->buf_index)
4024 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4027 req->epoll.epfd = READ_ONCE(sqe->fd);
4028 req->epoll.op = READ_ONCE(sqe->len);
4029 req->epoll.fd = READ_ONCE(sqe->off);
4031 if (ep_op_has_event(req->epoll.op)) {
4032 struct epoll_event __user *ev;
4034 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4035 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4045 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4047 #if defined(CONFIG_EPOLL)
4048 struct io_epoll *ie = &req->epoll;
4050 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4052 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4053 if (force_nonblock && ret == -EAGAIN)
4057 req_set_fail_links(req);
4058 __io_req_complete(req, issue_flags, ret, 0);
4065 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4067 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4068 if (sqe->ioprio || sqe->buf_index || sqe->off)
4070 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4073 req->madvise.addr = READ_ONCE(sqe->addr);
4074 req->madvise.len = READ_ONCE(sqe->len);
4075 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4082 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4084 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4085 struct io_madvise *ma = &req->madvise;
4088 if (issue_flags & IO_URING_F_NONBLOCK)
4091 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4093 req_set_fail_links(req);
4094 io_req_complete(req, ret);
4101 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4103 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4105 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4108 req->fadvise.offset = READ_ONCE(sqe->off);
4109 req->fadvise.len = READ_ONCE(sqe->len);
4110 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4114 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4116 struct io_fadvise *fa = &req->fadvise;
4119 if (issue_flags & IO_URING_F_NONBLOCK) {
4120 switch (fa->advice) {
4121 case POSIX_FADV_NORMAL:
4122 case POSIX_FADV_RANDOM:
4123 case POSIX_FADV_SEQUENTIAL:
4130 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4132 req_set_fail_links(req);
4133 __io_req_complete(req, issue_flags, ret, 0);
4137 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4139 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4141 if (sqe->ioprio || sqe->buf_index)
4143 if (req->flags & REQ_F_FIXED_FILE)
4146 req->statx.dfd = READ_ONCE(sqe->fd);
4147 req->statx.mask = READ_ONCE(sqe->len);
4148 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4149 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4150 req->statx.flags = READ_ONCE(sqe->statx_flags);
4155 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4157 struct io_statx *ctx = &req->statx;
4160 if (issue_flags & IO_URING_F_NONBLOCK)
4163 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4167 req_set_fail_links(req);
4168 io_req_complete(req, ret);
4172 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4174 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4176 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4177 sqe->rw_flags || sqe->buf_index)
4179 if (req->flags & REQ_F_FIXED_FILE)
4182 req->close.fd = READ_ONCE(sqe->fd);
4186 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4188 struct files_struct *files = current->files;
4189 struct io_close *close = &req->close;
4190 struct fdtable *fdt;
4191 struct file *file = NULL;
4194 spin_lock(&files->file_lock);
4195 fdt = files_fdtable(files);
4196 if (close->fd >= fdt->max_fds) {
4197 spin_unlock(&files->file_lock);
4200 file = fdt->fd[close->fd];
4201 if (!file || file->f_op == &io_uring_fops) {
4202 spin_unlock(&files->file_lock);
4207 /* if the file has a flush method, be safe and punt to async */
4208 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4209 spin_unlock(&files->file_lock);
4213 ret = __close_fd_get_file(close->fd, &file);
4214 spin_unlock(&files->file_lock);
4221 /* No ->flush() or already async, safely close from here */
4222 ret = filp_close(file, current->files);
4225 req_set_fail_links(req);
4228 __io_req_complete(req, issue_flags, ret, 0);
4232 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4234 struct io_ring_ctx *ctx = req->ctx;
4236 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4238 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4241 req->sync.off = READ_ONCE(sqe->off);
4242 req->sync.len = READ_ONCE(sqe->len);
4243 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4247 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4251 /* sync_file_range always requires a blocking context */
4252 if (issue_flags & IO_URING_F_NONBLOCK)
4255 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4258 req_set_fail_links(req);
4259 io_req_complete(req, ret);
4263 #if defined(CONFIG_NET)
4264 static int io_setup_async_msg(struct io_kiocb *req,
4265 struct io_async_msghdr *kmsg)
4267 struct io_async_msghdr *async_msg = req->async_data;
4271 if (io_alloc_async_data(req)) {
4272 kfree(kmsg->free_iov);
4275 async_msg = req->async_data;
4276 req->flags |= REQ_F_NEED_CLEANUP;
4277 memcpy(async_msg, kmsg, sizeof(*kmsg));
4278 async_msg->msg.msg_name = &async_msg->addr;
4279 /* if were using fast_iov, set it to the new one */
4280 if (!async_msg->free_iov)
4281 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4286 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4287 struct io_async_msghdr *iomsg)
4289 iomsg->msg.msg_name = &iomsg->addr;
4290 iomsg->free_iov = iomsg->fast_iov;
4291 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4292 req->sr_msg.msg_flags, &iomsg->free_iov);
4295 static int io_sendmsg_prep_async(struct io_kiocb *req)
4299 ret = io_sendmsg_copy_hdr(req, req->async_data);
4301 req->flags |= REQ_F_NEED_CLEANUP;
4305 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4307 struct io_sr_msg *sr = &req->sr_msg;
4309 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4312 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4313 sr->len = READ_ONCE(sqe->len);
4314 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4315 if (sr->msg_flags & MSG_DONTWAIT)
4316 req->flags |= REQ_F_NOWAIT;
4318 #ifdef CONFIG_COMPAT
4319 if (req->ctx->compat)
4320 sr->msg_flags |= MSG_CMSG_COMPAT;
4325 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4327 struct io_async_msghdr iomsg, *kmsg;
4328 struct socket *sock;
4333 sock = sock_from_file(req->file);
4334 if (unlikely(!sock))
4337 kmsg = req->async_data;
4339 ret = io_sendmsg_copy_hdr(req, &iomsg);
4345 flags = req->sr_msg.msg_flags;
4346 if (issue_flags & IO_URING_F_NONBLOCK)
4347 flags |= MSG_DONTWAIT;
4348 if (flags & MSG_WAITALL)
4349 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4351 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4352 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4353 return io_setup_async_msg(req, kmsg);
4354 if (ret == -ERESTARTSYS)
4357 /* fast path, check for non-NULL to avoid function call */
4359 kfree(kmsg->free_iov);
4360 req->flags &= ~REQ_F_NEED_CLEANUP;
4362 req_set_fail_links(req);
4363 __io_req_complete(req, issue_flags, ret, 0);
4367 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4369 struct io_sr_msg *sr = &req->sr_msg;
4372 struct socket *sock;
4377 sock = sock_from_file(req->file);
4378 if (unlikely(!sock))
4381 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4385 msg.msg_name = NULL;
4386 msg.msg_control = NULL;
4387 msg.msg_controllen = 0;
4388 msg.msg_namelen = 0;
4390 flags = req->sr_msg.msg_flags;
4391 if (issue_flags & IO_URING_F_NONBLOCK)
4392 flags |= MSG_DONTWAIT;
4393 if (flags & MSG_WAITALL)
4394 min_ret = iov_iter_count(&msg.msg_iter);
4396 msg.msg_flags = flags;
4397 ret = sock_sendmsg(sock, &msg);
4398 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4400 if (ret == -ERESTARTSYS)
4404 req_set_fail_links(req);
4405 __io_req_complete(req, issue_flags, ret, 0);
4409 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4410 struct io_async_msghdr *iomsg)
4412 struct io_sr_msg *sr = &req->sr_msg;
4413 struct iovec __user *uiov;
4417 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4418 &iomsg->uaddr, &uiov, &iov_len);
4422 if (req->flags & REQ_F_BUFFER_SELECT) {
4425 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4427 sr->len = iomsg->fast_iov[0].iov_len;
4428 iomsg->free_iov = NULL;
4430 iomsg->free_iov = iomsg->fast_iov;
4431 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4432 &iomsg->free_iov, &iomsg->msg.msg_iter,
4441 #ifdef CONFIG_COMPAT
4442 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4443 struct io_async_msghdr *iomsg)
4445 struct io_sr_msg *sr = &req->sr_msg;
4446 struct compat_iovec __user *uiov;
4451 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4456 uiov = compat_ptr(ptr);
4457 if (req->flags & REQ_F_BUFFER_SELECT) {
4458 compat_ssize_t clen;
4462 if (!access_ok(uiov, sizeof(*uiov)))
4464 if (__get_user(clen, &uiov->iov_len))
4469 iomsg->free_iov = NULL;
4471 iomsg->free_iov = iomsg->fast_iov;
4472 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4473 UIO_FASTIOV, &iomsg->free_iov,
4474 &iomsg->msg.msg_iter, true);
4483 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4484 struct io_async_msghdr *iomsg)
4486 iomsg->msg.msg_name = &iomsg->addr;
4488 #ifdef CONFIG_COMPAT
4489 if (req->ctx->compat)
4490 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4493 return __io_recvmsg_copy_hdr(req, iomsg);
4496 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4499 struct io_sr_msg *sr = &req->sr_msg;
4500 struct io_buffer *kbuf;
4502 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4507 req->flags |= REQ_F_BUFFER_SELECTED;
4511 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4513 return io_put_kbuf(req, req->sr_msg.kbuf);
4516 static int io_recvmsg_prep_async(struct io_kiocb *req)
4520 ret = io_recvmsg_copy_hdr(req, req->async_data);
4522 req->flags |= REQ_F_NEED_CLEANUP;
4526 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4528 struct io_sr_msg *sr = &req->sr_msg;
4530 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4533 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4534 sr->len = READ_ONCE(sqe->len);
4535 sr->bgid = READ_ONCE(sqe->buf_group);
4536 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4537 if (sr->msg_flags & MSG_DONTWAIT)
4538 req->flags |= REQ_F_NOWAIT;
4540 #ifdef CONFIG_COMPAT
4541 if (req->ctx->compat)
4542 sr->msg_flags |= MSG_CMSG_COMPAT;
4547 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4549 struct io_async_msghdr iomsg, *kmsg;
4550 struct socket *sock;
4551 struct io_buffer *kbuf;
4554 int ret, cflags = 0;
4555 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4557 sock = sock_from_file(req->file);
4558 if (unlikely(!sock))
4561 kmsg = req->async_data;
4563 ret = io_recvmsg_copy_hdr(req, &iomsg);
4569 if (req->flags & REQ_F_BUFFER_SELECT) {
4570 kbuf = io_recv_buffer_select(req, !force_nonblock);
4572 return PTR_ERR(kbuf);
4573 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4574 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4575 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4576 1, req->sr_msg.len);
4579 flags = req->sr_msg.msg_flags;
4581 flags |= MSG_DONTWAIT;
4582 if (flags & MSG_WAITALL)
4583 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4585 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4586 kmsg->uaddr, flags);
4587 if (force_nonblock && ret == -EAGAIN)
4588 return io_setup_async_msg(req, kmsg);
4589 if (ret == -ERESTARTSYS)
4592 if (req->flags & REQ_F_BUFFER_SELECTED)
4593 cflags = io_put_recv_kbuf(req);
4594 /* fast path, check for non-NULL to avoid function call */
4596 kfree(kmsg->free_iov);
4597 req->flags &= ~REQ_F_NEED_CLEANUP;
4598 if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4599 req_set_fail_links(req);
4600 __io_req_complete(req, issue_flags, ret, cflags);
4604 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4606 struct io_buffer *kbuf;
4607 struct io_sr_msg *sr = &req->sr_msg;
4609 void __user *buf = sr->buf;
4610 struct socket *sock;
4614 int ret, cflags = 0;
4615 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4617 sock = sock_from_file(req->file);
4618 if (unlikely(!sock))
4621 if (req->flags & REQ_F_BUFFER_SELECT) {
4622 kbuf = io_recv_buffer_select(req, !force_nonblock);
4624 return PTR_ERR(kbuf);
4625 buf = u64_to_user_ptr(kbuf->addr);
4628 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4632 msg.msg_name = NULL;
4633 msg.msg_control = NULL;
4634 msg.msg_controllen = 0;
4635 msg.msg_namelen = 0;
4636 msg.msg_iocb = NULL;
4639 flags = req->sr_msg.msg_flags;
4641 flags |= MSG_DONTWAIT;
4642 if (flags & MSG_WAITALL)
4643 min_ret = iov_iter_count(&msg.msg_iter);
4645 ret = sock_recvmsg(sock, &msg, flags);
4646 if (force_nonblock && ret == -EAGAIN)
4648 if (ret == -ERESTARTSYS)
4651 if (req->flags & REQ_F_BUFFER_SELECTED)
4652 cflags = io_put_recv_kbuf(req);
4653 if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4654 req_set_fail_links(req);
4655 __io_req_complete(req, issue_flags, ret, cflags);
4659 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4661 struct io_accept *accept = &req->accept;
4663 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4665 if (sqe->ioprio || sqe->len || sqe->buf_index)
4668 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4669 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4670 accept->flags = READ_ONCE(sqe->accept_flags);
4671 accept->nofile = rlimit(RLIMIT_NOFILE);
4675 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4677 struct io_accept *accept = &req->accept;
4678 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4679 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4682 if (req->file->f_flags & O_NONBLOCK)
4683 req->flags |= REQ_F_NOWAIT;
4685 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4686 accept->addr_len, accept->flags,
4688 if (ret == -EAGAIN && force_nonblock)
4691 if (ret == -ERESTARTSYS)
4693 req_set_fail_links(req);
4695 __io_req_complete(req, issue_flags, ret, 0);
4699 static int io_connect_prep_async(struct io_kiocb *req)
4701 struct io_async_connect *io = req->async_data;
4702 struct io_connect *conn = &req->connect;
4704 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4707 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4709 struct io_connect *conn = &req->connect;
4711 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4713 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4716 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4717 conn->addr_len = READ_ONCE(sqe->addr2);
4721 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4723 struct io_async_connect __io, *io;
4724 unsigned file_flags;
4726 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4728 if (req->async_data) {
4729 io = req->async_data;
4731 ret = move_addr_to_kernel(req->connect.addr,
4732 req->connect.addr_len,
4739 file_flags = force_nonblock ? O_NONBLOCK : 0;
4741 ret = __sys_connect_file(req->file, &io->address,
4742 req->connect.addr_len, file_flags);
4743 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4744 if (req->async_data)
4746 if (io_alloc_async_data(req)) {
4750 memcpy(req->async_data, &__io, sizeof(__io));
4753 if (ret == -ERESTARTSYS)
4757 req_set_fail_links(req);
4758 __io_req_complete(req, issue_flags, ret, 0);
4761 #else /* !CONFIG_NET */
4762 #define IO_NETOP_FN(op) \
4763 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4765 return -EOPNOTSUPP; \
4768 #define IO_NETOP_PREP(op) \
4770 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4772 return -EOPNOTSUPP; \
4775 #define IO_NETOP_PREP_ASYNC(op) \
4777 static int io_##op##_prep_async(struct io_kiocb *req) \
4779 return -EOPNOTSUPP; \
4782 IO_NETOP_PREP_ASYNC(sendmsg);
4783 IO_NETOP_PREP_ASYNC(recvmsg);
4784 IO_NETOP_PREP_ASYNC(connect);
4785 IO_NETOP_PREP(accept);
4788 #endif /* CONFIG_NET */
4790 struct io_poll_table {
4791 struct poll_table_struct pt;
4792 struct io_kiocb *req;
4796 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4797 __poll_t mask, task_work_func_t func)
4801 /* for instances that support it check for an event match first: */
4802 if (mask && !(mask & poll->events))
4805 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4807 list_del_init(&poll->wait.entry);
4810 req->task_work.func = func;
4813 * If this fails, then the task is exiting. When a task exits, the
4814 * work gets canceled, so just cancel this request as well instead
4815 * of executing it. We can't safely execute it anyway, as we may not
4816 * have the needed state needed for it anyway.
4818 ret = io_req_task_work_add(req);
4819 if (unlikely(ret)) {
4820 WRITE_ONCE(poll->canceled, true);
4821 io_req_task_work_add_fallback(req, func);
4826 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4827 __acquires(&req->ctx->completion_lock)
4829 struct io_ring_ctx *ctx = req->ctx;
4831 if (!req->result && !READ_ONCE(poll->canceled)) {
4832 struct poll_table_struct pt = { ._key = poll->events };
4834 req->result = vfs_poll(req->file, &pt) & poll->events;
4837 spin_lock_irq(&ctx->completion_lock);
4838 if (!req->result && !READ_ONCE(poll->canceled)) {
4839 add_wait_queue(poll->head, &poll->wait);
4846 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4848 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4849 if (req->opcode == IORING_OP_POLL_ADD)
4850 return req->async_data;
4851 return req->apoll->double_poll;
4854 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4856 if (req->opcode == IORING_OP_POLL_ADD)
4858 return &req->apoll->poll;
4861 static void io_poll_remove_double(struct io_kiocb *req)
4862 __must_hold(&req->ctx->completion_lock)
4864 struct io_poll_iocb *poll = io_poll_get_double(req);
4866 lockdep_assert_held(&req->ctx->completion_lock);
4868 if (poll && poll->head) {
4869 struct wait_queue_head *head = poll->head;
4871 spin_lock(&head->lock);
4872 list_del_init(&poll->wait.entry);
4873 if (poll->wait.private)
4876 spin_unlock(&head->lock);
4880 static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4881 __must_hold(&req->ctx->completion_lock)
4883 struct io_ring_ctx *ctx = req->ctx;
4884 unsigned flags = IORING_CQE_F_MORE;
4887 if (READ_ONCE(req->poll.canceled)) {
4889 req->poll.events |= EPOLLONESHOT;
4891 error = mangle_poll(mask);
4893 if (req->poll.events & EPOLLONESHOT)
4895 if (!io_cqring_fill_event(req, error, flags)) {
4896 io_poll_remove_waitqs(req);
4897 req->poll.done = true;
4900 io_commit_cqring(ctx);
4901 return !(flags & IORING_CQE_F_MORE);
4904 static void io_poll_task_func(struct callback_head *cb)
4906 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4907 struct io_ring_ctx *ctx = req->ctx;
4908 struct io_kiocb *nxt;
4910 if (io_poll_rewait(req, &req->poll)) {
4911 spin_unlock_irq(&ctx->completion_lock);
4915 done = io_poll_complete(req, req->result);
4917 hash_del(&req->hash_node);
4920 add_wait_queue(req->poll.head, &req->poll.wait);
4922 spin_unlock_irq(&ctx->completion_lock);
4923 io_cqring_ev_posted(ctx);
4926 nxt = io_put_req_find_next(req);
4928 __io_req_task_submit(nxt);
4933 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4934 int sync, void *key)
4936 struct io_kiocb *req = wait->private;
4937 struct io_poll_iocb *poll = io_poll_get_single(req);
4938 __poll_t mask = key_to_poll(key);
4940 /* for instances that support it check for an event match first: */
4941 if (mask && !(mask & poll->events))
4943 if (!(poll->events & EPOLLONESHOT))
4944 return poll->wait.func(&poll->wait, mode, sync, key);
4946 list_del_init(&wait->entry);
4948 if (poll && poll->head) {
4951 spin_lock(&poll->head->lock);
4952 done = list_empty(&poll->wait.entry);
4954 list_del_init(&poll->wait.entry);
4955 /* make sure double remove sees this as being gone */
4956 wait->private = NULL;
4957 spin_unlock(&poll->head->lock);
4959 /* use wait func handler, so it matches the rq type */
4960 poll->wait.func(&poll->wait, mode, sync, key);
4967 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4968 wait_queue_func_t wake_func)
4972 poll->canceled = false;
4973 poll->update_events = poll->update_user_data = false;
4974 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4975 /* mask in events that we always want/need */
4976 poll->events = events | IO_POLL_UNMASK;
4977 INIT_LIST_HEAD(&poll->wait.entry);
4978 init_waitqueue_func_entry(&poll->wait, wake_func);
4981 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4982 struct wait_queue_head *head,
4983 struct io_poll_iocb **poll_ptr)
4985 struct io_kiocb *req = pt->req;
4988 * If poll->head is already set, it's because the file being polled
4989 * uses multiple waitqueues for poll handling (eg one for read, one
4990 * for write). Setup a separate io_poll_iocb if this happens.
4992 if (unlikely(poll->head)) {
4993 struct io_poll_iocb *poll_one = poll;
4995 /* already have a 2nd entry, fail a third attempt */
4997 pt->error = -EINVAL;
5000 /* double add on the same waitqueue head, ignore */
5001 if (poll->head == head)
5003 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5005 pt->error = -ENOMEM;
5008 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5010 poll->wait.private = req;
5017 if (poll->events & EPOLLEXCLUSIVE)
5018 add_wait_queue_exclusive(head, &poll->wait);
5020 add_wait_queue(head, &poll->wait);
5023 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5024 struct poll_table_struct *p)
5026 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5027 struct async_poll *apoll = pt->req->apoll;
5029 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5032 static void io_async_task_func(struct callback_head *cb)
5034 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5035 struct async_poll *apoll = req->apoll;
5036 struct io_ring_ctx *ctx = req->ctx;
5038 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5040 if (io_poll_rewait(req, &apoll->poll)) {
5041 spin_unlock_irq(&ctx->completion_lock);
5045 hash_del(&req->hash_node);
5046 io_poll_remove_double(req);
5047 spin_unlock_irq(&ctx->completion_lock);
5049 if (!READ_ONCE(apoll->poll.canceled))
5050 __io_req_task_submit(req);
5052 io_req_complete_failed(req, -ECANCELED);
5054 kfree(apoll->double_poll);
5058 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5061 struct io_kiocb *req = wait->private;
5062 struct io_poll_iocb *poll = &req->apoll->poll;
5064 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5067 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5070 static void io_poll_req_insert(struct io_kiocb *req)
5072 struct io_ring_ctx *ctx = req->ctx;
5073 struct hlist_head *list;
5075 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5076 hlist_add_head(&req->hash_node, list);
5079 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5080 struct io_poll_iocb *poll,
5081 struct io_poll_table *ipt, __poll_t mask,
5082 wait_queue_func_t wake_func)
5083 __acquires(&ctx->completion_lock)
5085 struct io_ring_ctx *ctx = req->ctx;
5086 bool cancel = false;
5088 INIT_HLIST_NODE(&req->hash_node);
5089 io_init_poll_iocb(poll, mask, wake_func);
5090 poll->file = req->file;
5091 poll->wait.private = req;
5093 ipt->pt._key = mask;
5095 ipt->error = -EINVAL;
5097 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5099 spin_lock_irq(&ctx->completion_lock);
5100 if (likely(poll->head)) {
5101 spin_lock(&poll->head->lock);
5102 if (unlikely(list_empty(&poll->wait.entry))) {
5108 if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5109 list_del_init(&poll->wait.entry);
5111 WRITE_ONCE(poll->canceled, true);
5112 else if (!poll->done) /* actually waiting for an event */
5113 io_poll_req_insert(req);
5114 spin_unlock(&poll->head->lock);
5120 static bool io_arm_poll_handler(struct io_kiocb *req)
5122 const struct io_op_def *def = &io_op_defs[req->opcode];
5123 struct io_ring_ctx *ctx = req->ctx;
5124 struct async_poll *apoll;
5125 struct io_poll_table ipt;
5129 if (!req->file || !file_can_poll(req->file))
5131 if (req->flags & REQ_F_POLLED)
5135 else if (def->pollout)
5139 /* if we can't nonblock try, then no point in arming a poll handler */
5140 if (!io_file_supports_async(req, rw))
5143 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5144 if (unlikely(!apoll))
5146 apoll->double_poll = NULL;
5148 req->flags |= REQ_F_POLLED;
5151 mask = EPOLLONESHOT;
5153 mask |= POLLIN | POLLRDNORM;
5155 mask |= POLLOUT | POLLWRNORM;
5157 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5158 if ((req->opcode == IORING_OP_RECVMSG) &&
5159 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5162 mask |= POLLERR | POLLPRI;
5164 ipt.pt._qproc = io_async_queue_proc;
5166 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5168 if (ret || ipt.error) {
5169 io_poll_remove_double(req);
5170 spin_unlock_irq(&ctx->completion_lock);
5171 kfree(apoll->double_poll);
5175 spin_unlock_irq(&ctx->completion_lock);
5176 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5177 apoll->poll.events);
5181 static bool __io_poll_remove_one(struct io_kiocb *req,
5182 struct io_poll_iocb *poll, bool do_cancel)
5183 __must_hold(&req->ctx->completion_lock)
5185 bool do_complete = false;
5189 spin_lock(&poll->head->lock);
5191 WRITE_ONCE(poll->canceled, true);
5192 if (!list_empty(&poll->wait.entry)) {
5193 list_del_init(&poll->wait.entry);
5196 spin_unlock(&poll->head->lock);
5197 hash_del(&req->hash_node);
5201 static bool io_poll_remove_waitqs(struct io_kiocb *req)
5202 __must_hold(&req->ctx->completion_lock)
5206 io_poll_remove_double(req);
5208 if (req->opcode == IORING_OP_POLL_ADD) {
5209 do_complete = __io_poll_remove_one(req, &req->poll, true);
5211 struct async_poll *apoll = req->apoll;
5213 /* non-poll requests have submit ref still */
5214 do_complete = __io_poll_remove_one(req, &apoll->poll, true);
5217 kfree(apoll->double_poll);
5225 static bool io_poll_remove_one(struct io_kiocb *req)
5226 __must_hold(&req->ctx->completion_lock)
5230 do_complete = io_poll_remove_waitqs(req);
5232 io_cqring_fill_event(req, -ECANCELED, 0);
5233 io_commit_cqring(req->ctx);
5234 req_set_fail_links(req);
5235 io_put_req_deferred(req, 1);
5242 * Returns true if we found and killed one or more poll requests
5244 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5245 struct files_struct *files)
5247 struct hlist_node *tmp;
5248 struct io_kiocb *req;
5251 spin_lock_irq(&ctx->completion_lock);
5252 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5253 struct hlist_head *list;
5255 list = &ctx->cancel_hash[i];
5256 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5257 if (io_match_task(req, tsk, files))
5258 posted += io_poll_remove_one(req);
5261 spin_unlock_irq(&ctx->completion_lock);
5264 io_cqring_ev_posted(ctx);
5269 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr)
5270 __must_hold(&ctx->completion_lock)
5272 struct hlist_head *list;
5273 struct io_kiocb *req;
5275 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5276 hlist_for_each_entry(req, list, hash_node) {
5277 if (sqe_addr != req->user_data)
5285 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5286 __must_hold(&ctx->completion_lock)
5288 struct io_kiocb *req;
5290 req = io_poll_find(ctx, sqe_addr);
5293 if (io_poll_remove_one(req))
5299 static int io_poll_remove_prep(struct io_kiocb *req,
5300 const struct io_uring_sqe *sqe)
5302 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5304 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5308 req->poll_remove.addr = READ_ONCE(sqe->addr);
5313 * Find a running poll command that matches one specified in sqe->addr,
5314 * and remove it if found.
5316 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5318 struct io_ring_ctx *ctx = req->ctx;
5321 spin_lock_irq(&ctx->completion_lock);
5322 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5323 spin_unlock_irq(&ctx->completion_lock);
5326 req_set_fail_links(req);
5327 __io_req_complete(req, issue_flags, ret, 0);
5331 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5334 struct io_kiocb *req = wait->private;
5335 struct io_poll_iocb *poll = &req->poll;
5337 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5340 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5341 struct poll_table_struct *p)
5343 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5345 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5348 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5350 struct io_poll_iocb *poll = &req->poll;
5353 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5355 if (sqe->ioprio || sqe->buf_index)
5357 flags = READ_ONCE(sqe->len);
5358 if (flags & ~(IORING_POLL_ADD_MULTI | IORING_POLL_UPDATE_EVENTS |
5359 IORING_POLL_UPDATE_USER_DATA))
5361 events = READ_ONCE(sqe->poll32_events);
5363 events = swahw32(events);
5365 if (!(flags & IORING_POLL_ADD_MULTI))
5366 events |= EPOLLONESHOT;
5367 poll->update_events = poll->update_user_data = false;
5368 if (flags & IORING_POLL_UPDATE_EVENTS) {
5369 poll->update_events = true;
5370 poll->old_user_data = READ_ONCE(sqe->addr);
5372 if (flags & IORING_POLL_UPDATE_USER_DATA) {
5373 poll->update_user_data = true;
5374 poll->new_user_data = READ_ONCE(sqe->off);
5376 if (!(poll->update_events || poll->update_user_data) &&
5377 (sqe->off || sqe->addr))
5379 poll->events = demangle_poll(events) |
5380 (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5384 static int __io_poll_add(struct io_kiocb *req)
5386 struct io_poll_iocb *poll = &req->poll;
5387 struct io_ring_ctx *ctx = req->ctx;
5388 struct io_poll_table ipt;
5391 ipt.pt._qproc = io_poll_queue_proc;
5393 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5396 if (mask) { /* no async, we'd stolen it */
5398 io_poll_complete(req, mask);
5400 spin_unlock_irq(&ctx->completion_lock);
5403 io_cqring_ev_posted(ctx);
5404 if (poll->events & EPOLLONESHOT)
5410 static int io_poll_update(struct io_kiocb *req)
5412 struct io_ring_ctx *ctx = req->ctx;
5413 struct io_kiocb *preq;
5417 spin_lock_irq(&ctx->completion_lock);
5418 preq = io_poll_find(ctx, req->poll.old_user_data);
5422 } else if (preq->opcode != IORING_OP_POLL_ADD) {
5423 /* don't allow internal poll updates */
5429 * Don't allow racy completion with singleshot, as we cannot safely
5430 * update those. For multishot, if we're racing with completion, just
5431 * let completion re-add it.
5433 completing = !__io_poll_remove_one(preq, &preq->poll, false);
5434 if (completing && (preq->poll.events & EPOLLONESHOT)) {
5438 /* we now have a detached poll request. reissue. */
5442 spin_unlock_irq(&ctx->completion_lock);
5443 req_set_fail_links(req);
5444 io_req_complete(req, ret);
5447 /* only mask one event flags, keep behavior flags */
5448 if (req->poll.update_events) {
5449 preq->poll.events &= ~0xffff;
5450 preq->poll.events |= req->poll.events & 0xffff;
5451 preq->poll.events |= IO_POLL_UNMASK;
5453 if (req->poll.update_user_data)
5454 preq->user_data = req->poll.new_user_data;
5456 spin_unlock_irq(&ctx->completion_lock);
5458 /* complete update request, we're done with it */
5459 io_req_complete(req, ret);
5462 ret = __io_poll_add(preq);
5464 req_set_fail_links(preq);
5465 io_req_complete(preq, ret);
5471 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5473 if (!req->poll.update_events && !req->poll.update_user_data)
5474 return __io_poll_add(req);
5475 return io_poll_update(req);
5478 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5480 struct io_timeout_data *data = container_of(timer,
5481 struct io_timeout_data, timer);
5482 struct io_kiocb *req = data->req;
5483 struct io_ring_ctx *ctx = req->ctx;
5484 unsigned long flags;
5486 spin_lock_irqsave(&ctx->completion_lock, flags);
5487 list_del_init(&req->timeout.list);
5488 atomic_set(&req->ctx->cq_timeouts,
5489 atomic_read(&req->ctx->cq_timeouts) + 1);
5491 io_cqring_fill_event(req, -ETIME, 0);
5492 io_commit_cqring(ctx);
5493 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5495 io_cqring_ev_posted(ctx);
5496 req_set_fail_links(req);
5498 return HRTIMER_NORESTART;
5501 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5503 __must_hold(&ctx->completion_lock)
5505 struct io_timeout_data *io;
5506 struct io_kiocb *req;
5509 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5510 if (user_data == req->user_data) {
5517 return ERR_PTR(ret);
5519 io = req->async_data;
5520 ret = hrtimer_try_to_cancel(&io->timer);
5522 return ERR_PTR(-EALREADY);
5523 list_del_init(&req->timeout.list);
5527 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5528 __must_hold(&ctx->completion_lock)
5530 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5533 return PTR_ERR(req);
5535 req_set_fail_links(req);
5536 io_cqring_fill_event(req, -ECANCELED, 0);
5537 io_put_req_deferred(req, 1);
5541 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5542 struct timespec64 *ts, enum hrtimer_mode mode)
5543 __must_hold(&ctx->completion_lock)
5545 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5546 struct io_timeout_data *data;
5549 return PTR_ERR(req);
5551 req->timeout.off = 0; /* noseq */
5552 data = req->async_data;
5553 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5554 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5555 data->timer.function = io_timeout_fn;
5556 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5560 static int io_timeout_remove_prep(struct io_kiocb *req,
5561 const struct io_uring_sqe *sqe)
5563 struct io_timeout_rem *tr = &req->timeout_rem;
5565 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5567 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5569 if (sqe->ioprio || sqe->buf_index || sqe->len)
5572 tr->addr = READ_ONCE(sqe->addr);
5573 tr->flags = READ_ONCE(sqe->timeout_flags);
5574 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5575 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5577 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5579 } else if (tr->flags) {
5580 /* timeout removal doesn't support flags */
5587 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5589 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5594 * Remove or update an existing timeout command
5596 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5598 struct io_timeout_rem *tr = &req->timeout_rem;
5599 struct io_ring_ctx *ctx = req->ctx;
5602 spin_lock_irq(&ctx->completion_lock);
5603 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5604 ret = io_timeout_cancel(ctx, tr->addr);
5606 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5607 io_translate_timeout_mode(tr->flags));
5609 io_cqring_fill_event(req, ret, 0);
5610 io_commit_cqring(ctx);
5611 spin_unlock_irq(&ctx->completion_lock);
5612 io_cqring_ev_posted(ctx);
5614 req_set_fail_links(req);
5619 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5620 bool is_timeout_link)
5622 struct io_timeout_data *data;
5624 u32 off = READ_ONCE(sqe->off);
5626 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5628 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5630 if (off && is_timeout_link)
5632 flags = READ_ONCE(sqe->timeout_flags);
5633 if (flags & ~IORING_TIMEOUT_ABS)
5636 req->timeout.off = off;
5638 if (!req->async_data && io_alloc_async_data(req))
5641 data = req->async_data;
5644 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5647 data->mode = io_translate_timeout_mode(flags);
5648 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5649 if (is_timeout_link)
5650 io_req_track_inflight(req);
5654 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5656 struct io_ring_ctx *ctx = req->ctx;
5657 struct io_timeout_data *data = req->async_data;
5658 struct list_head *entry;
5659 u32 tail, off = req->timeout.off;
5661 spin_lock_irq(&ctx->completion_lock);
5664 * sqe->off holds how many events that need to occur for this
5665 * timeout event to be satisfied. If it isn't set, then this is
5666 * a pure timeout request, sequence isn't used.
5668 if (io_is_timeout_noseq(req)) {
5669 entry = ctx->timeout_list.prev;
5673 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5674 req->timeout.target_seq = tail + off;
5676 /* Update the last seq here in case io_flush_timeouts() hasn't.
5677 * This is safe because ->completion_lock is held, and submissions
5678 * and completions are never mixed in the same ->completion_lock section.
5680 ctx->cq_last_tm_flush = tail;
5683 * Insertion sort, ensuring the first entry in the list is always
5684 * the one we need first.
5686 list_for_each_prev(entry, &ctx->timeout_list) {
5687 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5690 if (io_is_timeout_noseq(nxt))
5692 /* nxt.seq is behind @tail, otherwise would've been completed */
5693 if (off >= nxt->timeout.target_seq - tail)
5697 list_add(&req->timeout.list, entry);
5698 data->timer.function = io_timeout_fn;
5699 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5700 spin_unlock_irq(&ctx->completion_lock);
5704 struct io_cancel_data {
5705 struct io_ring_ctx *ctx;
5709 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5711 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5712 struct io_cancel_data *cd = data;
5714 return req->ctx == cd->ctx && req->user_data == cd->user_data;
5717 static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5718 struct io_ring_ctx *ctx)
5720 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
5721 enum io_wq_cancel cancel_ret;
5724 if (!tctx || !tctx->io_wq)
5727 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
5728 switch (cancel_ret) {
5729 case IO_WQ_CANCEL_OK:
5732 case IO_WQ_CANCEL_RUNNING:
5735 case IO_WQ_CANCEL_NOTFOUND:
5743 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5744 struct io_kiocb *req, __u64 sqe_addr,
5747 unsigned long flags;
5750 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5751 spin_lock_irqsave(&ctx->completion_lock, flags);
5754 ret = io_timeout_cancel(ctx, sqe_addr);
5757 ret = io_poll_cancel(ctx, sqe_addr);
5761 io_cqring_fill_event(req, ret, 0);
5762 io_commit_cqring(ctx);
5763 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5764 io_cqring_ev_posted(ctx);
5767 req_set_fail_links(req);
5770 static int io_async_cancel_prep(struct io_kiocb *req,
5771 const struct io_uring_sqe *sqe)
5773 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5775 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5777 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5780 req->cancel.addr = READ_ONCE(sqe->addr);
5784 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5786 struct io_ring_ctx *ctx = req->ctx;
5787 u64 sqe_addr = req->cancel.addr;
5788 struct io_tctx_node *node;
5791 /* tasks should wait for their io-wq threads, so safe w/o sync */
5792 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
5793 spin_lock_irq(&ctx->completion_lock);
5796 ret = io_timeout_cancel(ctx, sqe_addr);
5799 ret = io_poll_cancel(ctx, sqe_addr);
5802 spin_unlock_irq(&ctx->completion_lock);
5804 /* slow path, try all io-wq's */
5805 io_ring_submit_lock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5807 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
5808 struct io_uring_task *tctx = node->task->io_uring;
5810 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
5814 io_ring_submit_unlock(ctx, !(issue_flags & IO_URING_F_NONBLOCK));
5816 spin_lock_irq(&ctx->completion_lock);
5818 io_cqring_fill_event(req, ret, 0);
5819 io_commit_cqring(ctx);
5820 spin_unlock_irq(&ctx->completion_lock);
5821 io_cqring_ev_posted(ctx);
5824 req_set_fail_links(req);
5829 static int io_rsrc_update_prep(struct io_kiocb *req,
5830 const struct io_uring_sqe *sqe)
5832 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5834 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5836 if (sqe->ioprio || sqe->rw_flags)
5839 req->rsrc_update.offset = READ_ONCE(sqe->off);
5840 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5841 if (!req->rsrc_update.nr_args)
5843 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5847 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5849 struct io_ring_ctx *ctx = req->ctx;
5850 struct io_uring_rsrc_update up;
5853 if (issue_flags & IO_URING_F_NONBLOCK)
5856 up.offset = req->rsrc_update.offset;
5857 up.data = req->rsrc_update.arg;
5859 mutex_lock(&ctx->uring_lock);
5860 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5861 mutex_unlock(&ctx->uring_lock);
5864 req_set_fail_links(req);
5865 __io_req_complete(req, issue_flags, ret, 0);
5869 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5871 switch (req->opcode) {
5874 case IORING_OP_READV:
5875 case IORING_OP_READ_FIXED:
5876 case IORING_OP_READ:
5877 return io_read_prep(req, sqe);
5878 case IORING_OP_WRITEV:
5879 case IORING_OP_WRITE_FIXED:
5880 case IORING_OP_WRITE:
5881 return io_write_prep(req, sqe);
5882 case IORING_OP_POLL_ADD:
5883 return io_poll_add_prep(req, sqe);
5884 case IORING_OP_POLL_REMOVE:
5885 return io_poll_remove_prep(req, sqe);
5886 case IORING_OP_FSYNC:
5887 return io_fsync_prep(req, sqe);
5888 case IORING_OP_SYNC_FILE_RANGE:
5889 return io_sfr_prep(req, sqe);
5890 case IORING_OP_SENDMSG:
5891 case IORING_OP_SEND:
5892 return io_sendmsg_prep(req, sqe);
5893 case IORING_OP_RECVMSG:
5894 case IORING_OP_RECV:
5895 return io_recvmsg_prep(req, sqe);
5896 case IORING_OP_CONNECT:
5897 return io_connect_prep(req, sqe);
5898 case IORING_OP_TIMEOUT:
5899 return io_timeout_prep(req, sqe, false);
5900 case IORING_OP_TIMEOUT_REMOVE:
5901 return io_timeout_remove_prep(req, sqe);
5902 case IORING_OP_ASYNC_CANCEL:
5903 return io_async_cancel_prep(req, sqe);
5904 case IORING_OP_LINK_TIMEOUT:
5905 return io_timeout_prep(req, sqe, true);
5906 case IORING_OP_ACCEPT:
5907 return io_accept_prep(req, sqe);
5908 case IORING_OP_FALLOCATE:
5909 return io_fallocate_prep(req, sqe);
5910 case IORING_OP_OPENAT:
5911 return io_openat_prep(req, sqe);
5912 case IORING_OP_CLOSE:
5913 return io_close_prep(req, sqe);
5914 case IORING_OP_FILES_UPDATE:
5915 return io_rsrc_update_prep(req, sqe);
5916 case IORING_OP_STATX:
5917 return io_statx_prep(req, sqe);
5918 case IORING_OP_FADVISE:
5919 return io_fadvise_prep(req, sqe);
5920 case IORING_OP_MADVISE:
5921 return io_madvise_prep(req, sqe);
5922 case IORING_OP_OPENAT2:
5923 return io_openat2_prep(req, sqe);
5924 case IORING_OP_EPOLL_CTL:
5925 return io_epoll_ctl_prep(req, sqe);
5926 case IORING_OP_SPLICE:
5927 return io_splice_prep(req, sqe);
5928 case IORING_OP_PROVIDE_BUFFERS:
5929 return io_provide_buffers_prep(req, sqe);
5930 case IORING_OP_REMOVE_BUFFERS:
5931 return io_remove_buffers_prep(req, sqe);
5933 return io_tee_prep(req, sqe);
5934 case IORING_OP_SHUTDOWN:
5935 return io_shutdown_prep(req, sqe);
5936 case IORING_OP_RENAMEAT:
5937 return io_renameat_prep(req, sqe);
5938 case IORING_OP_UNLINKAT:
5939 return io_unlinkat_prep(req, sqe);
5942 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5947 static int io_req_prep_async(struct io_kiocb *req)
5949 if (!io_op_defs[req->opcode].needs_async_setup)
5951 if (WARN_ON_ONCE(req->async_data))
5953 if (io_alloc_async_data(req))
5956 switch (req->opcode) {
5957 case IORING_OP_READV:
5958 return io_rw_prep_async(req, READ);
5959 case IORING_OP_WRITEV:
5960 return io_rw_prep_async(req, WRITE);
5961 case IORING_OP_SENDMSG:
5962 return io_sendmsg_prep_async(req);
5963 case IORING_OP_RECVMSG:
5964 return io_recvmsg_prep_async(req);
5965 case IORING_OP_CONNECT:
5966 return io_connect_prep_async(req);
5968 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
5973 static u32 io_get_sequence(struct io_kiocb *req)
5975 struct io_kiocb *pos;
5976 struct io_ring_ctx *ctx = req->ctx;
5977 u32 total_submitted, nr_reqs = 0;
5979 io_for_each_link(pos, req)
5982 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5983 return total_submitted - nr_reqs;
5986 static int io_req_defer(struct io_kiocb *req)
5988 struct io_ring_ctx *ctx = req->ctx;
5989 struct io_defer_entry *de;
5993 /* Still need defer if there is pending req in defer list. */
5994 if (likely(list_empty_careful(&ctx->defer_list) &&
5995 !(req->flags & REQ_F_IO_DRAIN)))
5998 seq = io_get_sequence(req);
5999 /* Still a chance to pass the sequence check */
6000 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
6003 ret = io_req_prep_async(req);
6006 io_prep_async_link(req);
6007 de = kmalloc(sizeof(*de), GFP_KERNEL);
6011 spin_lock_irq(&ctx->completion_lock);
6012 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
6013 spin_unlock_irq(&ctx->completion_lock);
6015 io_queue_async_work(req);
6016 return -EIOCBQUEUED;
6019 trace_io_uring_defer(ctx, req, req->user_data);
6022 list_add_tail(&de->list, &ctx->defer_list);
6023 spin_unlock_irq(&ctx->completion_lock);
6024 return -EIOCBQUEUED;
6027 static void io_clean_op(struct io_kiocb *req)
6029 if (req->flags & REQ_F_BUFFER_SELECTED) {
6030 switch (req->opcode) {
6031 case IORING_OP_READV:
6032 case IORING_OP_READ_FIXED:
6033 case IORING_OP_READ:
6034 kfree((void *)(unsigned long)req->rw.addr);
6036 case IORING_OP_RECVMSG:
6037 case IORING_OP_RECV:
6038 kfree(req->sr_msg.kbuf);
6041 req->flags &= ~REQ_F_BUFFER_SELECTED;
6044 if (req->flags & REQ_F_NEED_CLEANUP) {
6045 switch (req->opcode) {
6046 case IORING_OP_READV:
6047 case IORING_OP_READ_FIXED:
6048 case IORING_OP_READ:
6049 case IORING_OP_WRITEV:
6050 case IORING_OP_WRITE_FIXED:
6051 case IORING_OP_WRITE: {
6052 struct io_async_rw *io = req->async_data;
6054 kfree(io->free_iovec);
6057 case IORING_OP_RECVMSG:
6058 case IORING_OP_SENDMSG: {
6059 struct io_async_msghdr *io = req->async_data;
6061 kfree(io->free_iov);
6064 case IORING_OP_SPLICE:
6066 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
6067 io_put_file(req->splice.file_in);
6069 case IORING_OP_OPENAT:
6070 case IORING_OP_OPENAT2:
6071 if (req->open.filename)
6072 putname(req->open.filename);
6074 case IORING_OP_RENAMEAT:
6075 putname(req->rename.oldpath);
6076 putname(req->rename.newpath);
6078 case IORING_OP_UNLINKAT:
6079 putname(req->unlink.filename);
6082 req->flags &= ~REQ_F_NEED_CLEANUP;
6086 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
6088 struct io_ring_ctx *ctx = req->ctx;
6089 const struct cred *creds = NULL;
6092 if (req->work.creds && req->work.creds != current_cred())
6093 creds = override_creds(req->work.creds);
6095 switch (req->opcode) {
6097 ret = io_nop(req, issue_flags);
6099 case IORING_OP_READV:
6100 case IORING_OP_READ_FIXED:
6101 case IORING_OP_READ:
6102 ret = io_read(req, issue_flags);
6104 case IORING_OP_WRITEV:
6105 case IORING_OP_WRITE_FIXED:
6106 case IORING_OP_WRITE:
6107 ret = io_write(req, issue_flags);
6109 case IORING_OP_FSYNC:
6110 ret = io_fsync(req, issue_flags);
6112 case IORING_OP_POLL_ADD:
6113 ret = io_poll_add(req, issue_flags);
6115 case IORING_OP_POLL_REMOVE:
6116 ret = io_poll_remove(req, issue_flags);
6118 case IORING_OP_SYNC_FILE_RANGE:
6119 ret = io_sync_file_range(req, issue_flags);
6121 case IORING_OP_SENDMSG:
6122 ret = io_sendmsg(req, issue_flags);
6124 case IORING_OP_SEND:
6125 ret = io_send(req, issue_flags);
6127 case IORING_OP_RECVMSG:
6128 ret = io_recvmsg(req, issue_flags);
6130 case IORING_OP_RECV:
6131 ret = io_recv(req, issue_flags);
6133 case IORING_OP_TIMEOUT:
6134 ret = io_timeout(req, issue_flags);
6136 case IORING_OP_TIMEOUT_REMOVE:
6137 ret = io_timeout_remove(req, issue_flags);
6139 case IORING_OP_ACCEPT:
6140 ret = io_accept(req, issue_flags);
6142 case IORING_OP_CONNECT:
6143 ret = io_connect(req, issue_flags);
6145 case IORING_OP_ASYNC_CANCEL:
6146 ret = io_async_cancel(req, issue_flags);
6148 case IORING_OP_FALLOCATE:
6149 ret = io_fallocate(req, issue_flags);
6151 case IORING_OP_OPENAT:
6152 ret = io_openat(req, issue_flags);
6154 case IORING_OP_CLOSE:
6155 ret = io_close(req, issue_flags);
6157 case IORING_OP_FILES_UPDATE:
6158 ret = io_files_update(req, issue_flags);
6160 case IORING_OP_STATX:
6161 ret = io_statx(req, issue_flags);
6163 case IORING_OP_FADVISE:
6164 ret = io_fadvise(req, issue_flags);
6166 case IORING_OP_MADVISE:
6167 ret = io_madvise(req, issue_flags);
6169 case IORING_OP_OPENAT2:
6170 ret = io_openat2(req, issue_flags);
6172 case IORING_OP_EPOLL_CTL:
6173 ret = io_epoll_ctl(req, issue_flags);
6175 case IORING_OP_SPLICE:
6176 ret = io_splice(req, issue_flags);
6178 case IORING_OP_PROVIDE_BUFFERS:
6179 ret = io_provide_buffers(req, issue_flags);
6181 case IORING_OP_REMOVE_BUFFERS:
6182 ret = io_remove_buffers(req, issue_flags);
6185 ret = io_tee(req, issue_flags);
6187 case IORING_OP_SHUTDOWN:
6188 ret = io_shutdown(req, issue_flags);
6190 case IORING_OP_RENAMEAT:
6191 ret = io_renameat(req, issue_flags);
6193 case IORING_OP_UNLINKAT:
6194 ret = io_unlinkat(req, issue_flags);
6202 revert_creds(creds);
6207 /* If the op doesn't have a file, we're not polling for it */
6208 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6209 const bool in_async = io_wq_current_is_worker();
6211 /* workqueue context doesn't hold uring_lock, grab it now */
6213 mutex_lock(&ctx->uring_lock);
6215 io_iopoll_req_issued(req, in_async);
6218 mutex_unlock(&ctx->uring_lock);
6224 static void io_wq_submit_work(struct io_wq_work *work)
6226 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6227 struct io_kiocb *timeout;
6230 timeout = io_prep_linked_timeout(req);
6232 io_queue_linked_timeout(timeout);
6234 if (work->flags & IO_WQ_WORK_CANCEL)
6239 ret = io_issue_sqe(req, 0);
6241 * We can get EAGAIN for polled IO even though we're
6242 * forcing a sync submission from here, since we can't
6243 * wait for request slots on the block side.
6251 /* avoid locking problems by failing it from a clean context */
6253 /* io-wq is going to take one down */
6255 io_req_task_queue_fail(req, ret);
6259 #define FFS_ASYNC_READ 0x1UL
6260 #define FFS_ASYNC_WRITE 0x2UL
6262 #define FFS_ISREG 0x4UL
6264 #define FFS_ISREG 0x0UL
6266 #define FFS_MASK ~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
6268 static inline struct io_fixed_file *io_fixed_file_slot(struct io_rsrc_data *file_data,
6271 struct fixed_rsrc_table *table;
6273 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6274 return &table->files[i & IORING_FILE_TABLE_MASK];
6277 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6280 struct io_fixed_file *slot = io_fixed_file_slot(ctx->file_data, index);
6282 return (struct file *) (slot->file_ptr & FFS_MASK);
6285 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
6287 unsigned long file_ptr = (unsigned long) file;
6289 if (__io_file_supports_async(file, READ))
6290 file_ptr |= FFS_ASYNC_READ;
6291 if (__io_file_supports_async(file, WRITE))
6292 file_ptr |= FFS_ASYNC_WRITE;
6293 if (S_ISREG(file_inode(file)->i_mode))
6294 file_ptr |= FFS_ISREG;
6295 file_slot->file_ptr = file_ptr;
6298 static struct file *io_file_get(struct io_submit_state *state,
6299 struct io_kiocb *req, int fd, bool fixed)
6301 struct io_ring_ctx *ctx = req->ctx;
6305 unsigned long file_ptr;
6307 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6309 fd = array_index_nospec(fd, ctx->nr_user_files);
6310 file_ptr = io_fixed_file_slot(ctx->file_data, fd)->file_ptr;
6311 file = (struct file *) (file_ptr & FFS_MASK);
6312 file_ptr &= ~FFS_MASK;
6313 /* mask in overlapping REQ_F and FFS bits */
6314 req->flags |= (file_ptr << REQ_F_ASYNC_READ_BIT);
6315 io_req_set_rsrc_node(req);
6317 trace_io_uring_file_get(ctx, fd);
6318 file = __io_file_get(state, fd);
6320 /* we don't allow fixed io_uring files */
6321 if (file && unlikely(file->f_op == &io_uring_fops))
6322 io_req_track_inflight(req);
6328 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6330 struct io_timeout_data *data = container_of(timer,
6331 struct io_timeout_data, timer);
6332 struct io_kiocb *prev, *req = data->req;
6333 struct io_ring_ctx *ctx = req->ctx;
6334 unsigned long flags;
6336 spin_lock_irqsave(&ctx->completion_lock, flags);
6337 prev = req->timeout.head;
6338 req->timeout.head = NULL;
6341 * We don't expect the list to be empty, that will only happen if we
6342 * race with the completion of the linked work.
6344 if (prev && req_ref_inc_not_zero(prev))
6345 io_remove_next_linked(prev);
6348 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6351 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6352 io_put_req_deferred(prev, 1);
6354 io_req_complete_post(req, -ETIME, 0);
6356 io_put_req_deferred(req, 1);
6357 return HRTIMER_NORESTART;
6360 static void io_queue_linked_timeout(struct io_kiocb *req)
6362 struct io_ring_ctx *ctx = req->ctx;
6364 spin_lock_irq(&ctx->completion_lock);
6366 * If the back reference is NULL, then our linked request finished
6367 * before we got a chance to setup the timer
6369 if (req->timeout.head) {
6370 struct io_timeout_data *data = req->async_data;
6372 data->timer.function = io_link_timeout_fn;
6373 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6376 spin_unlock_irq(&ctx->completion_lock);
6377 /* drop submission reference */
6381 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6383 struct io_kiocb *nxt = req->link;
6385 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6386 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6389 nxt->timeout.head = req;
6390 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6391 req->flags |= REQ_F_LINK_TIMEOUT;
6395 static void __io_queue_sqe(struct io_kiocb *req)
6397 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6400 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6403 * We async punt it if the file wasn't marked NOWAIT, or if the file
6404 * doesn't support non-blocking read/write attempts
6407 /* drop submission reference */
6408 if (req->flags & REQ_F_COMPLETE_INLINE) {
6409 struct io_ring_ctx *ctx = req->ctx;
6410 struct io_comp_state *cs = &ctx->submit_state.comp;
6412 cs->reqs[cs->nr++] = req;
6413 if (cs->nr == ARRAY_SIZE(cs->reqs))
6414 io_submit_flush_completions(cs, ctx);
6418 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6419 if (!io_arm_poll_handler(req)) {
6421 * Queued up for async execution, worker will release
6422 * submit reference when the iocb is actually submitted.
6424 io_queue_async_work(req);
6427 io_req_complete_failed(req, ret);
6430 io_queue_linked_timeout(linked_timeout);
6433 static void io_queue_sqe(struct io_kiocb *req)
6437 ret = io_req_defer(req);
6439 if (ret != -EIOCBQUEUED) {
6441 io_req_complete_failed(req, ret);
6443 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6444 ret = io_req_prep_async(req);
6447 io_queue_async_work(req);
6449 __io_queue_sqe(req);
6454 * Check SQE restrictions (opcode and flags).
6456 * Returns 'true' if SQE is allowed, 'false' otherwise.
6458 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6459 struct io_kiocb *req,
6460 unsigned int sqe_flags)
6462 if (!ctx->restricted)
6465 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6468 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6469 ctx->restrictions.sqe_flags_required)
6472 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6473 ctx->restrictions.sqe_flags_required))
6479 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6480 const struct io_uring_sqe *sqe)
6482 struct io_submit_state *state;
6483 unsigned int sqe_flags;
6484 int personality, ret = 0;
6486 req->opcode = READ_ONCE(sqe->opcode);
6487 /* same numerical values with corresponding REQ_F_*, safe to copy */
6488 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6489 req->user_data = READ_ONCE(sqe->user_data);
6490 req->async_data = NULL;
6494 req->fixed_rsrc_refs = NULL;
6495 /* one is dropped after submission, the other at completion */
6496 atomic_set(&req->refs, 2);
6497 req->task = current;
6499 req->work.creds = NULL;
6501 /* enforce forwards compatibility on users */
6502 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6507 if (unlikely(req->opcode >= IORING_OP_LAST))
6510 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6513 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6514 !io_op_defs[req->opcode].buffer_select)
6517 personality = READ_ONCE(sqe->personality);
6519 req->work.creds = xa_load(&ctx->personalities, personality);
6520 if (!req->work.creds)
6522 get_cred(req->work.creds);
6524 state = &ctx->submit_state;
6527 * Plug now if we have more than 1 IO left after this, and the target
6528 * is potentially a read/write to block based storage.
6530 if (!state->plug_started && state->ios_left > 1 &&
6531 io_op_defs[req->opcode].plug) {
6532 blk_start_plug(&state->plug);
6533 state->plug_started = true;
6536 if (io_op_defs[req->opcode].needs_file) {
6537 bool fixed = req->flags & REQ_F_FIXED_FILE;
6539 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6540 if (unlikely(!req->file))
6548 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6549 const struct io_uring_sqe *sqe)
6551 struct io_submit_link *link = &ctx->submit_state.link;
6554 ret = io_init_req(ctx, req, sqe);
6555 if (unlikely(ret)) {
6558 /* fail even hard links since we don't submit */
6559 link->head->flags |= REQ_F_FAIL_LINK;
6560 io_req_complete_failed(link->head, -ECANCELED);
6563 io_req_complete_failed(req, ret);
6566 ret = io_req_prep(req, sqe);
6570 /* don't need @sqe from now on */
6571 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6572 true, ctx->flags & IORING_SETUP_SQPOLL);
6575 * If we already have a head request, queue this one for async
6576 * submittal once the head completes. If we don't have a head but
6577 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6578 * submitted sync once the chain is complete. If none of those
6579 * conditions are true (normal request), then just queue it.
6582 struct io_kiocb *head = link->head;
6585 * Taking sequential execution of a link, draining both sides
6586 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6587 * requests in the link. So, it drains the head and the
6588 * next after the link request. The last one is done via
6589 * drain_next flag to persist the effect across calls.
6591 if (req->flags & REQ_F_IO_DRAIN) {
6592 head->flags |= REQ_F_IO_DRAIN;
6593 ctx->drain_next = 1;
6595 ret = io_req_prep_async(req);
6598 trace_io_uring_link(ctx, req, head);
6599 link->last->link = req;
6602 /* last request of a link, enqueue the link */
6603 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6608 if (unlikely(ctx->drain_next)) {
6609 req->flags |= REQ_F_IO_DRAIN;
6610 ctx->drain_next = 0;
6612 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6624 * Batched submission is done, ensure local IO is flushed out.
6626 static void io_submit_state_end(struct io_submit_state *state,
6627 struct io_ring_ctx *ctx)
6629 if (state->link.head)
6630 io_queue_sqe(state->link.head);
6632 io_submit_flush_completions(&state->comp, ctx);
6633 if (state->plug_started)
6634 blk_finish_plug(&state->plug);
6635 io_state_file_put(state);
6639 * Start submission side cache.
6641 static void io_submit_state_start(struct io_submit_state *state,
6642 unsigned int max_ios)
6644 state->plug_started = false;
6645 state->ios_left = max_ios;
6646 /* set only head, no need to init link_last in advance */
6647 state->link.head = NULL;
6650 static void io_commit_sqring(struct io_ring_ctx *ctx)
6652 struct io_rings *rings = ctx->rings;
6655 * Ensure any loads from the SQEs are done at this point,
6656 * since once we write the new head, the application could
6657 * write new data to them.
6659 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6663 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6664 * that is mapped by userspace. This means that care needs to be taken to
6665 * ensure that reads are stable, as we cannot rely on userspace always
6666 * being a good citizen. If members of the sqe are validated and then later
6667 * used, it's important that those reads are done through READ_ONCE() to
6668 * prevent a re-load down the line.
6670 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6672 u32 *sq_array = ctx->sq_array;
6676 * The cached sq head (or cq tail) serves two purposes:
6678 * 1) allows us to batch the cost of updating the user visible
6680 * 2) allows the kernel side to track the head on its own, even
6681 * though the application is the one updating it.
6683 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6684 if (likely(head < ctx->sq_entries))
6685 return &ctx->sq_sqes[head];
6687 /* drop invalid entries */
6688 ctx->cached_sq_dropped++;
6689 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6693 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6697 /* if we have a backlog and couldn't flush it all, return BUSY */
6698 if (test_bit(0, &ctx->sq_check_overflow)) {
6699 if (!__io_cqring_overflow_flush(ctx, false))
6703 /* make sure SQ entry isn't read before tail */
6704 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6706 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6709 percpu_counter_add(¤t->io_uring->inflight, nr);
6710 refcount_add(nr, ¤t->usage);
6711 io_submit_state_start(&ctx->submit_state, nr);
6713 while (submitted < nr) {
6714 const struct io_uring_sqe *sqe;
6715 struct io_kiocb *req;
6717 req = io_alloc_req(ctx);
6718 if (unlikely(!req)) {
6720 submitted = -EAGAIN;
6723 sqe = io_get_sqe(ctx);
6724 if (unlikely(!sqe)) {
6725 kmem_cache_free(req_cachep, req);
6728 /* will complete beyond this point, count as submitted */
6730 if (io_submit_sqe(ctx, req, sqe))
6734 if (unlikely(submitted != nr)) {
6735 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6736 struct io_uring_task *tctx = current->io_uring;
6737 int unused = nr - ref_used;
6739 percpu_ref_put_many(&ctx->refs, unused);
6740 percpu_counter_sub(&tctx->inflight, unused);
6741 put_task_struct_many(current, unused);
6744 io_submit_state_end(&ctx->submit_state, ctx);
6745 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6746 io_commit_sqring(ctx);
6751 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6753 /* Tell userspace we may need a wakeup call */
6754 spin_lock_irq(&ctx->completion_lock);
6755 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6756 spin_unlock_irq(&ctx->completion_lock);
6759 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6761 spin_lock_irq(&ctx->completion_lock);
6762 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6763 spin_unlock_irq(&ctx->completion_lock);
6766 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6768 unsigned int to_submit;
6771 to_submit = io_sqring_entries(ctx);
6772 /* if we're handling multiple rings, cap submit size for fairness */
6773 if (cap_entries && to_submit > 8)
6776 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6777 unsigned nr_events = 0;
6779 mutex_lock(&ctx->uring_lock);
6780 if (!list_empty(&ctx->iopoll_list))
6781 io_do_iopoll(ctx, &nr_events, 0);
6783 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
6784 !(ctx->flags & IORING_SETUP_R_DISABLED))
6785 ret = io_submit_sqes(ctx, to_submit);
6786 mutex_unlock(&ctx->uring_lock);
6789 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6790 wake_up(&ctx->sqo_sq_wait);
6795 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6797 struct io_ring_ctx *ctx;
6798 unsigned sq_thread_idle = 0;
6800 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6801 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
6802 sqd->sq_thread_idle = sq_thread_idle;
6805 static int io_sq_thread(void *data)
6807 struct io_sq_data *sqd = data;
6808 struct io_ring_ctx *ctx;
6809 unsigned long timeout = 0;
6810 char buf[TASK_COMM_LEN];
6813 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
6814 set_task_comm(current, buf);
6815 current->pf_io_worker = NULL;
6817 if (sqd->sq_cpu != -1)
6818 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6820 set_cpus_allowed_ptr(current, cpu_online_mask);
6821 current->flags |= PF_NO_SETAFFINITY;
6823 mutex_lock(&sqd->lock);
6824 while (!test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state)) {
6826 bool cap_entries, sqt_spin, needs_sched;
6828 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
6829 signal_pending(current)) {
6830 bool did_sig = false;
6832 mutex_unlock(&sqd->lock);
6833 if (signal_pending(current)) {
6834 struct ksignal ksig;
6836 did_sig = get_signal(&ksig);
6839 mutex_lock(&sqd->lock);
6843 io_run_task_work_head(&sqd->park_task_work);
6844 timeout = jiffies + sqd->sq_thread_idle;
6848 cap_entries = !list_is_singular(&sqd->ctx_list);
6849 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6850 const struct cred *creds = NULL;
6852 if (ctx->sq_creds != current_cred())
6853 creds = override_creds(ctx->sq_creds);
6854 ret = __io_sq_thread(ctx, cap_entries);
6856 revert_creds(creds);
6857 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6861 if (sqt_spin || !time_after(jiffies, timeout)) {
6865 timeout = jiffies + sqd->sq_thread_idle;
6870 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6871 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6872 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6873 !list_empty_careful(&ctx->iopoll_list)) {
6874 needs_sched = false;
6877 if (io_sqring_entries(ctx)) {
6878 needs_sched = false;
6883 if (needs_sched && !test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state)) {
6884 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6885 io_ring_set_wakeup_flag(ctx);
6887 mutex_unlock(&sqd->lock);
6889 mutex_lock(&sqd->lock);
6890 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6891 io_ring_clear_wakeup_flag(ctx);
6894 finish_wait(&sqd->wait, &wait);
6895 io_run_task_work_head(&sqd->park_task_work);
6896 timeout = jiffies + sqd->sq_thread_idle;
6899 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6900 io_uring_cancel_sqpoll(ctx);
6902 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6903 io_ring_set_wakeup_flag(ctx);
6904 mutex_unlock(&sqd->lock);
6907 io_run_task_work_head(&sqd->park_task_work);
6908 complete(&sqd->exited);
6912 struct io_wait_queue {
6913 struct wait_queue_entry wq;
6914 struct io_ring_ctx *ctx;
6916 unsigned nr_timeouts;
6919 static inline bool io_should_wake(struct io_wait_queue *iowq)
6921 struct io_ring_ctx *ctx = iowq->ctx;
6924 * Wake up if we have enough events, or if a timeout occurred since we
6925 * started waiting. For timeouts, we always want to return to userspace,
6926 * regardless of event count.
6928 return io_cqring_events(ctx) >= iowq->to_wait ||
6929 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6932 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6933 int wake_flags, void *key)
6935 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6939 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6940 * the task, and the next invocation will do it.
6942 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6943 return autoremove_wake_function(curr, mode, wake_flags, key);
6947 static int io_run_task_work_sig(void)
6949 if (io_run_task_work())
6951 if (!signal_pending(current))
6953 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
6954 return -ERESTARTSYS;
6958 /* when returns >0, the caller should retry */
6959 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6960 struct io_wait_queue *iowq,
6961 signed long *timeout)
6965 /* make sure we run task_work before checking for signals */
6966 ret = io_run_task_work_sig();
6967 if (ret || io_should_wake(iowq))
6969 /* let the caller flush overflows, retry */
6970 if (test_bit(0, &ctx->cq_check_overflow))
6973 *timeout = schedule_timeout(*timeout);
6974 return !*timeout ? -ETIME : 1;
6978 * Wait until events become available, if we don't already have some. The
6979 * application must reap them itself, as they reside on the shared cq ring.
6981 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6982 const sigset_t __user *sig, size_t sigsz,
6983 struct __kernel_timespec __user *uts)
6985 struct io_wait_queue iowq = {
6988 .func = io_wake_function,
6989 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6992 .to_wait = min_events,
6994 struct io_rings *rings = ctx->rings;
6995 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6999 io_cqring_overflow_flush(ctx, false);
7000 if (io_cqring_events(ctx) >= min_events)
7002 if (!io_run_task_work())
7007 #ifdef CONFIG_COMPAT
7008 if (in_compat_syscall())
7009 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
7013 ret = set_user_sigmask(sig, sigsz);
7020 struct timespec64 ts;
7022 if (get_timespec64(&ts, uts))
7024 timeout = timespec64_to_jiffies(&ts);
7027 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
7028 trace_io_uring_cqring_wait(ctx, min_events);
7030 /* if we can't even flush overflow, don't wait for more */
7031 if (!io_cqring_overflow_flush(ctx, false)) {
7035 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
7036 TASK_INTERRUPTIBLE);
7037 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
7038 finish_wait(&ctx->wait, &iowq.wq);
7042 restore_saved_sigmask_unless(ret == -EINTR);
7044 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
7047 static void io_free_file_tables(struct io_rsrc_data *data, unsigned nr_files)
7049 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7051 for (i = 0; i < nr_tables; i++)
7052 kfree(data->table[i].files);
7057 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
7059 #if defined(CONFIG_UNIX)
7060 if (ctx->ring_sock) {
7061 struct sock *sock = ctx->ring_sock->sk;
7062 struct sk_buff *skb;
7064 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
7070 for (i = 0; i < ctx->nr_user_files; i++) {
7073 file = io_file_from_index(ctx, i);
7080 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
7082 struct io_rsrc_data *data = container_of(ref, struct io_rsrc_data, refs);
7084 complete(&data->done);
7087 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
7089 spin_lock_bh(&ctx->rsrc_ref_lock);
7092 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
7094 spin_unlock_bh(&ctx->rsrc_ref_lock);
7097 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
7099 percpu_ref_exit(&ref_node->refs);
7103 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
7104 struct io_rsrc_data *data_to_kill)
7106 WARN_ON_ONCE(!ctx->rsrc_backup_node);
7107 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
7110 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
7112 rsrc_node->rsrc_data = data_to_kill;
7113 io_rsrc_ref_lock(ctx);
7114 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
7115 io_rsrc_ref_unlock(ctx);
7117 percpu_ref_get(&data_to_kill->refs);
7118 percpu_ref_kill(&rsrc_node->refs);
7119 ctx->rsrc_node = NULL;
7122 if (!ctx->rsrc_node) {
7123 ctx->rsrc_node = ctx->rsrc_backup_node;
7124 ctx->rsrc_backup_node = NULL;
7128 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
7130 if (ctx->rsrc_backup_node)
7132 ctx->rsrc_backup_node = io_rsrc_node_alloc(ctx);
7133 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
7136 static int io_rsrc_ref_quiesce(struct io_rsrc_data *data, struct io_ring_ctx *ctx)
7140 /* As we may drop ->uring_lock, other task may have started quiesce */
7144 data->quiesce = true;
7146 ret = io_rsrc_node_switch_start(ctx);
7149 io_rsrc_node_switch(ctx, data);
7151 percpu_ref_kill(&data->refs);
7152 flush_delayed_work(&ctx->rsrc_put_work);
7154 ret = wait_for_completion_interruptible(&data->done);
7158 percpu_ref_resurrect(&data->refs);
7159 reinit_completion(&data->done);
7161 mutex_unlock(&ctx->uring_lock);
7162 ret = io_run_task_work_sig();
7163 mutex_lock(&ctx->uring_lock);
7165 data->quiesce = false;
7170 static struct io_rsrc_data *io_rsrc_data_alloc(struct io_ring_ctx *ctx,
7171 rsrc_put_fn *do_put)
7173 struct io_rsrc_data *data;
7175 data = kzalloc(sizeof(*data), GFP_KERNEL);
7179 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7180 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7185 data->do_put = do_put;
7186 init_completion(&data->done);
7190 static void io_rsrc_data_free(struct io_rsrc_data *data)
7192 percpu_ref_exit(&data->refs);
7196 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7198 struct io_rsrc_data *data = ctx->file_data;
7203 ret = io_rsrc_ref_quiesce(data, ctx);
7207 __io_sqe_files_unregister(ctx);
7208 io_free_file_tables(data, ctx->nr_user_files);
7209 io_rsrc_data_free(data);
7210 ctx->file_data = NULL;
7211 ctx->nr_user_files = 0;
7215 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7216 __releases(&sqd->lock)
7218 WARN_ON_ONCE(sqd->thread == current);
7221 * Do the dance but not conditional clear_bit() because it'd race with
7222 * other threads incrementing park_pending and setting the bit.
7224 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7225 if (atomic_dec_return(&sqd->park_pending))
7226 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7227 mutex_unlock(&sqd->lock);
7230 static void io_sq_thread_park(struct io_sq_data *sqd)
7231 __acquires(&sqd->lock)
7233 WARN_ON_ONCE(sqd->thread == current);
7235 atomic_inc(&sqd->park_pending);
7236 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7237 mutex_lock(&sqd->lock);
7239 wake_up_process(sqd->thread);
7242 static void io_sq_thread_stop(struct io_sq_data *sqd)
7244 WARN_ON_ONCE(sqd->thread == current);
7246 mutex_lock(&sqd->lock);
7247 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7249 wake_up_process(sqd->thread);
7250 mutex_unlock(&sqd->lock);
7251 wait_for_completion(&sqd->exited);
7254 static void io_put_sq_data(struct io_sq_data *sqd)
7256 if (refcount_dec_and_test(&sqd->refs)) {
7257 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
7259 io_sq_thread_stop(sqd);
7264 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7266 struct io_sq_data *sqd = ctx->sq_data;
7269 io_sq_thread_park(sqd);
7270 list_del_init(&ctx->sqd_list);
7271 io_sqd_update_thread_idle(sqd);
7272 io_sq_thread_unpark(sqd);
7274 io_put_sq_data(sqd);
7275 ctx->sq_data = NULL;
7277 put_cred(ctx->sq_creds);
7281 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7283 struct io_ring_ctx *ctx_attach;
7284 struct io_sq_data *sqd;
7287 f = fdget(p->wq_fd);
7289 return ERR_PTR(-ENXIO);
7290 if (f.file->f_op != &io_uring_fops) {
7292 return ERR_PTR(-EINVAL);
7295 ctx_attach = f.file->private_data;
7296 sqd = ctx_attach->sq_data;
7299 return ERR_PTR(-EINVAL);
7301 if (sqd->task_tgid != current->tgid) {
7303 return ERR_PTR(-EPERM);
7306 refcount_inc(&sqd->refs);
7311 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
7314 struct io_sq_data *sqd;
7317 if (p->flags & IORING_SETUP_ATTACH_WQ) {
7318 sqd = io_attach_sq_data(p);
7323 /* fall through for EPERM case, setup new sqd/task */
7324 if (PTR_ERR(sqd) != -EPERM)
7328 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7330 return ERR_PTR(-ENOMEM);
7332 atomic_set(&sqd->park_pending, 0);
7333 refcount_set(&sqd->refs, 1);
7334 INIT_LIST_HEAD(&sqd->ctx_list);
7335 mutex_init(&sqd->lock);
7336 init_waitqueue_head(&sqd->wait);
7337 init_completion(&sqd->exited);
7341 #if defined(CONFIG_UNIX)
7343 * Ensure the UNIX gc is aware of our file set, so we are certain that
7344 * the io_uring can be safely unregistered on process exit, even if we have
7345 * loops in the file referencing.
7347 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7349 struct sock *sk = ctx->ring_sock->sk;
7350 struct scm_fp_list *fpl;
7351 struct sk_buff *skb;
7354 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7358 skb = alloc_skb(0, GFP_KERNEL);
7367 fpl->user = get_uid(current_user());
7368 for (i = 0; i < nr; i++) {
7369 struct file *file = io_file_from_index(ctx, i + offset);
7373 fpl->fp[nr_files] = get_file(file);
7374 unix_inflight(fpl->user, fpl->fp[nr_files]);
7379 fpl->max = SCM_MAX_FD;
7380 fpl->count = nr_files;
7381 UNIXCB(skb).fp = fpl;
7382 skb->destructor = unix_destruct_scm;
7383 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7384 skb_queue_head(&sk->sk_receive_queue, skb);
7386 for (i = 0; i < nr_files; i++)
7397 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7398 * causes regular reference counting to break down. We rely on the UNIX
7399 * garbage collection to take care of this problem for us.
7401 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7403 unsigned left, total;
7407 left = ctx->nr_user_files;
7409 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7411 ret = __io_sqe_files_scm(ctx, this_files, total);
7415 total += this_files;
7421 while (total < ctx->nr_user_files) {
7422 struct file *file = io_file_from_index(ctx, total);
7432 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7438 static bool io_alloc_file_tables(struct io_rsrc_data *file_data,
7441 unsigned i, nr_tables = DIV_ROUND_UP(nr_files, IORING_MAX_FILES_TABLE);
7443 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7445 if (!file_data->table)
7448 for (i = 0; i < nr_tables; i++) {
7449 struct fixed_rsrc_table *table = &file_data->table[i];
7450 unsigned int this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7452 table->files = kcalloc(this_files, sizeof(struct file *),
7456 nr_files -= this_files;
7462 io_free_file_tables(file_data, nr_tables * IORING_MAX_FILES_TABLE);
7466 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7468 struct file *file = prsrc->file;
7469 #if defined(CONFIG_UNIX)
7470 struct sock *sock = ctx->ring_sock->sk;
7471 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7472 struct sk_buff *skb;
7475 __skb_queue_head_init(&list);
7478 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7479 * remove this entry and rearrange the file array.
7481 skb = skb_dequeue(head);
7483 struct scm_fp_list *fp;
7485 fp = UNIXCB(skb).fp;
7486 for (i = 0; i < fp->count; i++) {
7489 if (fp->fp[i] != file)
7492 unix_notinflight(fp->user, fp->fp[i]);
7493 left = fp->count - 1 - i;
7495 memmove(&fp->fp[i], &fp->fp[i + 1],
7496 left * sizeof(struct file *));
7503 __skb_queue_tail(&list, skb);
7513 __skb_queue_tail(&list, skb);
7515 skb = skb_dequeue(head);
7518 if (skb_peek(&list)) {
7519 spin_lock_irq(&head->lock);
7520 while ((skb = __skb_dequeue(&list)) != NULL)
7521 __skb_queue_tail(head, skb);
7522 spin_unlock_irq(&head->lock);
7529 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
7531 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
7532 struct io_ring_ctx *ctx = rsrc_data->ctx;
7533 struct io_rsrc_put *prsrc, *tmp;
7535 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7536 list_del(&prsrc->list);
7537 rsrc_data->do_put(ctx, prsrc);
7541 io_rsrc_node_destroy(ref_node);
7542 percpu_ref_put(&rsrc_data->refs);
7545 static void io_rsrc_put_work(struct work_struct *work)
7547 struct io_ring_ctx *ctx;
7548 struct llist_node *node;
7550 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7551 node = llist_del_all(&ctx->rsrc_put_llist);
7554 struct io_rsrc_node *ref_node;
7555 struct llist_node *next = node->next;
7557 ref_node = llist_entry(node, struct io_rsrc_node, llist);
7558 __io_rsrc_put_work(ref_node);
7563 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7565 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
7566 struct io_rsrc_data *data = node->rsrc_data;
7567 struct io_ring_ctx *ctx = data->ctx;
7568 bool first_add = false;
7571 io_rsrc_ref_lock(ctx);
7574 while (!list_empty(&ctx->rsrc_ref_list)) {
7575 node = list_first_entry(&ctx->rsrc_ref_list,
7576 struct io_rsrc_node, node);
7577 /* recycle ref nodes in order */
7580 list_del(&node->node);
7581 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
7583 io_rsrc_ref_unlock(ctx);
7585 delay = percpu_ref_is_dying(&data->refs) ? 0 : HZ;
7586 if (first_add || !delay)
7587 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7590 static struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx)
7592 struct io_rsrc_node *ref_node;
7594 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7598 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7603 INIT_LIST_HEAD(&ref_node->node);
7604 INIT_LIST_HEAD(&ref_node->rsrc_list);
7605 ref_node->done = false;
7609 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7612 __s32 __user *fds = (__s32 __user *) arg;
7616 struct io_rsrc_data *file_data;
7622 if (nr_args > IORING_MAX_FIXED_FILES)
7624 ret = io_rsrc_node_switch_start(ctx);
7628 file_data = io_rsrc_data_alloc(ctx, io_rsrc_file_put);
7631 ctx->file_data = file_data;
7634 if (!io_alloc_file_tables(file_data, nr_args))
7637 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7638 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7642 /* allow sparse sets */
7652 * Don't allow io_uring instances to be registered. If UNIX
7653 * isn't enabled, then this causes a reference cycle and this
7654 * instance can never get freed. If UNIX is enabled we'll
7655 * handle it just fine, but there's still no point in allowing
7656 * a ring fd as it doesn't support regular read/write anyway.
7658 if (file->f_op == &io_uring_fops) {
7662 io_fixed_file_set(io_fixed_file_slot(file_data, i), file);
7665 ret = io_sqe_files_scm(ctx);
7667 io_sqe_files_unregister(ctx);
7671 io_rsrc_node_switch(ctx, NULL);
7674 for (i = 0; i < ctx->nr_user_files; i++) {
7675 file = io_file_from_index(ctx, i);
7679 io_free_file_tables(file_data, nr_args);
7680 ctx->nr_user_files = 0;
7682 io_rsrc_data_free(ctx->file_data);
7683 ctx->file_data = NULL;
7687 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7690 #if defined(CONFIG_UNIX)
7691 struct sock *sock = ctx->ring_sock->sk;
7692 struct sk_buff_head *head = &sock->sk_receive_queue;
7693 struct sk_buff *skb;
7696 * See if we can merge this file into an existing skb SCM_RIGHTS
7697 * file set. If there's no room, fall back to allocating a new skb
7698 * and filling it in.
7700 spin_lock_irq(&head->lock);
7701 skb = skb_peek(head);
7703 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7705 if (fpl->count < SCM_MAX_FD) {
7706 __skb_unlink(skb, head);
7707 spin_unlock_irq(&head->lock);
7708 fpl->fp[fpl->count] = get_file(file);
7709 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7711 spin_lock_irq(&head->lock);
7712 __skb_queue_head(head, skb);
7717 spin_unlock_irq(&head->lock);
7724 return __io_sqe_files_scm(ctx, 1, index);
7730 static int io_queue_rsrc_removal(struct io_rsrc_data *data,
7731 struct io_rsrc_node *node, void *rsrc)
7733 struct io_rsrc_put *prsrc;
7735 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7740 list_add(&prsrc->list, &node->rsrc_list);
7744 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7745 struct io_uring_rsrc_update *up,
7748 struct io_rsrc_data *data = ctx->file_data;
7749 struct io_fixed_file *file_slot;
7754 bool needs_switch = false;
7756 if (check_add_overflow(up->offset, nr_args, &done))
7758 if (done > ctx->nr_user_files)
7760 err = io_rsrc_node_switch_start(ctx);
7764 fds = u64_to_user_ptr(up->data);
7765 for (done = 0; done < nr_args; done++) {
7767 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7771 if (fd == IORING_REGISTER_FILES_SKIP)
7774 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7775 file_slot = io_fixed_file_slot(ctx->file_data, i);
7777 if (file_slot->file_ptr) {
7778 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
7779 err = io_queue_rsrc_removal(data, ctx->rsrc_node, file);
7782 file_slot->file_ptr = 0;
7783 needs_switch = true;
7792 * Don't allow io_uring instances to be registered. If
7793 * UNIX isn't enabled, then this causes a reference
7794 * cycle and this instance can never get freed. If UNIX
7795 * is enabled we'll handle it just fine, but there's
7796 * still no point in allowing a ring fd as it doesn't
7797 * support regular read/write anyway.
7799 if (file->f_op == &io_uring_fops) {
7804 io_fixed_file_set(file_slot, file);
7805 err = io_sqe_file_register(ctx, file, i);
7807 file_slot->file_ptr = 0;
7815 io_rsrc_node_switch(ctx, data);
7816 return done ? done : err;
7819 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7822 struct io_uring_rsrc_update up;
7824 if (!ctx->file_data)
7828 if (copy_from_user(&up, arg, sizeof(up)))
7833 return __io_sqe_files_update(ctx, &up, nr_args);
7836 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7838 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7840 req = io_put_req_find_next(req);
7841 return req ? &req->work : NULL;
7844 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
7845 struct task_struct *task)
7847 struct io_wq_hash *hash;
7848 struct io_wq_data data;
7849 unsigned int concurrency;
7851 hash = ctx->hash_map;
7853 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7855 return ERR_PTR(-ENOMEM);
7856 refcount_set(&hash->refs, 1);
7857 init_waitqueue_head(&hash->wait);
7858 ctx->hash_map = hash;
7863 data.free_work = io_free_work;
7864 data.do_work = io_wq_submit_work;
7866 /* Do QD, or 4 * CPUS, whatever is smallest */
7867 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7869 return io_wq_create(concurrency, &data);
7872 static int io_uring_alloc_task_context(struct task_struct *task,
7873 struct io_ring_ctx *ctx)
7875 struct io_uring_task *tctx;
7878 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7879 if (unlikely(!tctx))
7882 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7883 if (unlikely(ret)) {
7888 tctx->io_wq = io_init_wq_offload(ctx, task);
7889 if (IS_ERR(tctx->io_wq)) {
7890 ret = PTR_ERR(tctx->io_wq);
7891 percpu_counter_destroy(&tctx->inflight);
7897 init_waitqueue_head(&tctx->wait);
7899 atomic_set(&tctx->in_idle, 0);
7900 atomic_set(&tctx->inflight_tracked, 0);
7901 task->io_uring = tctx;
7902 spin_lock_init(&tctx->task_lock);
7903 INIT_WQ_LIST(&tctx->task_list);
7904 tctx->task_state = 0;
7905 init_task_work(&tctx->task_work, tctx_task_work);
7909 void __io_uring_free(struct task_struct *tsk)
7911 struct io_uring_task *tctx = tsk->io_uring;
7913 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7914 WARN_ON_ONCE(tctx->io_wq);
7916 percpu_counter_destroy(&tctx->inflight);
7918 tsk->io_uring = NULL;
7921 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7922 struct io_uring_params *p)
7926 /* Retain compatibility with failing for an invalid attach attempt */
7927 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7928 IORING_SETUP_ATTACH_WQ) {
7931 f = fdget(p->wq_fd);
7934 if (f.file->f_op != &io_uring_fops) {
7940 if (ctx->flags & IORING_SETUP_SQPOLL) {
7941 struct task_struct *tsk;
7942 struct io_sq_data *sqd;
7945 sqd = io_get_sq_data(p, &attached);
7951 ctx->sq_creds = get_current_cred();
7953 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7954 if (!ctx->sq_thread_idle)
7955 ctx->sq_thread_idle = HZ;
7958 io_sq_thread_park(sqd);
7959 list_add(&ctx->sqd_list, &sqd->ctx_list);
7960 io_sqd_update_thread_idle(sqd);
7961 /* don't attach to a dying SQPOLL thread, would be racy */
7962 if (attached && !sqd->thread)
7964 io_sq_thread_unpark(sqd);
7971 if (p->flags & IORING_SETUP_SQ_AFF) {
7972 int cpu = p->sq_thread_cpu;
7975 if (cpu >= nr_cpu_ids)
7977 if (!cpu_online(cpu))
7985 sqd->task_pid = current->pid;
7986 sqd->task_tgid = current->tgid;
7987 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
7994 ret = io_uring_alloc_task_context(tsk, ctx);
7995 wake_up_new_task(tsk);
7998 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7999 /* Can't have SQ_AFF without SQPOLL */
8006 io_sq_thread_finish(ctx);
8009 complete(&ctx->sq_data->exited);
8013 static inline void __io_unaccount_mem(struct user_struct *user,
8014 unsigned long nr_pages)
8016 atomic_long_sub(nr_pages, &user->locked_vm);
8019 static inline int __io_account_mem(struct user_struct *user,
8020 unsigned long nr_pages)
8022 unsigned long page_limit, cur_pages, new_pages;
8024 /* Don't allow more pages than we can safely lock */
8025 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
8028 cur_pages = atomic_long_read(&user->locked_vm);
8029 new_pages = cur_pages + nr_pages;
8030 if (new_pages > page_limit)
8032 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
8033 new_pages) != cur_pages);
8038 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8041 __io_unaccount_mem(ctx->user, nr_pages);
8043 if (ctx->mm_account)
8044 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
8047 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
8052 ret = __io_account_mem(ctx->user, nr_pages);
8057 if (ctx->mm_account)
8058 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8063 static void io_mem_free(void *ptr)
8070 page = virt_to_head_page(ptr);
8071 if (put_page_testzero(page))
8072 free_compound_page(page);
8075 static void *io_mem_alloc(size_t size)
8077 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8078 __GFP_NORETRY | __GFP_ACCOUNT;
8080 return (void *) __get_free_pages(gfp_flags, get_order(size));
8083 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8086 struct io_rings *rings;
8087 size_t off, sq_array_size;
8089 off = struct_size(rings, cqes, cq_entries);
8090 if (off == SIZE_MAX)
8094 off = ALIGN(off, SMP_CACHE_BYTES);
8102 sq_array_size = array_size(sizeof(u32), sq_entries);
8103 if (sq_array_size == SIZE_MAX)
8106 if (check_add_overflow(off, sq_array_size, &off))
8112 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8116 if (!ctx->user_bufs)
8119 for (i = 0; i < ctx->nr_user_bufs; i++) {
8120 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8122 for (j = 0; j < imu->nr_bvecs; j++)
8123 unpin_user_page(imu->bvec[j].bv_page);
8125 if (imu->acct_pages)
8126 io_unaccount_mem(ctx, imu->acct_pages);
8131 kfree(ctx->user_bufs);
8132 ctx->user_bufs = NULL;
8133 ctx->nr_user_bufs = 0;
8137 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8138 void __user *arg, unsigned index)
8140 struct iovec __user *src;
8142 #ifdef CONFIG_COMPAT
8144 struct compat_iovec __user *ciovs;
8145 struct compat_iovec ciov;
8147 ciovs = (struct compat_iovec __user *) arg;
8148 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8151 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8152 dst->iov_len = ciov.iov_len;
8156 src = (struct iovec __user *) arg;
8157 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8163 * Not super efficient, but this is just a registration time. And we do cache
8164 * the last compound head, so generally we'll only do a full search if we don't
8167 * We check if the given compound head page has already been accounted, to
8168 * avoid double accounting it. This allows us to account the full size of the
8169 * page, not just the constituent pages of a huge page.
8171 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8172 int nr_pages, struct page *hpage)
8176 /* check current page array */
8177 for (i = 0; i < nr_pages; i++) {
8178 if (!PageCompound(pages[i]))
8180 if (compound_head(pages[i]) == hpage)
8184 /* check previously registered pages */
8185 for (i = 0; i < ctx->nr_user_bufs; i++) {
8186 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8188 for (j = 0; j < imu->nr_bvecs; j++) {
8189 if (!PageCompound(imu->bvec[j].bv_page))
8191 if (compound_head(imu->bvec[j].bv_page) == hpage)
8199 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8200 int nr_pages, struct io_mapped_ubuf *imu,
8201 struct page **last_hpage)
8205 for (i = 0; i < nr_pages; i++) {
8206 if (!PageCompound(pages[i])) {
8211 hpage = compound_head(pages[i]);
8212 if (hpage == *last_hpage)
8214 *last_hpage = hpage;
8215 if (headpage_already_acct(ctx, pages, i, hpage))
8217 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8221 if (!imu->acct_pages)
8224 ret = io_account_mem(ctx, imu->acct_pages);
8226 imu->acct_pages = 0;
8230 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8231 struct io_mapped_ubuf *imu,
8232 struct page **last_hpage)
8234 struct vm_area_struct **vmas = NULL;
8235 struct page **pages = NULL;
8236 unsigned long off, start, end, ubuf;
8238 int ret, pret, nr_pages, i;
8240 ubuf = (unsigned long) iov->iov_base;
8241 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8242 start = ubuf >> PAGE_SHIFT;
8243 nr_pages = end - start;
8247 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8251 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8256 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8262 mmap_read_lock(current->mm);
8263 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8265 if (pret == nr_pages) {
8266 /* don't support file backed memory */
8267 for (i = 0; i < nr_pages; i++) {
8268 struct vm_area_struct *vma = vmas[i];
8271 !is_file_hugepages(vma->vm_file)) {
8277 ret = pret < 0 ? pret : -EFAULT;
8279 mmap_read_unlock(current->mm);
8282 * if we did partial map, or found file backed vmas,
8283 * release any pages we did get
8286 unpin_user_pages(pages, pret);
8291 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8293 unpin_user_pages(pages, pret);
8298 off = ubuf & ~PAGE_MASK;
8299 size = iov->iov_len;
8300 for (i = 0; i < nr_pages; i++) {
8303 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8304 imu->bvec[i].bv_page = pages[i];
8305 imu->bvec[i].bv_len = vec_len;
8306 imu->bvec[i].bv_offset = off;
8310 /* store original address for later verification */
8312 imu->ubuf_end = ubuf + iov->iov_len;
8313 imu->nr_bvecs = nr_pages;
8321 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8325 if (!nr_args || nr_args > UIO_MAXIOV)
8328 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8330 if (!ctx->user_bufs)
8336 static int io_buffer_validate(struct iovec *iov)
8338 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
8341 * Don't impose further limits on the size and buffer
8342 * constraints here, we'll -EINVAL later when IO is
8343 * submitted if they are wrong.
8345 if (!iov->iov_base || !iov->iov_len)
8348 /* arbitrary limit, but we need something */
8349 if (iov->iov_len > SZ_1G)
8352 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
8358 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8359 unsigned int nr_args)
8363 struct page *last_hpage = NULL;
8365 ret = io_buffers_map_alloc(ctx, nr_args);
8369 for (i = 0; i < nr_args; i++) {
8370 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8372 ret = io_copy_iov(ctx, &iov, arg, i);
8376 ret = io_buffer_validate(&iov);
8380 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8384 ctx->nr_user_bufs++;
8388 io_sqe_buffers_unregister(ctx);
8393 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8395 __s32 __user *fds = arg;
8401 if (copy_from_user(&fd, fds, sizeof(*fds)))
8404 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8405 if (IS_ERR(ctx->cq_ev_fd)) {
8406 int ret = PTR_ERR(ctx->cq_ev_fd);
8407 ctx->cq_ev_fd = NULL;
8414 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8416 if (ctx->cq_ev_fd) {
8417 eventfd_ctx_put(ctx->cq_ev_fd);
8418 ctx->cq_ev_fd = NULL;
8425 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8427 struct io_buffer *buf;
8428 unsigned long index;
8430 xa_for_each(&ctx->io_buffers, index, buf)
8431 __io_remove_buffers(ctx, buf, index, -1U);
8434 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8436 struct io_kiocb *req, *nxt;
8438 list_for_each_entry_safe(req, nxt, list, compl.list) {
8439 if (tsk && req->task != tsk)
8441 list_del(&req->compl.list);
8442 kmem_cache_free(req_cachep, req);
8446 static void io_req_caches_free(struct io_ring_ctx *ctx)
8448 struct io_submit_state *submit_state = &ctx->submit_state;
8449 struct io_comp_state *cs = &ctx->submit_state.comp;
8451 mutex_lock(&ctx->uring_lock);
8453 if (submit_state->free_reqs) {
8454 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8455 submit_state->reqs);
8456 submit_state->free_reqs = 0;
8459 io_flush_cached_locked_reqs(ctx, cs);
8460 io_req_cache_free(&cs->free_list, NULL);
8461 mutex_unlock(&ctx->uring_lock);
8464 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8466 io_sq_thread_finish(ctx);
8467 io_sqe_buffers_unregister(ctx);
8469 if (ctx->mm_account) {
8470 mmdrop(ctx->mm_account);
8471 ctx->mm_account = NULL;
8474 mutex_lock(&ctx->uring_lock);
8475 io_sqe_files_unregister(ctx);
8477 __io_cqring_overflow_flush(ctx, true);
8478 mutex_unlock(&ctx->uring_lock);
8479 io_eventfd_unregister(ctx);
8480 io_destroy_buffers(ctx);
8482 /* there are no registered resources left, nobody uses it */
8484 io_rsrc_node_destroy(ctx->rsrc_node);
8485 if (ctx->rsrc_backup_node)
8486 io_rsrc_node_destroy(ctx->rsrc_backup_node);
8487 flush_delayed_work(&ctx->rsrc_put_work);
8489 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
8490 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
8492 #if defined(CONFIG_UNIX)
8493 if (ctx->ring_sock) {
8494 ctx->ring_sock->file = NULL; /* so that iput() is called */
8495 sock_release(ctx->ring_sock);
8499 io_mem_free(ctx->rings);
8500 io_mem_free(ctx->sq_sqes);
8502 percpu_ref_exit(&ctx->refs);
8503 free_uid(ctx->user);
8504 io_req_caches_free(ctx);
8506 io_wq_put_hash(ctx->hash_map);
8507 kfree(ctx->cancel_hash);
8511 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8513 struct io_ring_ctx *ctx = file->private_data;
8516 poll_wait(file, &ctx->cq_wait, wait);
8518 * synchronizes with barrier from wq_has_sleeper call in
8522 if (!io_sqring_full(ctx))
8523 mask |= EPOLLOUT | EPOLLWRNORM;
8526 * Don't flush cqring overflow list here, just do a simple check.
8527 * Otherwise there could possible be ABBA deadlock:
8530 * lock(&ctx->uring_lock);
8532 * lock(&ctx->uring_lock);
8535 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8536 * pushs them to do the flush.
8538 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8539 mask |= EPOLLIN | EPOLLRDNORM;
8544 static int io_uring_fasync(int fd, struct file *file, int on)
8546 struct io_ring_ctx *ctx = file->private_data;
8548 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8551 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8553 const struct cred *creds;
8555 creds = xa_erase(&ctx->personalities, id);
8564 static inline bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8566 return io_run_task_work_head(&ctx->exit_task_work);
8569 struct io_tctx_exit {
8570 struct callback_head task_work;
8571 struct completion completion;
8572 struct io_ring_ctx *ctx;
8575 static void io_tctx_exit_cb(struct callback_head *cb)
8577 struct io_uring_task *tctx = current->io_uring;
8578 struct io_tctx_exit *work;
8580 work = container_of(cb, struct io_tctx_exit, task_work);
8582 * When @in_idle, we're in cancellation and it's racy to remove the
8583 * node. It'll be removed by the end of cancellation, just ignore it.
8585 if (!atomic_read(&tctx->in_idle))
8586 io_uring_del_task_file((unsigned long)work->ctx);
8587 complete(&work->completion);
8590 static void io_ring_exit_work(struct work_struct *work)
8592 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
8593 unsigned long timeout = jiffies + HZ * 60 * 5;
8594 struct io_tctx_exit exit;
8595 struct io_tctx_node *node;
8598 /* prevent SQPOLL from submitting new requests */
8600 io_sq_thread_park(ctx->sq_data);
8601 list_del_init(&ctx->sqd_list);
8602 io_sqd_update_thread_idle(ctx->sq_data);
8603 io_sq_thread_unpark(ctx->sq_data);
8607 * If we're doing polled IO and end up having requests being
8608 * submitted async (out-of-line), then completions can come in while
8609 * we're waiting for refs to drop. We need to reap these manually,
8610 * as nobody else will be looking for them.
8613 io_uring_try_cancel_requests(ctx, NULL, NULL);
8615 WARN_ON_ONCE(time_after(jiffies, timeout));
8616 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8619 * Some may use context even when all refs and requests have been put,
8620 * and they are free to do so while still holding uring_lock or
8621 * completion_lock, see __io_req_task_submit(). Apart from other work,
8622 * this lock/unlock section also waits them to finish.
8624 mutex_lock(&ctx->uring_lock);
8625 while (!list_empty(&ctx->tctx_list)) {
8626 WARN_ON_ONCE(time_after(jiffies, timeout));
8628 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
8631 init_completion(&exit.completion);
8632 init_task_work(&exit.task_work, io_tctx_exit_cb);
8633 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
8634 if (WARN_ON_ONCE(ret))
8636 wake_up_process(node->task);
8638 mutex_unlock(&ctx->uring_lock);
8639 wait_for_completion(&exit.completion);
8641 mutex_lock(&ctx->uring_lock);
8643 mutex_unlock(&ctx->uring_lock);
8644 spin_lock_irq(&ctx->completion_lock);
8645 spin_unlock_irq(&ctx->completion_lock);
8647 io_ring_ctx_free(ctx);
8650 /* Returns true if we found and killed one or more timeouts */
8651 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
8652 struct files_struct *files)
8654 struct io_kiocb *req, *tmp;
8657 spin_lock_irq(&ctx->completion_lock);
8658 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
8659 if (io_match_task(req, tsk, files)) {
8660 io_kill_timeout(req, -ECANCELED);
8665 io_commit_cqring(ctx);
8666 spin_unlock_irq(&ctx->completion_lock);
8668 io_cqring_ev_posted(ctx);
8669 return canceled != 0;
8672 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8674 unsigned long index;
8675 struct creds *creds;
8677 mutex_lock(&ctx->uring_lock);
8678 percpu_ref_kill(&ctx->refs);
8680 __io_cqring_overflow_flush(ctx, true);
8681 xa_for_each(&ctx->personalities, index, creds)
8682 io_unregister_personality(ctx, index);
8683 mutex_unlock(&ctx->uring_lock);
8685 io_kill_timeouts(ctx, NULL, NULL);
8686 io_poll_remove_all(ctx, NULL, NULL);
8688 /* if we failed setting up the ctx, we might not have any rings */
8689 io_iopoll_try_reap_events(ctx);
8691 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8693 * Use system_unbound_wq to avoid spawning tons of event kworkers
8694 * if we're exiting a ton of rings at the same time. It just adds
8695 * noise and overhead, there's no discernable change in runtime
8696 * over using system_wq.
8698 queue_work(system_unbound_wq, &ctx->exit_work);
8701 static int io_uring_release(struct inode *inode, struct file *file)
8703 struct io_ring_ctx *ctx = file->private_data;
8705 file->private_data = NULL;
8706 io_ring_ctx_wait_and_kill(ctx);
8710 struct io_task_cancel {
8711 struct task_struct *task;
8712 struct files_struct *files;
8715 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8717 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8718 struct io_task_cancel *cancel = data;
8721 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8722 unsigned long flags;
8723 struct io_ring_ctx *ctx = req->ctx;
8725 /* protect against races with linked timeouts */
8726 spin_lock_irqsave(&ctx->completion_lock, flags);
8727 ret = io_match_task(req, cancel->task, cancel->files);
8728 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8730 ret = io_match_task(req, cancel->task, cancel->files);
8735 static bool io_cancel_defer_files(struct io_ring_ctx *ctx,
8736 struct task_struct *task,
8737 struct files_struct *files)
8739 struct io_defer_entry *de;
8742 spin_lock_irq(&ctx->completion_lock);
8743 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8744 if (io_match_task(de->req, task, files)) {
8745 list_cut_position(&list, &ctx->defer_list, &de->list);
8749 spin_unlock_irq(&ctx->completion_lock);
8750 if (list_empty(&list))
8753 while (!list_empty(&list)) {
8754 de = list_first_entry(&list, struct io_defer_entry, list);
8755 list_del_init(&de->list);
8756 io_req_complete_failed(de->req, -ECANCELED);
8762 static bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
8764 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8766 return req->ctx == data;
8769 static bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
8771 struct io_tctx_node *node;
8772 enum io_wq_cancel cret;
8775 mutex_lock(&ctx->uring_lock);
8776 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
8777 struct io_uring_task *tctx = node->task->io_uring;
8780 * io_wq will stay alive while we hold uring_lock, because it's
8781 * killed after ctx nodes, which requires to take the lock.
8783 if (!tctx || !tctx->io_wq)
8785 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
8786 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8788 mutex_unlock(&ctx->uring_lock);
8793 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8794 struct task_struct *task,
8795 struct files_struct *files)
8797 struct io_task_cancel cancel = { .task = task, .files = files, };
8798 struct io_uring_task *tctx = task ? task->io_uring : NULL;
8801 enum io_wq_cancel cret;
8805 ret |= io_uring_try_cancel_iowq(ctx);
8806 } else if (tctx && tctx->io_wq) {
8808 * Cancels requests of all rings, not only @ctx, but
8809 * it's fine as the task is in exit/exec.
8811 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8813 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8816 /* SQPOLL thread does its own polling */
8817 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && !files) ||
8818 (ctx->sq_data && ctx->sq_data->thread == current)) {
8819 while (!list_empty_careful(&ctx->iopoll_list)) {
8820 io_iopoll_try_reap_events(ctx);
8825 ret |= io_cancel_defer_files(ctx, task, files);
8826 ret |= io_poll_remove_all(ctx, task, files);
8827 ret |= io_kill_timeouts(ctx, task, files);
8828 ret |= io_run_task_work();
8829 ret |= io_run_ctx_fallback(ctx);
8836 static int __io_uring_add_task_file(struct io_ring_ctx *ctx)
8838 struct io_uring_task *tctx = current->io_uring;
8839 struct io_tctx_node *node;
8842 if (unlikely(!tctx)) {
8843 ret = io_uring_alloc_task_context(current, ctx);
8846 tctx = current->io_uring;
8848 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
8849 node = kmalloc(sizeof(*node), GFP_KERNEL);
8853 node->task = current;
8855 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
8862 mutex_lock(&ctx->uring_lock);
8863 list_add(&node->ctx_node, &ctx->tctx_list);
8864 mutex_unlock(&ctx->uring_lock);
8871 * Note that this task has used io_uring. We use it for cancelation purposes.
8873 static inline int io_uring_add_task_file(struct io_ring_ctx *ctx)
8875 struct io_uring_task *tctx = current->io_uring;
8877 if (likely(tctx && tctx->last == ctx))
8879 return __io_uring_add_task_file(ctx);
8883 * Remove this io_uring_file -> task mapping.
8885 static void io_uring_del_task_file(unsigned long index)
8887 struct io_uring_task *tctx = current->io_uring;
8888 struct io_tctx_node *node;
8892 node = xa_erase(&tctx->xa, index);
8896 WARN_ON_ONCE(current != node->task);
8897 WARN_ON_ONCE(list_empty(&node->ctx_node));
8899 mutex_lock(&node->ctx->uring_lock);
8900 list_del(&node->ctx_node);
8901 mutex_unlock(&node->ctx->uring_lock);
8903 if (tctx->last == node->ctx)
8908 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8910 struct io_tctx_node *node;
8911 unsigned long index;
8913 xa_for_each(&tctx->xa, index, node)
8914 io_uring_del_task_file(index);
8916 io_wq_put_and_exit(tctx->io_wq);
8921 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
8924 return atomic_read(&tctx->inflight_tracked);
8925 return percpu_counter_sum(&tctx->inflight);
8928 static void io_sqpoll_cancel_cb(struct callback_head *cb)
8930 struct io_tctx_exit *work = container_of(cb, struct io_tctx_exit, task_work);
8931 struct io_ring_ctx *ctx = work->ctx;
8932 struct io_sq_data *sqd = ctx->sq_data;
8935 io_uring_cancel_sqpoll(ctx);
8936 complete(&work->completion);
8939 static void io_sqpoll_cancel_sync(struct io_ring_ctx *ctx)
8941 struct io_sq_data *sqd = ctx->sq_data;
8942 struct io_tctx_exit work = { .ctx = ctx, };
8943 struct task_struct *task;
8945 io_sq_thread_park(sqd);
8946 list_del_init(&ctx->sqd_list);
8947 io_sqd_update_thread_idle(sqd);
8950 init_completion(&work.completion);
8951 init_task_work(&work.task_work, io_sqpoll_cancel_cb);
8952 io_task_work_add_head(&sqd->park_task_work, &work.task_work);
8953 wake_up_process(task);
8955 io_sq_thread_unpark(sqd);
8958 wait_for_completion(&work.completion);
8961 static void io_uring_try_cancel(struct files_struct *files)
8963 struct io_uring_task *tctx = current->io_uring;
8964 struct io_tctx_node *node;
8965 unsigned long index;
8967 xa_for_each(&tctx->xa, index, node) {
8968 struct io_ring_ctx *ctx = node->ctx;
8971 io_sqpoll_cancel_sync(ctx);
8974 io_uring_try_cancel_requests(ctx, current, files);
8978 /* should only be called by SQPOLL task */
8979 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8981 struct io_sq_data *sqd = ctx->sq_data;
8982 struct io_uring_task *tctx = current->io_uring;
8986 WARN_ON_ONCE(!sqd || ctx->sq_data->thread != current);
8988 atomic_inc(&tctx->in_idle);
8990 /* read completions before cancelations */
8991 inflight = tctx_inflight(tctx, false);
8994 io_uring_try_cancel_requests(ctx, current, NULL);
8996 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8998 * If we've seen completions, retry without waiting. This
8999 * avoids a race where a completion comes in before we did
9000 * prepare_to_wait().
9002 if (inflight == tctx_inflight(tctx, false))
9004 finish_wait(&tctx->wait, &wait);
9006 atomic_dec(&tctx->in_idle);
9010 * Find any io_uring fd that this task has registered or done IO on, and cancel
9013 void __io_uring_cancel(struct files_struct *files)
9015 struct io_uring_task *tctx = current->io_uring;
9019 /* make sure overflow events are dropped */
9020 atomic_inc(&tctx->in_idle);
9021 io_uring_try_cancel(files);
9024 /* read completions before cancelations */
9025 inflight = tctx_inflight(tctx, !!files);
9028 io_uring_try_cancel(files);
9029 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
9032 * If we've seen completions, retry without waiting. This
9033 * avoids a race where a completion comes in before we did
9034 * prepare_to_wait().
9036 if (inflight == tctx_inflight(tctx, !!files))
9038 finish_wait(&tctx->wait, &wait);
9040 atomic_dec(&tctx->in_idle);
9042 io_uring_clean_tctx(tctx);
9044 /* for exec all current's requests should be gone, kill tctx */
9045 __io_uring_free(current);
9049 static void *io_uring_validate_mmap_request(struct file *file,
9050 loff_t pgoff, size_t sz)
9052 struct io_ring_ctx *ctx = file->private_data;
9053 loff_t offset = pgoff << PAGE_SHIFT;
9058 case IORING_OFF_SQ_RING:
9059 case IORING_OFF_CQ_RING:
9062 case IORING_OFF_SQES:
9066 return ERR_PTR(-EINVAL);
9069 page = virt_to_head_page(ptr);
9070 if (sz > page_size(page))
9071 return ERR_PTR(-EINVAL);
9078 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9080 size_t sz = vma->vm_end - vma->vm_start;
9084 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9086 return PTR_ERR(ptr);
9088 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9089 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9092 #else /* !CONFIG_MMU */
9094 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9096 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9099 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9101 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9104 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9105 unsigned long addr, unsigned long len,
9106 unsigned long pgoff, unsigned long flags)
9110 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9112 return PTR_ERR(ptr);
9114 return (unsigned long) ptr;
9117 #endif /* !CONFIG_MMU */
9119 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9124 if (!io_sqring_full(ctx))
9126 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9128 if (!io_sqring_full(ctx))
9131 } while (!signal_pending(current));
9133 finish_wait(&ctx->sqo_sq_wait, &wait);
9137 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9138 struct __kernel_timespec __user **ts,
9139 const sigset_t __user **sig)
9141 struct io_uring_getevents_arg arg;
9144 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9145 * is just a pointer to the sigset_t.
9147 if (!(flags & IORING_ENTER_EXT_ARG)) {
9148 *sig = (const sigset_t __user *) argp;
9154 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9155 * timespec and sigset_t pointers if good.
9157 if (*argsz != sizeof(arg))
9159 if (copy_from_user(&arg, argp, sizeof(arg)))
9161 *sig = u64_to_user_ptr(arg.sigmask);
9162 *argsz = arg.sigmask_sz;
9163 *ts = u64_to_user_ptr(arg.ts);
9167 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9168 u32, min_complete, u32, flags, const void __user *, argp,
9171 struct io_ring_ctx *ctx;
9178 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9179 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG)))
9183 if (unlikely(!f.file))
9187 if (unlikely(f.file->f_op != &io_uring_fops))
9191 ctx = f.file->private_data;
9192 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
9196 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
9200 * For SQ polling, the thread will do all submissions and completions.
9201 * Just return the requested submit count, and wake the thread if
9205 if (ctx->flags & IORING_SETUP_SQPOLL) {
9206 io_cqring_overflow_flush(ctx, false);
9209 if (unlikely(ctx->sq_data->thread == NULL)) {
9212 if (flags & IORING_ENTER_SQ_WAKEUP)
9213 wake_up(&ctx->sq_data->wait);
9214 if (flags & IORING_ENTER_SQ_WAIT) {
9215 ret = io_sqpoll_wait_sq(ctx);
9219 submitted = to_submit;
9220 } else if (to_submit) {
9221 ret = io_uring_add_task_file(ctx);
9224 mutex_lock(&ctx->uring_lock);
9225 submitted = io_submit_sqes(ctx, to_submit);
9226 mutex_unlock(&ctx->uring_lock);
9228 if (submitted != to_submit)
9231 if (flags & IORING_ENTER_GETEVENTS) {
9232 const sigset_t __user *sig;
9233 struct __kernel_timespec __user *ts;
9235 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9239 min_complete = min(min_complete, ctx->cq_entries);
9242 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9243 * space applications don't need to do io completion events
9244 * polling again, they can rely on io_sq_thread to do polling
9245 * work, which can reduce cpu usage and uring_lock contention.
9247 if (ctx->flags & IORING_SETUP_IOPOLL &&
9248 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9249 ret = io_iopoll_check(ctx, min_complete);
9251 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9256 percpu_ref_put(&ctx->refs);
9259 return submitted ? submitted : ret;
9262 #ifdef CONFIG_PROC_FS
9263 static int io_uring_show_cred(struct seq_file *m, unsigned int id,
9264 const struct cred *cred)
9266 struct user_namespace *uns = seq_user_ns(m);
9267 struct group_info *gi;
9272 seq_printf(m, "%5d\n", id);
9273 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9274 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9275 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9276 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9277 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9278 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9279 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9280 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9281 seq_puts(m, "\n\tGroups:\t");
9282 gi = cred->group_info;
9283 for (g = 0; g < gi->ngroups; g++) {
9284 seq_put_decimal_ull(m, g ? " " : "",
9285 from_kgid_munged(uns, gi->gid[g]));
9287 seq_puts(m, "\n\tCapEff:\t");
9288 cap = cred->cap_effective;
9289 CAP_FOR_EACH_U32(__capi)
9290 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9295 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9297 struct io_sq_data *sq = NULL;
9302 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9303 * since fdinfo case grabs it in the opposite direction of normal use
9304 * cases. If we fail to get the lock, we just don't iterate any
9305 * structures that could be going away outside the io_uring mutex.
9307 has_lock = mutex_trylock(&ctx->uring_lock);
9309 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9315 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9316 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9317 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9318 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9319 struct file *f = io_file_from_index(ctx, i);
9322 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9324 seq_printf(m, "%5u: <none>\n", i);
9326 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9327 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9328 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9329 unsigned int len = buf->ubuf_end - buf->ubuf;
9331 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
9333 if (has_lock && !xa_empty(&ctx->personalities)) {
9334 unsigned long index;
9335 const struct cred *cred;
9337 seq_printf(m, "Personalities:\n");
9338 xa_for_each(&ctx->personalities, index, cred)
9339 io_uring_show_cred(m, index, cred);
9341 seq_printf(m, "PollList:\n");
9342 spin_lock_irq(&ctx->completion_lock);
9343 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9344 struct hlist_head *list = &ctx->cancel_hash[i];
9345 struct io_kiocb *req;
9347 hlist_for_each_entry(req, list, hash_node)
9348 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9349 req->task->task_works != NULL);
9351 spin_unlock_irq(&ctx->completion_lock);
9353 mutex_unlock(&ctx->uring_lock);
9356 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9358 struct io_ring_ctx *ctx = f->private_data;
9360 if (percpu_ref_tryget(&ctx->refs)) {
9361 __io_uring_show_fdinfo(ctx, m);
9362 percpu_ref_put(&ctx->refs);
9367 static const struct file_operations io_uring_fops = {
9368 .release = io_uring_release,
9369 .mmap = io_uring_mmap,
9371 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9372 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9374 .poll = io_uring_poll,
9375 .fasync = io_uring_fasync,
9376 #ifdef CONFIG_PROC_FS
9377 .show_fdinfo = io_uring_show_fdinfo,
9381 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9382 struct io_uring_params *p)
9384 struct io_rings *rings;
9385 size_t size, sq_array_offset;
9387 /* make sure these are sane, as we already accounted them */
9388 ctx->sq_entries = p->sq_entries;
9389 ctx->cq_entries = p->cq_entries;
9391 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9392 if (size == SIZE_MAX)
9395 rings = io_mem_alloc(size);
9400 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9401 rings->sq_ring_mask = p->sq_entries - 1;
9402 rings->cq_ring_mask = p->cq_entries - 1;
9403 rings->sq_ring_entries = p->sq_entries;
9404 rings->cq_ring_entries = p->cq_entries;
9405 ctx->sq_mask = rings->sq_ring_mask;
9406 ctx->cq_mask = rings->cq_ring_mask;
9408 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9409 if (size == SIZE_MAX) {
9410 io_mem_free(ctx->rings);
9415 ctx->sq_sqes = io_mem_alloc(size);
9416 if (!ctx->sq_sqes) {
9417 io_mem_free(ctx->rings);
9425 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9429 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9433 ret = io_uring_add_task_file(ctx);
9438 fd_install(fd, file);
9443 * Allocate an anonymous fd, this is what constitutes the application
9444 * visible backing of an io_uring instance. The application mmaps this
9445 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9446 * we have to tie this fd to a socket for file garbage collection purposes.
9448 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9451 #if defined(CONFIG_UNIX)
9454 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9457 return ERR_PTR(ret);
9460 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9461 O_RDWR | O_CLOEXEC);
9462 #if defined(CONFIG_UNIX)
9464 sock_release(ctx->ring_sock);
9465 ctx->ring_sock = NULL;
9467 ctx->ring_sock->file = file;
9473 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9474 struct io_uring_params __user *params)
9476 struct io_ring_ctx *ctx;
9482 if (entries > IORING_MAX_ENTRIES) {
9483 if (!(p->flags & IORING_SETUP_CLAMP))
9485 entries = IORING_MAX_ENTRIES;
9489 * Use twice as many entries for the CQ ring. It's possible for the
9490 * application to drive a higher depth than the size of the SQ ring,
9491 * since the sqes are only used at submission time. This allows for
9492 * some flexibility in overcommitting a bit. If the application has
9493 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9494 * of CQ ring entries manually.
9496 p->sq_entries = roundup_pow_of_two(entries);
9497 if (p->flags & IORING_SETUP_CQSIZE) {
9499 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9500 * to a power-of-two, if it isn't already. We do NOT impose
9501 * any cq vs sq ring sizing.
9505 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9506 if (!(p->flags & IORING_SETUP_CLAMP))
9508 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9510 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9511 if (p->cq_entries < p->sq_entries)
9514 p->cq_entries = 2 * p->sq_entries;
9517 ctx = io_ring_ctx_alloc(p);
9520 ctx->compat = in_compat_syscall();
9521 if (!capable(CAP_IPC_LOCK))
9522 ctx->user = get_uid(current_user());
9525 * This is just grabbed for accounting purposes. When a process exits,
9526 * the mm is exited and dropped before the files, hence we need to hang
9527 * on to this mm purely for the purposes of being able to unaccount
9528 * memory (locked/pinned vm). It's not used for anything else.
9530 mmgrab(current->mm);
9531 ctx->mm_account = current->mm;
9533 ret = io_allocate_scq_urings(ctx, p);
9537 ret = io_sq_offload_create(ctx, p);
9541 memset(&p->sq_off, 0, sizeof(p->sq_off));
9542 p->sq_off.head = offsetof(struct io_rings, sq.head);
9543 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9544 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9545 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9546 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9547 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9548 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9550 memset(&p->cq_off, 0, sizeof(p->cq_off));
9551 p->cq_off.head = offsetof(struct io_rings, cq.head);
9552 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9553 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9554 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9555 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9556 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9557 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9559 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9560 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9561 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9562 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9563 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9565 if (copy_to_user(params, p, sizeof(*p))) {
9570 file = io_uring_get_file(ctx);
9572 ret = PTR_ERR(file);
9577 * Install ring fd as the very last thing, so we don't risk someone
9578 * having closed it before we finish setup
9580 ret = io_uring_install_fd(ctx, file);
9582 /* fput will clean it up */
9587 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9590 io_ring_ctx_wait_and_kill(ctx);
9595 * Sets up an aio uring context, and returns the fd. Applications asks for a
9596 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9597 * params structure passed in.
9599 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9601 struct io_uring_params p;
9604 if (copy_from_user(&p, params, sizeof(p)))
9606 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9611 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9612 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9613 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9614 IORING_SETUP_R_DISABLED))
9617 return io_uring_create(entries, &p, params);
9620 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9621 struct io_uring_params __user *, params)
9623 return io_uring_setup(entries, params);
9626 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9628 struct io_uring_probe *p;
9632 size = struct_size(p, ops, nr_args);
9633 if (size == SIZE_MAX)
9635 p = kzalloc(size, GFP_KERNEL);
9640 if (copy_from_user(p, arg, size))
9643 if (memchr_inv(p, 0, size))
9646 p->last_op = IORING_OP_LAST - 1;
9647 if (nr_args > IORING_OP_LAST)
9648 nr_args = IORING_OP_LAST;
9650 for (i = 0; i < nr_args; i++) {
9652 if (!io_op_defs[i].not_supported)
9653 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9658 if (copy_to_user(arg, p, size))
9665 static int io_register_personality(struct io_ring_ctx *ctx)
9667 const struct cred *creds;
9671 creds = get_current_cred();
9673 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
9674 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
9681 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9682 unsigned int nr_args)
9684 struct io_uring_restriction *res;
9688 /* Restrictions allowed only if rings started disabled */
9689 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9692 /* We allow only a single restrictions registration */
9693 if (ctx->restrictions.registered)
9696 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9699 size = array_size(nr_args, sizeof(*res));
9700 if (size == SIZE_MAX)
9703 res = memdup_user(arg, size);
9705 return PTR_ERR(res);
9709 for (i = 0; i < nr_args; i++) {
9710 switch (res[i].opcode) {
9711 case IORING_RESTRICTION_REGISTER_OP:
9712 if (res[i].register_op >= IORING_REGISTER_LAST) {
9717 __set_bit(res[i].register_op,
9718 ctx->restrictions.register_op);
9720 case IORING_RESTRICTION_SQE_OP:
9721 if (res[i].sqe_op >= IORING_OP_LAST) {
9726 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9728 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9729 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9731 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9732 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9741 /* Reset all restrictions if an error happened */
9743 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9745 ctx->restrictions.registered = true;
9751 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9753 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9756 if (ctx->restrictions.registered)
9757 ctx->restricted = 1;
9759 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9760 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
9761 wake_up(&ctx->sq_data->wait);
9765 static bool io_register_op_must_quiesce(int op)
9768 case IORING_REGISTER_FILES:
9769 case IORING_UNREGISTER_FILES:
9770 case IORING_REGISTER_FILES_UPDATE:
9771 case IORING_REGISTER_PROBE:
9772 case IORING_REGISTER_PERSONALITY:
9773 case IORING_UNREGISTER_PERSONALITY:
9780 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9781 void __user *arg, unsigned nr_args)
9782 __releases(ctx->uring_lock)
9783 __acquires(ctx->uring_lock)
9788 * We're inside the ring mutex, if the ref is already dying, then
9789 * someone else killed the ctx or is already going through
9790 * io_uring_register().
9792 if (percpu_ref_is_dying(&ctx->refs))
9795 if (io_register_op_must_quiesce(opcode)) {
9796 percpu_ref_kill(&ctx->refs);
9799 * Drop uring mutex before waiting for references to exit. If
9800 * another thread is currently inside io_uring_enter() it might
9801 * need to grab the uring_lock to make progress. If we hold it
9802 * here across the drain wait, then we can deadlock. It's safe
9803 * to drop the mutex here, since no new references will come in
9804 * after we've killed the percpu ref.
9806 mutex_unlock(&ctx->uring_lock);
9808 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9811 ret = io_run_task_work_sig();
9816 mutex_lock(&ctx->uring_lock);
9819 percpu_ref_resurrect(&ctx->refs);
9824 if (ctx->restricted) {
9825 if (opcode >= IORING_REGISTER_LAST) {
9830 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9837 case IORING_REGISTER_BUFFERS:
9838 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9840 case IORING_UNREGISTER_BUFFERS:
9844 ret = io_sqe_buffers_unregister(ctx);
9846 case IORING_REGISTER_FILES:
9847 ret = io_sqe_files_register(ctx, arg, nr_args);
9849 case IORING_UNREGISTER_FILES:
9853 ret = io_sqe_files_unregister(ctx);
9855 case IORING_REGISTER_FILES_UPDATE:
9856 ret = io_sqe_files_update(ctx, arg, nr_args);
9858 case IORING_REGISTER_EVENTFD:
9859 case IORING_REGISTER_EVENTFD_ASYNC:
9863 ret = io_eventfd_register(ctx, arg);
9866 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9867 ctx->eventfd_async = 1;
9869 ctx->eventfd_async = 0;
9871 case IORING_UNREGISTER_EVENTFD:
9875 ret = io_eventfd_unregister(ctx);
9877 case IORING_REGISTER_PROBE:
9879 if (!arg || nr_args > 256)
9881 ret = io_probe(ctx, arg, nr_args);
9883 case IORING_REGISTER_PERSONALITY:
9887 ret = io_register_personality(ctx);
9889 case IORING_UNREGISTER_PERSONALITY:
9893 ret = io_unregister_personality(ctx, nr_args);
9895 case IORING_REGISTER_ENABLE_RINGS:
9899 ret = io_register_enable_rings(ctx);
9901 case IORING_REGISTER_RESTRICTIONS:
9902 ret = io_register_restrictions(ctx, arg, nr_args);
9910 if (io_register_op_must_quiesce(opcode)) {
9911 /* bring the ctx back to life */
9912 percpu_ref_reinit(&ctx->refs);
9914 reinit_completion(&ctx->ref_comp);
9919 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9920 void __user *, arg, unsigned int, nr_args)
9922 struct io_ring_ctx *ctx;
9931 if (f.file->f_op != &io_uring_fops)
9934 ctx = f.file->private_data;
9938 mutex_lock(&ctx->uring_lock);
9939 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9940 mutex_unlock(&ctx->uring_lock);
9941 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9942 ctx->cq_ev_fd != NULL, ret);
9948 static int __init io_uring_init(void)
9950 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9951 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9952 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9955 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9956 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9957 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9958 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9959 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9960 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9961 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9962 BUILD_BUG_SQE_ELEM(8, __u64, off);
9963 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9964 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9965 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9966 BUILD_BUG_SQE_ELEM(24, __u32, len);
9967 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9968 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9969 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9970 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9971 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9972 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9973 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9974 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9975 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9976 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9977 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9978 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9979 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9980 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9981 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9982 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9983 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9984 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9985 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9987 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9988 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9989 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9993 __initcall(io_uring_init);