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/fs_struct.h>
78 #include <linux/splice.h>
79 #include <linux/task_work.h>
80 #include <linux/pagemap.h>
81 #include <linux/io_uring.h>
82 #include <linux/blk-cgroup.h>
83 #include <linux/audit.h>
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
88 #include <uapi/linux/io_uring.h>
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
97 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
99 #define IORING_FILE_TABLE_SHIFT 9
100 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
101 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
102 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
103 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
104 IORING_REGISTER_LAST + IORING_OP_LAST)
106 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
107 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
111 u32 head ____cacheline_aligned_in_smp;
112 u32 tail ____cacheline_aligned_in_smp;
116 * This data is shared with the application through the mmap at offsets
117 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
119 * The offsets to the member fields are published through struct
120 * io_sqring_offsets when calling io_uring_setup.
124 * Head and tail offsets into the ring; the offsets need to be
125 * masked to get valid indices.
127 * The kernel controls head of the sq ring and the tail of the cq ring,
128 * and the application controls tail of the sq ring and the head of the
131 struct io_uring sq, cq;
133 * Bitmasks to apply to head and tail offsets (constant, equals
136 u32 sq_ring_mask, cq_ring_mask;
137 /* Ring sizes (constant, power of 2) */
138 u32 sq_ring_entries, cq_ring_entries;
140 * Number of invalid entries dropped by the kernel due to
141 * invalid index stored in array
143 * Written by the kernel, shouldn't be modified by the
144 * application (i.e. get number of "new events" by comparing to
147 * After a new SQ head value was read by the application this
148 * counter includes all submissions that were dropped reaching
149 * the new SQ head (and possibly more).
155 * Written by the kernel, shouldn't be modified by the
158 * The application needs a full memory barrier before checking
159 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
165 * Written by the application, shouldn't be modified by the
170 * Number of completion events lost because the queue was full;
171 * this should be avoided by the application by making sure
172 * there are not more requests pending than there is space in
173 * the completion queue.
175 * Written by the kernel, shouldn't be modified by the
176 * application (i.e. get number of "new events" by comparing to
179 * As completion events come in out of order this counter is not
180 * ordered with any other data.
184 * Ring buffer of completion events.
186 * The kernel writes completion events fresh every time they are
187 * produced, so the application is allowed to modify pending
190 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
193 enum io_uring_cmd_flags {
194 IO_URING_F_NONBLOCK = 1,
195 IO_URING_F_COMPLETE_DEFER = 2,
198 struct io_mapped_ubuf {
201 struct bio_vec *bvec;
202 unsigned int nr_bvecs;
203 unsigned long acct_pages;
209 struct list_head list;
216 struct fixed_rsrc_table {
220 struct fixed_rsrc_ref_node {
221 struct percpu_ref refs;
222 struct list_head node;
223 struct list_head rsrc_list;
224 struct fixed_rsrc_data *rsrc_data;
225 void (*rsrc_put)(struct io_ring_ctx *ctx,
226 struct io_rsrc_put *prsrc);
227 struct llist_node llist;
231 struct fixed_rsrc_data {
232 struct fixed_rsrc_table *table;
233 struct io_ring_ctx *ctx;
235 struct fixed_rsrc_ref_node *node;
236 struct percpu_ref refs;
237 struct completion done;
242 struct list_head list;
248 struct io_restriction {
249 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
250 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
251 u8 sqe_flags_allowed;
252 u8 sqe_flags_required;
257 IO_SQ_THREAD_SHOULD_STOP = 0,
258 IO_SQ_THREAD_SHOULD_PARK,
265 /* ctx's that are using this sqd */
266 struct list_head ctx_list;
267 struct list_head ctx_new_list;
268 struct mutex ctx_lock;
270 struct task_struct *thread;
271 struct wait_queue_head wait;
273 unsigned sq_thread_idle;
278 struct completion startup;
279 struct completion completion;
280 struct completion exited;
283 #define IO_IOPOLL_BATCH 8
284 #define IO_COMPL_BATCH 32
285 #define IO_REQ_CACHE_SIZE 32
286 #define IO_REQ_ALLOC_BATCH 8
288 struct io_comp_state {
289 struct io_kiocb *reqs[IO_COMPL_BATCH];
291 unsigned int locked_free_nr;
292 /* inline/task_work completion list, under ->uring_lock */
293 struct list_head free_list;
294 /* IRQ completion list, under ->completion_lock */
295 struct list_head locked_free_list;
298 struct io_submit_link {
299 struct io_kiocb *head;
300 struct io_kiocb *last;
303 struct io_submit_state {
304 struct blk_plug plug;
305 struct io_submit_link link;
308 * io_kiocb alloc cache
310 void *reqs[IO_REQ_CACHE_SIZE];
311 unsigned int free_reqs;
316 * Batch completion logic
318 struct io_comp_state comp;
321 * File reference cache
325 unsigned int file_refs;
326 unsigned int ios_left;
331 struct percpu_ref refs;
332 } ____cacheline_aligned_in_smp;
336 unsigned int compat: 1;
337 unsigned int cq_overflow_flushed: 1;
338 unsigned int drain_next: 1;
339 unsigned int eventfd_async: 1;
340 unsigned int restricted: 1;
341 unsigned int sqo_dead: 1;
342 unsigned int sqo_exec: 1;
345 * Ring buffer of indices into array of io_uring_sqe, which is
346 * mmapped by the application using the IORING_OFF_SQES offset.
348 * This indirection could e.g. be used to assign fixed
349 * io_uring_sqe entries to operations and only submit them to
350 * the queue when needed.
352 * The kernel modifies neither the indices array nor the entries
356 unsigned cached_sq_head;
359 unsigned sq_thread_idle;
360 unsigned cached_sq_dropped;
361 unsigned cached_cq_overflow;
362 unsigned long sq_check_overflow;
364 /* hashed buffered write serialization */
365 struct io_wq_hash *hash_map;
367 struct list_head defer_list;
368 struct list_head timeout_list;
369 struct list_head cq_overflow_list;
371 struct io_uring_sqe *sq_sqes;
372 } ____cacheline_aligned_in_smp;
375 struct mutex uring_lock;
376 wait_queue_head_t wait;
377 } ____cacheline_aligned_in_smp;
379 struct io_submit_state submit_state;
381 struct io_rings *rings;
386 struct task_struct *sqo_task;
388 /* Only used for accounting purposes */
389 struct mm_struct *mm_account;
391 struct io_sq_data *sq_data; /* if using sq thread polling */
393 struct wait_queue_head sqo_sq_wait;
394 struct list_head sqd_list;
397 * If used, fixed file set. Writers must ensure that ->refs is dead,
398 * readers must ensure that ->refs is alive as long as the file* is
399 * used. Only updated through io_uring_register(2).
401 struct fixed_rsrc_data *file_data;
402 unsigned nr_user_files;
404 /* if used, fixed mapped user buffers */
405 unsigned nr_user_bufs;
406 struct io_mapped_ubuf *user_bufs;
408 struct user_struct *user;
410 struct completion ref_comp;
411 struct completion sq_thread_comp;
413 #if defined(CONFIG_UNIX)
414 struct socket *ring_sock;
417 struct idr io_buffer_idr;
419 struct idr personality_idr;
422 unsigned cached_cq_tail;
425 atomic_t cq_timeouts;
426 unsigned cq_last_tm_flush;
427 unsigned long cq_check_overflow;
428 struct wait_queue_head cq_wait;
429 struct fasync_struct *cq_fasync;
430 struct eventfd_ctx *cq_ev_fd;
431 } ____cacheline_aligned_in_smp;
434 spinlock_t completion_lock;
437 * ->iopoll_list is protected by the ctx->uring_lock for
438 * io_uring instances that don't use IORING_SETUP_SQPOLL.
439 * For SQPOLL, only the single threaded io_sq_thread() will
440 * manipulate the list, hence no extra locking is needed there.
442 struct list_head iopoll_list;
443 struct hlist_head *cancel_hash;
444 unsigned cancel_hash_bits;
445 bool poll_multi_file;
447 spinlock_t inflight_lock;
448 struct list_head inflight_list;
449 } ____cacheline_aligned_in_smp;
451 struct delayed_work rsrc_put_work;
452 struct llist_head rsrc_put_llist;
453 struct list_head rsrc_ref_list;
454 spinlock_t rsrc_ref_lock;
456 struct io_restriction restrictions;
459 struct callback_head *exit_task_work;
461 struct wait_queue_head hash_wait;
463 /* Keep this last, we don't need it for the fast path */
464 struct work_struct exit_work;
468 * First field must be the file pointer in all the
469 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
471 struct io_poll_iocb {
473 struct wait_queue_head *head;
477 struct wait_queue_entry wait;
480 struct io_poll_remove {
490 struct io_timeout_data {
491 struct io_kiocb *req;
492 struct hrtimer timer;
493 struct timespec64 ts;
494 enum hrtimer_mode mode;
499 struct sockaddr __user *addr;
500 int __user *addr_len;
502 unsigned long nofile;
522 struct list_head list;
523 /* head of the link, used by linked timeouts only */
524 struct io_kiocb *head;
527 struct io_timeout_rem {
532 struct timespec64 ts;
537 /* NOTE: kiocb has the file as the first member, so don't do it here */
545 struct sockaddr __user *addr;
552 struct user_msghdr __user *umsg;
558 struct io_buffer *kbuf;
564 struct filename *filename;
566 unsigned long nofile;
569 struct io_rsrc_update {
595 struct epoll_event event;
599 struct file *file_out;
600 struct file *file_in;
607 struct io_provide_buf {
621 const char __user *filename;
622 struct statx __user *buffer;
634 struct filename *oldpath;
635 struct filename *newpath;
643 struct filename *filename;
646 struct io_completion {
648 struct list_head list;
652 struct io_async_connect {
653 struct sockaddr_storage address;
656 struct io_async_msghdr {
657 struct iovec fast_iov[UIO_FASTIOV];
658 /* points to an allocated iov, if NULL we use fast_iov instead */
659 struct iovec *free_iov;
660 struct sockaddr __user *uaddr;
662 struct sockaddr_storage addr;
666 struct iovec fast_iov[UIO_FASTIOV];
667 const struct iovec *free_iovec;
668 struct iov_iter iter;
670 struct wait_page_queue wpq;
674 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
675 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
676 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
677 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
678 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
679 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
685 REQ_F_LINK_TIMEOUT_BIT,
687 REQ_F_NEED_CLEANUP_BIT,
689 REQ_F_BUFFER_SELECTED_BIT,
690 REQ_F_NO_FILE_TABLE_BIT,
691 REQ_F_WORK_INITIALIZED_BIT,
692 REQ_F_LTIMEOUT_ACTIVE_BIT,
693 REQ_F_COMPLETE_INLINE_BIT,
695 /* not a real bit, just to check we're not overflowing the space */
701 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
702 /* drain existing IO first */
703 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
705 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
706 /* doesn't sever on completion < 0 */
707 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
709 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
710 /* IOSQE_BUFFER_SELECT */
711 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
713 /* fail rest of links */
714 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
715 /* on inflight list */
716 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
717 /* read/write uses file position */
718 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
719 /* must not punt to workers */
720 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
721 /* has or had linked timeout */
722 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
724 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
726 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
727 /* already went through poll handler */
728 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
729 /* buffer already selected */
730 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
731 /* doesn't need file table for this request */
732 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
733 /* io_wq_work is initialized */
734 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
735 /* linked timeout is active, i.e. prepared by link's head */
736 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
737 /* completion is deferred through io_comp_state */
738 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
742 struct io_poll_iocb poll;
743 struct io_poll_iocb *double_poll;
746 struct io_task_work {
747 struct io_wq_work_node node;
748 task_work_func_t func;
752 * NOTE! Each of the iocb union members has the file pointer
753 * as the first entry in their struct definition. So you can
754 * access the file pointer through any of the sub-structs,
755 * or directly as just 'ki_filp' in this struct.
761 struct io_poll_iocb poll;
762 struct io_poll_remove poll_remove;
763 struct io_accept accept;
765 struct io_cancel cancel;
766 struct io_timeout timeout;
767 struct io_timeout_rem timeout_rem;
768 struct io_connect connect;
769 struct io_sr_msg sr_msg;
771 struct io_close close;
772 struct io_rsrc_update rsrc_update;
773 struct io_fadvise fadvise;
774 struct io_madvise madvise;
775 struct io_epoll epoll;
776 struct io_splice splice;
777 struct io_provide_buf pbuf;
778 struct io_statx statx;
779 struct io_shutdown shutdown;
780 struct io_rename rename;
781 struct io_unlink unlink;
782 /* use only after cleaning per-op data, see io_clean_op() */
783 struct io_completion compl;
786 /* opcode allocated if it needs to store data for async defer */
789 /* polled IO has completed */
795 struct io_ring_ctx *ctx;
798 struct task_struct *task;
801 struct io_kiocb *link;
802 struct percpu_ref *fixed_rsrc_refs;
805 * 1. used with ctx->iopoll_list with reads/writes
806 * 2. to track reqs with ->files (see io_op_def::file_table)
808 struct list_head inflight_entry;
810 struct io_task_work io_task_work;
811 struct callback_head task_work;
813 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
814 struct hlist_node hash_node;
815 struct async_poll *apoll;
816 struct io_wq_work work;
819 struct io_defer_entry {
820 struct list_head list;
821 struct io_kiocb *req;
826 /* needs req->file assigned */
827 unsigned needs_file : 1;
828 /* hash wq insertion if file is a regular file */
829 unsigned hash_reg_file : 1;
830 /* unbound wq insertion if file is a non-regular file */
831 unsigned unbound_nonreg_file : 1;
832 /* opcode is not supported by this kernel */
833 unsigned not_supported : 1;
834 /* set if opcode supports polled "wait" */
836 unsigned pollout : 1;
837 /* op supports buffer selection */
838 unsigned buffer_select : 1;
839 /* must always have async data allocated */
840 unsigned needs_async_data : 1;
841 /* should block plug */
843 /* size of async data needed, if any */
844 unsigned short async_size;
847 static const struct io_op_def io_op_defs[] = {
848 [IORING_OP_NOP] = {},
849 [IORING_OP_READV] = {
851 .unbound_nonreg_file = 1,
854 .needs_async_data = 1,
856 .async_size = sizeof(struct io_async_rw),
858 [IORING_OP_WRITEV] = {
861 .unbound_nonreg_file = 1,
863 .needs_async_data = 1,
865 .async_size = sizeof(struct io_async_rw),
867 [IORING_OP_FSYNC] = {
870 [IORING_OP_READ_FIXED] = {
872 .unbound_nonreg_file = 1,
875 .async_size = sizeof(struct io_async_rw),
877 [IORING_OP_WRITE_FIXED] = {
880 .unbound_nonreg_file = 1,
883 .async_size = sizeof(struct io_async_rw),
885 [IORING_OP_POLL_ADD] = {
887 .unbound_nonreg_file = 1,
889 [IORING_OP_POLL_REMOVE] = {},
890 [IORING_OP_SYNC_FILE_RANGE] = {
893 [IORING_OP_SENDMSG] = {
895 .unbound_nonreg_file = 1,
897 .needs_async_data = 1,
898 .async_size = sizeof(struct io_async_msghdr),
900 [IORING_OP_RECVMSG] = {
902 .unbound_nonreg_file = 1,
905 .needs_async_data = 1,
906 .async_size = sizeof(struct io_async_msghdr),
908 [IORING_OP_TIMEOUT] = {
909 .needs_async_data = 1,
910 .async_size = sizeof(struct io_timeout_data),
912 [IORING_OP_TIMEOUT_REMOVE] = {
913 /* used by timeout updates' prep() */
915 [IORING_OP_ACCEPT] = {
917 .unbound_nonreg_file = 1,
920 [IORING_OP_ASYNC_CANCEL] = {},
921 [IORING_OP_LINK_TIMEOUT] = {
922 .needs_async_data = 1,
923 .async_size = sizeof(struct io_timeout_data),
925 [IORING_OP_CONNECT] = {
927 .unbound_nonreg_file = 1,
929 .needs_async_data = 1,
930 .async_size = sizeof(struct io_async_connect),
932 [IORING_OP_FALLOCATE] = {
935 [IORING_OP_OPENAT] = {},
936 [IORING_OP_CLOSE] = {},
937 [IORING_OP_FILES_UPDATE] = {},
938 [IORING_OP_STATX] = {},
941 .unbound_nonreg_file = 1,
945 .async_size = sizeof(struct io_async_rw),
947 [IORING_OP_WRITE] = {
949 .unbound_nonreg_file = 1,
952 .async_size = sizeof(struct io_async_rw),
954 [IORING_OP_FADVISE] = {
957 [IORING_OP_MADVISE] = {},
960 .unbound_nonreg_file = 1,
965 .unbound_nonreg_file = 1,
969 [IORING_OP_OPENAT2] = {
971 [IORING_OP_EPOLL_CTL] = {
972 .unbound_nonreg_file = 1,
974 [IORING_OP_SPLICE] = {
977 .unbound_nonreg_file = 1,
979 [IORING_OP_PROVIDE_BUFFERS] = {},
980 [IORING_OP_REMOVE_BUFFERS] = {},
984 .unbound_nonreg_file = 1,
986 [IORING_OP_SHUTDOWN] = {
989 [IORING_OP_RENAMEAT] = {},
990 [IORING_OP_UNLINKAT] = {},
993 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
994 struct task_struct *task,
995 struct files_struct *files);
996 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
997 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
998 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
999 struct io_ring_ctx *ctx);
1000 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
1002 static bool io_rw_reissue(struct io_kiocb *req);
1003 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1004 static void io_put_req(struct io_kiocb *req);
1005 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1006 static void io_double_put_req(struct io_kiocb *req);
1007 static void io_dismantle_req(struct io_kiocb *req);
1008 static void io_put_task(struct task_struct *task, int nr);
1009 static void io_queue_next(struct io_kiocb *req);
1010 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1011 static void __io_queue_linked_timeout(struct io_kiocb *req);
1012 static void io_queue_linked_timeout(struct io_kiocb *req);
1013 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1014 struct io_uring_rsrc_update *ip,
1016 static void __io_clean_op(struct io_kiocb *req);
1017 static struct file *io_file_get(struct io_submit_state *state,
1018 struct io_kiocb *req, int fd, bool fixed);
1019 static void __io_queue_sqe(struct io_kiocb *req);
1020 static void io_rsrc_put_work(struct work_struct *work);
1022 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1023 struct iov_iter *iter, bool needs_lock);
1024 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1025 const struct iovec *fast_iov,
1026 struct iov_iter *iter, bool force);
1027 static void io_req_task_queue(struct io_kiocb *req);
1028 static void io_submit_flush_completions(struct io_comp_state *cs,
1029 struct io_ring_ctx *ctx);
1031 static struct kmem_cache *req_cachep;
1033 static const struct file_operations io_uring_fops;
1035 struct sock *io_uring_get_socket(struct file *file)
1037 #if defined(CONFIG_UNIX)
1038 if (file->f_op == &io_uring_fops) {
1039 struct io_ring_ctx *ctx = file->private_data;
1041 return ctx->ring_sock->sk;
1046 EXPORT_SYMBOL(io_uring_get_socket);
1048 #define io_for_each_link(pos, head) \
1049 for (pos = (head); pos; pos = pos->link)
1051 static inline void io_clean_op(struct io_kiocb *req)
1053 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1057 static inline void io_set_resource_node(struct io_kiocb *req)
1059 struct io_ring_ctx *ctx = req->ctx;
1061 if (!req->fixed_rsrc_refs) {
1062 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1063 percpu_ref_get(req->fixed_rsrc_refs);
1067 static bool io_match_task(struct io_kiocb *head,
1068 struct task_struct *task,
1069 struct files_struct *files)
1071 struct io_kiocb *req;
1073 if (task && head->task != task) {
1074 /* in terms of cancelation, always match if req task is dead */
1075 if (head->task->flags & PF_EXITING)
1082 io_for_each_link(req, head) {
1083 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1085 if (req->file && req->file->f_op == &io_uring_fops)
1087 if (req->task->files == files)
1093 static inline void req_set_fail_links(struct io_kiocb *req)
1095 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1096 req->flags |= REQ_F_FAIL_LINK;
1099 static inline void __io_req_init_async(struct io_kiocb *req)
1101 memset(&req->work, 0, sizeof(req->work));
1102 req->flags |= REQ_F_WORK_INITIALIZED;
1106 * Note: must call io_req_init_async() for the first time you
1107 * touch any members of io_wq_work.
1109 static inline void io_req_init_async(struct io_kiocb *req)
1111 if (req->flags & REQ_F_WORK_INITIALIZED)
1114 __io_req_init_async(req);
1117 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1119 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1121 complete(&ctx->ref_comp);
1124 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1126 return !req->timeout.off;
1129 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1131 struct io_ring_ctx *ctx;
1134 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1139 * Use 5 bits less than the max cq entries, that should give us around
1140 * 32 entries per hash list if totally full and uniformly spread.
1142 hash_bits = ilog2(p->cq_entries);
1146 ctx->cancel_hash_bits = hash_bits;
1147 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1149 if (!ctx->cancel_hash)
1151 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1153 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1154 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1157 ctx->flags = p->flags;
1158 init_waitqueue_head(&ctx->sqo_sq_wait);
1159 INIT_LIST_HEAD(&ctx->sqd_list);
1160 init_waitqueue_head(&ctx->cq_wait);
1161 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1162 init_completion(&ctx->ref_comp);
1163 init_completion(&ctx->sq_thread_comp);
1164 idr_init(&ctx->io_buffer_idr);
1165 idr_init(&ctx->personality_idr);
1166 mutex_init(&ctx->uring_lock);
1167 init_waitqueue_head(&ctx->wait);
1168 spin_lock_init(&ctx->completion_lock);
1169 INIT_LIST_HEAD(&ctx->iopoll_list);
1170 INIT_LIST_HEAD(&ctx->defer_list);
1171 INIT_LIST_HEAD(&ctx->timeout_list);
1172 spin_lock_init(&ctx->inflight_lock);
1173 INIT_LIST_HEAD(&ctx->inflight_list);
1174 spin_lock_init(&ctx->rsrc_ref_lock);
1175 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1176 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1177 init_llist_head(&ctx->rsrc_put_llist);
1178 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1179 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1182 kfree(ctx->cancel_hash);
1187 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1189 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1190 struct io_ring_ctx *ctx = req->ctx;
1192 return seq != ctx->cached_cq_tail
1193 + READ_ONCE(ctx->cached_cq_overflow);
1199 static void io_req_clean_work(struct io_kiocb *req)
1201 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1204 if (req->work.creds) {
1205 put_cred(req->work.creds);
1206 req->work.creds = NULL;
1208 if (req->flags & REQ_F_INFLIGHT) {
1209 struct io_ring_ctx *ctx = req->ctx;
1210 struct io_uring_task *tctx = req->task->io_uring;
1211 unsigned long flags;
1213 spin_lock_irqsave(&ctx->inflight_lock, flags);
1214 list_del(&req->inflight_entry);
1215 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1216 req->flags &= ~REQ_F_INFLIGHT;
1217 if (atomic_read(&tctx->in_idle))
1218 wake_up(&tctx->wait);
1221 req->flags &= ~REQ_F_WORK_INITIALIZED;
1224 static void io_req_track_inflight(struct io_kiocb *req)
1226 struct io_ring_ctx *ctx = req->ctx;
1228 if (!(req->flags & REQ_F_INFLIGHT)) {
1229 io_req_init_async(req);
1230 req->flags |= REQ_F_INFLIGHT;
1232 spin_lock_irq(&ctx->inflight_lock);
1233 list_add(&req->inflight_entry, &ctx->inflight_list);
1234 spin_unlock_irq(&ctx->inflight_lock);
1238 static void io_prep_async_work(struct io_kiocb *req)
1240 const struct io_op_def *def = &io_op_defs[req->opcode];
1241 struct io_ring_ctx *ctx = req->ctx;
1243 io_req_init_async(req);
1245 if (req->flags & REQ_F_FORCE_ASYNC)
1246 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1248 if (req->flags & REQ_F_ISREG) {
1249 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1250 io_wq_hash_work(&req->work, file_inode(req->file));
1252 if (def->unbound_nonreg_file)
1253 req->work.flags |= IO_WQ_WORK_UNBOUND;
1255 if (!req->work.creds)
1256 req->work.creds = get_current_cred();
1259 static void io_prep_async_link(struct io_kiocb *req)
1261 struct io_kiocb *cur;
1263 io_for_each_link(cur, req)
1264 io_prep_async_work(cur);
1267 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1269 struct io_ring_ctx *ctx = req->ctx;
1270 struct io_kiocb *link = io_prep_linked_timeout(req);
1271 struct io_uring_task *tctx = req->task->io_uring;
1274 BUG_ON(!tctx->io_wq);
1276 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1277 &req->work, req->flags);
1278 io_wq_enqueue(tctx->io_wq, &req->work);
1282 static void io_queue_async_work(struct io_kiocb *req)
1284 struct io_kiocb *link;
1286 /* init ->work of the whole link before punting */
1287 io_prep_async_link(req);
1288 link = __io_queue_async_work(req);
1291 io_queue_linked_timeout(link);
1294 static void io_kill_timeout(struct io_kiocb *req)
1296 struct io_timeout_data *io = req->async_data;
1299 ret = hrtimer_try_to_cancel(&io->timer);
1301 atomic_set(&req->ctx->cq_timeouts,
1302 atomic_read(&req->ctx->cq_timeouts) + 1);
1303 list_del_init(&req->timeout.list);
1304 io_cqring_fill_event(req, 0);
1305 io_put_req_deferred(req, 1);
1310 * Returns true if we found and killed one or more timeouts
1312 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1313 struct files_struct *files)
1315 struct io_kiocb *req, *tmp;
1318 spin_lock_irq(&ctx->completion_lock);
1319 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1320 if (io_match_task(req, tsk, files)) {
1321 io_kill_timeout(req);
1325 spin_unlock_irq(&ctx->completion_lock);
1326 return canceled != 0;
1329 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1332 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1333 struct io_defer_entry, list);
1335 if (req_need_defer(de->req, de->seq))
1337 list_del_init(&de->list);
1338 io_req_task_queue(de->req);
1340 } while (!list_empty(&ctx->defer_list));
1343 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1347 if (list_empty(&ctx->timeout_list))
1350 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1353 u32 events_needed, events_got;
1354 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1355 struct io_kiocb, timeout.list);
1357 if (io_is_timeout_noseq(req))
1361 * Since seq can easily wrap around over time, subtract
1362 * the last seq at which timeouts were flushed before comparing.
1363 * Assuming not more than 2^31-1 events have happened since,
1364 * these subtractions won't have wrapped, so we can check if
1365 * target is in [last_seq, current_seq] by comparing the two.
1367 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1368 events_got = seq - ctx->cq_last_tm_flush;
1369 if (events_got < events_needed)
1372 list_del_init(&req->timeout.list);
1373 io_kill_timeout(req);
1374 } while (!list_empty(&ctx->timeout_list));
1376 ctx->cq_last_tm_flush = seq;
1379 static void io_commit_cqring(struct io_ring_ctx *ctx)
1381 io_flush_timeouts(ctx);
1383 /* order cqe stores with ring update */
1384 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1386 if (unlikely(!list_empty(&ctx->defer_list)))
1387 __io_queue_deferred(ctx);
1390 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1392 struct io_rings *r = ctx->rings;
1394 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1397 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1399 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1402 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1404 struct io_rings *rings = ctx->rings;
1408 * writes to the cq entry need to come after reading head; the
1409 * control dependency is enough as we're using WRITE_ONCE to
1412 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1415 tail = ctx->cached_cq_tail++;
1416 return &rings->cqes[tail & ctx->cq_mask];
1419 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1423 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1425 if (!ctx->eventfd_async)
1427 return io_wq_current_is_worker();
1430 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1432 /* see waitqueue_active() comment */
1435 if (waitqueue_active(&ctx->wait))
1436 wake_up(&ctx->wait);
1437 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1438 wake_up(&ctx->sq_data->wait);
1439 if (io_should_trigger_evfd(ctx))
1440 eventfd_signal(ctx->cq_ev_fd, 1);
1441 if (waitqueue_active(&ctx->cq_wait)) {
1442 wake_up_interruptible(&ctx->cq_wait);
1443 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1447 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1449 /* see waitqueue_active() comment */
1452 if (ctx->flags & IORING_SETUP_SQPOLL) {
1453 if (waitqueue_active(&ctx->wait))
1454 wake_up(&ctx->wait);
1456 if (io_should_trigger_evfd(ctx))
1457 eventfd_signal(ctx->cq_ev_fd, 1);
1458 if (waitqueue_active(&ctx->cq_wait)) {
1459 wake_up_interruptible(&ctx->cq_wait);
1460 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1464 /* Returns true if there are no backlogged entries after the flush */
1465 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1466 struct task_struct *tsk,
1467 struct files_struct *files)
1469 struct io_rings *rings = ctx->rings;
1470 struct io_kiocb *req, *tmp;
1471 struct io_uring_cqe *cqe;
1472 unsigned long flags;
1473 bool all_flushed, posted;
1476 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1480 spin_lock_irqsave(&ctx->completion_lock, flags);
1481 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1482 if (!io_match_task(req, tsk, files))
1485 cqe = io_get_cqring(ctx);
1489 list_move(&req->compl.list, &list);
1491 WRITE_ONCE(cqe->user_data, req->user_data);
1492 WRITE_ONCE(cqe->res, req->result);
1493 WRITE_ONCE(cqe->flags, req->compl.cflags);
1495 ctx->cached_cq_overflow++;
1496 WRITE_ONCE(ctx->rings->cq_overflow,
1497 ctx->cached_cq_overflow);
1502 all_flushed = list_empty(&ctx->cq_overflow_list);
1504 clear_bit(0, &ctx->sq_check_overflow);
1505 clear_bit(0, &ctx->cq_check_overflow);
1506 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1510 io_commit_cqring(ctx);
1511 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1513 io_cqring_ev_posted(ctx);
1515 while (!list_empty(&list)) {
1516 req = list_first_entry(&list, struct io_kiocb, compl.list);
1517 list_del(&req->compl.list);
1524 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1525 struct task_struct *tsk,
1526 struct files_struct *files)
1528 if (test_bit(0, &ctx->cq_check_overflow)) {
1529 /* iopoll syncs against uring_lock, not completion_lock */
1530 if (ctx->flags & IORING_SETUP_IOPOLL)
1531 mutex_lock(&ctx->uring_lock);
1532 __io_cqring_overflow_flush(ctx, force, tsk, files);
1533 if (ctx->flags & IORING_SETUP_IOPOLL)
1534 mutex_unlock(&ctx->uring_lock);
1538 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1540 struct io_ring_ctx *ctx = req->ctx;
1541 struct io_uring_cqe *cqe;
1543 trace_io_uring_complete(ctx, req->user_data, res);
1546 * If we can't get a cq entry, userspace overflowed the
1547 * submission (by quite a lot). Increment the overflow count in
1550 cqe = io_get_cqring(ctx);
1552 WRITE_ONCE(cqe->user_data, req->user_data);
1553 WRITE_ONCE(cqe->res, res);
1554 WRITE_ONCE(cqe->flags, cflags);
1555 } else if (ctx->cq_overflow_flushed ||
1556 atomic_read(&req->task->io_uring->in_idle)) {
1558 * If we're in ring overflow flush mode, or in task cancel mode,
1559 * then we cannot store the request for later flushing, we need
1560 * to drop it on the floor.
1562 ctx->cached_cq_overflow++;
1563 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1565 if (list_empty(&ctx->cq_overflow_list)) {
1566 set_bit(0, &ctx->sq_check_overflow);
1567 set_bit(0, &ctx->cq_check_overflow);
1568 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1572 req->compl.cflags = cflags;
1573 refcount_inc(&req->refs);
1574 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1578 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1580 __io_cqring_fill_event(req, res, 0);
1583 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1584 unsigned int cflags)
1586 struct io_ring_ctx *ctx = req->ctx;
1587 unsigned long flags;
1589 spin_lock_irqsave(&ctx->completion_lock, flags);
1590 __io_cqring_fill_event(req, res, cflags);
1591 io_commit_cqring(ctx);
1593 * If we're the last reference to this request, add to our locked
1596 if (refcount_dec_and_test(&req->refs)) {
1597 struct io_comp_state *cs = &ctx->submit_state.comp;
1599 io_dismantle_req(req);
1600 io_put_task(req->task, 1);
1601 list_add(&req->compl.list, &cs->locked_free_list);
1602 cs->locked_free_nr++;
1605 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1607 io_cqring_ev_posted(ctx);
1610 percpu_ref_put(&ctx->refs);
1614 static void io_req_complete_state(struct io_kiocb *req, long res,
1615 unsigned int cflags)
1619 req->compl.cflags = cflags;
1620 req->flags |= REQ_F_COMPLETE_INLINE;
1623 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1624 long res, unsigned cflags)
1626 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1627 io_req_complete_state(req, res, cflags);
1629 io_req_complete_post(req, res, cflags);
1632 static inline void io_req_complete(struct io_kiocb *req, long res)
1634 __io_req_complete(req, 0, res, 0);
1637 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1639 struct io_submit_state *state = &ctx->submit_state;
1640 struct io_comp_state *cs = &state->comp;
1641 struct io_kiocb *req = NULL;
1644 * If we have more than a batch's worth of requests in our IRQ side
1645 * locked cache, grab the lock and move them over to our submission
1648 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1649 spin_lock_irq(&ctx->completion_lock);
1650 list_splice_init(&cs->locked_free_list, &cs->free_list);
1651 cs->locked_free_nr = 0;
1652 spin_unlock_irq(&ctx->completion_lock);
1655 while (!list_empty(&cs->free_list)) {
1656 req = list_first_entry(&cs->free_list, struct io_kiocb,
1658 list_del(&req->compl.list);
1659 state->reqs[state->free_reqs++] = req;
1660 if (state->free_reqs == ARRAY_SIZE(state->reqs))
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 io_kiocb *req, struct file *file,
1707 static void io_dismantle_req(struct io_kiocb *req)
1711 if (req->async_data)
1712 kfree(req->async_data);
1714 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1715 if (req->fixed_rsrc_refs)
1716 percpu_ref_put(req->fixed_rsrc_refs);
1717 io_req_clean_work(req);
1720 static inline void io_put_task(struct task_struct *task, int nr)
1722 struct io_uring_task *tctx = task->io_uring;
1724 percpu_counter_sub(&tctx->inflight, nr);
1725 if (unlikely(atomic_read(&tctx->in_idle)))
1726 wake_up(&tctx->wait);
1727 put_task_struct_many(task, nr);
1730 static void __io_free_req(struct io_kiocb *req)
1732 struct io_ring_ctx *ctx = req->ctx;
1734 io_dismantle_req(req);
1735 io_put_task(req->task, 1);
1737 kmem_cache_free(req_cachep, req);
1738 percpu_ref_put(&ctx->refs);
1741 static inline void io_remove_next_linked(struct io_kiocb *req)
1743 struct io_kiocb *nxt = req->link;
1745 req->link = nxt->link;
1749 static void io_kill_linked_timeout(struct io_kiocb *req)
1751 struct io_ring_ctx *ctx = req->ctx;
1752 struct io_kiocb *link;
1753 bool cancelled = false;
1754 unsigned long flags;
1756 spin_lock_irqsave(&ctx->completion_lock, flags);
1760 * Can happen if a linked timeout fired and link had been like
1761 * req -> link t-out -> link t-out [-> ...]
1763 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1764 struct io_timeout_data *io = link->async_data;
1767 io_remove_next_linked(req);
1768 link->timeout.head = NULL;
1769 ret = hrtimer_try_to_cancel(&io->timer);
1771 io_cqring_fill_event(link, -ECANCELED);
1772 io_commit_cqring(ctx);
1776 req->flags &= ~REQ_F_LINK_TIMEOUT;
1777 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1780 io_cqring_ev_posted(ctx);
1786 static void io_fail_links(struct io_kiocb *req)
1788 struct io_kiocb *link, *nxt;
1789 struct io_ring_ctx *ctx = req->ctx;
1790 unsigned long flags;
1792 spin_lock_irqsave(&ctx->completion_lock, flags);
1800 trace_io_uring_fail_link(req, link);
1801 io_cqring_fill_event(link, -ECANCELED);
1804 * It's ok to free under spinlock as they're not linked anymore,
1805 * but avoid REQ_F_WORK_INITIALIZED because it may deadlock on
1808 if (link->flags & REQ_F_WORK_INITIALIZED)
1809 io_put_req_deferred(link, 2);
1811 io_double_put_req(link);
1814 io_commit_cqring(ctx);
1815 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1817 io_cqring_ev_posted(ctx);
1820 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1822 if (req->flags & REQ_F_LINK_TIMEOUT)
1823 io_kill_linked_timeout(req);
1826 * If LINK is set, we have dependent requests in this chain. If we
1827 * didn't fail this request, queue the first one up, moving any other
1828 * dependencies to the next request. In case of failure, fail the rest
1831 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
1832 struct io_kiocb *nxt = req->link;
1841 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1843 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1845 return __io_req_find_next(req);
1848 static bool __tctx_task_work(struct io_uring_task *tctx)
1850 struct io_ring_ctx *ctx = NULL;
1851 struct io_wq_work_list list;
1852 struct io_wq_work_node *node;
1854 if (wq_list_empty(&tctx->task_list))
1857 spin_lock_irq(&tctx->task_lock);
1858 list = tctx->task_list;
1859 INIT_WQ_LIST(&tctx->task_list);
1860 spin_unlock_irq(&tctx->task_lock);
1864 struct io_wq_work_node *next = node->next;
1865 struct io_ring_ctx *this_ctx;
1866 struct io_kiocb *req;
1868 req = container_of(node, struct io_kiocb, io_task_work.node);
1869 this_ctx = req->ctx;
1870 req->task_work.func(&req->task_work);
1875 } else if (ctx != this_ctx) {
1876 mutex_lock(&ctx->uring_lock);
1877 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1878 mutex_unlock(&ctx->uring_lock);
1883 if (ctx && ctx->submit_state.comp.nr) {
1884 mutex_lock(&ctx->uring_lock);
1885 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1886 mutex_unlock(&ctx->uring_lock);
1889 return list.first != NULL;
1892 static void tctx_task_work(struct callback_head *cb)
1894 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1896 while (__tctx_task_work(tctx))
1899 clear_bit(0, &tctx->task_state);
1902 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1903 enum task_work_notify_mode notify)
1905 struct io_uring_task *tctx = tsk->io_uring;
1906 struct io_wq_work_node *node, *prev;
1907 unsigned long flags;
1910 WARN_ON_ONCE(!tctx);
1912 spin_lock_irqsave(&tctx->task_lock, flags);
1913 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1914 spin_unlock_irqrestore(&tctx->task_lock, flags);
1916 /* task_work already pending, we're done */
1917 if (test_bit(0, &tctx->task_state) ||
1918 test_and_set_bit(0, &tctx->task_state))
1921 if (!task_work_add(tsk, &tctx->task_work, notify))
1925 * Slow path - we failed, find and delete work. if the work is not
1926 * in the list, it got run and we're fine.
1929 spin_lock_irqsave(&tctx->task_lock, flags);
1930 wq_list_for_each(node, prev, &tctx->task_list) {
1931 if (&req->io_task_work.node == node) {
1932 wq_list_del(&tctx->task_list, node, prev);
1937 spin_unlock_irqrestore(&tctx->task_lock, flags);
1938 clear_bit(0, &tctx->task_state);
1942 static int io_req_task_work_add(struct io_kiocb *req)
1944 struct task_struct *tsk = req->task;
1945 struct io_ring_ctx *ctx = req->ctx;
1946 enum task_work_notify_mode notify;
1949 if (tsk->flags & PF_EXITING)
1953 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1954 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1955 * processing task_work. There's no reliable way to tell if TWA_RESUME
1959 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1960 notify = TWA_SIGNAL;
1962 ret = io_task_work_add(tsk, req, notify);
1964 wake_up_process(tsk);
1969 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1970 task_work_func_t cb)
1972 struct io_ring_ctx *ctx = req->ctx;
1973 struct callback_head *head;
1975 init_task_work(&req->task_work, cb);
1977 head = READ_ONCE(ctx->exit_task_work);
1978 req->task_work.next = head;
1979 } while (cmpxchg(&ctx->exit_task_work, head, &req->task_work) != head);
1982 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1984 struct io_ring_ctx *ctx = req->ctx;
1986 spin_lock_irq(&ctx->completion_lock);
1987 io_cqring_fill_event(req, error);
1988 io_commit_cqring(ctx);
1989 spin_unlock_irq(&ctx->completion_lock);
1991 io_cqring_ev_posted(ctx);
1992 req_set_fail_links(req);
1993 io_double_put_req(req);
1996 static void io_req_task_cancel(struct callback_head *cb)
1998 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1999 struct io_ring_ctx *ctx = req->ctx;
2001 mutex_lock(&ctx->uring_lock);
2002 __io_req_task_cancel(req, req->result);
2003 mutex_unlock(&ctx->uring_lock);
2004 percpu_ref_put(&ctx->refs);
2007 static void __io_req_task_submit(struct io_kiocb *req)
2009 struct io_ring_ctx *ctx = req->ctx;
2011 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2012 mutex_lock(&ctx->uring_lock);
2013 if (!ctx->sqo_dead && !(current->flags & PF_EXITING) && !current->in_execve)
2014 __io_queue_sqe(req);
2016 __io_req_task_cancel(req, -EFAULT);
2017 mutex_unlock(&ctx->uring_lock);
2020 static void io_req_task_submit(struct callback_head *cb)
2022 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2024 __io_req_task_submit(req);
2027 static void io_req_task_queue(struct io_kiocb *req)
2031 req->task_work.func = io_req_task_submit;
2032 ret = io_req_task_work_add(req);
2033 if (unlikely(ret)) {
2034 req->result = -ECANCELED;
2035 percpu_ref_get(&req->ctx->refs);
2036 io_req_task_work_add_fallback(req, io_req_task_cancel);
2040 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2042 percpu_ref_get(&req->ctx->refs);
2044 req->task_work.func = io_req_task_cancel;
2046 if (unlikely(io_req_task_work_add(req)))
2047 io_req_task_work_add_fallback(req, io_req_task_cancel);
2050 static inline void io_queue_next(struct io_kiocb *req)
2052 struct io_kiocb *nxt = io_req_find_next(req);
2055 io_req_task_queue(nxt);
2058 static void io_free_req(struct io_kiocb *req)
2065 struct task_struct *task;
2070 static inline void io_init_req_batch(struct req_batch *rb)
2077 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2078 struct req_batch *rb)
2081 io_put_task(rb->task, rb->task_refs);
2083 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2086 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2087 struct io_submit_state *state)
2091 if (req->task != rb->task) {
2093 io_put_task(rb->task, rb->task_refs);
2094 rb->task = req->task;
2100 io_dismantle_req(req);
2101 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2102 state->reqs[state->free_reqs++] = req;
2104 list_add(&req->compl.list, &state->comp.free_list);
2107 static void io_submit_flush_completions(struct io_comp_state *cs,
2108 struct io_ring_ctx *ctx)
2111 struct io_kiocb *req;
2112 struct req_batch rb;
2114 io_init_req_batch(&rb);
2115 spin_lock_irq(&ctx->completion_lock);
2116 for (i = 0; i < nr; i++) {
2118 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2120 io_commit_cqring(ctx);
2121 spin_unlock_irq(&ctx->completion_lock);
2123 io_cqring_ev_posted(ctx);
2124 for (i = 0; i < nr; i++) {
2127 /* submission and completion refs */
2128 if (refcount_sub_and_test(2, &req->refs))
2129 io_req_free_batch(&rb, req, &ctx->submit_state);
2132 io_req_free_batch_finish(ctx, &rb);
2137 * Drop reference to request, return next in chain (if there is one) if this
2138 * was the last reference to this request.
2140 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2142 struct io_kiocb *nxt = NULL;
2144 if (refcount_dec_and_test(&req->refs)) {
2145 nxt = io_req_find_next(req);
2151 static void io_put_req(struct io_kiocb *req)
2153 if (refcount_dec_and_test(&req->refs))
2157 static void io_put_req_deferred_cb(struct callback_head *cb)
2159 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2164 static void io_free_req_deferred(struct io_kiocb *req)
2168 req->task_work.func = io_put_req_deferred_cb;
2169 ret = io_req_task_work_add(req);
2171 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2174 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2176 if (refcount_sub_and_test(refs, &req->refs))
2177 io_free_req_deferred(req);
2180 static void io_double_put_req(struct io_kiocb *req)
2182 /* drop both submit and complete references */
2183 if (refcount_sub_and_test(2, &req->refs))
2187 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2189 /* See comment at the top of this file */
2191 return __io_cqring_events(ctx);
2194 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2196 struct io_rings *rings = ctx->rings;
2198 /* make sure SQ entry isn't read before tail */
2199 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2202 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2204 unsigned int cflags;
2206 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2207 cflags |= IORING_CQE_F_BUFFER;
2208 req->flags &= ~REQ_F_BUFFER_SELECTED;
2213 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2215 struct io_buffer *kbuf;
2217 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2218 return io_put_kbuf(req, kbuf);
2221 static inline bool io_run_task_work(void)
2224 * Not safe to run on exiting task, and the task_work handling will
2225 * not add work to such a task.
2227 if (unlikely(current->flags & PF_EXITING))
2229 if (current->task_works) {
2230 __set_current_state(TASK_RUNNING);
2239 * Find and free completed poll iocbs
2241 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2242 struct list_head *done)
2244 struct req_batch rb;
2245 struct io_kiocb *req;
2247 /* order with ->result store in io_complete_rw_iopoll() */
2250 io_init_req_batch(&rb);
2251 while (!list_empty(done)) {
2254 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2255 list_del(&req->inflight_entry);
2257 if (READ_ONCE(req->result) == -EAGAIN) {
2258 req->iopoll_completed = 0;
2259 if (io_rw_reissue(req))
2263 if (req->flags & REQ_F_BUFFER_SELECTED)
2264 cflags = io_put_rw_kbuf(req);
2266 __io_cqring_fill_event(req, req->result, cflags);
2269 if (refcount_dec_and_test(&req->refs))
2270 io_req_free_batch(&rb, req, &ctx->submit_state);
2273 io_commit_cqring(ctx);
2274 io_cqring_ev_posted_iopoll(ctx);
2275 io_req_free_batch_finish(ctx, &rb);
2278 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2281 struct io_kiocb *req, *tmp;
2287 * Only spin for completions if we don't have multiple devices hanging
2288 * off our complete list, and we're under the requested amount.
2290 spin = !ctx->poll_multi_file && *nr_events < min;
2293 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2294 struct kiocb *kiocb = &req->rw.kiocb;
2297 * Move completed and retryable entries to our local lists.
2298 * If we find a request that requires polling, break out
2299 * and complete those lists first, if we have entries there.
2301 if (READ_ONCE(req->iopoll_completed)) {
2302 list_move_tail(&req->inflight_entry, &done);
2305 if (!list_empty(&done))
2308 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2312 /* iopoll may have completed current req */
2313 if (READ_ONCE(req->iopoll_completed))
2314 list_move_tail(&req->inflight_entry, &done);
2321 if (!list_empty(&done))
2322 io_iopoll_complete(ctx, nr_events, &done);
2328 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2329 * non-spinning poll check - we'll still enter the driver poll loop, but only
2330 * as a non-spinning completion check.
2332 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2335 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2338 ret = io_do_iopoll(ctx, nr_events, min);
2341 if (*nr_events >= min)
2349 * We can't just wait for polled events to come to us, we have to actively
2350 * find and complete them.
2352 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2354 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2357 mutex_lock(&ctx->uring_lock);
2358 while (!list_empty(&ctx->iopoll_list)) {
2359 unsigned int nr_events = 0;
2361 io_do_iopoll(ctx, &nr_events, 0);
2363 /* let it sleep and repeat later if can't complete a request */
2367 * Ensure we allow local-to-the-cpu processing to take place,
2368 * in this case we need to ensure that we reap all events.
2369 * Also let task_work, etc. to progress by releasing the mutex
2371 if (need_resched()) {
2372 mutex_unlock(&ctx->uring_lock);
2374 mutex_lock(&ctx->uring_lock);
2377 mutex_unlock(&ctx->uring_lock);
2380 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2382 unsigned int nr_events = 0;
2383 int iters = 0, ret = 0;
2386 * We disallow the app entering submit/complete with polling, but we
2387 * still need to lock the ring to prevent racing with polled issue
2388 * that got punted to a workqueue.
2390 mutex_lock(&ctx->uring_lock);
2393 * Don't enter poll loop if we already have events pending.
2394 * If we do, we can potentially be spinning for commands that
2395 * already triggered a CQE (eg in error).
2397 if (test_bit(0, &ctx->cq_check_overflow))
2398 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2399 if (io_cqring_events(ctx))
2403 * If a submit got punted to a workqueue, we can have the
2404 * application entering polling for a command before it gets
2405 * issued. That app will hold the uring_lock for the duration
2406 * of the poll right here, so we need to take a breather every
2407 * now and then to ensure that the issue has a chance to add
2408 * the poll to the issued list. Otherwise we can spin here
2409 * forever, while the workqueue is stuck trying to acquire the
2412 if (!(++iters & 7)) {
2413 mutex_unlock(&ctx->uring_lock);
2415 mutex_lock(&ctx->uring_lock);
2418 ret = io_iopoll_getevents(ctx, &nr_events, min);
2422 } while (min && !nr_events && !need_resched());
2424 mutex_unlock(&ctx->uring_lock);
2428 static void kiocb_end_write(struct io_kiocb *req)
2431 * Tell lockdep we inherited freeze protection from submission
2434 if (req->flags & REQ_F_ISREG) {
2435 struct inode *inode = file_inode(req->file);
2437 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2439 file_end_write(req->file);
2443 static bool io_resubmit_prep(struct io_kiocb *req)
2445 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2447 struct iov_iter iter;
2449 /* already prepared */
2450 if (req->async_data)
2453 switch (req->opcode) {
2454 case IORING_OP_READV:
2455 case IORING_OP_READ_FIXED:
2456 case IORING_OP_READ:
2459 case IORING_OP_WRITEV:
2460 case IORING_OP_WRITE_FIXED:
2461 case IORING_OP_WRITE:
2465 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2470 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2473 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2477 static bool io_rw_reissue(struct io_kiocb *req)
2480 umode_t mode = file_inode(req->file)->i_mode;
2482 if (!S_ISBLK(mode) && !S_ISREG(mode))
2484 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2487 * If ref is dying, we might be running poll reap from the exit work.
2488 * Don't attempt to reissue from that path, just let it fail with
2491 if (percpu_ref_is_dying(&req->ctx->refs))
2494 lockdep_assert_held(&req->ctx->uring_lock);
2496 if (io_resubmit_prep(req)) {
2497 refcount_inc(&req->refs);
2498 io_queue_async_work(req);
2501 req_set_fail_links(req);
2506 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2507 unsigned int issue_flags)
2511 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2513 if (res != req->result)
2514 req_set_fail_links(req);
2516 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2517 kiocb_end_write(req);
2518 if (req->flags & REQ_F_BUFFER_SELECTED)
2519 cflags = io_put_rw_kbuf(req);
2520 __io_req_complete(req, issue_flags, res, cflags);
2523 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2525 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2527 __io_complete_rw(req, res, res2, 0);
2530 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2532 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2534 if (kiocb->ki_flags & IOCB_WRITE)
2535 kiocb_end_write(req);
2537 if (res != -EAGAIN && res != req->result)
2538 req_set_fail_links(req);
2540 WRITE_ONCE(req->result, res);
2541 /* order with io_poll_complete() checking ->result */
2543 WRITE_ONCE(req->iopoll_completed, 1);
2547 * After the iocb has been issued, it's safe to be found on the poll list.
2548 * Adding the kiocb to the list AFTER submission ensures that we don't
2549 * find it from a io_iopoll_getevents() thread before the issuer is done
2550 * accessing the kiocb cookie.
2552 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2554 struct io_ring_ctx *ctx = req->ctx;
2557 * Track whether we have multiple files in our lists. This will impact
2558 * how we do polling eventually, not spinning if we're on potentially
2559 * different devices.
2561 if (list_empty(&ctx->iopoll_list)) {
2562 ctx->poll_multi_file = false;
2563 } else if (!ctx->poll_multi_file) {
2564 struct io_kiocb *list_req;
2566 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2568 if (list_req->file != req->file)
2569 ctx->poll_multi_file = true;
2573 * For fast devices, IO may have already completed. If it has, add
2574 * it to the front so we find it first.
2576 if (READ_ONCE(req->iopoll_completed))
2577 list_add(&req->inflight_entry, &ctx->iopoll_list);
2579 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2582 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2583 * task context or in io worker task context. If current task context is
2584 * sq thread, we don't need to check whether should wake up sq thread.
2586 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2587 wq_has_sleeper(&ctx->sq_data->wait))
2588 wake_up(&ctx->sq_data->wait);
2591 static inline void io_state_file_put(struct io_submit_state *state)
2593 if (state->file_refs) {
2594 fput_many(state->file, state->file_refs);
2595 state->file_refs = 0;
2600 * Get as many references to a file as we have IOs left in this submission,
2601 * assuming most submissions are for one file, or at least that each file
2602 * has more than one submission.
2604 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2609 if (state->file_refs) {
2610 if (state->fd == fd) {
2614 io_state_file_put(state);
2616 state->file = fget_many(fd, state->ios_left);
2617 if (unlikely(!state->file))
2621 state->file_refs = state->ios_left - 1;
2625 static bool io_bdev_nowait(struct block_device *bdev)
2627 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2631 * If we tracked the file through the SCM inflight mechanism, we could support
2632 * any file. For now, just ensure that anything potentially problematic is done
2635 static bool io_file_supports_async(struct file *file, int rw)
2637 umode_t mode = file_inode(file)->i_mode;
2639 if (S_ISBLK(mode)) {
2640 if (IS_ENABLED(CONFIG_BLOCK) &&
2641 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2645 if (S_ISCHR(mode) || S_ISSOCK(mode))
2647 if (S_ISREG(mode)) {
2648 if (IS_ENABLED(CONFIG_BLOCK) &&
2649 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2650 file->f_op != &io_uring_fops)
2655 /* any ->read/write should understand O_NONBLOCK */
2656 if (file->f_flags & O_NONBLOCK)
2659 if (!(file->f_mode & FMODE_NOWAIT))
2663 return file->f_op->read_iter != NULL;
2665 return file->f_op->write_iter != NULL;
2668 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2670 struct io_ring_ctx *ctx = req->ctx;
2671 struct kiocb *kiocb = &req->rw.kiocb;
2672 struct file *file = req->file;
2676 if (S_ISREG(file_inode(file)->i_mode))
2677 req->flags |= REQ_F_ISREG;
2679 kiocb->ki_pos = READ_ONCE(sqe->off);
2680 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2681 req->flags |= REQ_F_CUR_POS;
2682 kiocb->ki_pos = file->f_pos;
2684 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2685 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2686 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2690 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2691 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2692 req->flags |= REQ_F_NOWAIT;
2694 ioprio = READ_ONCE(sqe->ioprio);
2696 ret = ioprio_check_cap(ioprio);
2700 kiocb->ki_ioprio = ioprio;
2702 kiocb->ki_ioprio = get_current_ioprio();
2704 if (ctx->flags & IORING_SETUP_IOPOLL) {
2705 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2706 !kiocb->ki_filp->f_op->iopoll)
2709 kiocb->ki_flags |= IOCB_HIPRI;
2710 kiocb->ki_complete = io_complete_rw_iopoll;
2711 req->iopoll_completed = 0;
2713 if (kiocb->ki_flags & IOCB_HIPRI)
2715 kiocb->ki_complete = io_complete_rw;
2718 req->rw.addr = READ_ONCE(sqe->addr);
2719 req->rw.len = READ_ONCE(sqe->len);
2720 req->buf_index = READ_ONCE(sqe->buf_index);
2724 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2730 case -ERESTARTNOINTR:
2731 case -ERESTARTNOHAND:
2732 case -ERESTART_RESTARTBLOCK:
2734 * We can't just restart the syscall, since previously
2735 * submitted sqes may already be in progress. Just fail this
2741 kiocb->ki_complete(kiocb, ret, 0);
2745 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2746 unsigned int issue_flags)
2748 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2749 struct io_async_rw *io = req->async_data;
2751 /* add previously done IO, if any */
2752 if (io && io->bytes_done > 0) {
2754 ret = io->bytes_done;
2756 ret += io->bytes_done;
2759 if (req->flags & REQ_F_CUR_POS)
2760 req->file->f_pos = kiocb->ki_pos;
2761 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2762 __io_complete_rw(req, ret, 0, issue_flags);
2764 io_rw_done(kiocb, ret);
2767 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2769 struct io_ring_ctx *ctx = req->ctx;
2770 size_t len = req->rw.len;
2771 struct io_mapped_ubuf *imu;
2772 u16 index, buf_index = req->buf_index;
2776 if (unlikely(buf_index >= ctx->nr_user_bufs))
2778 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2779 imu = &ctx->user_bufs[index];
2780 buf_addr = req->rw.addr;
2783 if (buf_addr + len < buf_addr)
2785 /* not inside the mapped region */
2786 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2790 * May not be a start of buffer, set size appropriately
2791 * and advance us to the beginning.
2793 offset = buf_addr - imu->ubuf;
2794 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2798 * Don't use iov_iter_advance() here, as it's really slow for
2799 * using the latter parts of a big fixed buffer - it iterates
2800 * over each segment manually. We can cheat a bit here, because
2803 * 1) it's a BVEC iter, we set it up
2804 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2805 * first and last bvec
2807 * So just find our index, and adjust the iterator afterwards.
2808 * If the offset is within the first bvec (or the whole first
2809 * bvec, just use iov_iter_advance(). This makes it easier
2810 * since we can just skip the first segment, which may not
2811 * be PAGE_SIZE aligned.
2813 const struct bio_vec *bvec = imu->bvec;
2815 if (offset <= bvec->bv_len) {
2816 iov_iter_advance(iter, offset);
2818 unsigned long seg_skip;
2820 /* skip first vec */
2821 offset -= bvec->bv_len;
2822 seg_skip = 1 + (offset >> PAGE_SHIFT);
2824 iter->bvec = bvec + seg_skip;
2825 iter->nr_segs -= seg_skip;
2826 iter->count -= bvec->bv_len + offset;
2827 iter->iov_offset = offset & ~PAGE_MASK;
2834 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2837 mutex_unlock(&ctx->uring_lock);
2840 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2843 * "Normal" inline submissions always hold the uring_lock, since we
2844 * grab it from the system call. Same is true for the SQPOLL offload.
2845 * The only exception is when we've detached the request and issue it
2846 * from an async worker thread, grab the lock for that case.
2849 mutex_lock(&ctx->uring_lock);
2852 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2853 int bgid, struct io_buffer *kbuf,
2856 struct io_buffer *head;
2858 if (req->flags & REQ_F_BUFFER_SELECTED)
2861 io_ring_submit_lock(req->ctx, needs_lock);
2863 lockdep_assert_held(&req->ctx->uring_lock);
2865 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2867 if (!list_empty(&head->list)) {
2868 kbuf = list_last_entry(&head->list, struct io_buffer,
2870 list_del(&kbuf->list);
2873 idr_remove(&req->ctx->io_buffer_idr, bgid);
2875 if (*len > kbuf->len)
2878 kbuf = ERR_PTR(-ENOBUFS);
2881 io_ring_submit_unlock(req->ctx, needs_lock);
2886 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2889 struct io_buffer *kbuf;
2892 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2893 bgid = req->buf_index;
2894 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2897 req->rw.addr = (u64) (unsigned long) kbuf;
2898 req->flags |= REQ_F_BUFFER_SELECTED;
2899 return u64_to_user_ptr(kbuf->addr);
2902 #ifdef CONFIG_COMPAT
2903 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2906 struct compat_iovec __user *uiov;
2907 compat_ssize_t clen;
2911 uiov = u64_to_user_ptr(req->rw.addr);
2912 if (!access_ok(uiov, sizeof(*uiov)))
2914 if (__get_user(clen, &uiov->iov_len))
2920 buf = io_rw_buffer_select(req, &len, needs_lock);
2922 return PTR_ERR(buf);
2923 iov[0].iov_base = buf;
2924 iov[0].iov_len = (compat_size_t) len;
2929 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2932 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2936 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2939 len = iov[0].iov_len;
2942 buf = io_rw_buffer_select(req, &len, needs_lock);
2944 return PTR_ERR(buf);
2945 iov[0].iov_base = buf;
2946 iov[0].iov_len = len;
2950 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2953 if (req->flags & REQ_F_BUFFER_SELECTED) {
2954 struct io_buffer *kbuf;
2956 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2957 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2958 iov[0].iov_len = kbuf->len;
2961 if (req->rw.len != 1)
2964 #ifdef CONFIG_COMPAT
2965 if (req->ctx->compat)
2966 return io_compat_import(req, iov, needs_lock);
2969 return __io_iov_buffer_select(req, iov, needs_lock);
2972 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2973 struct iov_iter *iter, bool needs_lock)
2975 void __user *buf = u64_to_user_ptr(req->rw.addr);
2976 size_t sqe_len = req->rw.len;
2977 u8 opcode = req->opcode;
2980 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2982 return io_import_fixed(req, rw, iter);
2985 /* buffer index only valid with fixed read/write, or buffer select */
2986 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2989 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2990 if (req->flags & REQ_F_BUFFER_SELECT) {
2991 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2993 return PTR_ERR(buf);
2994 req->rw.len = sqe_len;
2997 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
3002 if (req->flags & REQ_F_BUFFER_SELECT) {
3003 ret = io_iov_buffer_select(req, *iovec, needs_lock);
3005 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3010 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3014 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3016 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3020 * For files that don't have ->read_iter() and ->write_iter(), handle them
3021 * by looping over ->read() or ->write() manually.
3023 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3025 struct kiocb *kiocb = &req->rw.kiocb;
3026 struct file *file = req->file;
3030 * Don't support polled IO through this interface, and we can't
3031 * support non-blocking either. For the latter, this just causes
3032 * the kiocb to be handled from an async context.
3034 if (kiocb->ki_flags & IOCB_HIPRI)
3036 if (kiocb->ki_flags & IOCB_NOWAIT)
3039 while (iov_iter_count(iter)) {
3043 if (!iov_iter_is_bvec(iter)) {
3044 iovec = iov_iter_iovec(iter);
3046 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3047 iovec.iov_len = req->rw.len;
3051 nr = file->f_op->read(file, iovec.iov_base,
3052 iovec.iov_len, io_kiocb_ppos(kiocb));
3054 nr = file->f_op->write(file, iovec.iov_base,
3055 iovec.iov_len, io_kiocb_ppos(kiocb));
3064 if (nr != iovec.iov_len)
3068 iov_iter_advance(iter, nr);
3074 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3075 const struct iovec *fast_iov, struct iov_iter *iter)
3077 struct io_async_rw *rw = req->async_data;
3079 memcpy(&rw->iter, iter, sizeof(*iter));
3080 rw->free_iovec = iovec;
3082 /* can only be fixed buffers, no need to do anything */
3083 if (iov_iter_is_bvec(iter))
3086 unsigned iov_off = 0;
3088 rw->iter.iov = rw->fast_iov;
3089 if (iter->iov != fast_iov) {
3090 iov_off = iter->iov - fast_iov;
3091 rw->iter.iov += iov_off;
3093 if (rw->fast_iov != fast_iov)
3094 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3095 sizeof(struct iovec) * iter->nr_segs);
3097 req->flags |= REQ_F_NEED_CLEANUP;
3101 static inline int __io_alloc_async_data(struct io_kiocb *req)
3103 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3104 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3105 return req->async_data == NULL;
3108 static int io_alloc_async_data(struct io_kiocb *req)
3110 if (!io_op_defs[req->opcode].needs_async_data)
3113 return __io_alloc_async_data(req);
3116 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3117 const struct iovec *fast_iov,
3118 struct iov_iter *iter, bool force)
3120 if (!force && !io_op_defs[req->opcode].needs_async_data)
3122 if (!req->async_data) {
3123 if (__io_alloc_async_data(req)) {
3128 io_req_map_rw(req, iovec, fast_iov, iter);
3133 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3135 struct io_async_rw *iorw = req->async_data;
3136 struct iovec *iov = iorw->fast_iov;
3139 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3140 if (unlikely(ret < 0))
3143 iorw->bytes_done = 0;
3144 iorw->free_iovec = iov;
3146 req->flags |= REQ_F_NEED_CLEANUP;
3150 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3152 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3154 return io_prep_rw(req, sqe);
3158 * This is our waitqueue callback handler, registered through lock_page_async()
3159 * when we initially tried to do the IO with the iocb armed our waitqueue.
3160 * This gets called when the page is unlocked, and we generally expect that to
3161 * happen when the page IO is completed and the page is now uptodate. This will
3162 * queue a task_work based retry of the operation, attempting to copy the data
3163 * again. If the latter fails because the page was NOT uptodate, then we will
3164 * do a thread based blocking retry of the operation. That's the unexpected
3167 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3168 int sync, void *arg)
3170 struct wait_page_queue *wpq;
3171 struct io_kiocb *req = wait->private;
3172 struct wait_page_key *key = arg;
3174 wpq = container_of(wait, struct wait_page_queue, wait);
3176 if (!wake_page_match(wpq, key))
3179 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3180 list_del_init(&wait->entry);
3182 /* submit ref gets dropped, acquire a new one */
3183 refcount_inc(&req->refs);
3184 io_req_task_queue(req);
3189 * This controls whether a given IO request should be armed for async page
3190 * based retry. If we return false here, the request is handed to the async
3191 * worker threads for retry. If we're doing buffered reads on a regular file,
3192 * we prepare a private wait_page_queue entry and retry the operation. This
3193 * will either succeed because the page is now uptodate and unlocked, or it
3194 * will register a callback when the page is unlocked at IO completion. Through
3195 * that callback, io_uring uses task_work to setup a retry of the operation.
3196 * That retry will attempt the buffered read again. The retry will generally
3197 * succeed, or in rare cases where it fails, we then fall back to using the
3198 * async worker threads for a blocking retry.
3200 static bool io_rw_should_retry(struct io_kiocb *req)
3202 struct io_async_rw *rw = req->async_data;
3203 struct wait_page_queue *wait = &rw->wpq;
3204 struct kiocb *kiocb = &req->rw.kiocb;
3206 /* never retry for NOWAIT, we just complete with -EAGAIN */
3207 if (req->flags & REQ_F_NOWAIT)
3210 /* Only for buffered IO */
3211 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3215 * just use poll if we can, and don't attempt if the fs doesn't
3216 * support callback based unlocks
3218 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3221 wait->wait.func = io_async_buf_func;
3222 wait->wait.private = req;
3223 wait->wait.flags = 0;
3224 INIT_LIST_HEAD(&wait->wait.entry);
3225 kiocb->ki_flags |= IOCB_WAITQ;
3226 kiocb->ki_flags &= ~IOCB_NOWAIT;
3227 kiocb->ki_waitq = wait;
3231 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3233 if (req->file->f_op->read_iter)
3234 return call_read_iter(req->file, &req->rw.kiocb, iter);
3235 else if (req->file->f_op->read)
3236 return loop_rw_iter(READ, req, iter);
3241 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3243 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3244 struct kiocb *kiocb = &req->rw.kiocb;
3245 struct iov_iter __iter, *iter = &__iter;
3246 struct io_async_rw *rw = req->async_data;
3247 ssize_t io_size, ret, ret2;
3248 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3254 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3258 io_size = iov_iter_count(iter);
3259 req->result = io_size;
3261 /* Ensure we clear previously set non-block flag */
3262 if (!force_nonblock)
3263 kiocb->ki_flags &= ~IOCB_NOWAIT;
3265 kiocb->ki_flags |= IOCB_NOWAIT;
3267 /* If the file doesn't support async, just async punt */
3268 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3269 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3270 return ret ?: -EAGAIN;
3273 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3274 if (unlikely(ret)) {
3279 ret = io_iter_do_read(req, iter);
3281 if (ret == -EIOCBQUEUED) {
3283 } else if (ret == -EAGAIN) {
3284 /* IOPOLL retry should happen for io-wq threads */
3285 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3287 /* no retry on NONBLOCK nor RWF_NOWAIT */
3288 if (req->flags & REQ_F_NOWAIT)
3290 /* some cases will consume bytes even on error returns */
3291 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3293 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3294 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3295 /* read all, failed, already did sync or don't want to retry */
3299 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3304 rw = req->async_data;
3305 /* now use our persistent iterator, if we aren't already */
3310 rw->bytes_done += ret;
3311 /* if we can retry, do so with the callbacks armed */
3312 if (!io_rw_should_retry(req)) {
3313 kiocb->ki_flags &= ~IOCB_WAITQ;
3318 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3319 * we get -EIOCBQUEUED, then we'll get a notification when the
3320 * desired page gets unlocked. We can also get a partial read
3321 * here, and if we do, then just retry at the new offset.
3323 ret = io_iter_do_read(req, iter);
3324 if (ret == -EIOCBQUEUED)
3326 /* we got some bytes, but not all. retry. */
3327 } while (ret > 0 && ret < io_size);
3329 kiocb_done(kiocb, ret, issue_flags);
3331 /* it's faster to check here then delegate to kfree */
3337 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3339 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3341 return io_prep_rw(req, sqe);
3344 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3346 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3347 struct kiocb *kiocb = &req->rw.kiocb;
3348 struct iov_iter __iter, *iter = &__iter;
3349 struct io_async_rw *rw = req->async_data;
3350 ssize_t ret, ret2, io_size;
3351 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3357 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3361 io_size = iov_iter_count(iter);
3362 req->result = io_size;
3364 /* Ensure we clear previously set non-block flag */
3365 if (!force_nonblock)
3366 kiocb->ki_flags &= ~IOCB_NOWAIT;
3368 kiocb->ki_flags |= IOCB_NOWAIT;
3370 /* If the file doesn't support async, just async punt */
3371 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3374 /* file path doesn't support NOWAIT for non-direct_IO */
3375 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3376 (req->flags & REQ_F_ISREG))
3379 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3384 * Open-code file_start_write here to grab freeze protection,
3385 * which will be released by another thread in
3386 * io_complete_rw(). Fool lockdep by telling it the lock got
3387 * released so that it doesn't complain about the held lock when
3388 * we return to userspace.
3390 if (req->flags & REQ_F_ISREG) {
3391 sb_start_write(file_inode(req->file)->i_sb);
3392 __sb_writers_release(file_inode(req->file)->i_sb,
3395 kiocb->ki_flags |= IOCB_WRITE;
3397 if (req->file->f_op->write_iter)
3398 ret2 = call_write_iter(req->file, kiocb, iter);
3399 else if (req->file->f_op->write)
3400 ret2 = loop_rw_iter(WRITE, req, iter);
3405 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3406 * retry them without IOCB_NOWAIT.
3408 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3410 /* no retry on NONBLOCK nor RWF_NOWAIT */
3411 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3413 if (!force_nonblock || ret2 != -EAGAIN) {
3414 /* IOPOLL retry should happen for io-wq threads */
3415 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3418 kiocb_done(kiocb, ret2, issue_flags);
3421 /* some cases will consume bytes even on error returns */
3422 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3423 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3424 return ret ?: -EAGAIN;
3427 /* it's reportedly faster than delegating the null check to kfree() */
3433 static int io_renameat_prep(struct io_kiocb *req,
3434 const struct io_uring_sqe *sqe)
3436 struct io_rename *ren = &req->rename;
3437 const char __user *oldf, *newf;
3439 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3442 ren->old_dfd = READ_ONCE(sqe->fd);
3443 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3444 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3445 ren->new_dfd = READ_ONCE(sqe->len);
3446 ren->flags = READ_ONCE(sqe->rename_flags);
3448 ren->oldpath = getname(oldf);
3449 if (IS_ERR(ren->oldpath))
3450 return PTR_ERR(ren->oldpath);
3452 ren->newpath = getname(newf);
3453 if (IS_ERR(ren->newpath)) {
3454 putname(ren->oldpath);
3455 return PTR_ERR(ren->newpath);
3458 req->flags |= REQ_F_NEED_CLEANUP;
3462 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3464 struct io_rename *ren = &req->rename;
3467 if (issue_flags & IO_URING_F_NONBLOCK)
3470 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3471 ren->newpath, ren->flags);
3473 req->flags &= ~REQ_F_NEED_CLEANUP;
3475 req_set_fail_links(req);
3476 io_req_complete(req, ret);
3480 static int io_unlinkat_prep(struct io_kiocb *req,
3481 const struct io_uring_sqe *sqe)
3483 struct io_unlink *un = &req->unlink;
3484 const char __user *fname;
3486 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3489 un->dfd = READ_ONCE(sqe->fd);
3491 un->flags = READ_ONCE(sqe->unlink_flags);
3492 if (un->flags & ~AT_REMOVEDIR)
3495 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3496 un->filename = getname(fname);
3497 if (IS_ERR(un->filename))
3498 return PTR_ERR(un->filename);
3500 req->flags |= REQ_F_NEED_CLEANUP;
3504 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3506 struct io_unlink *un = &req->unlink;
3509 if (issue_flags & IO_URING_F_NONBLOCK)
3512 if (un->flags & AT_REMOVEDIR)
3513 ret = do_rmdir(un->dfd, un->filename);
3515 ret = do_unlinkat(un->dfd, un->filename);
3517 req->flags &= ~REQ_F_NEED_CLEANUP;
3519 req_set_fail_links(req);
3520 io_req_complete(req, ret);
3524 static int io_shutdown_prep(struct io_kiocb *req,
3525 const struct io_uring_sqe *sqe)
3527 #if defined(CONFIG_NET)
3528 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3530 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3534 req->shutdown.how = READ_ONCE(sqe->len);
3541 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3543 #if defined(CONFIG_NET)
3544 struct socket *sock;
3547 if (issue_flags & IO_URING_F_NONBLOCK)
3550 sock = sock_from_file(req->file);
3551 if (unlikely(!sock))
3554 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3556 req_set_fail_links(req);
3557 io_req_complete(req, ret);
3564 static int __io_splice_prep(struct io_kiocb *req,
3565 const struct io_uring_sqe *sqe)
3567 struct io_splice* sp = &req->splice;
3568 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3570 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3574 sp->len = READ_ONCE(sqe->len);
3575 sp->flags = READ_ONCE(sqe->splice_flags);
3577 if (unlikely(sp->flags & ~valid_flags))
3580 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3581 (sp->flags & SPLICE_F_FD_IN_FIXED));
3584 req->flags |= REQ_F_NEED_CLEANUP;
3586 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3588 * Splice operation will be punted aync, and here need to
3589 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3591 io_req_init_async(req);
3592 req->work.flags |= IO_WQ_WORK_UNBOUND;
3598 static int io_tee_prep(struct io_kiocb *req,
3599 const struct io_uring_sqe *sqe)
3601 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3603 return __io_splice_prep(req, sqe);
3606 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3608 struct io_splice *sp = &req->splice;
3609 struct file *in = sp->file_in;
3610 struct file *out = sp->file_out;
3611 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3614 if (issue_flags & IO_URING_F_NONBLOCK)
3617 ret = do_tee(in, out, sp->len, flags);
3619 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3620 req->flags &= ~REQ_F_NEED_CLEANUP;
3623 req_set_fail_links(req);
3624 io_req_complete(req, ret);
3628 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3630 struct io_splice* sp = &req->splice;
3632 sp->off_in = READ_ONCE(sqe->splice_off_in);
3633 sp->off_out = READ_ONCE(sqe->off);
3634 return __io_splice_prep(req, sqe);
3637 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3639 struct io_splice *sp = &req->splice;
3640 struct file *in = sp->file_in;
3641 struct file *out = sp->file_out;
3642 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3643 loff_t *poff_in, *poff_out;
3646 if (issue_flags & IO_URING_F_NONBLOCK)
3649 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3650 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3653 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3655 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3656 req->flags &= ~REQ_F_NEED_CLEANUP;
3659 req_set_fail_links(req);
3660 io_req_complete(req, ret);
3665 * IORING_OP_NOP just posts a completion event, nothing else.
3667 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3669 struct io_ring_ctx *ctx = req->ctx;
3671 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3674 __io_req_complete(req, issue_flags, 0, 0);
3678 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3680 struct io_ring_ctx *ctx = req->ctx;
3685 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3687 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3690 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3691 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3694 req->sync.off = READ_ONCE(sqe->off);
3695 req->sync.len = READ_ONCE(sqe->len);
3699 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3701 loff_t end = req->sync.off + req->sync.len;
3704 /* fsync always requires a blocking context */
3705 if (issue_flags & IO_URING_F_NONBLOCK)
3708 ret = vfs_fsync_range(req->file, req->sync.off,
3709 end > 0 ? end : LLONG_MAX,
3710 req->sync.flags & IORING_FSYNC_DATASYNC);
3712 req_set_fail_links(req);
3713 io_req_complete(req, ret);
3717 static int io_fallocate_prep(struct io_kiocb *req,
3718 const struct io_uring_sqe *sqe)
3720 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3722 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3725 req->sync.off = READ_ONCE(sqe->off);
3726 req->sync.len = READ_ONCE(sqe->addr);
3727 req->sync.mode = READ_ONCE(sqe->len);
3731 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3735 /* fallocate always requiring blocking context */
3736 if (issue_flags & IO_URING_F_NONBLOCK)
3738 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3741 req_set_fail_links(req);
3742 io_req_complete(req, ret);
3746 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3748 const char __user *fname;
3751 if (unlikely(sqe->ioprio || sqe->buf_index))
3753 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3756 /* open.how should be already initialised */
3757 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3758 req->open.how.flags |= O_LARGEFILE;
3760 req->open.dfd = READ_ONCE(sqe->fd);
3761 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3762 req->open.filename = getname(fname);
3763 if (IS_ERR(req->open.filename)) {
3764 ret = PTR_ERR(req->open.filename);
3765 req->open.filename = NULL;
3768 req->open.nofile = rlimit(RLIMIT_NOFILE);
3769 req->flags |= REQ_F_NEED_CLEANUP;
3773 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3777 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3779 mode = READ_ONCE(sqe->len);
3780 flags = READ_ONCE(sqe->open_flags);
3781 req->open.how = build_open_how(flags, mode);
3782 return __io_openat_prep(req, sqe);
3785 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3787 struct open_how __user *how;
3791 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3793 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3794 len = READ_ONCE(sqe->len);
3795 if (len < OPEN_HOW_SIZE_VER0)
3798 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3803 return __io_openat_prep(req, sqe);
3806 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3808 struct open_flags op;
3811 bool resolve_nonblock;
3814 ret = build_open_flags(&req->open.how, &op);
3817 nonblock_set = op.open_flag & O_NONBLOCK;
3818 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3819 if (issue_flags & IO_URING_F_NONBLOCK) {
3821 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3822 * it'll always -EAGAIN
3824 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3826 op.lookup_flags |= LOOKUP_CACHED;
3827 op.open_flag |= O_NONBLOCK;
3830 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3834 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3835 /* only retry if RESOLVE_CACHED wasn't already set by application */
3836 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3837 file == ERR_PTR(-EAGAIN)) {
3839 * We could hang on to this 'fd', but seems like marginal
3840 * gain for something that is now known to be a slower path.
3841 * So just put it, and we'll get a new one when we retry.
3849 ret = PTR_ERR(file);
3851 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3852 file->f_flags &= ~O_NONBLOCK;
3853 fsnotify_open(file);
3854 fd_install(ret, file);
3857 putname(req->open.filename);
3858 req->flags &= ~REQ_F_NEED_CLEANUP;
3860 req_set_fail_links(req);
3861 io_req_complete(req, ret);
3865 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3867 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
3870 static int io_remove_buffers_prep(struct io_kiocb *req,
3871 const struct io_uring_sqe *sqe)
3873 struct io_provide_buf *p = &req->pbuf;
3876 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3879 tmp = READ_ONCE(sqe->fd);
3880 if (!tmp || tmp > USHRT_MAX)
3883 memset(p, 0, sizeof(*p));
3885 p->bgid = READ_ONCE(sqe->buf_group);
3889 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3890 int bgid, unsigned nbufs)
3894 /* shouldn't happen */
3898 /* the head kbuf is the list itself */
3899 while (!list_empty(&buf->list)) {
3900 struct io_buffer *nxt;
3902 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3903 list_del(&nxt->list);
3910 idr_remove(&ctx->io_buffer_idr, bgid);
3915 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3917 struct io_provide_buf *p = &req->pbuf;
3918 struct io_ring_ctx *ctx = req->ctx;
3919 struct io_buffer *head;
3921 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3923 io_ring_submit_lock(ctx, !force_nonblock);
3925 lockdep_assert_held(&ctx->uring_lock);
3928 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3930 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3932 req_set_fail_links(req);
3934 /* need to hold the lock to complete IOPOLL requests */
3935 if (ctx->flags & IORING_SETUP_IOPOLL) {
3936 __io_req_complete(req, issue_flags, ret, 0);
3937 io_ring_submit_unlock(ctx, !force_nonblock);
3939 io_ring_submit_unlock(ctx, !force_nonblock);
3940 __io_req_complete(req, issue_flags, ret, 0);
3945 static int io_provide_buffers_prep(struct io_kiocb *req,
3946 const struct io_uring_sqe *sqe)
3948 struct io_provide_buf *p = &req->pbuf;
3951 if (sqe->ioprio || sqe->rw_flags)
3954 tmp = READ_ONCE(sqe->fd);
3955 if (!tmp || tmp > USHRT_MAX)
3958 p->addr = READ_ONCE(sqe->addr);
3959 p->len = READ_ONCE(sqe->len);
3961 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3964 p->bgid = READ_ONCE(sqe->buf_group);
3965 tmp = READ_ONCE(sqe->off);
3966 if (tmp > USHRT_MAX)
3972 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3974 struct io_buffer *buf;
3975 u64 addr = pbuf->addr;
3976 int i, bid = pbuf->bid;
3978 for (i = 0; i < pbuf->nbufs; i++) {
3979 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3984 buf->len = pbuf->len;
3989 INIT_LIST_HEAD(&buf->list);
3992 list_add_tail(&buf->list, &(*head)->list);
3996 return i ? i : -ENOMEM;
3999 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
4001 struct io_provide_buf *p = &req->pbuf;
4002 struct io_ring_ctx *ctx = req->ctx;
4003 struct io_buffer *head, *list;
4005 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4007 io_ring_submit_lock(ctx, !force_nonblock);
4009 lockdep_assert_held(&ctx->uring_lock);
4011 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
4013 ret = io_add_buffers(p, &head);
4018 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
4021 __io_remove_buffers(ctx, head, p->bgid, -1U);
4027 req_set_fail_links(req);
4029 /* need to hold the lock to complete IOPOLL requests */
4030 if (ctx->flags & IORING_SETUP_IOPOLL) {
4031 __io_req_complete(req, issue_flags, ret, 0);
4032 io_ring_submit_unlock(ctx, !force_nonblock);
4034 io_ring_submit_unlock(ctx, !force_nonblock);
4035 __io_req_complete(req, issue_flags, ret, 0);
4040 static int io_epoll_ctl_prep(struct io_kiocb *req,
4041 const struct io_uring_sqe *sqe)
4043 #if defined(CONFIG_EPOLL)
4044 if (sqe->ioprio || sqe->buf_index)
4046 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4049 req->epoll.epfd = READ_ONCE(sqe->fd);
4050 req->epoll.op = READ_ONCE(sqe->len);
4051 req->epoll.fd = READ_ONCE(sqe->off);
4053 if (ep_op_has_event(req->epoll.op)) {
4054 struct epoll_event __user *ev;
4056 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4057 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4067 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4069 #if defined(CONFIG_EPOLL)
4070 struct io_epoll *ie = &req->epoll;
4072 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4074 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4075 if (force_nonblock && ret == -EAGAIN)
4079 req_set_fail_links(req);
4080 __io_req_complete(req, issue_flags, ret, 0);
4087 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4089 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4090 if (sqe->ioprio || sqe->buf_index || sqe->off)
4092 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4095 req->madvise.addr = READ_ONCE(sqe->addr);
4096 req->madvise.len = READ_ONCE(sqe->len);
4097 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4104 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4106 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4107 struct io_madvise *ma = &req->madvise;
4110 if (issue_flags & IO_URING_F_NONBLOCK)
4113 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4115 req_set_fail_links(req);
4116 io_req_complete(req, ret);
4123 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4125 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4127 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4130 req->fadvise.offset = READ_ONCE(sqe->off);
4131 req->fadvise.len = READ_ONCE(sqe->len);
4132 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4136 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4138 struct io_fadvise *fa = &req->fadvise;
4141 if (issue_flags & IO_URING_F_NONBLOCK) {
4142 switch (fa->advice) {
4143 case POSIX_FADV_NORMAL:
4144 case POSIX_FADV_RANDOM:
4145 case POSIX_FADV_SEQUENTIAL:
4152 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4154 req_set_fail_links(req);
4155 io_req_complete(req, ret);
4159 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4161 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4163 if (sqe->ioprio || sqe->buf_index)
4165 if (req->flags & REQ_F_FIXED_FILE)
4168 req->statx.dfd = READ_ONCE(sqe->fd);
4169 req->statx.mask = READ_ONCE(sqe->len);
4170 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4171 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4172 req->statx.flags = READ_ONCE(sqe->statx_flags);
4177 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4179 struct io_statx *ctx = &req->statx;
4182 if (issue_flags & IO_URING_F_NONBLOCK) {
4183 /* only need file table for an actual valid fd */
4184 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4185 req->flags |= REQ_F_NO_FILE_TABLE;
4189 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4193 req_set_fail_links(req);
4194 io_req_complete(req, ret);
4198 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4200 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4202 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4203 sqe->rw_flags || sqe->buf_index)
4205 if (req->flags & REQ_F_FIXED_FILE)
4208 req->close.fd = READ_ONCE(sqe->fd);
4212 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4214 struct files_struct *files = current->files;
4215 struct io_close *close = &req->close;
4216 struct fdtable *fdt;
4222 spin_lock(&files->file_lock);
4223 fdt = files_fdtable(files);
4224 if (close->fd >= fdt->max_fds) {
4225 spin_unlock(&files->file_lock);
4228 file = fdt->fd[close->fd];
4230 spin_unlock(&files->file_lock);
4234 if (file->f_op == &io_uring_fops) {
4235 spin_unlock(&files->file_lock);
4240 /* if the file has a flush method, be safe and punt to async */
4241 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4242 spin_unlock(&files->file_lock);
4246 ret = __close_fd_get_file(close->fd, &file);
4247 spin_unlock(&files->file_lock);
4254 /* No ->flush() or already async, safely close from here */
4255 ret = filp_close(file, current->files);
4258 req_set_fail_links(req);
4261 __io_req_complete(req, issue_flags, ret, 0);
4265 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4267 struct io_ring_ctx *ctx = req->ctx;
4269 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4271 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4274 req->sync.off = READ_ONCE(sqe->off);
4275 req->sync.len = READ_ONCE(sqe->len);
4276 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4280 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4284 /* sync_file_range always requires a blocking context */
4285 if (issue_flags & IO_URING_F_NONBLOCK)
4288 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4291 req_set_fail_links(req);
4292 io_req_complete(req, ret);
4296 #if defined(CONFIG_NET)
4297 static int io_setup_async_msg(struct io_kiocb *req,
4298 struct io_async_msghdr *kmsg)
4300 struct io_async_msghdr *async_msg = req->async_data;
4304 if (io_alloc_async_data(req)) {
4305 kfree(kmsg->free_iov);
4308 async_msg = req->async_data;
4309 req->flags |= REQ_F_NEED_CLEANUP;
4310 memcpy(async_msg, kmsg, sizeof(*kmsg));
4311 async_msg->msg.msg_name = &async_msg->addr;
4312 /* if were using fast_iov, set it to the new one */
4313 if (!async_msg->free_iov)
4314 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4319 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4320 struct io_async_msghdr *iomsg)
4322 iomsg->msg.msg_name = &iomsg->addr;
4323 iomsg->free_iov = iomsg->fast_iov;
4324 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4325 req->sr_msg.msg_flags, &iomsg->free_iov);
4328 static int io_sendmsg_prep_async(struct io_kiocb *req)
4332 if (!io_op_defs[req->opcode].needs_async_data)
4334 ret = io_sendmsg_copy_hdr(req, req->async_data);
4336 req->flags |= REQ_F_NEED_CLEANUP;
4340 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4342 struct io_sr_msg *sr = &req->sr_msg;
4344 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4347 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4348 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4349 sr->len = READ_ONCE(sqe->len);
4351 #ifdef CONFIG_COMPAT
4352 if (req->ctx->compat)
4353 sr->msg_flags |= MSG_CMSG_COMPAT;
4358 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4360 struct io_async_msghdr iomsg, *kmsg;
4361 struct socket *sock;
4365 sock = sock_from_file(req->file);
4366 if (unlikely(!sock))
4369 kmsg = req->async_data;
4371 ret = io_sendmsg_copy_hdr(req, &iomsg);
4377 flags = req->sr_msg.msg_flags;
4378 if (flags & MSG_DONTWAIT)
4379 req->flags |= REQ_F_NOWAIT;
4380 else if (issue_flags & IO_URING_F_NONBLOCK)
4381 flags |= MSG_DONTWAIT;
4383 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4384 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4385 return io_setup_async_msg(req, kmsg);
4386 if (ret == -ERESTARTSYS)
4389 /* fast path, check for non-NULL to avoid function call */
4391 kfree(kmsg->free_iov);
4392 req->flags &= ~REQ_F_NEED_CLEANUP;
4394 req_set_fail_links(req);
4395 __io_req_complete(req, issue_flags, ret, 0);
4399 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4401 struct io_sr_msg *sr = &req->sr_msg;
4404 struct socket *sock;
4408 sock = sock_from_file(req->file);
4409 if (unlikely(!sock))
4412 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4416 msg.msg_name = NULL;
4417 msg.msg_control = NULL;
4418 msg.msg_controllen = 0;
4419 msg.msg_namelen = 0;
4421 flags = req->sr_msg.msg_flags;
4422 if (flags & MSG_DONTWAIT)
4423 req->flags |= REQ_F_NOWAIT;
4424 else if (issue_flags & IO_URING_F_NONBLOCK)
4425 flags |= MSG_DONTWAIT;
4427 msg.msg_flags = flags;
4428 ret = sock_sendmsg(sock, &msg);
4429 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4431 if (ret == -ERESTARTSYS)
4435 req_set_fail_links(req);
4436 __io_req_complete(req, issue_flags, ret, 0);
4440 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4441 struct io_async_msghdr *iomsg)
4443 struct io_sr_msg *sr = &req->sr_msg;
4444 struct iovec __user *uiov;
4448 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4449 &iomsg->uaddr, &uiov, &iov_len);
4453 if (req->flags & REQ_F_BUFFER_SELECT) {
4456 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4458 sr->len = iomsg->fast_iov[0].iov_len;
4459 iomsg->free_iov = NULL;
4461 iomsg->free_iov = iomsg->fast_iov;
4462 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4463 &iomsg->free_iov, &iomsg->msg.msg_iter,
4472 #ifdef CONFIG_COMPAT
4473 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4474 struct io_async_msghdr *iomsg)
4476 struct compat_msghdr __user *msg_compat;
4477 struct io_sr_msg *sr = &req->sr_msg;
4478 struct compat_iovec __user *uiov;
4483 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4484 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4489 uiov = compat_ptr(ptr);
4490 if (req->flags & REQ_F_BUFFER_SELECT) {
4491 compat_ssize_t clen;
4495 if (!access_ok(uiov, sizeof(*uiov)))
4497 if (__get_user(clen, &uiov->iov_len))
4502 iomsg->free_iov = NULL;
4504 iomsg->free_iov = iomsg->fast_iov;
4505 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4506 UIO_FASTIOV, &iomsg->free_iov,
4507 &iomsg->msg.msg_iter, true);
4516 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4517 struct io_async_msghdr *iomsg)
4519 iomsg->msg.msg_name = &iomsg->addr;
4521 #ifdef CONFIG_COMPAT
4522 if (req->ctx->compat)
4523 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4526 return __io_recvmsg_copy_hdr(req, iomsg);
4529 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4532 struct io_sr_msg *sr = &req->sr_msg;
4533 struct io_buffer *kbuf;
4535 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4540 req->flags |= REQ_F_BUFFER_SELECTED;
4544 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4546 return io_put_kbuf(req, req->sr_msg.kbuf);
4549 static int io_recvmsg_prep_async(struct io_kiocb *req)
4553 if (!io_op_defs[req->opcode].needs_async_data)
4555 ret = io_recvmsg_copy_hdr(req, req->async_data);
4557 req->flags |= REQ_F_NEED_CLEANUP;
4561 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4563 struct io_sr_msg *sr = &req->sr_msg;
4565 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4568 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4569 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4570 sr->len = READ_ONCE(sqe->len);
4571 sr->bgid = READ_ONCE(sqe->buf_group);
4573 #ifdef CONFIG_COMPAT
4574 if (req->ctx->compat)
4575 sr->msg_flags |= MSG_CMSG_COMPAT;
4580 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4582 struct io_async_msghdr iomsg, *kmsg;
4583 struct socket *sock;
4584 struct io_buffer *kbuf;
4586 int ret, cflags = 0;
4587 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4589 sock = sock_from_file(req->file);
4590 if (unlikely(!sock))
4593 kmsg = req->async_data;
4595 ret = io_recvmsg_copy_hdr(req, &iomsg);
4601 if (req->flags & REQ_F_BUFFER_SELECT) {
4602 kbuf = io_recv_buffer_select(req, !force_nonblock);
4604 return PTR_ERR(kbuf);
4605 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4606 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4607 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4608 1, req->sr_msg.len);
4611 flags = req->sr_msg.msg_flags;
4612 if (flags & MSG_DONTWAIT)
4613 req->flags |= REQ_F_NOWAIT;
4614 else if (force_nonblock)
4615 flags |= MSG_DONTWAIT;
4617 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4618 kmsg->uaddr, flags);
4619 if (force_nonblock && ret == -EAGAIN)
4620 return io_setup_async_msg(req, kmsg);
4621 if (ret == -ERESTARTSYS)
4624 if (req->flags & REQ_F_BUFFER_SELECTED)
4625 cflags = io_put_recv_kbuf(req);
4626 /* fast path, check for non-NULL to avoid function call */
4628 kfree(kmsg->free_iov);
4629 req->flags &= ~REQ_F_NEED_CLEANUP;
4631 req_set_fail_links(req);
4632 __io_req_complete(req, issue_flags, ret, cflags);
4636 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4638 struct io_buffer *kbuf;
4639 struct io_sr_msg *sr = &req->sr_msg;
4641 void __user *buf = sr->buf;
4642 struct socket *sock;
4645 int ret, cflags = 0;
4646 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4648 sock = sock_from_file(req->file);
4649 if (unlikely(!sock))
4652 if (req->flags & REQ_F_BUFFER_SELECT) {
4653 kbuf = io_recv_buffer_select(req, !force_nonblock);
4655 return PTR_ERR(kbuf);
4656 buf = u64_to_user_ptr(kbuf->addr);
4659 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4663 msg.msg_name = NULL;
4664 msg.msg_control = NULL;
4665 msg.msg_controllen = 0;
4666 msg.msg_namelen = 0;
4667 msg.msg_iocb = NULL;
4670 flags = req->sr_msg.msg_flags;
4671 if (flags & MSG_DONTWAIT)
4672 req->flags |= REQ_F_NOWAIT;
4673 else if (force_nonblock)
4674 flags |= MSG_DONTWAIT;
4676 ret = sock_recvmsg(sock, &msg, flags);
4677 if (force_nonblock && ret == -EAGAIN)
4679 if (ret == -ERESTARTSYS)
4682 if (req->flags & REQ_F_BUFFER_SELECTED)
4683 cflags = io_put_recv_kbuf(req);
4685 req_set_fail_links(req);
4686 __io_req_complete(req, issue_flags, ret, cflags);
4690 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4692 struct io_accept *accept = &req->accept;
4694 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4696 if (sqe->ioprio || sqe->len || sqe->buf_index)
4699 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4700 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4701 accept->flags = READ_ONCE(sqe->accept_flags);
4702 accept->nofile = rlimit(RLIMIT_NOFILE);
4706 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4708 struct io_accept *accept = &req->accept;
4709 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4710 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4713 if (req->file->f_flags & O_NONBLOCK)
4714 req->flags |= REQ_F_NOWAIT;
4716 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4717 accept->addr_len, accept->flags,
4719 if (ret == -EAGAIN && force_nonblock)
4722 if (ret == -ERESTARTSYS)
4724 req_set_fail_links(req);
4726 __io_req_complete(req, issue_flags, ret, 0);
4730 static int io_connect_prep_async(struct io_kiocb *req)
4732 struct io_async_connect *io = req->async_data;
4733 struct io_connect *conn = &req->connect;
4735 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4738 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4740 struct io_connect *conn = &req->connect;
4742 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4744 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4747 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4748 conn->addr_len = READ_ONCE(sqe->addr2);
4752 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4754 struct io_async_connect __io, *io;
4755 unsigned file_flags;
4757 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4759 if (req->async_data) {
4760 io = req->async_data;
4762 ret = move_addr_to_kernel(req->connect.addr,
4763 req->connect.addr_len,
4770 file_flags = force_nonblock ? O_NONBLOCK : 0;
4772 ret = __sys_connect_file(req->file, &io->address,
4773 req->connect.addr_len, file_flags);
4774 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4775 if (req->async_data)
4777 if (io_alloc_async_data(req)) {
4781 io = req->async_data;
4782 memcpy(req->async_data, &__io, sizeof(__io));
4785 if (ret == -ERESTARTSYS)
4789 req_set_fail_links(req);
4790 __io_req_complete(req, issue_flags, ret, 0);
4793 #else /* !CONFIG_NET */
4794 #define IO_NETOP_FN(op) \
4795 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4797 return -EOPNOTSUPP; \
4800 #define IO_NETOP_PREP(op) \
4802 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4804 return -EOPNOTSUPP; \
4807 #define IO_NETOP_PREP_ASYNC(op) \
4809 static int io_##op##_prep_async(struct io_kiocb *req) \
4811 return -EOPNOTSUPP; \
4814 IO_NETOP_PREP_ASYNC(sendmsg);
4815 IO_NETOP_PREP_ASYNC(recvmsg);
4816 IO_NETOP_PREP_ASYNC(connect);
4817 IO_NETOP_PREP(accept);
4820 #endif /* CONFIG_NET */
4822 struct io_poll_table {
4823 struct poll_table_struct pt;
4824 struct io_kiocb *req;
4828 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4829 __poll_t mask, task_work_func_t func)
4833 /* for instances that support it check for an event match first: */
4834 if (mask && !(mask & poll->events))
4837 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4839 list_del_init(&poll->wait.entry);
4842 req->task_work.func = func;
4843 percpu_ref_get(&req->ctx->refs);
4846 * If this fails, then the task is exiting. When a task exits, the
4847 * work gets canceled, so just cancel this request as well instead
4848 * of executing it. We can't safely execute it anyway, as we may not
4849 * have the needed state needed for it anyway.
4851 ret = io_req_task_work_add(req);
4852 if (unlikely(ret)) {
4853 WRITE_ONCE(poll->canceled, true);
4854 io_req_task_work_add_fallback(req, func);
4859 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4860 __acquires(&req->ctx->completion_lock)
4862 struct io_ring_ctx *ctx = req->ctx;
4864 if (!req->result && !READ_ONCE(poll->canceled)) {
4865 struct poll_table_struct pt = { ._key = poll->events };
4867 req->result = vfs_poll(req->file, &pt) & poll->events;
4870 spin_lock_irq(&ctx->completion_lock);
4871 if (!req->result && !READ_ONCE(poll->canceled)) {
4872 add_wait_queue(poll->head, &poll->wait);
4879 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4881 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4882 if (req->opcode == IORING_OP_POLL_ADD)
4883 return req->async_data;
4884 return req->apoll->double_poll;
4887 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4889 if (req->opcode == IORING_OP_POLL_ADD)
4891 return &req->apoll->poll;
4894 static void io_poll_remove_double(struct io_kiocb *req)
4896 struct io_poll_iocb *poll = io_poll_get_double(req);
4898 lockdep_assert_held(&req->ctx->completion_lock);
4900 if (poll && poll->head) {
4901 struct wait_queue_head *head = poll->head;
4903 spin_lock(&head->lock);
4904 list_del_init(&poll->wait.entry);
4905 if (poll->wait.private)
4906 refcount_dec(&req->refs);
4908 spin_unlock(&head->lock);
4912 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4914 struct io_ring_ctx *ctx = req->ctx;
4916 io_poll_remove_double(req);
4917 req->poll.done = true;
4918 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4919 io_commit_cqring(ctx);
4922 static void io_poll_task_func(struct callback_head *cb)
4924 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4925 struct io_ring_ctx *ctx = req->ctx;
4926 struct io_kiocb *nxt;
4928 if (io_poll_rewait(req, &req->poll)) {
4929 spin_unlock_irq(&ctx->completion_lock);
4931 hash_del(&req->hash_node);
4932 io_poll_complete(req, req->result, 0);
4933 spin_unlock_irq(&ctx->completion_lock);
4935 nxt = io_put_req_find_next(req);
4936 io_cqring_ev_posted(ctx);
4938 __io_req_task_submit(nxt);
4941 percpu_ref_put(&ctx->refs);
4944 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4945 int sync, void *key)
4947 struct io_kiocb *req = wait->private;
4948 struct io_poll_iocb *poll = io_poll_get_single(req);
4949 __poll_t mask = key_to_poll(key);
4951 /* for instances that support it check for an event match first: */
4952 if (mask && !(mask & poll->events))
4955 list_del_init(&wait->entry);
4957 if (poll && poll->head) {
4960 spin_lock(&poll->head->lock);
4961 done = list_empty(&poll->wait.entry);
4963 list_del_init(&poll->wait.entry);
4964 /* make sure double remove sees this as being gone */
4965 wait->private = NULL;
4966 spin_unlock(&poll->head->lock);
4968 /* use wait func handler, so it matches the rq type */
4969 poll->wait.func(&poll->wait, mode, sync, key);
4972 refcount_dec(&req->refs);
4976 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4977 wait_queue_func_t wake_func)
4981 poll->canceled = false;
4982 poll->events = events;
4983 INIT_LIST_HEAD(&poll->wait.entry);
4984 init_waitqueue_func_entry(&poll->wait, wake_func);
4987 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4988 struct wait_queue_head *head,
4989 struct io_poll_iocb **poll_ptr)
4991 struct io_kiocb *req = pt->req;
4994 * If poll->head is already set, it's because the file being polled
4995 * uses multiple waitqueues for poll handling (eg one for read, one
4996 * for write). Setup a separate io_poll_iocb if this happens.
4998 if (unlikely(poll->head)) {
4999 struct io_poll_iocb *poll_one = poll;
5001 /* already have a 2nd entry, fail a third attempt */
5003 pt->error = -EINVAL;
5006 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5008 pt->error = -ENOMEM;
5011 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5012 refcount_inc(&req->refs);
5013 poll->wait.private = req;
5020 if (poll->events & EPOLLEXCLUSIVE)
5021 add_wait_queue_exclusive(head, &poll->wait);
5023 add_wait_queue(head, &poll->wait);
5026 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5027 struct poll_table_struct *p)
5029 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5030 struct async_poll *apoll = pt->req->apoll;
5032 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5035 static void io_async_task_func(struct callback_head *cb)
5037 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
5038 struct async_poll *apoll = req->apoll;
5039 struct io_ring_ctx *ctx = req->ctx;
5041 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5043 if (io_poll_rewait(req, &apoll->poll)) {
5044 spin_unlock_irq(&ctx->completion_lock);
5045 percpu_ref_put(&ctx->refs);
5049 /* If req is still hashed, it cannot have been canceled. Don't check. */
5050 if (hash_hashed(&req->hash_node))
5051 hash_del(&req->hash_node);
5053 io_poll_remove_double(req);
5054 spin_unlock_irq(&ctx->completion_lock);
5056 if (!READ_ONCE(apoll->poll.canceled))
5057 __io_req_task_submit(req);
5059 __io_req_task_cancel(req, -ECANCELED);
5061 percpu_ref_put(&ctx->refs);
5062 kfree(apoll->double_poll);
5066 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5069 struct io_kiocb *req = wait->private;
5070 struct io_poll_iocb *poll = &req->apoll->poll;
5072 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5075 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5078 static void io_poll_req_insert(struct io_kiocb *req)
5080 struct io_ring_ctx *ctx = req->ctx;
5081 struct hlist_head *list;
5083 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5084 hlist_add_head(&req->hash_node, list);
5087 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5088 struct io_poll_iocb *poll,
5089 struct io_poll_table *ipt, __poll_t mask,
5090 wait_queue_func_t wake_func)
5091 __acquires(&ctx->completion_lock)
5093 struct io_ring_ctx *ctx = req->ctx;
5094 bool cancel = false;
5096 INIT_HLIST_NODE(&req->hash_node);
5097 io_init_poll_iocb(poll, mask, wake_func);
5098 poll->file = req->file;
5099 poll->wait.private = req;
5101 ipt->pt._key = mask;
5103 ipt->error = -EINVAL;
5105 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5107 spin_lock_irq(&ctx->completion_lock);
5108 if (likely(poll->head)) {
5109 spin_lock(&poll->head->lock);
5110 if (unlikely(list_empty(&poll->wait.entry))) {
5116 if (mask || ipt->error)
5117 list_del_init(&poll->wait.entry);
5119 WRITE_ONCE(poll->canceled, true);
5120 else if (!poll->done) /* actually waiting for an event */
5121 io_poll_req_insert(req);
5122 spin_unlock(&poll->head->lock);
5128 static bool io_arm_poll_handler(struct io_kiocb *req)
5130 const struct io_op_def *def = &io_op_defs[req->opcode];
5131 struct io_ring_ctx *ctx = req->ctx;
5132 struct async_poll *apoll;
5133 struct io_poll_table ipt;
5137 if (!req->file || !file_can_poll(req->file))
5139 if (req->flags & REQ_F_POLLED)
5143 else if (def->pollout)
5147 /* if we can't nonblock try, then no point in arming a poll handler */
5148 if (!io_file_supports_async(req->file, rw))
5151 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5152 if (unlikely(!apoll))
5154 apoll->double_poll = NULL;
5156 req->flags |= REQ_F_POLLED;
5161 mask |= POLLIN | POLLRDNORM;
5163 mask |= POLLOUT | POLLWRNORM;
5165 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5166 if ((req->opcode == IORING_OP_RECVMSG) &&
5167 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5170 mask |= POLLERR | POLLPRI;
5172 ipt.pt._qproc = io_async_queue_proc;
5174 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5176 if (ret || ipt.error) {
5177 io_poll_remove_double(req);
5178 spin_unlock_irq(&ctx->completion_lock);
5179 kfree(apoll->double_poll);
5183 spin_unlock_irq(&ctx->completion_lock);
5184 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5185 apoll->poll.events);
5189 static bool __io_poll_remove_one(struct io_kiocb *req,
5190 struct io_poll_iocb *poll)
5192 bool do_complete = false;
5194 spin_lock(&poll->head->lock);
5195 WRITE_ONCE(poll->canceled, true);
5196 if (!list_empty(&poll->wait.entry)) {
5197 list_del_init(&poll->wait.entry);
5200 spin_unlock(&poll->head->lock);
5201 hash_del(&req->hash_node);
5205 static bool io_poll_remove_one(struct io_kiocb *req)
5209 io_poll_remove_double(req);
5211 if (req->opcode == IORING_OP_POLL_ADD) {
5212 do_complete = __io_poll_remove_one(req, &req->poll);
5214 struct async_poll *apoll = req->apoll;
5216 /* non-poll requests have submit ref still */
5217 do_complete = __io_poll_remove_one(req, &apoll->poll);
5220 kfree(apoll->double_poll);
5226 io_cqring_fill_event(req, -ECANCELED);
5227 io_commit_cqring(req->ctx);
5228 req_set_fail_links(req);
5229 io_put_req_deferred(req, 1);
5236 * Returns true if we found and killed one or more poll requests
5238 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5239 struct files_struct *files)
5241 struct hlist_node *tmp;
5242 struct io_kiocb *req;
5245 spin_lock_irq(&ctx->completion_lock);
5246 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5247 struct hlist_head *list;
5249 list = &ctx->cancel_hash[i];
5250 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5251 if (io_match_task(req, tsk, files))
5252 posted += io_poll_remove_one(req);
5255 spin_unlock_irq(&ctx->completion_lock);
5258 io_cqring_ev_posted(ctx);
5263 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5265 struct hlist_head *list;
5266 struct io_kiocb *req;
5268 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5269 hlist_for_each_entry(req, list, hash_node) {
5270 if (sqe_addr != req->user_data)
5272 if (io_poll_remove_one(req))
5280 static int io_poll_remove_prep(struct io_kiocb *req,
5281 const struct io_uring_sqe *sqe)
5283 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5285 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5289 req->poll_remove.addr = READ_ONCE(sqe->addr);
5294 * Find a running poll command that matches one specified in sqe->addr,
5295 * and remove it if found.
5297 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5299 struct io_ring_ctx *ctx = req->ctx;
5302 spin_lock_irq(&ctx->completion_lock);
5303 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5304 spin_unlock_irq(&ctx->completion_lock);
5307 req_set_fail_links(req);
5308 io_req_complete(req, ret);
5312 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5315 struct io_kiocb *req = wait->private;
5316 struct io_poll_iocb *poll = &req->poll;
5318 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5321 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5322 struct poll_table_struct *p)
5324 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5326 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5329 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5331 struct io_poll_iocb *poll = &req->poll;
5334 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5336 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5339 events = READ_ONCE(sqe->poll32_events);
5341 events = swahw32(events);
5343 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5344 (events & EPOLLEXCLUSIVE);
5348 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5350 struct io_poll_iocb *poll = &req->poll;
5351 struct io_ring_ctx *ctx = req->ctx;
5352 struct io_poll_table ipt;
5355 ipt.pt._qproc = io_poll_queue_proc;
5357 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5360 if (mask) { /* no async, we'd stolen it */
5362 io_poll_complete(req, mask, 0);
5364 spin_unlock_irq(&ctx->completion_lock);
5367 io_cqring_ev_posted(ctx);
5373 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5375 struct io_timeout_data *data = container_of(timer,
5376 struct io_timeout_data, timer);
5377 struct io_kiocb *req = data->req;
5378 struct io_ring_ctx *ctx = req->ctx;
5379 unsigned long flags;
5381 spin_lock_irqsave(&ctx->completion_lock, flags);
5382 list_del_init(&req->timeout.list);
5383 atomic_set(&req->ctx->cq_timeouts,
5384 atomic_read(&req->ctx->cq_timeouts) + 1);
5386 io_cqring_fill_event(req, -ETIME);
5387 io_commit_cqring(ctx);
5388 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5390 io_cqring_ev_posted(ctx);
5391 req_set_fail_links(req);
5393 return HRTIMER_NORESTART;
5396 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5399 struct io_timeout_data *io;
5400 struct io_kiocb *req;
5403 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5404 if (user_data == req->user_data) {
5411 return ERR_PTR(ret);
5413 io = req->async_data;
5414 ret = hrtimer_try_to_cancel(&io->timer);
5416 return ERR_PTR(-EALREADY);
5417 list_del_init(&req->timeout.list);
5421 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5423 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5426 return PTR_ERR(req);
5428 req_set_fail_links(req);
5429 io_cqring_fill_event(req, -ECANCELED);
5430 io_put_req_deferred(req, 1);
5434 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5435 struct timespec64 *ts, enum hrtimer_mode mode)
5437 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5438 struct io_timeout_data *data;
5441 return PTR_ERR(req);
5443 req->timeout.off = 0; /* noseq */
5444 data = req->async_data;
5445 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5446 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5447 data->timer.function = io_timeout_fn;
5448 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5452 static int io_timeout_remove_prep(struct io_kiocb *req,
5453 const struct io_uring_sqe *sqe)
5455 struct io_timeout_rem *tr = &req->timeout_rem;
5457 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5459 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5461 if (sqe->ioprio || sqe->buf_index || sqe->len)
5464 tr->addr = READ_ONCE(sqe->addr);
5465 tr->flags = READ_ONCE(sqe->timeout_flags);
5466 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5467 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5469 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5471 } else if (tr->flags) {
5472 /* timeout removal doesn't support flags */
5479 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5481 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5486 * Remove or update an existing timeout command
5488 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5490 struct io_timeout_rem *tr = &req->timeout_rem;
5491 struct io_ring_ctx *ctx = req->ctx;
5494 spin_lock_irq(&ctx->completion_lock);
5495 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5496 ret = io_timeout_cancel(ctx, tr->addr);
5498 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5499 io_translate_timeout_mode(tr->flags));
5501 io_cqring_fill_event(req, ret);
5502 io_commit_cqring(ctx);
5503 spin_unlock_irq(&ctx->completion_lock);
5504 io_cqring_ev_posted(ctx);
5506 req_set_fail_links(req);
5511 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5512 bool is_timeout_link)
5514 struct io_timeout_data *data;
5516 u32 off = READ_ONCE(sqe->off);
5518 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5520 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5522 if (off && is_timeout_link)
5524 flags = READ_ONCE(sqe->timeout_flags);
5525 if (flags & ~IORING_TIMEOUT_ABS)
5528 req->timeout.off = off;
5530 if (!req->async_data && io_alloc_async_data(req))
5533 data = req->async_data;
5536 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5539 data->mode = io_translate_timeout_mode(flags);
5540 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5544 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5546 struct io_ring_ctx *ctx = req->ctx;
5547 struct io_timeout_data *data = req->async_data;
5548 struct list_head *entry;
5549 u32 tail, off = req->timeout.off;
5551 spin_lock_irq(&ctx->completion_lock);
5554 * sqe->off holds how many events that need to occur for this
5555 * timeout event to be satisfied. If it isn't set, then this is
5556 * a pure timeout request, sequence isn't used.
5558 if (io_is_timeout_noseq(req)) {
5559 entry = ctx->timeout_list.prev;
5563 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5564 req->timeout.target_seq = tail + off;
5566 /* Update the last seq here in case io_flush_timeouts() hasn't.
5567 * This is safe because ->completion_lock is held, and submissions
5568 * and completions are never mixed in the same ->completion_lock section.
5570 ctx->cq_last_tm_flush = tail;
5573 * Insertion sort, ensuring the first entry in the list is always
5574 * the one we need first.
5576 list_for_each_prev(entry, &ctx->timeout_list) {
5577 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5580 if (io_is_timeout_noseq(nxt))
5582 /* nxt.seq is behind @tail, otherwise would've been completed */
5583 if (off >= nxt->timeout.target_seq - tail)
5587 list_add(&req->timeout.list, entry);
5588 data->timer.function = io_timeout_fn;
5589 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5590 spin_unlock_irq(&ctx->completion_lock);
5594 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5596 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5598 return req->user_data == (unsigned long) data;
5601 static int io_async_cancel_one(struct io_uring_task *tctx, void *sqe_addr)
5603 enum io_wq_cancel cancel_ret;
5609 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, sqe_addr, false);
5610 switch (cancel_ret) {
5611 case IO_WQ_CANCEL_OK:
5614 case IO_WQ_CANCEL_RUNNING:
5617 case IO_WQ_CANCEL_NOTFOUND:
5625 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5626 struct io_kiocb *req, __u64 sqe_addr,
5629 unsigned long flags;
5632 ret = io_async_cancel_one(req->task->io_uring,
5633 (void *) (unsigned long) sqe_addr);
5634 if (ret != -ENOENT) {
5635 spin_lock_irqsave(&ctx->completion_lock, flags);
5639 spin_lock_irqsave(&ctx->completion_lock, flags);
5640 ret = io_timeout_cancel(ctx, sqe_addr);
5643 ret = io_poll_cancel(ctx, sqe_addr);
5647 io_cqring_fill_event(req, ret);
5648 io_commit_cqring(ctx);
5649 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5650 io_cqring_ev_posted(ctx);
5653 req_set_fail_links(req);
5657 static int io_async_cancel_prep(struct io_kiocb *req,
5658 const struct io_uring_sqe *sqe)
5660 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5662 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5664 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5667 req->cancel.addr = READ_ONCE(sqe->addr);
5671 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5673 struct io_ring_ctx *ctx = req->ctx;
5675 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5679 static int io_rsrc_update_prep(struct io_kiocb *req,
5680 const struct io_uring_sqe *sqe)
5682 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5684 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5686 if (sqe->ioprio || sqe->rw_flags)
5689 req->rsrc_update.offset = READ_ONCE(sqe->off);
5690 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5691 if (!req->rsrc_update.nr_args)
5693 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5697 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5699 struct io_ring_ctx *ctx = req->ctx;
5700 struct io_uring_rsrc_update up;
5703 if (issue_flags & IO_URING_F_NONBLOCK)
5706 up.offset = req->rsrc_update.offset;
5707 up.data = req->rsrc_update.arg;
5709 mutex_lock(&ctx->uring_lock);
5710 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5711 mutex_unlock(&ctx->uring_lock);
5714 req_set_fail_links(req);
5715 __io_req_complete(req, issue_flags, ret, 0);
5719 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5721 switch (req->opcode) {
5724 case IORING_OP_READV:
5725 case IORING_OP_READ_FIXED:
5726 case IORING_OP_READ:
5727 return io_read_prep(req, sqe);
5728 case IORING_OP_WRITEV:
5729 case IORING_OP_WRITE_FIXED:
5730 case IORING_OP_WRITE:
5731 return io_write_prep(req, sqe);
5732 case IORING_OP_POLL_ADD:
5733 return io_poll_add_prep(req, sqe);
5734 case IORING_OP_POLL_REMOVE:
5735 return io_poll_remove_prep(req, sqe);
5736 case IORING_OP_FSYNC:
5737 return io_fsync_prep(req, sqe);
5738 case IORING_OP_SYNC_FILE_RANGE:
5739 return io_sfr_prep(req, sqe);
5740 case IORING_OP_SENDMSG:
5741 case IORING_OP_SEND:
5742 return io_sendmsg_prep(req, sqe);
5743 case IORING_OP_RECVMSG:
5744 case IORING_OP_RECV:
5745 return io_recvmsg_prep(req, sqe);
5746 case IORING_OP_CONNECT:
5747 return io_connect_prep(req, sqe);
5748 case IORING_OP_TIMEOUT:
5749 return io_timeout_prep(req, sqe, false);
5750 case IORING_OP_TIMEOUT_REMOVE:
5751 return io_timeout_remove_prep(req, sqe);
5752 case IORING_OP_ASYNC_CANCEL:
5753 return io_async_cancel_prep(req, sqe);
5754 case IORING_OP_LINK_TIMEOUT:
5755 return io_timeout_prep(req, sqe, true);
5756 case IORING_OP_ACCEPT:
5757 return io_accept_prep(req, sqe);
5758 case IORING_OP_FALLOCATE:
5759 return io_fallocate_prep(req, sqe);
5760 case IORING_OP_OPENAT:
5761 return io_openat_prep(req, sqe);
5762 case IORING_OP_CLOSE:
5763 return io_close_prep(req, sqe);
5764 case IORING_OP_FILES_UPDATE:
5765 return io_rsrc_update_prep(req, sqe);
5766 case IORING_OP_STATX:
5767 return io_statx_prep(req, sqe);
5768 case IORING_OP_FADVISE:
5769 return io_fadvise_prep(req, sqe);
5770 case IORING_OP_MADVISE:
5771 return io_madvise_prep(req, sqe);
5772 case IORING_OP_OPENAT2:
5773 return io_openat2_prep(req, sqe);
5774 case IORING_OP_EPOLL_CTL:
5775 return io_epoll_ctl_prep(req, sqe);
5776 case IORING_OP_SPLICE:
5777 return io_splice_prep(req, sqe);
5778 case IORING_OP_PROVIDE_BUFFERS:
5779 return io_provide_buffers_prep(req, sqe);
5780 case IORING_OP_REMOVE_BUFFERS:
5781 return io_remove_buffers_prep(req, sqe);
5783 return io_tee_prep(req, sqe);
5784 case IORING_OP_SHUTDOWN:
5785 return io_shutdown_prep(req, sqe);
5786 case IORING_OP_RENAMEAT:
5787 return io_renameat_prep(req, sqe);
5788 case IORING_OP_UNLINKAT:
5789 return io_unlinkat_prep(req, sqe);
5792 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5797 static int io_req_prep_async(struct io_kiocb *req)
5799 switch (req->opcode) {
5800 case IORING_OP_READV:
5801 case IORING_OP_READ_FIXED:
5802 case IORING_OP_READ:
5803 return io_rw_prep_async(req, READ);
5804 case IORING_OP_WRITEV:
5805 case IORING_OP_WRITE_FIXED:
5806 case IORING_OP_WRITE:
5807 return io_rw_prep_async(req, WRITE);
5808 case IORING_OP_SENDMSG:
5809 case IORING_OP_SEND:
5810 return io_sendmsg_prep_async(req);
5811 case IORING_OP_RECVMSG:
5812 case IORING_OP_RECV:
5813 return io_recvmsg_prep_async(req);
5814 case IORING_OP_CONNECT:
5815 return io_connect_prep_async(req);
5820 static int io_req_defer_prep(struct io_kiocb *req)
5822 if (!io_op_defs[req->opcode].needs_async_data)
5824 /* some opcodes init it during the inital prep */
5825 if (req->async_data)
5827 if (__io_alloc_async_data(req))
5829 return io_req_prep_async(req);
5832 static u32 io_get_sequence(struct io_kiocb *req)
5834 struct io_kiocb *pos;
5835 struct io_ring_ctx *ctx = req->ctx;
5836 u32 total_submitted, nr_reqs = 0;
5838 io_for_each_link(pos, req)
5841 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5842 return total_submitted - nr_reqs;
5845 static int io_req_defer(struct io_kiocb *req)
5847 struct io_ring_ctx *ctx = req->ctx;
5848 struct io_defer_entry *de;
5852 /* Still need defer if there is pending req in defer list. */
5853 if (likely(list_empty_careful(&ctx->defer_list) &&
5854 !(req->flags & REQ_F_IO_DRAIN)))
5857 seq = io_get_sequence(req);
5858 /* Still a chance to pass the sequence check */
5859 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5862 ret = io_req_defer_prep(req);
5865 io_prep_async_link(req);
5866 de = kmalloc(sizeof(*de), GFP_KERNEL);
5870 spin_lock_irq(&ctx->completion_lock);
5871 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5872 spin_unlock_irq(&ctx->completion_lock);
5874 io_queue_async_work(req);
5875 return -EIOCBQUEUED;
5878 trace_io_uring_defer(ctx, req, req->user_data);
5881 list_add_tail(&de->list, &ctx->defer_list);
5882 spin_unlock_irq(&ctx->completion_lock);
5883 return -EIOCBQUEUED;
5886 static void __io_clean_op(struct io_kiocb *req)
5888 if (req->flags & REQ_F_BUFFER_SELECTED) {
5889 switch (req->opcode) {
5890 case IORING_OP_READV:
5891 case IORING_OP_READ_FIXED:
5892 case IORING_OP_READ:
5893 kfree((void *)(unsigned long)req->rw.addr);
5895 case IORING_OP_RECVMSG:
5896 case IORING_OP_RECV:
5897 kfree(req->sr_msg.kbuf);
5900 req->flags &= ~REQ_F_BUFFER_SELECTED;
5903 if (req->flags & REQ_F_NEED_CLEANUP) {
5904 switch (req->opcode) {
5905 case IORING_OP_READV:
5906 case IORING_OP_READ_FIXED:
5907 case IORING_OP_READ:
5908 case IORING_OP_WRITEV:
5909 case IORING_OP_WRITE_FIXED:
5910 case IORING_OP_WRITE: {
5911 struct io_async_rw *io = req->async_data;
5913 kfree(io->free_iovec);
5916 case IORING_OP_RECVMSG:
5917 case IORING_OP_SENDMSG: {
5918 struct io_async_msghdr *io = req->async_data;
5920 kfree(io->free_iov);
5923 case IORING_OP_SPLICE:
5925 io_put_file(req, req->splice.file_in,
5926 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5928 case IORING_OP_OPENAT:
5929 case IORING_OP_OPENAT2:
5930 if (req->open.filename)
5931 putname(req->open.filename);
5933 case IORING_OP_RENAMEAT:
5934 putname(req->rename.oldpath);
5935 putname(req->rename.newpath);
5937 case IORING_OP_UNLINKAT:
5938 putname(req->unlink.filename);
5941 req->flags &= ~REQ_F_NEED_CLEANUP;
5945 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
5947 struct io_ring_ctx *ctx = req->ctx;
5950 switch (req->opcode) {
5952 ret = io_nop(req, issue_flags);
5954 case IORING_OP_READV:
5955 case IORING_OP_READ_FIXED:
5956 case IORING_OP_READ:
5957 ret = io_read(req, issue_flags);
5959 case IORING_OP_WRITEV:
5960 case IORING_OP_WRITE_FIXED:
5961 case IORING_OP_WRITE:
5962 ret = io_write(req, issue_flags);
5964 case IORING_OP_FSYNC:
5965 ret = io_fsync(req, issue_flags);
5967 case IORING_OP_POLL_ADD:
5968 ret = io_poll_add(req, issue_flags);
5970 case IORING_OP_POLL_REMOVE:
5971 ret = io_poll_remove(req, issue_flags);
5973 case IORING_OP_SYNC_FILE_RANGE:
5974 ret = io_sync_file_range(req, issue_flags);
5976 case IORING_OP_SENDMSG:
5977 ret = io_sendmsg(req, issue_flags);
5979 case IORING_OP_SEND:
5980 ret = io_send(req, issue_flags);
5982 case IORING_OP_RECVMSG:
5983 ret = io_recvmsg(req, issue_flags);
5985 case IORING_OP_RECV:
5986 ret = io_recv(req, issue_flags);
5988 case IORING_OP_TIMEOUT:
5989 ret = io_timeout(req, issue_flags);
5991 case IORING_OP_TIMEOUT_REMOVE:
5992 ret = io_timeout_remove(req, issue_flags);
5994 case IORING_OP_ACCEPT:
5995 ret = io_accept(req, issue_flags);
5997 case IORING_OP_CONNECT:
5998 ret = io_connect(req, issue_flags);
6000 case IORING_OP_ASYNC_CANCEL:
6001 ret = io_async_cancel(req, issue_flags);
6003 case IORING_OP_FALLOCATE:
6004 ret = io_fallocate(req, issue_flags);
6006 case IORING_OP_OPENAT:
6007 ret = io_openat(req, issue_flags);
6009 case IORING_OP_CLOSE:
6010 ret = io_close(req, issue_flags);
6012 case IORING_OP_FILES_UPDATE:
6013 ret = io_files_update(req, issue_flags);
6015 case IORING_OP_STATX:
6016 ret = io_statx(req, issue_flags);
6018 case IORING_OP_FADVISE:
6019 ret = io_fadvise(req, issue_flags);
6021 case IORING_OP_MADVISE:
6022 ret = io_madvise(req, issue_flags);
6024 case IORING_OP_OPENAT2:
6025 ret = io_openat2(req, issue_flags);
6027 case IORING_OP_EPOLL_CTL:
6028 ret = io_epoll_ctl(req, issue_flags);
6030 case IORING_OP_SPLICE:
6031 ret = io_splice(req, issue_flags);
6033 case IORING_OP_PROVIDE_BUFFERS:
6034 ret = io_provide_buffers(req, issue_flags);
6036 case IORING_OP_REMOVE_BUFFERS:
6037 ret = io_remove_buffers(req, issue_flags);
6040 ret = io_tee(req, issue_flags);
6042 case IORING_OP_SHUTDOWN:
6043 ret = io_shutdown(req, issue_flags);
6045 case IORING_OP_RENAMEAT:
6046 ret = io_renameat(req, issue_flags);
6048 case IORING_OP_UNLINKAT:
6049 ret = io_unlinkat(req, issue_flags);
6059 /* If the op doesn't have a file, we're not polling for it */
6060 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6061 const bool in_async = io_wq_current_is_worker();
6063 /* workqueue context doesn't hold uring_lock, grab it now */
6065 mutex_lock(&ctx->uring_lock);
6067 io_iopoll_req_issued(req, in_async);
6070 mutex_unlock(&ctx->uring_lock);
6076 static void io_wq_submit_work(struct io_wq_work *work)
6078 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6079 struct io_kiocb *timeout;
6082 timeout = io_prep_linked_timeout(req);
6084 io_queue_linked_timeout(timeout);
6086 if (work->flags & IO_WQ_WORK_CANCEL)
6091 ret = io_issue_sqe(req, 0);
6093 * We can get EAGAIN for polled IO even though we're
6094 * forcing a sync submission from here, since we can't
6095 * wait for request slots on the block side.
6103 /* avoid locking problems by failing it from a clean context */
6105 /* io-wq is going to take one down */
6106 refcount_inc(&req->refs);
6107 io_req_task_queue_fail(req, ret);
6111 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6114 struct fixed_rsrc_table *table;
6116 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6117 return table->files[index & IORING_FILE_TABLE_MASK];
6120 static struct file *io_file_get(struct io_submit_state *state,
6121 struct io_kiocb *req, int fd, bool fixed)
6123 struct io_ring_ctx *ctx = req->ctx;
6127 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6129 fd = array_index_nospec(fd, ctx->nr_user_files);
6130 file = io_file_from_index(ctx, fd);
6131 io_set_resource_node(req);
6133 trace_io_uring_file_get(ctx, fd);
6134 file = __io_file_get(state, fd);
6137 if (file && unlikely(file->f_op == &io_uring_fops))
6138 io_req_track_inflight(req);
6142 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6144 struct io_timeout_data *data = container_of(timer,
6145 struct io_timeout_data, timer);
6146 struct io_kiocb *prev, *req = data->req;
6147 struct io_ring_ctx *ctx = req->ctx;
6148 unsigned long flags;
6150 spin_lock_irqsave(&ctx->completion_lock, flags);
6151 prev = req->timeout.head;
6152 req->timeout.head = NULL;
6155 * We don't expect the list to be empty, that will only happen if we
6156 * race with the completion of the linked work.
6158 if (prev && refcount_inc_not_zero(&prev->refs))
6159 io_remove_next_linked(prev);
6162 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6165 req_set_fail_links(prev);
6166 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6167 io_put_req_deferred(prev, 1);
6169 io_req_complete_post(req, -ETIME, 0);
6170 io_put_req_deferred(req, 1);
6172 return HRTIMER_NORESTART;
6175 static void __io_queue_linked_timeout(struct io_kiocb *req)
6178 * If the back reference is NULL, then our linked request finished
6179 * before we got a chance to setup the timer
6181 if (req->timeout.head) {
6182 struct io_timeout_data *data = req->async_data;
6184 data->timer.function = io_link_timeout_fn;
6185 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6190 static void io_queue_linked_timeout(struct io_kiocb *req)
6192 struct io_ring_ctx *ctx = req->ctx;
6194 spin_lock_irq(&ctx->completion_lock);
6195 __io_queue_linked_timeout(req);
6196 spin_unlock_irq(&ctx->completion_lock);
6198 /* drop submission reference */
6202 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6204 struct io_kiocb *nxt = req->link;
6206 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6207 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6210 nxt->timeout.head = req;
6211 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6212 req->flags |= REQ_F_LINK_TIMEOUT;
6216 static void __io_queue_sqe(struct io_kiocb *req)
6218 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6219 const struct cred *old_creds = NULL;
6222 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
6223 req->work.creds != current_cred())
6224 old_creds = override_creds(req->work.creds);
6226 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6229 revert_creds(old_creds);
6232 * We async punt it if the file wasn't marked NOWAIT, or if the file
6233 * doesn't support non-blocking read/write attempts
6235 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6236 if (!io_arm_poll_handler(req)) {
6238 * Queued up for async execution, worker will release
6239 * submit reference when the iocb is actually submitted.
6241 io_queue_async_work(req);
6243 } else if (likely(!ret)) {
6244 /* drop submission reference */
6245 if (req->flags & REQ_F_COMPLETE_INLINE) {
6246 struct io_ring_ctx *ctx = req->ctx;
6247 struct io_comp_state *cs = &ctx->submit_state.comp;
6249 cs->reqs[cs->nr++] = req;
6250 if (cs->nr == ARRAY_SIZE(cs->reqs))
6251 io_submit_flush_completions(cs, ctx);
6256 req_set_fail_links(req);
6258 io_req_complete(req, ret);
6261 io_queue_linked_timeout(linked_timeout);
6264 static void io_queue_sqe(struct io_kiocb *req)
6268 ret = io_req_defer(req);
6270 if (ret != -EIOCBQUEUED) {
6272 req_set_fail_links(req);
6274 io_req_complete(req, ret);
6276 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6277 ret = io_req_defer_prep(req);
6280 io_queue_async_work(req);
6282 __io_queue_sqe(req);
6287 * Check SQE restrictions (opcode and flags).
6289 * Returns 'true' if SQE is allowed, 'false' otherwise.
6291 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6292 struct io_kiocb *req,
6293 unsigned int sqe_flags)
6295 if (!ctx->restricted)
6298 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6301 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6302 ctx->restrictions.sqe_flags_required)
6305 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6306 ctx->restrictions.sqe_flags_required))
6312 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6313 const struct io_uring_sqe *sqe)
6315 struct io_submit_state *state;
6316 unsigned int sqe_flags;
6319 req->opcode = READ_ONCE(sqe->opcode);
6320 /* same numerical values with corresponding REQ_F_*, safe to copy */
6321 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6322 req->user_data = READ_ONCE(sqe->user_data);
6323 req->async_data = NULL;
6327 req->fixed_rsrc_refs = NULL;
6328 /* one is dropped after submission, the other at completion */
6329 refcount_set(&req->refs, 2);
6330 req->task = current;
6333 /* enforce forwards compatibility on users */
6334 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6339 if (unlikely(req->opcode >= IORING_OP_LAST))
6342 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6345 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6346 !io_op_defs[req->opcode].buffer_select)
6349 id = READ_ONCE(sqe->personality);
6351 __io_req_init_async(req);
6352 req->work.creds = idr_find(&ctx->personality_idr, id);
6353 if (unlikely(!req->work.creds))
6355 get_cred(req->work.creds);
6358 state = &ctx->submit_state;
6361 * Plug now if we have more than 1 IO left after this, and the target
6362 * is potentially a read/write to block based storage.
6364 if (!state->plug_started && state->ios_left > 1 &&
6365 io_op_defs[req->opcode].plug) {
6366 blk_start_plug(&state->plug);
6367 state->plug_started = true;
6370 if (io_op_defs[req->opcode].needs_file) {
6371 bool fixed = req->flags & REQ_F_FIXED_FILE;
6373 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6374 if (unlikely(!req->file))
6382 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6383 const struct io_uring_sqe *sqe)
6385 struct io_submit_link *link = &ctx->submit_state.link;
6388 ret = io_init_req(ctx, req, sqe);
6389 if (unlikely(ret)) {
6392 io_req_complete(req, ret);
6394 /* fail even hard links since we don't submit */
6395 link->head->flags |= REQ_F_FAIL_LINK;
6396 io_put_req(link->head);
6397 io_req_complete(link->head, -ECANCELED);
6402 ret = io_req_prep(req, sqe);
6406 /* don't need @sqe from now on */
6407 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6408 true, ctx->flags & IORING_SETUP_SQPOLL);
6411 * If we already have a head request, queue this one for async
6412 * submittal once the head completes. If we don't have a head but
6413 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6414 * submitted sync once the chain is complete. If none of those
6415 * conditions are true (normal request), then just queue it.
6418 struct io_kiocb *head = link->head;
6421 * Taking sequential execution of a link, draining both sides
6422 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6423 * requests in the link. So, it drains the head and the
6424 * next after the link request. The last one is done via
6425 * drain_next flag to persist the effect across calls.
6427 if (req->flags & REQ_F_IO_DRAIN) {
6428 head->flags |= REQ_F_IO_DRAIN;
6429 ctx->drain_next = 1;
6431 ret = io_req_defer_prep(req);
6434 trace_io_uring_link(ctx, req, head);
6435 link->last->link = req;
6438 /* last request of a link, enqueue the link */
6439 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6444 if (unlikely(ctx->drain_next)) {
6445 req->flags |= REQ_F_IO_DRAIN;
6446 ctx->drain_next = 0;
6448 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6460 * Batched submission is done, ensure local IO is flushed out.
6462 static void io_submit_state_end(struct io_submit_state *state,
6463 struct io_ring_ctx *ctx)
6465 if (state->link.head)
6466 io_queue_sqe(state->link.head);
6468 io_submit_flush_completions(&state->comp, ctx);
6469 if (state->plug_started)
6470 blk_finish_plug(&state->plug);
6471 io_state_file_put(state);
6475 * Start submission side cache.
6477 static void io_submit_state_start(struct io_submit_state *state,
6478 unsigned int max_ios)
6480 state->plug_started = false;
6481 state->ios_left = max_ios;
6482 /* set only head, no need to init link_last in advance */
6483 state->link.head = NULL;
6486 static void io_commit_sqring(struct io_ring_ctx *ctx)
6488 struct io_rings *rings = ctx->rings;
6491 * Ensure any loads from the SQEs are done at this point,
6492 * since once we write the new head, the application could
6493 * write new data to them.
6495 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6499 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6500 * that is mapped by userspace. This means that care needs to be taken to
6501 * ensure that reads are stable, as we cannot rely on userspace always
6502 * being a good citizen. If members of the sqe are validated and then later
6503 * used, it's important that those reads are done through READ_ONCE() to
6504 * prevent a re-load down the line.
6506 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6508 u32 *sq_array = ctx->sq_array;
6512 * The cached sq head (or cq tail) serves two purposes:
6514 * 1) allows us to batch the cost of updating the user visible
6516 * 2) allows the kernel side to track the head on its own, even
6517 * though the application is the one updating it.
6519 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6520 if (likely(head < ctx->sq_entries))
6521 return &ctx->sq_sqes[head];
6523 /* drop invalid entries */
6524 ctx->cached_sq_dropped++;
6525 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6529 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6533 /* if we have a backlog and couldn't flush it all, return BUSY */
6534 if (test_bit(0, &ctx->sq_check_overflow)) {
6535 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6539 /* make sure SQ entry isn't read before tail */
6540 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6542 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6545 percpu_counter_add(¤t->io_uring->inflight, nr);
6546 refcount_add(nr, ¤t->usage);
6547 io_submit_state_start(&ctx->submit_state, nr);
6549 while (submitted < nr) {
6550 const struct io_uring_sqe *sqe;
6551 struct io_kiocb *req;
6553 req = io_alloc_req(ctx);
6554 if (unlikely(!req)) {
6556 submitted = -EAGAIN;
6559 sqe = io_get_sqe(ctx);
6560 if (unlikely(!sqe)) {
6561 kmem_cache_free(req_cachep, req);
6564 /* will complete beyond this point, count as submitted */
6566 if (io_submit_sqe(ctx, req, sqe))
6570 if (unlikely(submitted != nr)) {
6571 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6572 struct io_uring_task *tctx = current->io_uring;
6573 int unused = nr - ref_used;
6575 percpu_ref_put_many(&ctx->refs, unused);
6576 percpu_counter_sub(&tctx->inflight, unused);
6577 put_task_struct_many(current, unused);
6580 io_submit_state_end(&ctx->submit_state, ctx);
6581 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6582 io_commit_sqring(ctx);
6587 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6589 /* Tell userspace we may need a wakeup call */
6590 spin_lock_irq(&ctx->completion_lock);
6591 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6592 spin_unlock_irq(&ctx->completion_lock);
6595 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6597 spin_lock_irq(&ctx->completion_lock);
6598 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6599 spin_unlock_irq(&ctx->completion_lock);
6602 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6604 unsigned int to_submit;
6607 to_submit = io_sqring_entries(ctx);
6608 /* if we're handling multiple rings, cap submit size for fairness */
6609 if (cap_entries && to_submit > 8)
6612 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6613 unsigned nr_events = 0;
6615 mutex_lock(&ctx->uring_lock);
6616 if (!list_empty(&ctx->iopoll_list))
6617 io_do_iopoll(ctx, &nr_events, 0);
6619 if (to_submit && !ctx->sqo_dead &&
6620 likely(!percpu_ref_is_dying(&ctx->refs)))
6621 ret = io_submit_sqes(ctx, to_submit);
6622 mutex_unlock(&ctx->uring_lock);
6625 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6626 wake_up(&ctx->sqo_sq_wait);
6631 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6633 struct io_ring_ctx *ctx;
6634 unsigned sq_thread_idle = 0;
6636 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6637 if (sq_thread_idle < ctx->sq_thread_idle)
6638 sq_thread_idle = ctx->sq_thread_idle;
6641 sqd->sq_thread_idle = sq_thread_idle;
6644 static void io_sqd_init_new(struct io_sq_data *sqd)
6646 struct io_ring_ctx *ctx;
6648 while (!list_empty(&sqd->ctx_new_list)) {
6649 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6650 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6651 complete(&ctx->sq_thread_comp);
6654 io_sqd_update_thread_idle(sqd);
6657 static bool io_sq_thread_should_stop(struct io_sq_data *sqd)
6659 return test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6662 static bool io_sq_thread_should_park(struct io_sq_data *sqd)
6664 return test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
6667 static void io_sq_thread_parkme(struct io_sq_data *sqd)
6671 * TASK_PARKED is a special state; we must serialize against
6672 * possible pending wakeups to avoid store-store collisions on
6675 * Such a collision might possibly result in the task state
6676 * changin from TASK_PARKED and us failing the
6677 * wait_task_inactive() in kthread_park().
6679 set_special_state(TASK_PARKED);
6680 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state))
6684 * Thread is going to call schedule(), do not preempt it,
6685 * or the caller of kthread_park() may spend more time in
6686 * wait_task_inactive().
6689 complete(&sqd->completion);
6690 schedule_preempt_disabled();
6693 __set_current_state(TASK_RUNNING);
6696 static int io_sq_thread(void *data)
6698 struct io_sq_data *sqd = data;
6699 struct io_ring_ctx *ctx;
6700 unsigned long timeout = 0;
6701 char buf[TASK_COMM_LEN];
6704 sprintf(buf, "iou-sqp-%d", sqd->task_pid);
6705 set_task_comm(current, buf);
6706 sqd->thread = current;
6707 current->pf_io_worker = NULL;
6709 if (sqd->sq_cpu != -1)
6710 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6712 set_cpus_allowed_ptr(current, cpu_online_mask);
6713 current->flags |= PF_NO_SETAFFINITY;
6715 complete(&sqd->completion);
6717 wait_for_completion(&sqd->startup);
6719 while (!io_sq_thread_should_stop(sqd)) {
6721 bool cap_entries, sqt_spin, needs_sched;
6724 * Any changes to the sqd lists are synchronized through the
6725 * thread parking. This synchronizes the thread vs users,
6726 * the users are synchronized on the sqd->ctx_lock.
6728 if (io_sq_thread_should_park(sqd)) {
6729 io_sq_thread_parkme(sqd);
6732 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
6733 io_sqd_init_new(sqd);
6734 timeout = jiffies + sqd->sq_thread_idle;
6736 if (fatal_signal_pending(current))
6739 cap_entries = !list_is_singular(&sqd->ctx_list);
6740 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6741 ret = __io_sq_thread(ctx, cap_entries);
6742 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6746 if (sqt_spin || !time_after(jiffies, timeout)) {
6750 timeout = jiffies + sqd->sq_thread_idle;
6755 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6756 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6757 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6758 !list_empty_careful(&ctx->iopoll_list)) {
6759 needs_sched = false;
6762 if (io_sqring_entries(ctx)) {
6763 needs_sched = false;
6768 if (needs_sched && !io_sq_thread_should_park(sqd)) {
6769 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6770 io_ring_set_wakeup_flag(ctx);
6773 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6774 io_ring_clear_wakeup_flag(ctx);
6777 finish_wait(&sqd->wait, &wait);
6778 timeout = jiffies + sqd->sq_thread_idle;
6781 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6782 io_uring_cancel_sqpoll(ctx);
6787 * Clear thread under lock so that concurrent parks work correctly
6789 complete_all(&sqd->completion);
6790 mutex_lock(&sqd->lock);
6792 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6794 io_ring_set_wakeup_flag(ctx);
6796 mutex_unlock(&sqd->lock);
6798 complete(&sqd->exited);
6802 struct io_wait_queue {
6803 struct wait_queue_entry wq;
6804 struct io_ring_ctx *ctx;
6806 unsigned nr_timeouts;
6809 static inline bool io_should_wake(struct io_wait_queue *iowq)
6811 struct io_ring_ctx *ctx = iowq->ctx;
6814 * Wake up if we have enough events, or if a timeout occurred since we
6815 * started waiting. For timeouts, we always want to return to userspace,
6816 * regardless of event count.
6818 return io_cqring_events(ctx) >= iowq->to_wait ||
6819 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6822 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6823 int wake_flags, void *key)
6825 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6829 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6830 * the task, and the next invocation will do it.
6832 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6833 return autoremove_wake_function(curr, mode, wake_flags, key);
6837 static int io_run_task_work_sig(void)
6839 if (io_run_task_work())
6841 if (!signal_pending(current))
6843 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
6844 return -ERESTARTSYS;
6848 /* when returns >0, the caller should retry */
6849 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6850 struct io_wait_queue *iowq,
6851 signed long *timeout)
6855 /* make sure we run task_work before checking for signals */
6856 ret = io_run_task_work_sig();
6857 if (ret || io_should_wake(iowq))
6859 /* let the caller flush overflows, retry */
6860 if (test_bit(0, &ctx->cq_check_overflow))
6863 *timeout = schedule_timeout(*timeout);
6864 return !*timeout ? -ETIME : 1;
6868 * Wait until events become available, if we don't already have some. The
6869 * application must reap them itself, as they reside on the shared cq ring.
6871 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6872 const sigset_t __user *sig, size_t sigsz,
6873 struct __kernel_timespec __user *uts)
6875 struct io_wait_queue iowq = {
6878 .func = io_wake_function,
6879 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6882 .to_wait = min_events,
6884 struct io_rings *rings = ctx->rings;
6885 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6889 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6890 if (io_cqring_events(ctx) >= min_events)
6892 if (!io_run_task_work())
6897 #ifdef CONFIG_COMPAT
6898 if (in_compat_syscall())
6899 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6903 ret = set_user_sigmask(sig, sigsz);
6910 struct timespec64 ts;
6912 if (get_timespec64(&ts, uts))
6914 timeout = timespec64_to_jiffies(&ts);
6917 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6918 trace_io_uring_cqring_wait(ctx, min_events);
6920 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6921 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6922 TASK_INTERRUPTIBLE);
6923 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
6924 finish_wait(&ctx->wait, &iowq.wq);
6927 restore_saved_sigmask_unless(ret == -EINTR);
6929 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6932 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6934 #if defined(CONFIG_UNIX)
6935 if (ctx->ring_sock) {
6936 struct sock *sock = ctx->ring_sock->sk;
6937 struct sk_buff *skb;
6939 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6945 for (i = 0; i < ctx->nr_user_files; i++) {
6948 file = io_file_from_index(ctx, i);
6955 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
6957 struct fixed_rsrc_data *data;
6959 data = container_of(ref, struct fixed_rsrc_data, refs);
6960 complete(&data->done);
6963 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
6965 spin_lock_bh(&ctx->rsrc_ref_lock);
6968 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
6970 spin_unlock_bh(&ctx->rsrc_ref_lock);
6973 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
6974 struct fixed_rsrc_data *rsrc_data,
6975 struct fixed_rsrc_ref_node *ref_node)
6977 io_rsrc_ref_lock(ctx);
6978 rsrc_data->node = ref_node;
6979 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
6980 io_rsrc_ref_unlock(ctx);
6981 percpu_ref_get(&rsrc_data->refs);
6984 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
6986 struct fixed_rsrc_ref_node *ref_node = NULL;
6988 io_rsrc_ref_lock(ctx);
6989 ref_node = data->node;
6991 io_rsrc_ref_unlock(ctx);
6993 percpu_ref_kill(&ref_node->refs);
6996 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
6997 struct io_ring_ctx *ctx,
6998 void (*rsrc_put)(struct io_ring_ctx *ctx,
6999 struct io_rsrc_put *prsrc))
7001 struct fixed_rsrc_ref_node *backup_node;
7007 data->quiesce = true;
7010 backup_node = alloc_fixed_rsrc_ref_node(ctx);
7013 backup_node->rsrc_data = data;
7014 backup_node->rsrc_put = rsrc_put;
7016 io_sqe_rsrc_kill_node(ctx, data);
7017 percpu_ref_kill(&data->refs);
7018 flush_delayed_work(&ctx->rsrc_put_work);
7020 ret = wait_for_completion_interruptible(&data->done);
7024 percpu_ref_resurrect(&data->refs);
7025 io_sqe_rsrc_set_node(ctx, data, backup_node);
7027 reinit_completion(&data->done);
7028 mutex_unlock(&ctx->uring_lock);
7029 ret = io_run_task_work_sig();
7030 mutex_lock(&ctx->uring_lock);
7032 data->quiesce = false;
7035 destroy_fixed_rsrc_ref_node(backup_node);
7039 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7041 struct fixed_rsrc_data *data;
7043 data = kzalloc(sizeof(*data), GFP_KERNEL);
7047 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7048 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7053 init_completion(&data->done);
7057 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7059 percpu_ref_exit(&data->refs);
7064 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7066 struct fixed_rsrc_data *data = ctx->file_data;
7067 unsigned nr_tables, i;
7071 * percpu_ref_is_dying() is to stop parallel files unregister
7072 * Since we possibly drop uring lock later in this function to
7075 if (!data || percpu_ref_is_dying(&data->refs))
7077 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7081 __io_sqe_files_unregister(ctx);
7082 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7083 for (i = 0; i < nr_tables; i++)
7084 kfree(data->table[i].files);
7085 free_fixed_rsrc_data(data);
7086 ctx->file_data = NULL;
7087 ctx->nr_user_files = 0;
7091 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7092 __releases(&sqd->lock)
7096 if (sqd->thread == current)
7098 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7099 wake_up_state(sqd->thread, TASK_PARKED);
7100 mutex_unlock(&sqd->lock);
7103 static bool io_sq_thread_park(struct io_sq_data *sqd)
7104 __acquires(&sqd->lock)
7106 if (sqd->thread == current)
7108 mutex_lock(&sqd->lock);
7110 mutex_unlock(&sqd->lock);
7113 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7114 wake_up_process(sqd->thread);
7115 wait_for_completion(&sqd->completion);
7119 static void io_sq_thread_stop(struct io_sq_data *sqd)
7124 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7125 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state));
7126 wake_up_process(sqd->thread);
7127 wait_for_completion(&sqd->exited);
7130 static void io_put_sq_data(struct io_sq_data *sqd)
7132 if (refcount_dec_and_test(&sqd->refs)) {
7133 io_sq_thread_stop(sqd);
7138 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7140 struct io_sq_data *sqd = ctx->sq_data;
7143 complete(&sqd->startup);
7145 wait_for_completion(&ctx->sq_thread_comp);
7146 io_sq_thread_park(sqd);
7149 mutex_lock(&sqd->ctx_lock);
7150 list_del(&ctx->sqd_list);
7151 io_sqd_update_thread_idle(sqd);
7152 mutex_unlock(&sqd->ctx_lock);
7155 io_sq_thread_unpark(sqd);
7157 io_put_sq_data(sqd);
7158 ctx->sq_data = NULL;
7162 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7164 struct io_ring_ctx *ctx_attach;
7165 struct io_sq_data *sqd;
7168 f = fdget(p->wq_fd);
7170 return ERR_PTR(-ENXIO);
7171 if (f.file->f_op != &io_uring_fops) {
7173 return ERR_PTR(-EINVAL);
7176 ctx_attach = f.file->private_data;
7177 sqd = ctx_attach->sq_data;
7180 return ERR_PTR(-EINVAL);
7183 refcount_inc(&sqd->refs);
7188 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7190 struct io_sq_data *sqd;
7192 if (p->flags & IORING_SETUP_ATTACH_WQ)
7193 return io_attach_sq_data(p);
7195 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7197 return ERR_PTR(-ENOMEM);
7199 refcount_set(&sqd->refs, 1);
7200 INIT_LIST_HEAD(&sqd->ctx_list);
7201 INIT_LIST_HEAD(&sqd->ctx_new_list);
7202 mutex_init(&sqd->ctx_lock);
7203 mutex_init(&sqd->lock);
7204 init_waitqueue_head(&sqd->wait);
7205 init_completion(&sqd->startup);
7206 init_completion(&sqd->completion);
7207 init_completion(&sqd->exited);
7211 #if defined(CONFIG_UNIX)
7213 * Ensure the UNIX gc is aware of our file set, so we are certain that
7214 * the io_uring can be safely unregistered on process exit, even if we have
7215 * loops in the file referencing.
7217 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7219 struct sock *sk = ctx->ring_sock->sk;
7220 struct scm_fp_list *fpl;
7221 struct sk_buff *skb;
7224 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7228 skb = alloc_skb(0, GFP_KERNEL);
7237 fpl->user = get_uid(current_user());
7238 for (i = 0; i < nr; i++) {
7239 struct file *file = io_file_from_index(ctx, i + offset);
7243 fpl->fp[nr_files] = get_file(file);
7244 unix_inflight(fpl->user, fpl->fp[nr_files]);
7249 fpl->max = SCM_MAX_FD;
7250 fpl->count = nr_files;
7251 UNIXCB(skb).fp = fpl;
7252 skb->destructor = unix_destruct_scm;
7253 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7254 skb_queue_head(&sk->sk_receive_queue, skb);
7256 for (i = 0; i < nr_files; i++)
7267 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7268 * causes regular reference counting to break down. We rely on the UNIX
7269 * garbage collection to take care of this problem for us.
7271 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7273 unsigned left, total;
7277 left = ctx->nr_user_files;
7279 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7281 ret = __io_sqe_files_scm(ctx, this_files, total);
7285 total += this_files;
7291 while (total < ctx->nr_user_files) {
7292 struct file *file = io_file_from_index(ctx, total);
7302 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7308 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7309 unsigned nr_tables, unsigned nr_files)
7313 for (i = 0; i < nr_tables; i++) {
7314 struct fixed_rsrc_table *table = &file_data->table[i];
7315 unsigned this_files;
7317 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7318 table->files = kcalloc(this_files, sizeof(struct file *),
7322 nr_files -= this_files;
7328 for (i = 0; i < nr_tables; i++) {
7329 struct fixed_rsrc_table *table = &file_data->table[i];
7330 kfree(table->files);
7335 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7337 struct file *file = prsrc->file;
7338 #if defined(CONFIG_UNIX)
7339 struct sock *sock = ctx->ring_sock->sk;
7340 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7341 struct sk_buff *skb;
7344 __skb_queue_head_init(&list);
7347 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7348 * remove this entry and rearrange the file array.
7350 skb = skb_dequeue(head);
7352 struct scm_fp_list *fp;
7354 fp = UNIXCB(skb).fp;
7355 for (i = 0; i < fp->count; i++) {
7358 if (fp->fp[i] != file)
7361 unix_notinflight(fp->user, fp->fp[i]);
7362 left = fp->count - 1 - i;
7364 memmove(&fp->fp[i], &fp->fp[i + 1],
7365 left * sizeof(struct file *));
7372 __skb_queue_tail(&list, skb);
7382 __skb_queue_tail(&list, skb);
7384 skb = skb_dequeue(head);
7387 if (skb_peek(&list)) {
7388 spin_lock_irq(&head->lock);
7389 while ((skb = __skb_dequeue(&list)) != NULL)
7390 __skb_queue_tail(head, skb);
7391 spin_unlock_irq(&head->lock);
7398 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7400 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7401 struct io_ring_ctx *ctx = rsrc_data->ctx;
7402 struct io_rsrc_put *prsrc, *tmp;
7404 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7405 list_del(&prsrc->list);
7406 ref_node->rsrc_put(ctx, prsrc);
7410 percpu_ref_exit(&ref_node->refs);
7412 percpu_ref_put(&rsrc_data->refs);
7415 static void io_rsrc_put_work(struct work_struct *work)
7417 struct io_ring_ctx *ctx;
7418 struct llist_node *node;
7420 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7421 node = llist_del_all(&ctx->rsrc_put_llist);
7424 struct fixed_rsrc_ref_node *ref_node;
7425 struct llist_node *next = node->next;
7427 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7428 __io_rsrc_put_work(ref_node);
7433 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7436 struct fixed_rsrc_table *table;
7438 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7439 return &table->files[i & IORING_FILE_TABLE_MASK];
7442 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7444 struct fixed_rsrc_ref_node *ref_node;
7445 struct fixed_rsrc_data *data;
7446 struct io_ring_ctx *ctx;
7447 bool first_add = false;
7450 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7451 data = ref_node->rsrc_data;
7454 io_rsrc_ref_lock(ctx);
7455 ref_node->done = true;
7457 while (!list_empty(&ctx->rsrc_ref_list)) {
7458 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7459 struct fixed_rsrc_ref_node, node);
7460 /* recycle ref nodes in order */
7461 if (!ref_node->done)
7463 list_del(&ref_node->node);
7464 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7466 io_rsrc_ref_unlock(ctx);
7468 if (percpu_ref_is_dying(&data->refs))
7472 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7474 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7477 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7478 struct io_ring_ctx *ctx)
7480 struct fixed_rsrc_ref_node *ref_node;
7482 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7486 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7491 INIT_LIST_HEAD(&ref_node->node);
7492 INIT_LIST_HEAD(&ref_node->rsrc_list);
7493 ref_node->done = false;
7497 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7498 struct fixed_rsrc_ref_node *ref_node)
7500 ref_node->rsrc_data = ctx->file_data;
7501 ref_node->rsrc_put = io_ring_file_put;
7504 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7506 percpu_ref_exit(&ref_node->refs);
7511 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7514 __s32 __user *fds = (__s32 __user *) arg;
7515 unsigned nr_tables, i;
7517 int fd, ret = -ENOMEM;
7518 struct fixed_rsrc_ref_node *ref_node;
7519 struct fixed_rsrc_data *file_data;
7525 if (nr_args > IORING_MAX_FIXED_FILES)
7528 file_data = alloc_fixed_rsrc_data(ctx);
7531 ctx->file_data = file_data;
7533 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7534 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7536 if (!file_data->table)
7539 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7542 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7543 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7547 /* allow sparse sets */
7557 * Don't allow io_uring instances to be registered. If UNIX
7558 * isn't enabled, then this causes a reference cycle and this
7559 * instance can never get freed. If UNIX is enabled we'll
7560 * handle it just fine, but there's still no point in allowing
7561 * a ring fd as it doesn't support regular read/write anyway.
7563 if (file->f_op == &io_uring_fops) {
7567 *io_fixed_file_slot(file_data, i) = file;
7570 ret = io_sqe_files_scm(ctx);
7572 io_sqe_files_unregister(ctx);
7576 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7578 io_sqe_files_unregister(ctx);
7581 init_fixed_file_ref_node(ctx, ref_node);
7583 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7586 for (i = 0; i < ctx->nr_user_files; i++) {
7587 file = io_file_from_index(ctx, i);
7591 for (i = 0; i < nr_tables; i++)
7592 kfree(file_data->table[i].files);
7593 ctx->nr_user_files = 0;
7595 free_fixed_rsrc_data(ctx->file_data);
7596 ctx->file_data = NULL;
7600 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7603 #if defined(CONFIG_UNIX)
7604 struct sock *sock = ctx->ring_sock->sk;
7605 struct sk_buff_head *head = &sock->sk_receive_queue;
7606 struct sk_buff *skb;
7609 * See if we can merge this file into an existing skb SCM_RIGHTS
7610 * file set. If there's no room, fall back to allocating a new skb
7611 * and filling it in.
7613 spin_lock_irq(&head->lock);
7614 skb = skb_peek(head);
7616 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7618 if (fpl->count < SCM_MAX_FD) {
7619 __skb_unlink(skb, head);
7620 spin_unlock_irq(&head->lock);
7621 fpl->fp[fpl->count] = get_file(file);
7622 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7624 spin_lock_irq(&head->lock);
7625 __skb_queue_head(head, skb);
7630 spin_unlock_irq(&head->lock);
7637 return __io_sqe_files_scm(ctx, 1, index);
7643 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7645 struct io_rsrc_put *prsrc;
7646 struct fixed_rsrc_ref_node *ref_node = data->node;
7648 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7653 list_add(&prsrc->list, &ref_node->rsrc_list);
7658 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7661 return io_queue_rsrc_removal(data, (void *)file);
7664 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7665 struct io_uring_rsrc_update *up,
7668 struct fixed_rsrc_data *data = ctx->file_data;
7669 struct fixed_rsrc_ref_node *ref_node;
7670 struct file *file, **file_slot;
7674 bool needs_switch = false;
7676 if (check_add_overflow(up->offset, nr_args, &done))
7678 if (done > ctx->nr_user_files)
7681 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7684 init_fixed_file_ref_node(ctx, ref_node);
7686 fds = u64_to_user_ptr(up->data);
7687 for (done = 0; done < nr_args; done++) {
7689 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7693 if (fd == IORING_REGISTER_FILES_SKIP)
7696 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7697 file_slot = io_fixed_file_slot(ctx->file_data, i);
7700 err = io_queue_file_removal(data, *file_slot);
7704 needs_switch = true;
7713 * Don't allow io_uring instances to be registered. If
7714 * UNIX isn't enabled, then this causes a reference
7715 * cycle and this instance can never get freed. If UNIX
7716 * is enabled we'll handle it just fine, but there's
7717 * still no point in allowing a ring fd as it doesn't
7718 * support regular read/write anyway.
7720 if (file->f_op == &io_uring_fops) {
7726 err = io_sqe_file_register(ctx, file, i);
7736 percpu_ref_kill(&data->node->refs);
7737 io_sqe_rsrc_set_node(ctx, data, ref_node);
7739 destroy_fixed_rsrc_ref_node(ref_node);
7741 return done ? done : err;
7744 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7747 struct io_uring_rsrc_update up;
7749 if (!ctx->file_data)
7753 if (copy_from_user(&up, arg, sizeof(up)))
7758 return __io_sqe_files_update(ctx, &up, nr_args);
7761 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7763 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7765 req = io_put_req_find_next(req);
7766 return req ? &req->work : NULL;
7769 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7771 struct io_wq_hash *hash;
7772 struct io_wq_data data;
7773 unsigned int concurrency;
7775 hash = ctx->hash_map;
7777 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7779 return ERR_PTR(-ENOMEM);
7780 refcount_set(&hash->refs, 1);
7781 init_waitqueue_head(&hash->wait);
7782 ctx->hash_map = hash;
7786 data.free_work = io_free_work;
7787 data.do_work = io_wq_submit_work;
7789 /* Do QD, or 4 * CPUS, whatever is smallest */
7790 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7792 return io_wq_create(concurrency, &data);
7795 static int io_uring_alloc_task_context(struct task_struct *task,
7796 struct io_ring_ctx *ctx)
7798 struct io_uring_task *tctx;
7801 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7802 if (unlikely(!tctx))
7805 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7806 if (unlikely(ret)) {
7811 tctx->io_wq = io_init_wq_offload(ctx);
7812 if (IS_ERR(tctx->io_wq)) {
7813 ret = PTR_ERR(tctx->io_wq);
7814 percpu_counter_destroy(&tctx->inflight);
7820 init_waitqueue_head(&tctx->wait);
7822 atomic_set(&tctx->in_idle, 0);
7823 tctx->sqpoll = false;
7824 task->io_uring = tctx;
7825 spin_lock_init(&tctx->task_lock);
7826 INIT_WQ_LIST(&tctx->task_list);
7827 tctx->task_state = 0;
7828 init_task_work(&tctx->task_work, tctx_task_work);
7832 void __io_uring_free(struct task_struct *tsk)
7834 struct io_uring_task *tctx = tsk->io_uring;
7836 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7837 percpu_counter_destroy(&tctx->inflight);
7839 tsk->io_uring = NULL;
7842 static int io_sq_thread_fork(struct io_sq_data *sqd, struct io_ring_ctx *ctx)
7846 clear_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7847 reinit_completion(&sqd->completion);
7848 ctx->sqo_dead = ctx->sqo_exec = 0;
7849 sqd->task_pid = current->pid;
7850 current->flags |= PF_IO_WORKER;
7851 ret = io_wq_fork_thread(io_sq_thread, sqd);
7852 current->flags &= ~PF_IO_WORKER;
7857 wait_for_completion(&sqd->completion);
7858 return io_uring_alloc_task_context(sqd->thread, ctx);
7861 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7862 struct io_uring_params *p)
7866 /* Retain compatibility with failing for an invalid attach attempt */
7867 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7868 IORING_SETUP_ATTACH_WQ) {
7871 f = fdget(p->wq_fd);
7874 if (f.file->f_op != &io_uring_fops) {
7880 if (ctx->flags & IORING_SETUP_SQPOLL) {
7881 struct io_sq_data *sqd;
7884 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7887 sqd = io_get_sq_data(p);
7894 io_sq_thread_park(sqd);
7895 mutex_lock(&sqd->ctx_lock);
7896 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7897 mutex_unlock(&sqd->ctx_lock);
7898 io_sq_thread_unpark(sqd);
7900 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7901 if (!ctx->sq_thread_idle)
7902 ctx->sq_thread_idle = HZ;
7907 if (p->flags & IORING_SETUP_SQ_AFF) {
7908 int cpu = p->sq_thread_cpu;
7911 if (cpu >= nr_cpu_ids)
7913 if (!cpu_online(cpu))
7921 sqd->task_pid = current->pid;
7922 current->flags |= PF_IO_WORKER;
7923 ret = io_wq_fork_thread(io_sq_thread, sqd);
7924 current->flags &= ~PF_IO_WORKER;
7929 wait_for_completion(&sqd->completion);
7930 ret = io_uring_alloc_task_context(sqd->thread, ctx);
7933 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7934 /* Can't have SQ_AFF without SQPOLL */
7941 io_sq_thread_finish(ctx);
7945 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7947 struct io_sq_data *sqd = ctx->sq_data;
7949 if (ctx->flags & IORING_SETUP_SQPOLL)
7950 complete(&sqd->startup);
7953 static inline void __io_unaccount_mem(struct user_struct *user,
7954 unsigned long nr_pages)
7956 atomic_long_sub(nr_pages, &user->locked_vm);
7959 static inline int __io_account_mem(struct user_struct *user,
7960 unsigned long nr_pages)
7962 unsigned long page_limit, cur_pages, new_pages;
7964 /* Don't allow more pages than we can safely lock */
7965 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7968 cur_pages = atomic_long_read(&user->locked_vm);
7969 new_pages = cur_pages + nr_pages;
7970 if (new_pages > page_limit)
7972 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7973 new_pages) != cur_pages);
7978 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7981 __io_unaccount_mem(ctx->user, nr_pages);
7983 if (ctx->mm_account)
7984 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7987 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7992 ret = __io_account_mem(ctx->user, nr_pages);
7997 if (ctx->mm_account)
7998 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
8003 static void io_mem_free(void *ptr)
8010 page = virt_to_head_page(ptr);
8011 if (put_page_testzero(page))
8012 free_compound_page(page);
8015 static void *io_mem_alloc(size_t size)
8017 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
8018 __GFP_NORETRY | __GFP_ACCOUNT;
8020 return (void *) __get_free_pages(gfp_flags, get_order(size));
8023 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
8026 struct io_rings *rings;
8027 size_t off, sq_array_size;
8029 off = struct_size(rings, cqes, cq_entries);
8030 if (off == SIZE_MAX)
8034 off = ALIGN(off, SMP_CACHE_BYTES);
8042 sq_array_size = array_size(sizeof(u32), sq_entries);
8043 if (sq_array_size == SIZE_MAX)
8046 if (check_add_overflow(off, sq_array_size, &off))
8052 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8056 if (!ctx->user_bufs)
8059 for (i = 0; i < ctx->nr_user_bufs; i++) {
8060 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8062 for (j = 0; j < imu->nr_bvecs; j++)
8063 unpin_user_page(imu->bvec[j].bv_page);
8065 if (imu->acct_pages)
8066 io_unaccount_mem(ctx, imu->acct_pages);
8071 kfree(ctx->user_bufs);
8072 ctx->user_bufs = NULL;
8073 ctx->nr_user_bufs = 0;
8077 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8078 void __user *arg, unsigned index)
8080 struct iovec __user *src;
8082 #ifdef CONFIG_COMPAT
8084 struct compat_iovec __user *ciovs;
8085 struct compat_iovec ciov;
8087 ciovs = (struct compat_iovec __user *) arg;
8088 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8091 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8092 dst->iov_len = ciov.iov_len;
8096 src = (struct iovec __user *) arg;
8097 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8103 * Not super efficient, but this is just a registration time. And we do cache
8104 * the last compound head, so generally we'll only do a full search if we don't
8107 * We check if the given compound head page has already been accounted, to
8108 * avoid double accounting it. This allows us to account the full size of the
8109 * page, not just the constituent pages of a huge page.
8111 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8112 int nr_pages, struct page *hpage)
8116 /* check current page array */
8117 for (i = 0; i < nr_pages; i++) {
8118 if (!PageCompound(pages[i]))
8120 if (compound_head(pages[i]) == hpage)
8124 /* check previously registered pages */
8125 for (i = 0; i < ctx->nr_user_bufs; i++) {
8126 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8128 for (j = 0; j < imu->nr_bvecs; j++) {
8129 if (!PageCompound(imu->bvec[j].bv_page))
8131 if (compound_head(imu->bvec[j].bv_page) == hpage)
8139 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8140 int nr_pages, struct io_mapped_ubuf *imu,
8141 struct page **last_hpage)
8145 for (i = 0; i < nr_pages; i++) {
8146 if (!PageCompound(pages[i])) {
8151 hpage = compound_head(pages[i]);
8152 if (hpage == *last_hpage)
8154 *last_hpage = hpage;
8155 if (headpage_already_acct(ctx, pages, i, hpage))
8157 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8161 if (!imu->acct_pages)
8164 ret = io_account_mem(ctx, imu->acct_pages);
8166 imu->acct_pages = 0;
8170 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8171 struct io_mapped_ubuf *imu,
8172 struct page **last_hpage)
8174 struct vm_area_struct **vmas = NULL;
8175 struct page **pages = NULL;
8176 unsigned long off, start, end, ubuf;
8178 int ret, pret, nr_pages, i;
8180 ubuf = (unsigned long) iov->iov_base;
8181 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8182 start = ubuf >> PAGE_SHIFT;
8183 nr_pages = end - start;
8187 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8191 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8196 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8202 mmap_read_lock(current->mm);
8203 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8205 if (pret == nr_pages) {
8206 /* don't support file backed memory */
8207 for (i = 0; i < nr_pages; i++) {
8208 struct vm_area_struct *vma = vmas[i];
8211 !is_file_hugepages(vma->vm_file)) {
8217 ret = pret < 0 ? pret : -EFAULT;
8219 mmap_read_unlock(current->mm);
8222 * if we did partial map, or found file backed vmas,
8223 * release any pages we did get
8226 unpin_user_pages(pages, pret);
8231 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8233 unpin_user_pages(pages, pret);
8238 off = ubuf & ~PAGE_MASK;
8239 size = iov->iov_len;
8240 for (i = 0; i < nr_pages; i++) {
8243 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8244 imu->bvec[i].bv_page = pages[i];
8245 imu->bvec[i].bv_len = vec_len;
8246 imu->bvec[i].bv_offset = off;
8250 /* store original address for later verification */
8252 imu->len = iov->iov_len;
8253 imu->nr_bvecs = nr_pages;
8261 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8265 if (!nr_args || nr_args > UIO_MAXIOV)
8268 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8270 if (!ctx->user_bufs)
8276 static int io_buffer_validate(struct iovec *iov)
8279 * Don't impose further limits on the size and buffer
8280 * constraints here, we'll -EINVAL later when IO is
8281 * submitted if they are wrong.
8283 if (!iov->iov_base || !iov->iov_len)
8286 /* arbitrary limit, but we need something */
8287 if (iov->iov_len > SZ_1G)
8293 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8294 unsigned int nr_args)
8298 struct page *last_hpage = NULL;
8300 ret = io_buffers_map_alloc(ctx, nr_args);
8304 for (i = 0; i < nr_args; i++) {
8305 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8307 ret = io_copy_iov(ctx, &iov, arg, i);
8311 ret = io_buffer_validate(&iov);
8315 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8319 ctx->nr_user_bufs++;
8323 io_sqe_buffers_unregister(ctx);
8328 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8330 __s32 __user *fds = arg;
8336 if (copy_from_user(&fd, fds, sizeof(*fds)))
8339 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8340 if (IS_ERR(ctx->cq_ev_fd)) {
8341 int ret = PTR_ERR(ctx->cq_ev_fd);
8342 ctx->cq_ev_fd = NULL;
8349 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8351 if (ctx->cq_ev_fd) {
8352 eventfd_ctx_put(ctx->cq_ev_fd);
8353 ctx->cq_ev_fd = NULL;
8360 static int __io_destroy_buffers(int id, void *p, void *data)
8362 struct io_ring_ctx *ctx = data;
8363 struct io_buffer *buf = p;
8365 __io_remove_buffers(ctx, buf, id, -1U);
8369 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8371 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8372 idr_destroy(&ctx->io_buffer_idr);
8375 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8377 struct io_kiocb *req, *nxt;
8379 list_for_each_entry_safe(req, nxt, list, compl.list) {
8380 if (tsk && req->task != tsk)
8382 list_del(&req->compl.list);
8383 kmem_cache_free(req_cachep, req);
8387 static void io_req_caches_free(struct io_ring_ctx *ctx, struct task_struct *tsk)
8389 struct io_submit_state *submit_state = &ctx->submit_state;
8390 struct io_comp_state *cs = &ctx->submit_state.comp;
8392 mutex_lock(&ctx->uring_lock);
8394 if (submit_state->free_reqs) {
8395 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8396 submit_state->reqs);
8397 submit_state->free_reqs = 0;
8400 spin_lock_irq(&ctx->completion_lock);
8401 list_splice_init(&cs->locked_free_list, &cs->free_list);
8402 cs->locked_free_nr = 0;
8403 spin_unlock_irq(&ctx->completion_lock);
8405 io_req_cache_free(&cs->free_list, NULL);
8407 mutex_unlock(&ctx->uring_lock);
8410 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8413 * Some may use context even when all refs and requests have been put,
8414 * and they are free to do so while still holding uring_lock, see
8415 * __io_req_task_submit(). Wait for them to finish.
8417 mutex_lock(&ctx->uring_lock);
8418 mutex_unlock(&ctx->uring_lock);
8420 io_sq_thread_finish(ctx);
8421 io_sqe_buffers_unregister(ctx);
8423 if (ctx->mm_account) {
8424 mmdrop(ctx->mm_account);
8425 ctx->mm_account = NULL;
8428 mutex_lock(&ctx->uring_lock);
8429 io_sqe_files_unregister(ctx);
8430 mutex_unlock(&ctx->uring_lock);
8431 io_eventfd_unregister(ctx);
8432 io_destroy_buffers(ctx);
8433 idr_destroy(&ctx->personality_idr);
8435 #if defined(CONFIG_UNIX)
8436 if (ctx->ring_sock) {
8437 ctx->ring_sock->file = NULL; /* so that iput() is called */
8438 sock_release(ctx->ring_sock);
8442 io_mem_free(ctx->rings);
8443 io_mem_free(ctx->sq_sqes);
8445 percpu_ref_exit(&ctx->refs);
8446 free_uid(ctx->user);
8447 io_req_caches_free(ctx, NULL);
8449 io_wq_put_hash(ctx->hash_map);
8450 kfree(ctx->cancel_hash);
8454 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8456 struct io_ring_ctx *ctx = file->private_data;
8459 poll_wait(file, &ctx->cq_wait, wait);
8461 * synchronizes with barrier from wq_has_sleeper call in
8465 if (!io_sqring_full(ctx))
8466 mask |= EPOLLOUT | EPOLLWRNORM;
8469 * Don't flush cqring overflow list here, just do a simple check.
8470 * Otherwise there could possible be ABBA deadlock:
8473 * lock(&ctx->uring_lock);
8475 * lock(&ctx->uring_lock);
8478 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8479 * pushs them to do the flush.
8481 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8482 mask |= EPOLLIN | EPOLLRDNORM;
8487 static int io_uring_fasync(int fd, struct file *file, int on)
8489 struct io_ring_ctx *ctx = file->private_data;
8491 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8494 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8496 const struct cred *creds;
8498 creds = idr_remove(&ctx->personality_idr, id);
8507 static int io_remove_personalities(int id, void *p, void *data)
8509 struct io_ring_ctx *ctx = data;
8511 io_unregister_personality(ctx, id);
8515 static void io_run_ctx_fallback(struct io_ring_ctx *ctx)
8517 struct callback_head *work, *head, *next;
8522 work = READ_ONCE(ctx->exit_task_work);
8523 } while (cmpxchg(&ctx->exit_task_work, work, head) != work);
8537 static void io_ring_exit_work(struct work_struct *work)
8539 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8543 * If we're doing polled IO and end up having requests being
8544 * submitted async (out-of-line), then completions can come in while
8545 * we're waiting for refs to drop. We need to reap these manually,
8546 * as nobody else will be looking for them.
8549 io_uring_try_cancel_requests(ctx, NULL, NULL);
8550 io_run_ctx_fallback(ctx);
8551 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8552 io_ring_ctx_free(ctx);
8555 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8557 mutex_lock(&ctx->uring_lock);
8558 percpu_ref_kill(&ctx->refs);
8560 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8563 /* if force is set, the ring is going away. always drop after that */
8564 ctx->cq_overflow_flushed = 1;
8566 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8567 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8568 mutex_unlock(&ctx->uring_lock);
8570 io_kill_timeouts(ctx, NULL, NULL);
8571 io_poll_remove_all(ctx, NULL, NULL);
8573 /* if we failed setting up the ctx, we might not have any rings */
8574 io_iopoll_try_reap_events(ctx);
8576 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8578 * Use system_unbound_wq to avoid spawning tons of event kworkers
8579 * if we're exiting a ton of rings at the same time. It just adds
8580 * noise and overhead, there's no discernable change in runtime
8581 * over using system_wq.
8583 queue_work(system_unbound_wq, &ctx->exit_work);
8586 static int io_uring_release(struct inode *inode, struct file *file)
8588 struct io_ring_ctx *ctx = file->private_data;
8590 file->private_data = NULL;
8591 io_ring_ctx_wait_and_kill(ctx);
8595 struct io_task_cancel {
8596 struct task_struct *task;
8597 struct files_struct *files;
8600 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8602 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8603 struct io_task_cancel *cancel = data;
8606 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8607 unsigned long flags;
8608 struct io_ring_ctx *ctx = req->ctx;
8610 /* protect against races with linked timeouts */
8611 spin_lock_irqsave(&ctx->completion_lock, flags);
8612 ret = io_match_task(req, cancel->task, cancel->files);
8613 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8615 ret = io_match_task(req, cancel->task, cancel->files);
8620 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8621 struct task_struct *task,
8622 struct files_struct *files)
8624 struct io_defer_entry *de = NULL;
8627 spin_lock_irq(&ctx->completion_lock);
8628 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8629 if (io_match_task(de->req, task, files)) {
8630 list_cut_position(&list, &ctx->defer_list, &de->list);
8634 spin_unlock_irq(&ctx->completion_lock);
8636 while (!list_empty(&list)) {
8637 de = list_first_entry(&list, struct io_defer_entry, list);
8638 list_del_init(&de->list);
8639 req_set_fail_links(de->req);
8640 io_put_req(de->req);
8641 io_req_complete(de->req, -ECANCELED);
8646 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8647 struct task_struct *task,
8648 struct files_struct *files)
8650 struct io_task_cancel cancel = { .task = task, .files = files, };
8651 struct io_uring_task *tctx = current->io_uring;
8654 enum io_wq_cancel cret;
8657 if (tctx && tctx->io_wq) {
8658 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8660 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8663 /* SQPOLL thread does its own polling */
8664 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8665 while (!list_empty_careful(&ctx->iopoll_list)) {
8666 io_iopoll_try_reap_events(ctx);
8671 ret |= io_poll_remove_all(ctx, task, files);
8672 ret |= io_kill_timeouts(ctx, task, files);
8673 ret |= io_run_task_work();
8674 io_cqring_overflow_flush(ctx, true, task, files);
8681 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8682 struct task_struct *task,
8683 struct files_struct *files)
8685 struct io_kiocb *req;
8688 spin_lock_irq(&ctx->inflight_lock);
8689 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8690 cnt += io_match_task(req, task, files);
8691 spin_unlock_irq(&ctx->inflight_lock);
8695 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8696 struct task_struct *task,
8697 struct files_struct *files)
8699 while (!list_empty_careful(&ctx->inflight_list)) {
8703 inflight = io_uring_count_inflight(ctx, task, files);
8707 io_uring_try_cancel_requests(ctx, task, files);
8710 io_sq_thread_unpark(ctx->sq_data);
8711 prepare_to_wait(&task->io_uring->wait, &wait,
8712 TASK_UNINTERRUPTIBLE);
8713 if (inflight == io_uring_count_inflight(ctx, task, files))
8715 finish_wait(&task->io_uring->wait, &wait);
8717 io_sq_thread_park(ctx->sq_data);
8721 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8723 mutex_lock(&ctx->uring_lock);
8725 mutex_unlock(&ctx->uring_lock);
8727 /* make sure callers enter the ring to get error */
8729 io_ring_set_wakeup_flag(ctx);
8733 * We need to iteratively cancel requests, in case a request has dependent
8734 * hard links. These persist even for failure of cancelations, hence keep
8735 * looping until none are found.
8737 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8738 struct files_struct *files)
8740 struct task_struct *task = current;
8741 bool did_park = false;
8743 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8744 io_disable_sqo_submit(ctx);
8745 did_park = io_sq_thread_park(ctx->sq_data);
8747 task = ctx->sq_data->thread;
8748 atomic_inc(&task->io_uring->in_idle);
8752 io_cancel_defer_files(ctx, task, files);
8754 io_uring_cancel_files(ctx, task, files);
8756 io_uring_try_cancel_requests(ctx, task, NULL);
8759 atomic_dec(&task->io_uring->in_idle);
8760 io_sq_thread_unpark(ctx->sq_data);
8765 * Note that this task has used io_uring. We use it for cancelation purposes.
8767 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8769 struct io_uring_task *tctx = current->io_uring;
8772 if (unlikely(!tctx)) {
8773 ret = io_uring_alloc_task_context(current, ctx);
8776 tctx = current->io_uring;
8778 if (tctx->last != file) {
8779 void *old = xa_load(&tctx->xa, (unsigned long)file);
8783 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8790 /* one and only SQPOLL file note, held by sqo_task */
8791 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
8792 current != ctx->sqo_task);
8798 * This is race safe in that the task itself is doing this, hence it
8799 * cannot be going through the exit/cancel paths at the same time.
8800 * This cannot be modified while exit/cancel is running.
8802 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8803 tctx->sqpoll = true;
8809 * Remove this io_uring_file -> task mapping.
8811 static void io_uring_del_task_file(struct file *file)
8813 struct io_uring_task *tctx = current->io_uring;
8815 if (tctx->last == file)
8817 file = xa_erase(&tctx->xa, (unsigned long)file);
8822 static void io_uring_remove_task_files(struct io_uring_task *tctx)
8825 unsigned long index;
8827 xa_for_each(&tctx->xa, index, file)
8828 io_uring_del_task_file(file);
8831 void __io_uring_files_cancel(struct files_struct *files)
8833 struct io_uring_task *tctx = current->io_uring;
8835 unsigned long index;
8837 /* make sure overflow events are dropped */
8838 atomic_inc(&tctx->in_idle);
8839 xa_for_each(&tctx->xa, index, file)
8840 io_uring_cancel_task_requests(file->private_data, files);
8841 atomic_dec(&tctx->in_idle);
8844 io_uring_remove_task_files(tctx);
8846 io_wq_put(tctx->io_wq);
8852 static s64 tctx_inflight(struct io_uring_task *tctx)
8854 return percpu_counter_sum(&tctx->inflight);
8857 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8859 struct io_sq_data *sqd = ctx->sq_data;
8860 struct io_uring_task *tctx;
8866 io_disable_sqo_submit(ctx);
8867 if (!io_sq_thread_park(sqd))
8869 tctx = ctx->sq_data->thread->io_uring;
8871 atomic_inc(&tctx->in_idle);
8873 /* read completions before cancelations */
8874 inflight = tctx_inflight(tctx);
8877 io_uring_cancel_task_requests(ctx, NULL);
8879 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8881 * If we've seen completions, retry without waiting. This
8882 * avoids a race where a completion comes in before we did
8883 * prepare_to_wait().
8885 if (inflight == tctx_inflight(tctx))
8887 finish_wait(&tctx->wait, &wait);
8889 atomic_dec(&tctx->in_idle);
8890 io_sq_thread_unpark(sqd);
8894 * Find any io_uring fd that this task has registered or done IO on, and cancel
8897 void __io_uring_task_cancel(void)
8899 struct io_uring_task *tctx = current->io_uring;
8903 /* make sure overflow events are dropped */
8904 atomic_inc(&tctx->in_idle);
8906 /* trigger io_disable_sqo_submit() */
8909 unsigned long index;
8911 xa_for_each(&tctx->xa, index, file)
8912 io_uring_cancel_sqpoll(file->private_data);
8916 /* read completions before cancelations */
8917 inflight = tctx_inflight(tctx);
8920 __io_uring_files_cancel(NULL);
8922 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8925 * If we've seen completions, retry without waiting. This
8926 * avoids a race where a completion comes in before we did
8927 * prepare_to_wait().
8929 if (inflight == tctx_inflight(tctx))
8931 finish_wait(&tctx->wait, &wait);
8934 atomic_dec(&tctx->in_idle);
8936 io_uring_remove_task_files(tctx);
8939 static int io_uring_flush(struct file *file, void *data)
8941 struct io_uring_task *tctx = current->io_uring;
8942 struct io_ring_ctx *ctx = file->private_data;
8944 /* Ignore helper thread files exit */
8945 if (current->flags & PF_IO_WORKER)
8948 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
8949 io_uring_cancel_task_requests(ctx, NULL);
8950 io_req_caches_free(ctx, current);
8953 io_run_ctx_fallback(ctx);
8958 /* we should have cancelled and erased it before PF_EXITING */
8959 WARN_ON_ONCE((current->flags & PF_EXITING) &&
8960 xa_load(&tctx->xa, (unsigned long)file));
8963 * fput() is pending, will be 2 if the only other ref is our potential
8964 * task file note. If the task is exiting, drop regardless of count.
8966 if (atomic_long_read(&file->f_count) != 2)
8969 if (ctx->flags & IORING_SETUP_SQPOLL) {
8970 /* there is only one file note, which is owned by sqo_task */
8971 WARN_ON_ONCE(ctx->sqo_task != current &&
8972 xa_load(&tctx->xa, (unsigned long)file));
8973 /* sqo_dead check is for when this happens after cancellation */
8974 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
8975 !xa_load(&tctx->xa, (unsigned long)file));
8977 io_disable_sqo_submit(ctx);
8980 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
8981 io_uring_del_task_file(file);
8985 static void *io_uring_validate_mmap_request(struct file *file,
8986 loff_t pgoff, size_t sz)
8988 struct io_ring_ctx *ctx = file->private_data;
8989 loff_t offset = pgoff << PAGE_SHIFT;
8994 case IORING_OFF_SQ_RING:
8995 case IORING_OFF_CQ_RING:
8998 case IORING_OFF_SQES:
9002 return ERR_PTR(-EINVAL);
9005 page = virt_to_head_page(ptr);
9006 if (sz > page_size(page))
9007 return ERR_PTR(-EINVAL);
9014 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9016 size_t sz = vma->vm_end - vma->vm_start;
9020 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9022 return PTR_ERR(ptr);
9024 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9025 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9028 #else /* !CONFIG_MMU */
9030 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9032 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9035 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9037 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9040 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9041 unsigned long addr, unsigned long len,
9042 unsigned long pgoff, unsigned long flags)
9046 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9048 return PTR_ERR(ptr);
9050 return (unsigned long) ptr;
9053 #endif /* !CONFIG_MMU */
9055 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9061 if (!io_sqring_full(ctx))
9064 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9066 if (unlikely(ctx->sqo_dead)) {
9071 if (!io_sqring_full(ctx))
9075 } while (!signal_pending(current));
9077 finish_wait(&ctx->sqo_sq_wait, &wait);
9082 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9083 struct __kernel_timespec __user **ts,
9084 const sigset_t __user **sig)
9086 struct io_uring_getevents_arg arg;
9089 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9090 * is just a pointer to the sigset_t.
9092 if (!(flags & IORING_ENTER_EXT_ARG)) {
9093 *sig = (const sigset_t __user *) argp;
9099 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9100 * timespec and sigset_t pointers if good.
9102 if (*argsz != sizeof(arg))
9104 if (copy_from_user(&arg, argp, sizeof(arg)))
9106 *sig = u64_to_user_ptr(arg.sigmask);
9107 *argsz = arg.sigmask_sz;
9108 *ts = u64_to_user_ptr(arg.ts);
9112 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9113 u32, min_complete, u32, flags, const void __user *, argp,
9116 struct io_ring_ctx *ctx;
9123 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9124 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9132 if (f.file->f_op != &io_uring_fops)
9136 ctx = f.file->private_data;
9137 if (!percpu_ref_tryget(&ctx->refs))
9141 if (ctx->flags & IORING_SETUP_R_DISABLED)
9145 * For SQ polling, the thread will do all submissions and completions.
9146 * Just return the requested submit count, and wake the thread if
9150 if (ctx->flags & IORING_SETUP_SQPOLL) {
9151 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9153 if (unlikely(ctx->sqo_exec)) {
9154 ret = io_sq_thread_fork(ctx->sq_data, ctx);
9160 if (unlikely(ctx->sqo_dead))
9162 if (flags & IORING_ENTER_SQ_WAKEUP)
9163 wake_up(&ctx->sq_data->wait);
9164 if (flags & IORING_ENTER_SQ_WAIT) {
9165 ret = io_sqpoll_wait_sq(ctx);
9169 submitted = to_submit;
9170 } else if (to_submit) {
9171 ret = io_uring_add_task_file(ctx, f.file);
9174 mutex_lock(&ctx->uring_lock);
9175 submitted = io_submit_sqes(ctx, to_submit);
9176 mutex_unlock(&ctx->uring_lock);
9178 if (submitted != to_submit)
9181 if (flags & IORING_ENTER_GETEVENTS) {
9182 const sigset_t __user *sig;
9183 struct __kernel_timespec __user *ts;
9185 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9189 min_complete = min(min_complete, ctx->cq_entries);
9192 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9193 * space applications don't need to do io completion events
9194 * polling again, they can rely on io_sq_thread to do polling
9195 * work, which can reduce cpu usage and uring_lock contention.
9197 if (ctx->flags & IORING_SETUP_IOPOLL &&
9198 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9199 ret = io_iopoll_check(ctx, min_complete);
9201 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9206 percpu_ref_put(&ctx->refs);
9209 return submitted ? submitted : ret;
9212 #ifdef CONFIG_PROC_FS
9213 static int io_uring_show_cred(int id, void *p, void *data)
9215 const struct cred *cred = p;
9216 struct seq_file *m = data;
9217 struct user_namespace *uns = seq_user_ns(m);
9218 struct group_info *gi;
9223 seq_printf(m, "%5d\n", id);
9224 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9225 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9226 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9227 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9228 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9229 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9230 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9231 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9232 seq_puts(m, "\n\tGroups:\t");
9233 gi = cred->group_info;
9234 for (g = 0; g < gi->ngroups; g++) {
9235 seq_put_decimal_ull(m, g ? " " : "",
9236 from_kgid_munged(uns, gi->gid[g]));
9238 seq_puts(m, "\n\tCapEff:\t");
9239 cap = cred->cap_effective;
9240 CAP_FOR_EACH_U32(__capi)
9241 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9246 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9248 struct io_sq_data *sq = NULL;
9253 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9254 * since fdinfo case grabs it in the opposite direction of normal use
9255 * cases. If we fail to get the lock, we just don't iterate any
9256 * structures that could be going away outside the io_uring mutex.
9258 has_lock = mutex_trylock(&ctx->uring_lock);
9260 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9266 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9267 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9268 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9269 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9270 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9273 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9275 seq_printf(m, "%5u: <none>\n", i);
9277 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9278 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9279 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9281 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9282 (unsigned int) buf->len);
9284 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9285 seq_printf(m, "Personalities:\n");
9286 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9288 seq_printf(m, "PollList:\n");
9289 spin_lock_irq(&ctx->completion_lock);
9290 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9291 struct hlist_head *list = &ctx->cancel_hash[i];
9292 struct io_kiocb *req;
9294 hlist_for_each_entry(req, list, hash_node)
9295 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9296 req->task->task_works != NULL);
9298 spin_unlock_irq(&ctx->completion_lock);
9300 mutex_unlock(&ctx->uring_lock);
9303 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9305 struct io_ring_ctx *ctx = f->private_data;
9307 if (percpu_ref_tryget(&ctx->refs)) {
9308 __io_uring_show_fdinfo(ctx, m);
9309 percpu_ref_put(&ctx->refs);
9314 static const struct file_operations io_uring_fops = {
9315 .release = io_uring_release,
9316 .flush = io_uring_flush,
9317 .mmap = io_uring_mmap,
9319 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9320 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9322 .poll = io_uring_poll,
9323 .fasync = io_uring_fasync,
9324 #ifdef CONFIG_PROC_FS
9325 .show_fdinfo = io_uring_show_fdinfo,
9329 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9330 struct io_uring_params *p)
9332 struct io_rings *rings;
9333 size_t size, sq_array_offset;
9335 /* make sure these are sane, as we already accounted them */
9336 ctx->sq_entries = p->sq_entries;
9337 ctx->cq_entries = p->cq_entries;
9339 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9340 if (size == SIZE_MAX)
9343 rings = io_mem_alloc(size);
9348 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9349 rings->sq_ring_mask = p->sq_entries - 1;
9350 rings->cq_ring_mask = p->cq_entries - 1;
9351 rings->sq_ring_entries = p->sq_entries;
9352 rings->cq_ring_entries = p->cq_entries;
9353 ctx->sq_mask = rings->sq_ring_mask;
9354 ctx->cq_mask = rings->cq_ring_mask;
9356 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9357 if (size == SIZE_MAX) {
9358 io_mem_free(ctx->rings);
9363 ctx->sq_sqes = io_mem_alloc(size);
9364 if (!ctx->sq_sqes) {
9365 io_mem_free(ctx->rings);
9373 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9377 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9381 ret = io_uring_add_task_file(ctx, file);
9386 fd_install(fd, file);
9391 * Allocate an anonymous fd, this is what constitutes the application
9392 * visible backing of an io_uring instance. The application mmaps this
9393 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9394 * we have to tie this fd to a socket for file garbage collection purposes.
9396 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9399 #if defined(CONFIG_UNIX)
9402 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9405 return ERR_PTR(ret);
9408 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9409 O_RDWR | O_CLOEXEC);
9410 #if defined(CONFIG_UNIX)
9412 sock_release(ctx->ring_sock);
9413 ctx->ring_sock = NULL;
9415 ctx->ring_sock->file = file;
9421 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9422 struct io_uring_params __user *params)
9424 struct io_ring_ctx *ctx;
9430 if (entries > IORING_MAX_ENTRIES) {
9431 if (!(p->flags & IORING_SETUP_CLAMP))
9433 entries = IORING_MAX_ENTRIES;
9437 * Use twice as many entries for the CQ ring. It's possible for the
9438 * application to drive a higher depth than the size of the SQ ring,
9439 * since the sqes are only used at submission time. This allows for
9440 * some flexibility in overcommitting a bit. If the application has
9441 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9442 * of CQ ring entries manually.
9444 p->sq_entries = roundup_pow_of_two(entries);
9445 if (p->flags & IORING_SETUP_CQSIZE) {
9447 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9448 * to a power-of-two, if it isn't already. We do NOT impose
9449 * any cq vs sq ring sizing.
9453 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9454 if (!(p->flags & IORING_SETUP_CLAMP))
9456 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9458 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9459 if (p->cq_entries < p->sq_entries)
9462 p->cq_entries = 2 * p->sq_entries;
9465 ctx = io_ring_ctx_alloc(p);
9468 ctx->compat = in_compat_syscall();
9469 if (!capable(CAP_IPC_LOCK))
9470 ctx->user = get_uid(current_user());
9471 ctx->sqo_task = current;
9474 * This is just grabbed for accounting purposes. When a process exits,
9475 * the mm is exited and dropped before the files, hence we need to hang
9476 * on to this mm purely for the purposes of being able to unaccount
9477 * memory (locked/pinned vm). It's not used for anything else.
9479 mmgrab(current->mm);
9480 ctx->mm_account = current->mm;
9482 ret = io_allocate_scq_urings(ctx, p);
9486 ret = io_sq_offload_create(ctx, p);
9490 if (!(p->flags & IORING_SETUP_R_DISABLED))
9491 io_sq_offload_start(ctx);
9493 memset(&p->sq_off, 0, sizeof(p->sq_off));
9494 p->sq_off.head = offsetof(struct io_rings, sq.head);
9495 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9496 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9497 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9498 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9499 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9500 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9502 memset(&p->cq_off, 0, sizeof(p->cq_off));
9503 p->cq_off.head = offsetof(struct io_rings, cq.head);
9504 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9505 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9506 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9507 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9508 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9509 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9511 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9512 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9513 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9514 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9515 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9517 if (copy_to_user(params, p, sizeof(*p))) {
9522 file = io_uring_get_file(ctx);
9524 ret = PTR_ERR(file);
9529 * Install ring fd as the very last thing, so we don't risk someone
9530 * having closed it before we finish setup
9532 ret = io_uring_install_fd(ctx, file);
9534 io_disable_sqo_submit(ctx);
9535 /* fput will clean it up */
9540 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9543 io_disable_sqo_submit(ctx);
9544 io_ring_ctx_wait_and_kill(ctx);
9549 * Sets up an aio uring context, and returns the fd. Applications asks for a
9550 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9551 * params structure passed in.
9553 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9555 struct io_uring_params p;
9558 if (copy_from_user(&p, params, sizeof(p)))
9560 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9565 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9566 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9567 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9568 IORING_SETUP_R_DISABLED))
9571 return io_uring_create(entries, &p, params);
9574 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9575 struct io_uring_params __user *, params)
9577 return io_uring_setup(entries, params);
9580 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9582 struct io_uring_probe *p;
9586 size = struct_size(p, ops, nr_args);
9587 if (size == SIZE_MAX)
9589 p = kzalloc(size, GFP_KERNEL);
9594 if (copy_from_user(p, arg, size))
9597 if (memchr_inv(p, 0, size))
9600 p->last_op = IORING_OP_LAST - 1;
9601 if (nr_args > IORING_OP_LAST)
9602 nr_args = IORING_OP_LAST;
9604 for (i = 0; i < nr_args; i++) {
9606 if (!io_op_defs[i].not_supported)
9607 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9612 if (copy_to_user(arg, p, size))
9619 static int io_register_personality(struct io_ring_ctx *ctx)
9621 const struct cred *creds;
9624 creds = get_current_cred();
9626 ret = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9627 USHRT_MAX, GFP_KERNEL);
9633 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9634 unsigned int nr_args)
9636 struct io_uring_restriction *res;
9640 /* Restrictions allowed only if rings started disabled */
9641 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9644 /* We allow only a single restrictions registration */
9645 if (ctx->restrictions.registered)
9648 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9651 size = array_size(nr_args, sizeof(*res));
9652 if (size == SIZE_MAX)
9655 res = memdup_user(arg, size);
9657 return PTR_ERR(res);
9661 for (i = 0; i < nr_args; i++) {
9662 switch (res[i].opcode) {
9663 case IORING_RESTRICTION_REGISTER_OP:
9664 if (res[i].register_op >= IORING_REGISTER_LAST) {
9669 __set_bit(res[i].register_op,
9670 ctx->restrictions.register_op);
9672 case IORING_RESTRICTION_SQE_OP:
9673 if (res[i].sqe_op >= IORING_OP_LAST) {
9678 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9680 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9681 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9683 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9684 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9693 /* Reset all restrictions if an error happened */
9695 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9697 ctx->restrictions.registered = true;
9703 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9705 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9708 if (ctx->restrictions.registered)
9709 ctx->restricted = 1;
9711 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9713 io_sq_offload_start(ctx);
9718 static bool io_register_op_must_quiesce(int op)
9721 case IORING_UNREGISTER_FILES:
9722 case IORING_REGISTER_FILES_UPDATE:
9723 case IORING_REGISTER_PROBE:
9724 case IORING_REGISTER_PERSONALITY:
9725 case IORING_UNREGISTER_PERSONALITY:
9732 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9733 void __user *arg, unsigned nr_args)
9734 __releases(ctx->uring_lock)
9735 __acquires(ctx->uring_lock)
9740 * We're inside the ring mutex, if the ref is already dying, then
9741 * someone else killed the ctx or is already going through
9742 * io_uring_register().
9744 if (percpu_ref_is_dying(&ctx->refs))
9747 if (io_register_op_must_quiesce(opcode)) {
9748 percpu_ref_kill(&ctx->refs);
9751 * Drop uring mutex before waiting for references to exit. If
9752 * another thread is currently inside io_uring_enter() it might
9753 * need to grab the uring_lock to make progress. If we hold it
9754 * here across the drain wait, then we can deadlock. It's safe
9755 * to drop the mutex here, since no new references will come in
9756 * after we've killed the percpu ref.
9758 mutex_unlock(&ctx->uring_lock);
9760 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9763 ret = io_run_task_work_sig();
9768 mutex_lock(&ctx->uring_lock);
9771 percpu_ref_resurrect(&ctx->refs);
9776 if (ctx->restricted) {
9777 if (opcode >= IORING_REGISTER_LAST) {
9782 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9789 case IORING_REGISTER_BUFFERS:
9790 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9792 case IORING_UNREGISTER_BUFFERS:
9796 ret = io_sqe_buffers_unregister(ctx);
9798 case IORING_REGISTER_FILES:
9799 ret = io_sqe_files_register(ctx, arg, nr_args);
9801 case IORING_UNREGISTER_FILES:
9805 ret = io_sqe_files_unregister(ctx);
9807 case IORING_REGISTER_FILES_UPDATE:
9808 ret = io_sqe_files_update(ctx, arg, nr_args);
9810 case IORING_REGISTER_EVENTFD:
9811 case IORING_REGISTER_EVENTFD_ASYNC:
9815 ret = io_eventfd_register(ctx, arg);
9818 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9819 ctx->eventfd_async = 1;
9821 ctx->eventfd_async = 0;
9823 case IORING_UNREGISTER_EVENTFD:
9827 ret = io_eventfd_unregister(ctx);
9829 case IORING_REGISTER_PROBE:
9831 if (!arg || nr_args > 256)
9833 ret = io_probe(ctx, arg, nr_args);
9835 case IORING_REGISTER_PERSONALITY:
9839 ret = io_register_personality(ctx);
9841 case IORING_UNREGISTER_PERSONALITY:
9845 ret = io_unregister_personality(ctx, nr_args);
9847 case IORING_REGISTER_ENABLE_RINGS:
9851 ret = io_register_enable_rings(ctx);
9853 case IORING_REGISTER_RESTRICTIONS:
9854 ret = io_register_restrictions(ctx, arg, nr_args);
9862 if (io_register_op_must_quiesce(opcode)) {
9863 /* bring the ctx back to life */
9864 percpu_ref_reinit(&ctx->refs);
9866 reinit_completion(&ctx->ref_comp);
9871 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9872 void __user *, arg, unsigned int, nr_args)
9874 struct io_ring_ctx *ctx;
9883 if (f.file->f_op != &io_uring_fops)
9886 ctx = f.file->private_data;
9890 mutex_lock(&ctx->uring_lock);
9891 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9892 mutex_unlock(&ctx->uring_lock);
9893 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9894 ctx->cq_ev_fd != NULL, ret);
9900 static int __init io_uring_init(void)
9902 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9903 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9904 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9907 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9908 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9909 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9910 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9911 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9912 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9913 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9914 BUILD_BUG_SQE_ELEM(8, __u64, off);
9915 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9916 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9917 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9918 BUILD_BUG_SQE_ELEM(24, __u32, len);
9919 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9920 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9921 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9922 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9923 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9924 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9925 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9926 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9927 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9928 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9929 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9930 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9931 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9932 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9933 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9934 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9935 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9936 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9937 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9939 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9940 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9941 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9945 __initcall(io_uring_init);