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_LTIMEOUT_ACTIVE_BIT,
692 REQ_F_COMPLETE_INLINE_BIT,
694 /* not a real bit, just to check we're not overflowing the space */
700 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
701 /* drain existing IO first */
702 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
704 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
705 /* doesn't sever on completion < 0 */
706 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
708 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
709 /* IOSQE_BUFFER_SELECT */
710 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
712 /* fail rest of links */
713 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
714 /* on inflight list */
715 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
716 /* read/write uses file position */
717 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
718 /* must not punt to workers */
719 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
720 /* has or had linked timeout */
721 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
723 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
725 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
726 /* already went through poll handler */
727 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
728 /* buffer already selected */
729 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
730 /* doesn't need file table for this request */
731 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
732 /* linked timeout is active, i.e. prepared by link's head */
733 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
734 /* completion is deferred through io_comp_state */
735 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
739 struct io_poll_iocb poll;
740 struct io_poll_iocb *double_poll;
743 struct io_task_work {
744 struct io_wq_work_node node;
745 task_work_func_t func;
749 * NOTE! Each of the iocb union members has the file pointer
750 * as the first entry in their struct definition. So you can
751 * access the file pointer through any of the sub-structs,
752 * or directly as just 'ki_filp' in this struct.
758 struct io_poll_iocb poll;
759 struct io_poll_remove poll_remove;
760 struct io_accept accept;
762 struct io_cancel cancel;
763 struct io_timeout timeout;
764 struct io_timeout_rem timeout_rem;
765 struct io_connect connect;
766 struct io_sr_msg sr_msg;
768 struct io_close close;
769 struct io_rsrc_update rsrc_update;
770 struct io_fadvise fadvise;
771 struct io_madvise madvise;
772 struct io_epoll epoll;
773 struct io_splice splice;
774 struct io_provide_buf pbuf;
775 struct io_statx statx;
776 struct io_shutdown shutdown;
777 struct io_rename rename;
778 struct io_unlink unlink;
779 /* use only after cleaning per-op data, see io_clean_op() */
780 struct io_completion compl;
783 /* opcode allocated if it needs to store data for async defer */
786 /* polled IO has completed */
792 struct io_ring_ctx *ctx;
795 struct task_struct *task;
798 struct io_kiocb *link;
799 struct percpu_ref *fixed_rsrc_refs;
802 * 1. used with ctx->iopoll_list with reads/writes
803 * 2. to track reqs with ->files (see io_op_def::file_table)
805 struct list_head inflight_entry;
807 struct io_task_work io_task_work;
808 struct callback_head task_work;
810 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
811 struct hlist_node hash_node;
812 struct async_poll *apoll;
813 struct io_wq_work work;
816 struct io_defer_entry {
817 struct list_head list;
818 struct io_kiocb *req;
823 /* needs req->file assigned */
824 unsigned needs_file : 1;
825 /* hash wq insertion if file is a regular file */
826 unsigned hash_reg_file : 1;
827 /* unbound wq insertion if file is a non-regular file */
828 unsigned unbound_nonreg_file : 1;
829 /* opcode is not supported by this kernel */
830 unsigned not_supported : 1;
831 /* set if opcode supports polled "wait" */
833 unsigned pollout : 1;
834 /* op supports buffer selection */
835 unsigned buffer_select : 1;
836 /* must always have async data allocated */
837 unsigned needs_async_data : 1;
838 /* should block plug */
840 /* size of async data needed, if any */
841 unsigned short async_size;
844 static const struct io_op_def io_op_defs[] = {
845 [IORING_OP_NOP] = {},
846 [IORING_OP_READV] = {
848 .unbound_nonreg_file = 1,
851 .needs_async_data = 1,
853 .async_size = sizeof(struct io_async_rw),
855 [IORING_OP_WRITEV] = {
858 .unbound_nonreg_file = 1,
860 .needs_async_data = 1,
862 .async_size = sizeof(struct io_async_rw),
864 [IORING_OP_FSYNC] = {
867 [IORING_OP_READ_FIXED] = {
869 .unbound_nonreg_file = 1,
872 .async_size = sizeof(struct io_async_rw),
874 [IORING_OP_WRITE_FIXED] = {
877 .unbound_nonreg_file = 1,
880 .async_size = sizeof(struct io_async_rw),
882 [IORING_OP_POLL_ADD] = {
884 .unbound_nonreg_file = 1,
886 [IORING_OP_POLL_REMOVE] = {},
887 [IORING_OP_SYNC_FILE_RANGE] = {
890 [IORING_OP_SENDMSG] = {
892 .unbound_nonreg_file = 1,
894 .needs_async_data = 1,
895 .async_size = sizeof(struct io_async_msghdr),
897 [IORING_OP_RECVMSG] = {
899 .unbound_nonreg_file = 1,
902 .needs_async_data = 1,
903 .async_size = sizeof(struct io_async_msghdr),
905 [IORING_OP_TIMEOUT] = {
906 .needs_async_data = 1,
907 .async_size = sizeof(struct io_timeout_data),
909 [IORING_OP_TIMEOUT_REMOVE] = {
910 /* used by timeout updates' prep() */
912 [IORING_OP_ACCEPT] = {
914 .unbound_nonreg_file = 1,
917 [IORING_OP_ASYNC_CANCEL] = {},
918 [IORING_OP_LINK_TIMEOUT] = {
919 .needs_async_data = 1,
920 .async_size = sizeof(struct io_timeout_data),
922 [IORING_OP_CONNECT] = {
924 .unbound_nonreg_file = 1,
926 .needs_async_data = 1,
927 .async_size = sizeof(struct io_async_connect),
929 [IORING_OP_FALLOCATE] = {
932 [IORING_OP_OPENAT] = {},
933 [IORING_OP_CLOSE] = {},
934 [IORING_OP_FILES_UPDATE] = {},
935 [IORING_OP_STATX] = {},
938 .unbound_nonreg_file = 1,
942 .async_size = sizeof(struct io_async_rw),
944 [IORING_OP_WRITE] = {
946 .unbound_nonreg_file = 1,
949 .async_size = sizeof(struct io_async_rw),
951 [IORING_OP_FADVISE] = {
954 [IORING_OP_MADVISE] = {},
957 .unbound_nonreg_file = 1,
962 .unbound_nonreg_file = 1,
966 [IORING_OP_OPENAT2] = {
968 [IORING_OP_EPOLL_CTL] = {
969 .unbound_nonreg_file = 1,
971 [IORING_OP_SPLICE] = {
974 .unbound_nonreg_file = 1,
976 [IORING_OP_PROVIDE_BUFFERS] = {},
977 [IORING_OP_REMOVE_BUFFERS] = {},
981 .unbound_nonreg_file = 1,
983 [IORING_OP_SHUTDOWN] = {
986 [IORING_OP_RENAMEAT] = {},
987 [IORING_OP_UNLINKAT] = {},
990 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
991 struct task_struct *task,
992 struct files_struct *files);
993 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
994 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
995 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
996 struct io_ring_ctx *ctx);
997 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
999 static bool io_rw_reissue(struct io_kiocb *req);
1000 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1001 static void io_put_req(struct io_kiocb *req);
1002 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1003 static void io_double_put_req(struct io_kiocb *req);
1004 static void io_dismantle_req(struct io_kiocb *req);
1005 static void io_put_task(struct task_struct *task, int nr);
1006 static void io_queue_next(struct io_kiocb *req);
1007 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1008 static void __io_queue_linked_timeout(struct io_kiocb *req);
1009 static void io_queue_linked_timeout(struct io_kiocb *req);
1010 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1011 struct io_uring_rsrc_update *ip,
1013 static void __io_clean_op(struct io_kiocb *req);
1014 static struct file *io_file_get(struct io_submit_state *state,
1015 struct io_kiocb *req, int fd, bool fixed);
1016 static void __io_queue_sqe(struct io_kiocb *req);
1017 static void io_rsrc_put_work(struct work_struct *work);
1019 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1020 struct iov_iter *iter, bool needs_lock);
1021 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1022 const struct iovec *fast_iov,
1023 struct iov_iter *iter, bool force);
1024 static void io_req_task_queue(struct io_kiocb *req);
1025 static void io_submit_flush_completions(struct io_comp_state *cs,
1026 struct io_ring_ctx *ctx);
1028 static struct kmem_cache *req_cachep;
1030 static const struct file_operations io_uring_fops;
1032 struct sock *io_uring_get_socket(struct file *file)
1034 #if defined(CONFIG_UNIX)
1035 if (file->f_op == &io_uring_fops) {
1036 struct io_ring_ctx *ctx = file->private_data;
1038 return ctx->ring_sock->sk;
1043 EXPORT_SYMBOL(io_uring_get_socket);
1045 #define io_for_each_link(pos, head) \
1046 for (pos = (head); pos; pos = pos->link)
1048 static inline void io_clean_op(struct io_kiocb *req)
1050 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1054 static inline void io_set_resource_node(struct io_kiocb *req)
1056 struct io_ring_ctx *ctx = req->ctx;
1058 if (!req->fixed_rsrc_refs) {
1059 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1060 percpu_ref_get(req->fixed_rsrc_refs);
1064 static bool io_match_task(struct io_kiocb *head,
1065 struct task_struct *task,
1066 struct files_struct *files)
1068 struct io_kiocb *req;
1070 if (task && head->task != task) {
1071 /* in terms of cancelation, always match if req task is dead */
1072 if (head->task->flags & PF_EXITING)
1079 io_for_each_link(req, head) {
1080 if (req->file && req->file->f_op == &io_uring_fops)
1082 if (req->task->files == files)
1088 static inline void req_set_fail_links(struct io_kiocb *req)
1090 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1091 req->flags |= REQ_F_FAIL_LINK;
1094 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1096 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1098 complete(&ctx->ref_comp);
1101 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1103 return !req->timeout.off;
1106 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1108 struct io_ring_ctx *ctx;
1111 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1116 * Use 5 bits less than the max cq entries, that should give us around
1117 * 32 entries per hash list if totally full and uniformly spread.
1119 hash_bits = ilog2(p->cq_entries);
1123 ctx->cancel_hash_bits = hash_bits;
1124 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1126 if (!ctx->cancel_hash)
1128 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1130 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1131 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1134 ctx->flags = p->flags;
1135 init_waitqueue_head(&ctx->sqo_sq_wait);
1136 INIT_LIST_HEAD(&ctx->sqd_list);
1137 init_waitqueue_head(&ctx->cq_wait);
1138 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1139 init_completion(&ctx->ref_comp);
1140 init_completion(&ctx->sq_thread_comp);
1141 idr_init(&ctx->io_buffer_idr);
1142 idr_init(&ctx->personality_idr);
1143 mutex_init(&ctx->uring_lock);
1144 init_waitqueue_head(&ctx->wait);
1145 spin_lock_init(&ctx->completion_lock);
1146 INIT_LIST_HEAD(&ctx->iopoll_list);
1147 INIT_LIST_HEAD(&ctx->defer_list);
1148 INIT_LIST_HEAD(&ctx->timeout_list);
1149 spin_lock_init(&ctx->inflight_lock);
1150 INIT_LIST_HEAD(&ctx->inflight_list);
1151 spin_lock_init(&ctx->rsrc_ref_lock);
1152 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1153 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1154 init_llist_head(&ctx->rsrc_put_llist);
1155 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1156 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1159 kfree(ctx->cancel_hash);
1164 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1166 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1167 struct io_ring_ctx *ctx = req->ctx;
1169 return seq != ctx->cached_cq_tail
1170 + READ_ONCE(ctx->cached_cq_overflow);
1176 static void io_req_clean_work(struct io_kiocb *req)
1178 if (req->flags & REQ_F_INFLIGHT) {
1179 struct io_ring_ctx *ctx = req->ctx;
1180 struct io_uring_task *tctx = req->task->io_uring;
1181 unsigned long flags;
1183 spin_lock_irqsave(&ctx->inflight_lock, flags);
1184 list_del(&req->inflight_entry);
1185 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1186 req->flags &= ~REQ_F_INFLIGHT;
1187 if (atomic_read(&tctx->in_idle))
1188 wake_up(&tctx->wait);
1192 static void io_req_track_inflight(struct io_kiocb *req)
1194 struct io_ring_ctx *ctx = req->ctx;
1196 if (!(req->flags & REQ_F_INFLIGHT)) {
1197 req->flags |= REQ_F_INFLIGHT;
1199 spin_lock_irq(&ctx->inflight_lock);
1200 list_add(&req->inflight_entry, &ctx->inflight_list);
1201 spin_unlock_irq(&ctx->inflight_lock);
1205 static void io_prep_async_work(struct io_kiocb *req)
1207 const struct io_op_def *def = &io_op_defs[req->opcode];
1208 struct io_ring_ctx *ctx = req->ctx;
1210 if (req->flags & REQ_F_FORCE_ASYNC)
1211 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1213 if (req->flags & REQ_F_ISREG) {
1214 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1215 io_wq_hash_work(&req->work, file_inode(req->file));
1217 if (def->unbound_nonreg_file)
1218 req->work.flags |= IO_WQ_WORK_UNBOUND;
1222 static void io_prep_async_link(struct io_kiocb *req)
1224 struct io_kiocb *cur;
1226 io_for_each_link(cur, req)
1227 io_prep_async_work(cur);
1230 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1232 struct io_ring_ctx *ctx = req->ctx;
1233 struct io_kiocb *link = io_prep_linked_timeout(req);
1234 struct io_uring_task *tctx = req->task->io_uring;
1237 BUG_ON(!tctx->io_wq);
1239 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1240 &req->work, req->flags);
1241 io_wq_enqueue(tctx->io_wq, &req->work);
1245 static void io_queue_async_work(struct io_kiocb *req)
1247 struct io_kiocb *link;
1249 /* init ->work of the whole link before punting */
1250 io_prep_async_link(req);
1251 link = __io_queue_async_work(req);
1254 io_queue_linked_timeout(link);
1257 static void io_kill_timeout(struct io_kiocb *req)
1259 struct io_timeout_data *io = req->async_data;
1262 ret = hrtimer_try_to_cancel(&io->timer);
1264 atomic_set(&req->ctx->cq_timeouts,
1265 atomic_read(&req->ctx->cq_timeouts) + 1);
1266 list_del_init(&req->timeout.list);
1267 io_cqring_fill_event(req, 0);
1268 io_put_req_deferred(req, 1);
1273 * Returns true if we found and killed one or more timeouts
1275 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1276 struct files_struct *files)
1278 struct io_kiocb *req, *tmp;
1281 spin_lock_irq(&ctx->completion_lock);
1282 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1283 if (io_match_task(req, tsk, files)) {
1284 io_kill_timeout(req);
1288 spin_unlock_irq(&ctx->completion_lock);
1289 return canceled != 0;
1292 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1295 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1296 struct io_defer_entry, list);
1298 if (req_need_defer(de->req, de->seq))
1300 list_del_init(&de->list);
1301 io_req_task_queue(de->req);
1303 } while (!list_empty(&ctx->defer_list));
1306 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1310 if (list_empty(&ctx->timeout_list))
1313 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1316 u32 events_needed, events_got;
1317 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1318 struct io_kiocb, timeout.list);
1320 if (io_is_timeout_noseq(req))
1324 * Since seq can easily wrap around over time, subtract
1325 * the last seq at which timeouts were flushed before comparing.
1326 * Assuming not more than 2^31-1 events have happened since,
1327 * these subtractions won't have wrapped, so we can check if
1328 * target is in [last_seq, current_seq] by comparing the two.
1330 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1331 events_got = seq - ctx->cq_last_tm_flush;
1332 if (events_got < events_needed)
1335 list_del_init(&req->timeout.list);
1336 io_kill_timeout(req);
1337 } while (!list_empty(&ctx->timeout_list));
1339 ctx->cq_last_tm_flush = seq;
1342 static void io_commit_cqring(struct io_ring_ctx *ctx)
1344 io_flush_timeouts(ctx);
1346 /* order cqe stores with ring update */
1347 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1349 if (unlikely(!list_empty(&ctx->defer_list)))
1350 __io_queue_deferred(ctx);
1353 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1355 struct io_rings *r = ctx->rings;
1357 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1360 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1362 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1365 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1367 struct io_rings *rings = ctx->rings;
1371 * writes to the cq entry need to come after reading head; the
1372 * control dependency is enough as we're using WRITE_ONCE to
1375 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1378 tail = ctx->cached_cq_tail++;
1379 return &rings->cqes[tail & ctx->cq_mask];
1382 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1386 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1388 if (!ctx->eventfd_async)
1390 return io_wq_current_is_worker();
1393 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1395 /* see waitqueue_active() comment */
1398 if (waitqueue_active(&ctx->wait))
1399 wake_up(&ctx->wait);
1400 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1401 wake_up(&ctx->sq_data->wait);
1402 if (io_should_trigger_evfd(ctx))
1403 eventfd_signal(ctx->cq_ev_fd, 1);
1404 if (waitqueue_active(&ctx->cq_wait)) {
1405 wake_up_interruptible(&ctx->cq_wait);
1406 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1410 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1412 /* see waitqueue_active() comment */
1415 if (ctx->flags & IORING_SETUP_SQPOLL) {
1416 if (waitqueue_active(&ctx->wait))
1417 wake_up(&ctx->wait);
1419 if (io_should_trigger_evfd(ctx))
1420 eventfd_signal(ctx->cq_ev_fd, 1);
1421 if (waitqueue_active(&ctx->cq_wait)) {
1422 wake_up_interruptible(&ctx->cq_wait);
1423 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1427 /* Returns true if there are no backlogged entries after the flush */
1428 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1429 struct task_struct *tsk,
1430 struct files_struct *files)
1432 struct io_rings *rings = ctx->rings;
1433 struct io_kiocb *req, *tmp;
1434 struct io_uring_cqe *cqe;
1435 unsigned long flags;
1436 bool all_flushed, posted;
1439 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1443 spin_lock_irqsave(&ctx->completion_lock, flags);
1444 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1445 if (!io_match_task(req, tsk, files))
1448 cqe = io_get_cqring(ctx);
1452 list_move(&req->compl.list, &list);
1454 WRITE_ONCE(cqe->user_data, req->user_data);
1455 WRITE_ONCE(cqe->res, req->result);
1456 WRITE_ONCE(cqe->flags, req->compl.cflags);
1458 ctx->cached_cq_overflow++;
1459 WRITE_ONCE(ctx->rings->cq_overflow,
1460 ctx->cached_cq_overflow);
1465 all_flushed = list_empty(&ctx->cq_overflow_list);
1467 clear_bit(0, &ctx->sq_check_overflow);
1468 clear_bit(0, &ctx->cq_check_overflow);
1469 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1473 io_commit_cqring(ctx);
1474 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1476 io_cqring_ev_posted(ctx);
1478 while (!list_empty(&list)) {
1479 req = list_first_entry(&list, struct io_kiocb, compl.list);
1480 list_del(&req->compl.list);
1487 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1488 struct task_struct *tsk,
1489 struct files_struct *files)
1491 if (test_bit(0, &ctx->cq_check_overflow)) {
1492 /* iopoll syncs against uring_lock, not completion_lock */
1493 if (ctx->flags & IORING_SETUP_IOPOLL)
1494 mutex_lock(&ctx->uring_lock);
1495 __io_cqring_overflow_flush(ctx, force, tsk, files);
1496 if (ctx->flags & IORING_SETUP_IOPOLL)
1497 mutex_unlock(&ctx->uring_lock);
1501 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1503 struct io_ring_ctx *ctx = req->ctx;
1504 struct io_uring_cqe *cqe;
1506 trace_io_uring_complete(ctx, req->user_data, res);
1509 * If we can't get a cq entry, userspace overflowed the
1510 * submission (by quite a lot). Increment the overflow count in
1513 cqe = io_get_cqring(ctx);
1515 WRITE_ONCE(cqe->user_data, req->user_data);
1516 WRITE_ONCE(cqe->res, res);
1517 WRITE_ONCE(cqe->flags, cflags);
1518 } else if (ctx->cq_overflow_flushed ||
1519 atomic_read(&req->task->io_uring->in_idle)) {
1521 * If we're in ring overflow flush mode, or in task cancel mode,
1522 * then we cannot store the request for later flushing, we need
1523 * to drop it on the floor.
1525 ctx->cached_cq_overflow++;
1526 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1528 if (list_empty(&ctx->cq_overflow_list)) {
1529 set_bit(0, &ctx->sq_check_overflow);
1530 set_bit(0, &ctx->cq_check_overflow);
1531 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1535 req->compl.cflags = cflags;
1536 refcount_inc(&req->refs);
1537 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1541 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1543 __io_cqring_fill_event(req, res, 0);
1546 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1547 unsigned int cflags)
1549 struct io_ring_ctx *ctx = req->ctx;
1550 unsigned long flags;
1552 spin_lock_irqsave(&ctx->completion_lock, flags);
1553 __io_cqring_fill_event(req, res, cflags);
1554 io_commit_cqring(ctx);
1556 * If we're the last reference to this request, add to our locked
1559 if (refcount_dec_and_test(&req->refs)) {
1560 struct io_comp_state *cs = &ctx->submit_state.comp;
1562 io_dismantle_req(req);
1563 io_put_task(req->task, 1);
1564 list_add(&req->compl.list, &cs->locked_free_list);
1565 cs->locked_free_nr++;
1568 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1570 io_cqring_ev_posted(ctx);
1573 percpu_ref_put(&ctx->refs);
1577 static void io_req_complete_state(struct io_kiocb *req, long res,
1578 unsigned int cflags)
1582 req->compl.cflags = cflags;
1583 req->flags |= REQ_F_COMPLETE_INLINE;
1586 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1587 long res, unsigned cflags)
1589 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1590 io_req_complete_state(req, res, cflags);
1592 io_req_complete_post(req, res, cflags);
1595 static inline void io_req_complete(struct io_kiocb *req, long res)
1597 __io_req_complete(req, 0, res, 0);
1600 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1602 struct io_submit_state *state = &ctx->submit_state;
1603 struct io_comp_state *cs = &state->comp;
1604 struct io_kiocb *req = NULL;
1607 * If we have more than a batch's worth of requests in our IRQ side
1608 * locked cache, grab the lock and move them over to our submission
1611 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1612 spin_lock_irq(&ctx->completion_lock);
1613 list_splice_init(&cs->locked_free_list, &cs->free_list);
1614 cs->locked_free_nr = 0;
1615 spin_unlock_irq(&ctx->completion_lock);
1618 while (!list_empty(&cs->free_list)) {
1619 req = list_first_entry(&cs->free_list, struct io_kiocb,
1621 list_del(&req->compl.list);
1622 state->reqs[state->free_reqs++] = req;
1623 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1630 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1632 struct io_submit_state *state = &ctx->submit_state;
1634 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1636 if (!state->free_reqs) {
1637 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1640 if (io_flush_cached_reqs(ctx))
1643 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1647 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1648 * retry single alloc to be on the safe side.
1650 if (unlikely(ret <= 0)) {
1651 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1652 if (!state->reqs[0])
1656 state->free_reqs = ret;
1660 return state->reqs[state->free_reqs];
1663 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1670 static void io_dismantle_req(struct io_kiocb *req)
1674 if (req->async_data)
1675 kfree(req->async_data);
1677 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1678 if (req->fixed_rsrc_refs)
1679 percpu_ref_put(req->fixed_rsrc_refs);
1680 io_req_clean_work(req);
1683 static inline void io_put_task(struct task_struct *task, int nr)
1685 struct io_uring_task *tctx = task->io_uring;
1687 percpu_counter_sub(&tctx->inflight, nr);
1688 if (unlikely(atomic_read(&tctx->in_idle)))
1689 wake_up(&tctx->wait);
1690 put_task_struct_many(task, nr);
1693 static void __io_free_req(struct io_kiocb *req)
1695 struct io_ring_ctx *ctx = req->ctx;
1697 io_dismantle_req(req);
1698 io_put_task(req->task, 1);
1700 kmem_cache_free(req_cachep, req);
1701 percpu_ref_put(&ctx->refs);
1704 static inline void io_remove_next_linked(struct io_kiocb *req)
1706 struct io_kiocb *nxt = req->link;
1708 req->link = nxt->link;
1712 static void io_kill_linked_timeout(struct io_kiocb *req)
1714 struct io_ring_ctx *ctx = req->ctx;
1715 struct io_kiocb *link;
1716 bool cancelled = false;
1717 unsigned long flags;
1719 spin_lock_irqsave(&ctx->completion_lock, flags);
1723 * Can happen if a linked timeout fired and link had been like
1724 * req -> link t-out -> link t-out [-> ...]
1726 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1727 struct io_timeout_data *io = link->async_data;
1730 io_remove_next_linked(req);
1731 link->timeout.head = NULL;
1732 ret = hrtimer_try_to_cancel(&io->timer);
1734 io_cqring_fill_event(link, -ECANCELED);
1735 io_commit_cqring(ctx);
1739 req->flags &= ~REQ_F_LINK_TIMEOUT;
1740 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1743 io_cqring_ev_posted(ctx);
1749 static void io_fail_links(struct io_kiocb *req)
1751 struct io_kiocb *link, *nxt;
1752 struct io_ring_ctx *ctx = req->ctx;
1753 unsigned long flags;
1755 spin_lock_irqsave(&ctx->completion_lock, flags);
1763 trace_io_uring_fail_link(req, link);
1764 io_cqring_fill_event(link, -ECANCELED);
1766 io_put_req_deferred(link, 2);
1769 io_commit_cqring(ctx);
1770 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1772 io_cqring_ev_posted(ctx);
1775 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1777 if (req->flags & REQ_F_LINK_TIMEOUT)
1778 io_kill_linked_timeout(req);
1781 * If LINK is set, we have dependent requests in this chain. If we
1782 * didn't fail this request, queue the first one up, moving any other
1783 * dependencies to the next request. In case of failure, fail the rest
1786 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
1787 struct io_kiocb *nxt = req->link;
1796 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1798 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1800 return __io_req_find_next(req);
1803 static bool __tctx_task_work(struct io_uring_task *tctx)
1805 struct io_ring_ctx *ctx = NULL;
1806 struct io_wq_work_list list;
1807 struct io_wq_work_node *node;
1809 if (wq_list_empty(&tctx->task_list))
1812 spin_lock_irq(&tctx->task_lock);
1813 list = tctx->task_list;
1814 INIT_WQ_LIST(&tctx->task_list);
1815 spin_unlock_irq(&tctx->task_lock);
1819 struct io_wq_work_node *next = node->next;
1820 struct io_ring_ctx *this_ctx;
1821 struct io_kiocb *req;
1823 req = container_of(node, struct io_kiocb, io_task_work.node);
1824 this_ctx = req->ctx;
1825 req->task_work.func(&req->task_work);
1830 } else if (ctx != this_ctx) {
1831 mutex_lock(&ctx->uring_lock);
1832 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1833 mutex_unlock(&ctx->uring_lock);
1838 if (ctx && ctx->submit_state.comp.nr) {
1839 mutex_lock(&ctx->uring_lock);
1840 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1841 mutex_unlock(&ctx->uring_lock);
1844 return list.first != NULL;
1847 static void tctx_task_work(struct callback_head *cb)
1849 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1851 clear_bit(0, &tctx->task_state);
1853 while (__tctx_task_work(tctx))
1857 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1858 enum task_work_notify_mode notify)
1860 struct io_uring_task *tctx = tsk->io_uring;
1861 struct io_wq_work_node *node, *prev;
1862 unsigned long flags;
1865 WARN_ON_ONCE(!tctx);
1867 spin_lock_irqsave(&tctx->task_lock, flags);
1868 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1869 spin_unlock_irqrestore(&tctx->task_lock, flags);
1871 /* task_work already pending, we're done */
1872 if (test_bit(0, &tctx->task_state) ||
1873 test_and_set_bit(0, &tctx->task_state))
1876 if (!task_work_add(tsk, &tctx->task_work, notify))
1880 * Slow path - we failed, find and delete work. if the work is not
1881 * in the list, it got run and we're fine.
1884 spin_lock_irqsave(&tctx->task_lock, flags);
1885 wq_list_for_each(node, prev, &tctx->task_list) {
1886 if (&req->io_task_work.node == node) {
1887 wq_list_del(&tctx->task_list, node, prev);
1892 spin_unlock_irqrestore(&tctx->task_lock, flags);
1893 clear_bit(0, &tctx->task_state);
1897 static int io_req_task_work_add(struct io_kiocb *req)
1899 struct task_struct *tsk = req->task;
1900 struct io_ring_ctx *ctx = req->ctx;
1901 enum task_work_notify_mode notify;
1904 if (tsk->flags & PF_EXITING)
1908 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1909 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1910 * processing task_work. There's no reliable way to tell if TWA_RESUME
1914 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1915 notify = TWA_SIGNAL;
1917 ret = io_task_work_add(tsk, req, notify);
1919 wake_up_process(tsk);
1924 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1925 task_work_func_t cb)
1927 struct io_ring_ctx *ctx = req->ctx;
1928 struct callback_head *head;
1930 init_task_work(&req->task_work, cb);
1932 head = READ_ONCE(ctx->exit_task_work);
1933 req->task_work.next = head;
1934 } while (cmpxchg(&ctx->exit_task_work, head, &req->task_work) != head);
1937 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1939 struct io_ring_ctx *ctx = req->ctx;
1941 spin_lock_irq(&ctx->completion_lock);
1942 io_cqring_fill_event(req, error);
1943 io_commit_cqring(ctx);
1944 spin_unlock_irq(&ctx->completion_lock);
1946 io_cqring_ev_posted(ctx);
1947 req_set_fail_links(req);
1948 io_double_put_req(req);
1951 static void io_req_task_cancel(struct callback_head *cb)
1953 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1954 struct io_ring_ctx *ctx = req->ctx;
1956 mutex_lock(&ctx->uring_lock);
1957 __io_req_task_cancel(req, req->result);
1958 mutex_unlock(&ctx->uring_lock);
1959 percpu_ref_put(&ctx->refs);
1962 static void __io_req_task_submit(struct io_kiocb *req)
1964 struct io_ring_ctx *ctx = req->ctx;
1966 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
1967 mutex_lock(&ctx->uring_lock);
1968 if (!ctx->sqo_dead && !(current->flags & PF_EXITING) && !current->in_execve)
1969 __io_queue_sqe(req);
1971 __io_req_task_cancel(req, -EFAULT);
1972 mutex_unlock(&ctx->uring_lock);
1975 static void io_req_task_submit(struct callback_head *cb)
1977 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1979 __io_req_task_submit(req);
1982 static void io_req_task_queue(struct io_kiocb *req)
1986 req->task_work.func = io_req_task_submit;
1987 ret = io_req_task_work_add(req);
1988 if (unlikely(ret)) {
1989 req->result = -ECANCELED;
1990 percpu_ref_get(&req->ctx->refs);
1991 io_req_task_work_add_fallback(req, io_req_task_cancel);
1995 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1997 percpu_ref_get(&req->ctx->refs);
1999 req->task_work.func = io_req_task_cancel;
2001 if (unlikely(io_req_task_work_add(req)))
2002 io_req_task_work_add_fallback(req, io_req_task_cancel);
2005 static inline void io_queue_next(struct io_kiocb *req)
2007 struct io_kiocb *nxt = io_req_find_next(req);
2010 io_req_task_queue(nxt);
2013 static void io_free_req(struct io_kiocb *req)
2020 struct task_struct *task;
2025 static inline void io_init_req_batch(struct req_batch *rb)
2032 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2033 struct req_batch *rb)
2036 io_put_task(rb->task, rb->task_refs);
2038 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2041 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2042 struct io_submit_state *state)
2046 if (req->task != rb->task) {
2048 io_put_task(rb->task, rb->task_refs);
2049 rb->task = req->task;
2055 io_dismantle_req(req);
2056 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2057 state->reqs[state->free_reqs++] = req;
2059 list_add(&req->compl.list, &state->comp.free_list);
2062 static void io_submit_flush_completions(struct io_comp_state *cs,
2063 struct io_ring_ctx *ctx)
2066 struct io_kiocb *req;
2067 struct req_batch rb;
2069 io_init_req_batch(&rb);
2070 spin_lock_irq(&ctx->completion_lock);
2071 for (i = 0; i < nr; i++) {
2073 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2075 io_commit_cqring(ctx);
2076 spin_unlock_irq(&ctx->completion_lock);
2078 io_cqring_ev_posted(ctx);
2079 for (i = 0; i < nr; i++) {
2082 /* submission and completion refs */
2083 if (refcount_sub_and_test(2, &req->refs))
2084 io_req_free_batch(&rb, req, &ctx->submit_state);
2087 io_req_free_batch_finish(ctx, &rb);
2092 * Drop reference to request, return next in chain (if there is one) if this
2093 * was the last reference to this request.
2095 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2097 struct io_kiocb *nxt = NULL;
2099 if (refcount_dec_and_test(&req->refs)) {
2100 nxt = io_req_find_next(req);
2106 static void io_put_req(struct io_kiocb *req)
2108 if (refcount_dec_and_test(&req->refs))
2112 static void io_put_req_deferred_cb(struct callback_head *cb)
2114 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2119 static void io_free_req_deferred(struct io_kiocb *req)
2123 req->task_work.func = io_put_req_deferred_cb;
2124 ret = io_req_task_work_add(req);
2126 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2129 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2131 if (refcount_sub_and_test(refs, &req->refs))
2132 io_free_req_deferred(req);
2135 static void io_double_put_req(struct io_kiocb *req)
2137 /* drop both submit and complete references */
2138 if (refcount_sub_and_test(2, &req->refs))
2142 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2144 /* See comment at the top of this file */
2146 return __io_cqring_events(ctx);
2149 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2151 struct io_rings *rings = ctx->rings;
2153 /* make sure SQ entry isn't read before tail */
2154 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2157 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2159 unsigned int cflags;
2161 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2162 cflags |= IORING_CQE_F_BUFFER;
2163 req->flags &= ~REQ_F_BUFFER_SELECTED;
2168 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2170 struct io_buffer *kbuf;
2172 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2173 return io_put_kbuf(req, kbuf);
2176 static inline bool io_run_task_work(void)
2179 * Not safe to run on exiting task, and the task_work handling will
2180 * not add work to such a task.
2182 if (unlikely(current->flags & PF_EXITING))
2184 if (current->task_works) {
2185 __set_current_state(TASK_RUNNING);
2194 * Find and free completed poll iocbs
2196 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2197 struct list_head *done)
2199 struct req_batch rb;
2200 struct io_kiocb *req;
2202 /* order with ->result store in io_complete_rw_iopoll() */
2205 io_init_req_batch(&rb);
2206 while (!list_empty(done)) {
2209 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2210 list_del(&req->inflight_entry);
2212 if (READ_ONCE(req->result) == -EAGAIN) {
2213 req->iopoll_completed = 0;
2214 if (io_rw_reissue(req))
2218 if (req->flags & REQ_F_BUFFER_SELECTED)
2219 cflags = io_put_rw_kbuf(req);
2221 __io_cqring_fill_event(req, req->result, cflags);
2224 if (refcount_dec_and_test(&req->refs))
2225 io_req_free_batch(&rb, req, &ctx->submit_state);
2228 io_commit_cqring(ctx);
2229 io_cqring_ev_posted_iopoll(ctx);
2230 io_req_free_batch_finish(ctx, &rb);
2233 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2236 struct io_kiocb *req, *tmp;
2242 * Only spin for completions if we don't have multiple devices hanging
2243 * off our complete list, and we're under the requested amount.
2245 spin = !ctx->poll_multi_file && *nr_events < min;
2248 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2249 struct kiocb *kiocb = &req->rw.kiocb;
2252 * Move completed and retryable entries to our local lists.
2253 * If we find a request that requires polling, break out
2254 * and complete those lists first, if we have entries there.
2256 if (READ_ONCE(req->iopoll_completed)) {
2257 list_move_tail(&req->inflight_entry, &done);
2260 if (!list_empty(&done))
2263 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2267 /* iopoll may have completed current req */
2268 if (READ_ONCE(req->iopoll_completed))
2269 list_move_tail(&req->inflight_entry, &done);
2276 if (!list_empty(&done))
2277 io_iopoll_complete(ctx, nr_events, &done);
2283 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2284 * non-spinning poll check - we'll still enter the driver poll loop, but only
2285 * as a non-spinning completion check.
2287 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2290 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2293 ret = io_do_iopoll(ctx, nr_events, min);
2296 if (*nr_events >= min)
2304 * We can't just wait for polled events to come to us, we have to actively
2305 * find and complete them.
2307 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2309 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2312 mutex_lock(&ctx->uring_lock);
2313 while (!list_empty(&ctx->iopoll_list)) {
2314 unsigned int nr_events = 0;
2316 io_do_iopoll(ctx, &nr_events, 0);
2318 /* let it sleep and repeat later if can't complete a request */
2322 * Ensure we allow local-to-the-cpu processing to take place,
2323 * in this case we need to ensure that we reap all events.
2324 * Also let task_work, etc. to progress by releasing the mutex
2326 if (need_resched()) {
2327 mutex_unlock(&ctx->uring_lock);
2329 mutex_lock(&ctx->uring_lock);
2332 mutex_unlock(&ctx->uring_lock);
2335 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2337 unsigned int nr_events = 0;
2338 int iters = 0, ret = 0;
2341 * We disallow the app entering submit/complete with polling, but we
2342 * still need to lock the ring to prevent racing with polled issue
2343 * that got punted to a workqueue.
2345 mutex_lock(&ctx->uring_lock);
2348 * Don't enter poll loop if we already have events pending.
2349 * If we do, we can potentially be spinning for commands that
2350 * already triggered a CQE (eg in error).
2352 if (test_bit(0, &ctx->cq_check_overflow))
2353 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2354 if (io_cqring_events(ctx))
2358 * If a submit got punted to a workqueue, we can have the
2359 * application entering polling for a command before it gets
2360 * issued. That app will hold the uring_lock for the duration
2361 * of the poll right here, so we need to take a breather every
2362 * now and then to ensure that the issue has a chance to add
2363 * the poll to the issued list. Otherwise we can spin here
2364 * forever, while the workqueue is stuck trying to acquire the
2367 if (!(++iters & 7)) {
2368 mutex_unlock(&ctx->uring_lock);
2370 mutex_lock(&ctx->uring_lock);
2373 ret = io_iopoll_getevents(ctx, &nr_events, min);
2377 } while (min && !nr_events && !need_resched());
2379 mutex_unlock(&ctx->uring_lock);
2383 static void kiocb_end_write(struct io_kiocb *req)
2386 * Tell lockdep we inherited freeze protection from submission
2389 if (req->flags & REQ_F_ISREG) {
2390 struct inode *inode = file_inode(req->file);
2392 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2394 file_end_write(req->file);
2398 static bool io_resubmit_prep(struct io_kiocb *req)
2400 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2402 struct iov_iter iter;
2404 /* already prepared */
2405 if (req->async_data)
2408 switch (req->opcode) {
2409 case IORING_OP_READV:
2410 case IORING_OP_READ_FIXED:
2411 case IORING_OP_READ:
2414 case IORING_OP_WRITEV:
2415 case IORING_OP_WRITE_FIXED:
2416 case IORING_OP_WRITE:
2420 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2425 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2428 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2432 static bool io_rw_reissue(struct io_kiocb *req)
2435 umode_t mode = file_inode(req->file)->i_mode;
2437 if (!S_ISBLK(mode) && !S_ISREG(mode))
2439 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2442 * If ref is dying, we might be running poll reap from the exit work.
2443 * Don't attempt to reissue from that path, just let it fail with
2446 if (percpu_ref_is_dying(&req->ctx->refs))
2449 lockdep_assert_held(&req->ctx->uring_lock);
2451 if (io_resubmit_prep(req)) {
2452 refcount_inc(&req->refs);
2453 io_queue_async_work(req);
2456 req_set_fail_links(req);
2461 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2462 unsigned int issue_flags)
2466 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2468 if (res != req->result)
2469 req_set_fail_links(req);
2471 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2472 kiocb_end_write(req);
2473 if (req->flags & REQ_F_BUFFER_SELECTED)
2474 cflags = io_put_rw_kbuf(req);
2475 __io_req_complete(req, issue_flags, res, cflags);
2478 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2480 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2482 __io_complete_rw(req, res, res2, 0);
2485 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2487 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2489 if (kiocb->ki_flags & IOCB_WRITE)
2490 kiocb_end_write(req);
2492 if (res != -EAGAIN && res != req->result)
2493 req_set_fail_links(req);
2495 WRITE_ONCE(req->result, res);
2496 /* order with io_poll_complete() checking ->result */
2498 WRITE_ONCE(req->iopoll_completed, 1);
2502 * After the iocb has been issued, it's safe to be found on the poll list.
2503 * Adding the kiocb to the list AFTER submission ensures that we don't
2504 * find it from a io_iopoll_getevents() thread before the issuer is done
2505 * accessing the kiocb cookie.
2507 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2509 struct io_ring_ctx *ctx = req->ctx;
2512 * Track whether we have multiple files in our lists. This will impact
2513 * how we do polling eventually, not spinning if we're on potentially
2514 * different devices.
2516 if (list_empty(&ctx->iopoll_list)) {
2517 ctx->poll_multi_file = false;
2518 } else if (!ctx->poll_multi_file) {
2519 struct io_kiocb *list_req;
2521 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2523 if (list_req->file != req->file)
2524 ctx->poll_multi_file = true;
2528 * For fast devices, IO may have already completed. If it has, add
2529 * it to the front so we find it first.
2531 if (READ_ONCE(req->iopoll_completed))
2532 list_add(&req->inflight_entry, &ctx->iopoll_list);
2534 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2537 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2538 * task context or in io worker task context. If current task context is
2539 * sq thread, we don't need to check whether should wake up sq thread.
2541 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2542 wq_has_sleeper(&ctx->sq_data->wait))
2543 wake_up(&ctx->sq_data->wait);
2546 static inline void io_state_file_put(struct io_submit_state *state)
2548 if (state->file_refs) {
2549 fput_many(state->file, state->file_refs);
2550 state->file_refs = 0;
2555 * Get as many references to a file as we have IOs left in this submission,
2556 * assuming most submissions are for one file, or at least that each file
2557 * has more than one submission.
2559 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2564 if (state->file_refs) {
2565 if (state->fd == fd) {
2569 io_state_file_put(state);
2571 state->file = fget_many(fd, state->ios_left);
2572 if (unlikely(!state->file))
2576 state->file_refs = state->ios_left - 1;
2580 static bool io_bdev_nowait(struct block_device *bdev)
2582 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2586 * If we tracked the file through the SCM inflight mechanism, we could support
2587 * any file. For now, just ensure that anything potentially problematic is done
2590 static bool io_file_supports_async(struct file *file, int rw)
2592 umode_t mode = file_inode(file)->i_mode;
2594 if (S_ISBLK(mode)) {
2595 if (IS_ENABLED(CONFIG_BLOCK) &&
2596 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2600 if (S_ISCHR(mode) || S_ISSOCK(mode))
2602 if (S_ISREG(mode)) {
2603 if (IS_ENABLED(CONFIG_BLOCK) &&
2604 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2605 file->f_op != &io_uring_fops)
2610 /* any ->read/write should understand O_NONBLOCK */
2611 if (file->f_flags & O_NONBLOCK)
2614 if (!(file->f_mode & FMODE_NOWAIT))
2618 return file->f_op->read_iter != NULL;
2620 return file->f_op->write_iter != NULL;
2623 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2625 struct io_ring_ctx *ctx = req->ctx;
2626 struct kiocb *kiocb = &req->rw.kiocb;
2627 struct file *file = req->file;
2631 if (S_ISREG(file_inode(file)->i_mode))
2632 req->flags |= REQ_F_ISREG;
2634 kiocb->ki_pos = READ_ONCE(sqe->off);
2635 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2636 req->flags |= REQ_F_CUR_POS;
2637 kiocb->ki_pos = file->f_pos;
2639 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2640 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2641 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2645 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2646 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2647 req->flags |= REQ_F_NOWAIT;
2649 ioprio = READ_ONCE(sqe->ioprio);
2651 ret = ioprio_check_cap(ioprio);
2655 kiocb->ki_ioprio = ioprio;
2657 kiocb->ki_ioprio = get_current_ioprio();
2659 if (ctx->flags & IORING_SETUP_IOPOLL) {
2660 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2661 !kiocb->ki_filp->f_op->iopoll)
2664 kiocb->ki_flags |= IOCB_HIPRI;
2665 kiocb->ki_complete = io_complete_rw_iopoll;
2666 req->iopoll_completed = 0;
2668 if (kiocb->ki_flags & IOCB_HIPRI)
2670 kiocb->ki_complete = io_complete_rw;
2673 req->rw.addr = READ_ONCE(sqe->addr);
2674 req->rw.len = READ_ONCE(sqe->len);
2675 req->buf_index = READ_ONCE(sqe->buf_index);
2679 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2685 case -ERESTARTNOINTR:
2686 case -ERESTARTNOHAND:
2687 case -ERESTART_RESTARTBLOCK:
2689 * We can't just restart the syscall, since previously
2690 * submitted sqes may already be in progress. Just fail this
2696 kiocb->ki_complete(kiocb, ret, 0);
2700 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2701 unsigned int issue_flags)
2703 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2704 struct io_async_rw *io = req->async_data;
2706 /* add previously done IO, if any */
2707 if (io && io->bytes_done > 0) {
2709 ret = io->bytes_done;
2711 ret += io->bytes_done;
2714 if (req->flags & REQ_F_CUR_POS)
2715 req->file->f_pos = kiocb->ki_pos;
2716 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2717 __io_complete_rw(req, ret, 0, issue_flags);
2719 io_rw_done(kiocb, ret);
2722 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2724 struct io_ring_ctx *ctx = req->ctx;
2725 size_t len = req->rw.len;
2726 struct io_mapped_ubuf *imu;
2727 u16 index, buf_index = req->buf_index;
2731 if (unlikely(buf_index >= ctx->nr_user_bufs))
2733 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2734 imu = &ctx->user_bufs[index];
2735 buf_addr = req->rw.addr;
2738 if (buf_addr + len < buf_addr)
2740 /* not inside the mapped region */
2741 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2745 * May not be a start of buffer, set size appropriately
2746 * and advance us to the beginning.
2748 offset = buf_addr - imu->ubuf;
2749 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2753 * Don't use iov_iter_advance() here, as it's really slow for
2754 * using the latter parts of a big fixed buffer - it iterates
2755 * over each segment manually. We can cheat a bit here, because
2758 * 1) it's a BVEC iter, we set it up
2759 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2760 * first and last bvec
2762 * So just find our index, and adjust the iterator afterwards.
2763 * If the offset is within the first bvec (or the whole first
2764 * bvec, just use iov_iter_advance(). This makes it easier
2765 * since we can just skip the first segment, which may not
2766 * be PAGE_SIZE aligned.
2768 const struct bio_vec *bvec = imu->bvec;
2770 if (offset <= bvec->bv_len) {
2771 iov_iter_advance(iter, offset);
2773 unsigned long seg_skip;
2775 /* skip first vec */
2776 offset -= bvec->bv_len;
2777 seg_skip = 1 + (offset >> PAGE_SHIFT);
2779 iter->bvec = bvec + seg_skip;
2780 iter->nr_segs -= seg_skip;
2781 iter->count -= bvec->bv_len + offset;
2782 iter->iov_offset = offset & ~PAGE_MASK;
2789 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2792 mutex_unlock(&ctx->uring_lock);
2795 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2798 * "Normal" inline submissions always hold the uring_lock, since we
2799 * grab it from the system call. Same is true for the SQPOLL offload.
2800 * The only exception is when we've detached the request and issue it
2801 * from an async worker thread, grab the lock for that case.
2804 mutex_lock(&ctx->uring_lock);
2807 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2808 int bgid, struct io_buffer *kbuf,
2811 struct io_buffer *head;
2813 if (req->flags & REQ_F_BUFFER_SELECTED)
2816 io_ring_submit_lock(req->ctx, needs_lock);
2818 lockdep_assert_held(&req->ctx->uring_lock);
2820 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2822 if (!list_empty(&head->list)) {
2823 kbuf = list_last_entry(&head->list, struct io_buffer,
2825 list_del(&kbuf->list);
2828 idr_remove(&req->ctx->io_buffer_idr, bgid);
2830 if (*len > kbuf->len)
2833 kbuf = ERR_PTR(-ENOBUFS);
2836 io_ring_submit_unlock(req->ctx, needs_lock);
2841 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2844 struct io_buffer *kbuf;
2847 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2848 bgid = req->buf_index;
2849 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2852 req->rw.addr = (u64) (unsigned long) kbuf;
2853 req->flags |= REQ_F_BUFFER_SELECTED;
2854 return u64_to_user_ptr(kbuf->addr);
2857 #ifdef CONFIG_COMPAT
2858 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2861 struct compat_iovec __user *uiov;
2862 compat_ssize_t clen;
2866 uiov = u64_to_user_ptr(req->rw.addr);
2867 if (!access_ok(uiov, sizeof(*uiov)))
2869 if (__get_user(clen, &uiov->iov_len))
2875 buf = io_rw_buffer_select(req, &len, needs_lock);
2877 return PTR_ERR(buf);
2878 iov[0].iov_base = buf;
2879 iov[0].iov_len = (compat_size_t) len;
2884 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2887 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2891 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2894 len = iov[0].iov_len;
2897 buf = io_rw_buffer_select(req, &len, needs_lock);
2899 return PTR_ERR(buf);
2900 iov[0].iov_base = buf;
2901 iov[0].iov_len = len;
2905 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2908 if (req->flags & REQ_F_BUFFER_SELECTED) {
2909 struct io_buffer *kbuf;
2911 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2912 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2913 iov[0].iov_len = kbuf->len;
2916 if (req->rw.len != 1)
2919 #ifdef CONFIG_COMPAT
2920 if (req->ctx->compat)
2921 return io_compat_import(req, iov, needs_lock);
2924 return __io_iov_buffer_select(req, iov, needs_lock);
2927 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2928 struct iov_iter *iter, bool needs_lock)
2930 void __user *buf = u64_to_user_ptr(req->rw.addr);
2931 size_t sqe_len = req->rw.len;
2932 u8 opcode = req->opcode;
2935 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2937 return io_import_fixed(req, rw, iter);
2940 /* buffer index only valid with fixed read/write, or buffer select */
2941 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2944 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2945 if (req->flags & REQ_F_BUFFER_SELECT) {
2946 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2948 return PTR_ERR(buf);
2949 req->rw.len = sqe_len;
2952 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2957 if (req->flags & REQ_F_BUFFER_SELECT) {
2958 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2960 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
2965 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
2969 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2971 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2975 * For files that don't have ->read_iter() and ->write_iter(), handle them
2976 * by looping over ->read() or ->write() manually.
2978 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
2980 struct kiocb *kiocb = &req->rw.kiocb;
2981 struct file *file = req->file;
2985 * Don't support polled IO through this interface, and we can't
2986 * support non-blocking either. For the latter, this just causes
2987 * the kiocb to be handled from an async context.
2989 if (kiocb->ki_flags & IOCB_HIPRI)
2991 if (kiocb->ki_flags & IOCB_NOWAIT)
2994 while (iov_iter_count(iter)) {
2998 if (!iov_iter_is_bvec(iter)) {
2999 iovec = iov_iter_iovec(iter);
3001 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3002 iovec.iov_len = req->rw.len;
3006 nr = file->f_op->read(file, iovec.iov_base,
3007 iovec.iov_len, io_kiocb_ppos(kiocb));
3009 nr = file->f_op->write(file, iovec.iov_base,
3010 iovec.iov_len, io_kiocb_ppos(kiocb));
3019 if (nr != iovec.iov_len)
3023 iov_iter_advance(iter, nr);
3029 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3030 const struct iovec *fast_iov, struct iov_iter *iter)
3032 struct io_async_rw *rw = req->async_data;
3034 memcpy(&rw->iter, iter, sizeof(*iter));
3035 rw->free_iovec = iovec;
3037 /* can only be fixed buffers, no need to do anything */
3038 if (iov_iter_is_bvec(iter))
3041 unsigned iov_off = 0;
3043 rw->iter.iov = rw->fast_iov;
3044 if (iter->iov != fast_iov) {
3045 iov_off = iter->iov - fast_iov;
3046 rw->iter.iov += iov_off;
3048 if (rw->fast_iov != fast_iov)
3049 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3050 sizeof(struct iovec) * iter->nr_segs);
3052 req->flags |= REQ_F_NEED_CLEANUP;
3056 static inline int __io_alloc_async_data(struct io_kiocb *req)
3058 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3059 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3060 return req->async_data == NULL;
3063 static int io_alloc_async_data(struct io_kiocb *req)
3065 if (!io_op_defs[req->opcode].needs_async_data)
3068 return __io_alloc_async_data(req);
3071 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3072 const struct iovec *fast_iov,
3073 struct iov_iter *iter, bool force)
3075 if (!force && !io_op_defs[req->opcode].needs_async_data)
3077 if (!req->async_data) {
3078 if (__io_alloc_async_data(req)) {
3083 io_req_map_rw(req, iovec, fast_iov, iter);
3088 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3090 struct io_async_rw *iorw = req->async_data;
3091 struct iovec *iov = iorw->fast_iov;
3094 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3095 if (unlikely(ret < 0))
3098 iorw->bytes_done = 0;
3099 iorw->free_iovec = iov;
3101 req->flags |= REQ_F_NEED_CLEANUP;
3105 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3107 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3109 return io_prep_rw(req, sqe);
3113 * This is our waitqueue callback handler, registered through lock_page_async()
3114 * when we initially tried to do the IO with the iocb armed our waitqueue.
3115 * This gets called when the page is unlocked, and we generally expect that to
3116 * happen when the page IO is completed and the page is now uptodate. This will
3117 * queue a task_work based retry of the operation, attempting to copy the data
3118 * again. If the latter fails because the page was NOT uptodate, then we will
3119 * do a thread based blocking retry of the operation. That's the unexpected
3122 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3123 int sync, void *arg)
3125 struct wait_page_queue *wpq;
3126 struct io_kiocb *req = wait->private;
3127 struct wait_page_key *key = arg;
3129 wpq = container_of(wait, struct wait_page_queue, wait);
3131 if (!wake_page_match(wpq, key))
3134 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3135 list_del_init(&wait->entry);
3137 /* submit ref gets dropped, acquire a new one */
3138 refcount_inc(&req->refs);
3139 io_req_task_queue(req);
3144 * This controls whether a given IO request should be armed for async page
3145 * based retry. If we return false here, the request is handed to the async
3146 * worker threads for retry. If we're doing buffered reads on a regular file,
3147 * we prepare a private wait_page_queue entry and retry the operation. This
3148 * will either succeed because the page is now uptodate and unlocked, or it
3149 * will register a callback when the page is unlocked at IO completion. Through
3150 * that callback, io_uring uses task_work to setup a retry of the operation.
3151 * That retry will attempt the buffered read again. The retry will generally
3152 * succeed, or in rare cases where it fails, we then fall back to using the
3153 * async worker threads for a blocking retry.
3155 static bool io_rw_should_retry(struct io_kiocb *req)
3157 struct io_async_rw *rw = req->async_data;
3158 struct wait_page_queue *wait = &rw->wpq;
3159 struct kiocb *kiocb = &req->rw.kiocb;
3161 /* never retry for NOWAIT, we just complete with -EAGAIN */
3162 if (req->flags & REQ_F_NOWAIT)
3165 /* Only for buffered IO */
3166 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3170 * just use poll if we can, and don't attempt if the fs doesn't
3171 * support callback based unlocks
3173 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3176 wait->wait.func = io_async_buf_func;
3177 wait->wait.private = req;
3178 wait->wait.flags = 0;
3179 INIT_LIST_HEAD(&wait->wait.entry);
3180 kiocb->ki_flags |= IOCB_WAITQ;
3181 kiocb->ki_flags &= ~IOCB_NOWAIT;
3182 kiocb->ki_waitq = wait;
3186 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3188 if (req->file->f_op->read_iter)
3189 return call_read_iter(req->file, &req->rw.kiocb, iter);
3190 else if (req->file->f_op->read)
3191 return loop_rw_iter(READ, req, iter);
3196 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3198 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3199 struct kiocb *kiocb = &req->rw.kiocb;
3200 struct iov_iter __iter, *iter = &__iter;
3201 struct io_async_rw *rw = req->async_data;
3202 ssize_t io_size, ret, ret2;
3203 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3209 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3213 io_size = iov_iter_count(iter);
3214 req->result = io_size;
3216 /* Ensure we clear previously set non-block flag */
3217 if (!force_nonblock)
3218 kiocb->ki_flags &= ~IOCB_NOWAIT;
3220 kiocb->ki_flags |= IOCB_NOWAIT;
3222 /* If the file doesn't support async, just async punt */
3223 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3224 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3225 return ret ?: -EAGAIN;
3228 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3229 if (unlikely(ret)) {
3234 ret = io_iter_do_read(req, iter);
3236 if (ret == -EIOCBQUEUED) {
3238 } else if (ret == -EAGAIN) {
3239 /* IOPOLL retry should happen for io-wq threads */
3240 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3242 /* no retry on NONBLOCK nor RWF_NOWAIT */
3243 if (req->flags & REQ_F_NOWAIT)
3245 /* some cases will consume bytes even on error returns */
3246 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3248 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3249 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3250 /* read all, failed, already did sync or don't want to retry */
3254 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3259 rw = req->async_data;
3260 /* now use our persistent iterator, if we aren't already */
3265 rw->bytes_done += ret;
3266 /* if we can retry, do so with the callbacks armed */
3267 if (!io_rw_should_retry(req)) {
3268 kiocb->ki_flags &= ~IOCB_WAITQ;
3273 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3274 * we get -EIOCBQUEUED, then we'll get a notification when the
3275 * desired page gets unlocked. We can also get a partial read
3276 * here, and if we do, then just retry at the new offset.
3278 ret = io_iter_do_read(req, iter);
3279 if (ret == -EIOCBQUEUED)
3281 /* we got some bytes, but not all. retry. */
3282 } while (ret > 0 && ret < io_size);
3284 kiocb_done(kiocb, ret, issue_flags);
3286 /* it's faster to check here then delegate to kfree */
3292 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3294 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3296 return io_prep_rw(req, sqe);
3299 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3301 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3302 struct kiocb *kiocb = &req->rw.kiocb;
3303 struct iov_iter __iter, *iter = &__iter;
3304 struct io_async_rw *rw = req->async_data;
3305 ssize_t ret, ret2, io_size;
3306 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3312 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3316 io_size = iov_iter_count(iter);
3317 req->result = io_size;
3319 /* Ensure we clear previously set non-block flag */
3320 if (!force_nonblock)
3321 kiocb->ki_flags &= ~IOCB_NOWAIT;
3323 kiocb->ki_flags |= IOCB_NOWAIT;
3325 /* If the file doesn't support async, just async punt */
3326 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3329 /* file path doesn't support NOWAIT for non-direct_IO */
3330 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3331 (req->flags & REQ_F_ISREG))
3334 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3339 * Open-code file_start_write here to grab freeze protection,
3340 * which will be released by another thread in
3341 * io_complete_rw(). Fool lockdep by telling it the lock got
3342 * released so that it doesn't complain about the held lock when
3343 * we return to userspace.
3345 if (req->flags & REQ_F_ISREG) {
3346 sb_start_write(file_inode(req->file)->i_sb);
3347 __sb_writers_release(file_inode(req->file)->i_sb,
3350 kiocb->ki_flags |= IOCB_WRITE;
3352 if (req->file->f_op->write_iter)
3353 ret2 = call_write_iter(req->file, kiocb, iter);
3354 else if (req->file->f_op->write)
3355 ret2 = loop_rw_iter(WRITE, req, iter);
3360 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3361 * retry them without IOCB_NOWAIT.
3363 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3365 /* no retry on NONBLOCK nor RWF_NOWAIT */
3366 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3368 if (!force_nonblock || ret2 != -EAGAIN) {
3369 /* IOPOLL retry should happen for io-wq threads */
3370 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3373 kiocb_done(kiocb, ret2, issue_flags);
3376 /* some cases will consume bytes even on error returns */
3377 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3378 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3379 return ret ?: -EAGAIN;
3382 /* it's reportedly faster than delegating the null check to kfree() */
3388 static int io_renameat_prep(struct io_kiocb *req,
3389 const struct io_uring_sqe *sqe)
3391 struct io_rename *ren = &req->rename;
3392 const char __user *oldf, *newf;
3394 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3397 ren->old_dfd = READ_ONCE(sqe->fd);
3398 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3399 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3400 ren->new_dfd = READ_ONCE(sqe->len);
3401 ren->flags = READ_ONCE(sqe->rename_flags);
3403 ren->oldpath = getname(oldf);
3404 if (IS_ERR(ren->oldpath))
3405 return PTR_ERR(ren->oldpath);
3407 ren->newpath = getname(newf);
3408 if (IS_ERR(ren->newpath)) {
3409 putname(ren->oldpath);
3410 return PTR_ERR(ren->newpath);
3413 req->flags |= REQ_F_NEED_CLEANUP;
3417 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3419 struct io_rename *ren = &req->rename;
3422 if (issue_flags & IO_URING_F_NONBLOCK)
3425 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3426 ren->newpath, ren->flags);
3428 req->flags &= ~REQ_F_NEED_CLEANUP;
3430 req_set_fail_links(req);
3431 io_req_complete(req, ret);
3435 static int io_unlinkat_prep(struct io_kiocb *req,
3436 const struct io_uring_sqe *sqe)
3438 struct io_unlink *un = &req->unlink;
3439 const char __user *fname;
3441 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3444 un->dfd = READ_ONCE(sqe->fd);
3446 un->flags = READ_ONCE(sqe->unlink_flags);
3447 if (un->flags & ~AT_REMOVEDIR)
3450 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3451 un->filename = getname(fname);
3452 if (IS_ERR(un->filename))
3453 return PTR_ERR(un->filename);
3455 req->flags |= REQ_F_NEED_CLEANUP;
3459 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3461 struct io_unlink *un = &req->unlink;
3464 if (issue_flags & IO_URING_F_NONBLOCK)
3467 if (un->flags & AT_REMOVEDIR)
3468 ret = do_rmdir(un->dfd, un->filename);
3470 ret = do_unlinkat(un->dfd, un->filename);
3472 req->flags &= ~REQ_F_NEED_CLEANUP;
3474 req_set_fail_links(req);
3475 io_req_complete(req, ret);
3479 static int io_shutdown_prep(struct io_kiocb *req,
3480 const struct io_uring_sqe *sqe)
3482 #if defined(CONFIG_NET)
3483 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3485 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3489 req->shutdown.how = READ_ONCE(sqe->len);
3496 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3498 #if defined(CONFIG_NET)
3499 struct socket *sock;
3502 if (issue_flags & IO_URING_F_NONBLOCK)
3505 sock = sock_from_file(req->file);
3506 if (unlikely(!sock))
3509 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3511 req_set_fail_links(req);
3512 io_req_complete(req, ret);
3519 static int __io_splice_prep(struct io_kiocb *req,
3520 const struct io_uring_sqe *sqe)
3522 struct io_splice* sp = &req->splice;
3523 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3525 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3529 sp->len = READ_ONCE(sqe->len);
3530 sp->flags = READ_ONCE(sqe->splice_flags);
3532 if (unlikely(sp->flags & ~valid_flags))
3535 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3536 (sp->flags & SPLICE_F_FD_IN_FIXED));
3539 req->flags |= REQ_F_NEED_CLEANUP;
3541 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3543 * Splice operation will be punted aync, and here need to
3544 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3546 req->work.flags |= IO_WQ_WORK_UNBOUND;
3552 static int io_tee_prep(struct io_kiocb *req,
3553 const struct io_uring_sqe *sqe)
3555 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3557 return __io_splice_prep(req, sqe);
3560 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3562 struct io_splice *sp = &req->splice;
3563 struct file *in = sp->file_in;
3564 struct file *out = sp->file_out;
3565 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3568 if (issue_flags & IO_URING_F_NONBLOCK)
3571 ret = do_tee(in, out, sp->len, flags);
3573 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3574 req->flags &= ~REQ_F_NEED_CLEANUP;
3577 req_set_fail_links(req);
3578 io_req_complete(req, ret);
3582 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3584 struct io_splice* sp = &req->splice;
3586 sp->off_in = READ_ONCE(sqe->splice_off_in);
3587 sp->off_out = READ_ONCE(sqe->off);
3588 return __io_splice_prep(req, sqe);
3591 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3593 struct io_splice *sp = &req->splice;
3594 struct file *in = sp->file_in;
3595 struct file *out = sp->file_out;
3596 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3597 loff_t *poff_in, *poff_out;
3600 if (issue_flags & IO_URING_F_NONBLOCK)
3603 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3604 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3607 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3609 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3610 req->flags &= ~REQ_F_NEED_CLEANUP;
3613 req_set_fail_links(req);
3614 io_req_complete(req, ret);
3619 * IORING_OP_NOP just posts a completion event, nothing else.
3621 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3623 struct io_ring_ctx *ctx = req->ctx;
3625 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3628 __io_req_complete(req, issue_flags, 0, 0);
3632 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3634 struct io_ring_ctx *ctx = req->ctx;
3639 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3641 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3644 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3645 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3648 req->sync.off = READ_ONCE(sqe->off);
3649 req->sync.len = READ_ONCE(sqe->len);
3653 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3655 loff_t end = req->sync.off + req->sync.len;
3658 /* fsync always requires a blocking context */
3659 if (issue_flags & IO_URING_F_NONBLOCK)
3662 ret = vfs_fsync_range(req->file, req->sync.off,
3663 end > 0 ? end : LLONG_MAX,
3664 req->sync.flags & IORING_FSYNC_DATASYNC);
3666 req_set_fail_links(req);
3667 io_req_complete(req, ret);
3671 static int io_fallocate_prep(struct io_kiocb *req,
3672 const struct io_uring_sqe *sqe)
3674 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3676 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3679 req->sync.off = READ_ONCE(sqe->off);
3680 req->sync.len = READ_ONCE(sqe->addr);
3681 req->sync.mode = READ_ONCE(sqe->len);
3685 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3689 /* fallocate always requiring blocking context */
3690 if (issue_flags & IO_URING_F_NONBLOCK)
3692 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3695 req_set_fail_links(req);
3696 io_req_complete(req, ret);
3700 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3702 const char __user *fname;
3705 if (unlikely(sqe->ioprio || sqe->buf_index))
3707 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3710 /* open.how should be already initialised */
3711 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3712 req->open.how.flags |= O_LARGEFILE;
3714 req->open.dfd = READ_ONCE(sqe->fd);
3715 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3716 req->open.filename = getname(fname);
3717 if (IS_ERR(req->open.filename)) {
3718 ret = PTR_ERR(req->open.filename);
3719 req->open.filename = NULL;
3722 req->open.nofile = rlimit(RLIMIT_NOFILE);
3723 req->flags |= REQ_F_NEED_CLEANUP;
3727 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3731 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3733 mode = READ_ONCE(sqe->len);
3734 flags = READ_ONCE(sqe->open_flags);
3735 req->open.how = build_open_how(flags, mode);
3736 return __io_openat_prep(req, sqe);
3739 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3741 struct open_how __user *how;
3745 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3747 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3748 len = READ_ONCE(sqe->len);
3749 if (len < OPEN_HOW_SIZE_VER0)
3752 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3757 return __io_openat_prep(req, sqe);
3760 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3762 struct open_flags op;
3765 bool resolve_nonblock;
3768 ret = build_open_flags(&req->open.how, &op);
3771 nonblock_set = op.open_flag & O_NONBLOCK;
3772 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3773 if (issue_flags & IO_URING_F_NONBLOCK) {
3775 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3776 * it'll always -EAGAIN
3778 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3780 op.lookup_flags |= LOOKUP_CACHED;
3781 op.open_flag |= O_NONBLOCK;
3784 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3788 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3789 /* only retry if RESOLVE_CACHED wasn't already set by application */
3790 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3791 file == ERR_PTR(-EAGAIN)) {
3793 * We could hang on to this 'fd', but seems like marginal
3794 * gain for something that is now known to be a slower path.
3795 * So just put it, and we'll get a new one when we retry.
3803 ret = PTR_ERR(file);
3805 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3806 file->f_flags &= ~O_NONBLOCK;
3807 fsnotify_open(file);
3808 fd_install(ret, file);
3811 putname(req->open.filename);
3812 req->flags &= ~REQ_F_NEED_CLEANUP;
3814 req_set_fail_links(req);
3815 io_req_complete(req, ret);
3819 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3821 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
3824 static int io_remove_buffers_prep(struct io_kiocb *req,
3825 const struct io_uring_sqe *sqe)
3827 struct io_provide_buf *p = &req->pbuf;
3830 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3833 tmp = READ_ONCE(sqe->fd);
3834 if (!tmp || tmp > USHRT_MAX)
3837 memset(p, 0, sizeof(*p));
3839 p->bgid = READ_ONCE(sqe->buf_group);
3843 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3844 int bgid, unsigned nbufs)
3848 /* shouldn't happen */
3852 /* the head kbuf is the list itself */
3853 while (!list_empty(&buf->list)) {
3854 struct io_buffer *nxt;
3856 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3857 list_del(&nxt->list);
3864 idr_remove(&ctx->io_buffer_idr, bgid);
3869 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3871 struct io_provide_buf *p = &req->pbuf;
3872 struct io_ring_ctx *ctx = req->ctx;
3873 struct io_buffer *head;
3875 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3877 io_ring_submit_lock(ctx, !force_nonblock);
3879 lockdep_assert_held(&ctx->uring_lock);
3882 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3884 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3886 req_set_fail_links(req);
3888 /* need to hold the lock to complete IOPOLL requests */
3889 if (ctx->flags & IORING_SETUP_IOPOLL) {
3890 __io_req_complete(req, issue_flags, ret, 0);
3891 io_ring_submit_unlock(ctx, !force_nonblock);
3893 io_ring_submit_unlock(ctx, !force_nonblock);
3894 __io_req_complete(req, issue_flags, ret, 0);
3899 static int io_provide_buffers_prep(struct io_kiocb *req,
3900 const struct io_uring_sqe *sqe)
3902 struct io_provide_buf *p = &req->pbuf;
3905 if (sqe->ioprio || sqe->rw_flags)
3908 tmp = READ_ONCE(sqe->fd);
3909 if (!tmp || tmp > USHRT_MAX)
3912 p->addr = READ_ONCE(sqe->addr);
3913 p->len = READ_ONCE(sqe->len);
3915 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3918 p->bgid = READ_ONCE(sqe->buf_group);
3919 tmp = READ_ONCE(sqe->off);
3920 if (tmp > USHRT_MAX)
3926 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3928 struct io_buffer *buf;
3929 u64 addr = pbuf->addr;
3930 int i, bid = pbuf->bid;
3932 for (i = 0; i < pbuf->nbufs; i++) {
3933 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3938 buf->len = pbuf->len;
3943 INIT_LIST_HEAD(&buf->list);
3946 list_add_tail(&buf->list, &(*head)->list);
3950 return i ? i : -ENOMEM;
3953 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3955 struct io_provide_buf *p = &req->pbuf;
3956 struct io_ring_ctx *ctx = req->ctx;
3957 struct io_buffer *head, *list;
3959 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3961 io_ring_submit_lock(ctx, !force_nonblock);
3963 lockdep_assert_held(&ctx->uring_lock);
3965 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3967 ret = io_add_buffers(p, &head);
3972 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3975 __io_remove_buffers(ctx, head, p->bgid, -1U);
3981 req_set_fail_links(req);
3983 /* need to hold the lock to complete IOPOLL requests */
3984 if (ctx->flags & IORING_SETUP_IOPOLL) {
3985 __io_req_complete(req, issue_flags, ret, 0);
3986 io_ring_submit_unlock(ctx, !force_nonblock);
3988 io_ring_submit_unlock(ctx, !force_nonblock);
3989 __io_req_complete(req, issue_flags, ret, 0);
3994 static int io_epoll_ctl_prep(struct io_kiocb *req,
3995 const struct io_uring_sqe *sqe)
3997 #if defined(CONFIG_EPOLL)
3998 if (sqe->ioprio || sqe->buf_index)
4000 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4003 req->epoll.epfd = READ_ONCE(sqe->fd);
4004 req->epoll.op = READ_ONCE(sqe->len);
4005 req->epoll.fd = READ_ONCE(sqe->off);
4007 if (ep_op_has_event(req->epoll.op)) {
4008 struct epoll_event __user *ev;
4010 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4011 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4021 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4023 #if defined(CONFIG_EPOLL)
4024 struct io_epoll *ie = &req->epoll;
4026 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4028 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4029 if (force_nonblock && ret == -EAGAIN)
4033 req_set_fail_links(req);
4034 __io_req_complete(req, issue_flags, ret, 0);
4041 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4043 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4044 if (sqe->ioprio || sqe->buf_index || sqe->off)
4046 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4049 req->madvise.addr = READ_ONCE(sqe->addr);
4050 req->madvise.len = READ_ONCE(sqe->len);
4051 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4058 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4060 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4061 struct io_madvise *ma = &req->madvise;
4064 if (issue_flags & IO_URING_F_NONBLOCK)
4067 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4069 req_set_fail_links(req);
4070 io_req_complete(req, ret);
4077 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4079 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4081 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4084 req->fadvise.offset = READ_ONCE(sqe->off);
4085 req->fadvise.len = READ_ONCE(sqe->len);
4086 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4090 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4092 struct io_fadvise *fa = &req->fadvise;
4095 if (issue_flags & IO_URING_F_NONBLOCK) {
4096 switch (fa->advice) {
4097 case POSIX_FADV_NORMAL:
4098 case POSIX_FADV_RANDOM:
4099 case POSIX_FADV_SEQUENTIAL:
4106 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4108 req_set_fail_links(req);
4109 io_req_complete(req, ret);
4113 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4115 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4117 if (sqe->ioprio || sqe->buf_index)
4119 if (req->flags & REQ_F_FIXED_FILE)
4122 req->statx.dfd = READ_ONCE(sqe->fd);
4123 req->statx.mask = READ_ONCE(sqe->len);
4124 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4125 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4126 req->statx.flags = READ_ONCE(sqe->statx_flags);
4131 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4133 struct io_statx *ctx = &req->statx;
4136 if (issue_flags & IO_URING_F_NONBLOCK) {
4137 /* only need file table for an actual valid fd */
4138 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4139 req->flags |= REQ_F_NO_FILE_TABLE;
4143 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4147 req_set_fail_links(req);
4148 io_req_complete(req, ret);
4152 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4154 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4156 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4157 sqe->rw_flags || sqe->buf_index)
4159 if (req->flags & REQ_F_FIXED_FILE)
4162 req->close.fd = READ_ONCE(sqe->fd);
4166 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4168 struct files_struct *files = current->files;
4169 struct io_close *close = &req->close;
4170 struct fdtable *fdt;
4176 spin_lock(&files->file_lock);
4177 fdt = files_fdtable(files);
4178 if (close->fd >= fdt->max_fds) {
4179 spin_unlock(&files->file_lock);
4182 file = fdt->fd[close->fd];
4184 spin_unlock(&files->file_lock);
4188 if (file->f_op == &io_uring_fops) {
4189 spin_unlock(&files->file_lock);
4194 /* if the file has a flush method, be safe and punt to async */
4195 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4196 spin_unlock(&files->file_lock);
4200 ret = __close_fd_get_file(close->fd, &file);
4201 spin_unlock(&files->file_lock);
4208 /* No ->flush() or already async, safely close from here */
4209 ret = filp_close(file, current->files);
4212 req_set_fail_links(req);
4215 __io_req_complete(req, issue_flags, ret, 0);
4219 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4221 struct io_ring_ctx *ctx = req->ctx;
4223 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4225 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4228 req->sync.off = READ_ONCE(sqe->off);
4229 req->sync.len = READ_ONCE(sqe->len);
4230 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4234 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4238 /* sync_file_range always requires a blocking context */
4239 if (issue_flags & IO_URING_F_NONBLOCK)
4242 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4245 req_set_fail_links(req);
4246 io_req_complete(req, ret);
4250 #if defined(CONFIG_NET)
4251 static int io_setup_async_msg(struct io_kiocb *req,
4252 struct io_async_msghdr *kmsg)
4254 struct io_async_msghdr *async_msg = req->async_data;
4258 if (io_alloc_async_data(req)) {
4259 kfree(kmsg->free_iov);
4262 async_msg = req->async_data;
4263 req->flags |= REQ_F_NEED_CLEANUP;
4264 memcpy(async_msg, kmsg, sizeof(*kmsg));
4265 async_msg->msg.msg_name = &async_msg->addr;
4266 /* if were using fast_iov, set it to the new one */
4267 if (!async_msg->free_iov)
4268 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4273 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4274 struct io_async_msghdr *iomsg)
4276 iomsg->msg.msg_name = &iomsg->addr;
4277 iomsg->free_iov = iomsg->fast_iov;
4278 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4279 req->sr_msg.msg_flags, &iomsg->free_iov);
4282 static int io_sendmsg_prep_async(struct io_kiocb *req)
4286 if (!io_op_defs[req->opcode].needs_async_data)
4288 ret = io_sendmsg_copy_hdr(req, req->async_data);
4290 req->flags |= REQ_F_NEED_CLEANUP;
4294 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4296 struct io_sr_msg *sr = &req->sr_msg;
4298 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4301 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4302 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4303 sr->len = READ_ONCE(sqe->len);
4305 #ifdef CONFIG_COMPAT
4306 if (req->ctx->compat)
4307 sr->msg_flags |= MSG_CMSG_COMPAT;
4312 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4314 struct io_async_msghdr iomsg, *kmsg;
4315 struct socket *sock;
4319 sock = sock_from_file(req->file);
4320 if (unlikely(!sock))
4323 kmsg = req->async_data;
4325 ret = io_sendmsg_copy_hdr(req, &iomsg);
4331 flags = req->sr_msg.msg_flags;
4332 if (flags & MSG_DONTWAIT)
4333 req->flags |= REQ_F_NOWAIT;
4334 else if (issue_flags & IO_URING_F_NONBLOCK)
4335 flags |= MSG_DONTWAIT;
4337 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4338 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4339 return io_setup_async_msg(req, kmsg);
4340 if (ret == -ERESTARTSYS)
4343 /* fast path, check for non-NULL to avoid function call */
4345 kfree(kmsg->free_iov);
4346 req->flags &= ~REQ_F_NEED_CLEANUP;
4348 req_set_fail_links(req);
4349 __io_req_complete(req, issue_flags, ret, 0);
4353 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4355 struct io_sr_msg *sr = &req->sr_msg;
4358 struct socket *sock;
4362 sock = sock_from_file(req->file);
4363 if (unlikely(!sock))
4366 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4370 msg.msg_name = NULL;
4371 msg.msg_control = NULL;
4372 msg.msg_controllen = 0;
4373 msg.msg_namelen = 0;
4375 flags = req->sr_msg.msg_flags;
4376 if (flags & MSG_DONTWAIT)
4377 req->flags |= REQ_F_NOWAIT;
4378 else if (issue_flags & IO_URING_F_NONBLOCK)
4379 flags |= MSG_DONTWAIT;
4381 msg.msg_flags = flags;
4382 ret = sock_sendmsg(sock, &msg);
4383 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4385 if (ret == -ERESTARTSYS)
4389 req_set_fail_links(req);
4390 __io_req_complete(req, issue_flags, ret, 0);
4394 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4395 struct io_async_msghdr *iomsg)
4397 struct io_sr_msg *sr = &req->sr_msg;
4398 struct iovec __user *uiov;
4402 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4403 &iomsg->uaddr, &uiov, &iov_len);
4407 if (req->flags & REQ_F_BUFFER_SELECT) {
4410 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4412 sr->len = iomsg->fast_iov[0].iov_len;
4413 iomsg->free_iov = NULL;
4415 iomsg->free_iov = iomsg->fast_iov;
4416 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4417 &iomsg->free_iov, &iomsg->msg.msg_iter,
4426 #ifdef CONFIG_COMPAT
4427 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4428 struct io_async_msghdr *iomsg)
4430 struct compat_msghdr __user *msg_compat;
4431 struct io_sr_msg *sr = &req->sr_msg;
4432 struct compat_iovec __user *uiov;
4437 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4438 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4443 uiov = compat_ptr(ptr);
4444 if (req->flags & REQ_F_BUFFER_SELECT) {
4445 compat_ssize_t clen;
4449 if (!access_ok(uiov, sizeof(*uiov)))
4451 if (__get_user(clen, &uiov->iov_len))
4456 iomsg->free_iov = NULL;
4458 iomsg->free_iov = iomsg->fast_iov;
4459 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4460 UIO_FASTIOV, &iomsg->free_iov,
4461 &iomsg->msg.msg_iter, true);
4470 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4471 struct io_async_msghdr *iomsg)
4473 iomsg->msg.msg_name = &iomsg->addr;
4475 #ifdef CONFIG_COMPAT
4476 if (req->ctx->compat)
4477 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4480 return __io_recvmsg_copy_hdr(req, iomsg);
4483 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4486 struct io_sr_msg *sr = &req->sr_msg;
4487 struct io_buffer *kbuf;
4489 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4494 req->flags |= REQ_F_BUFFER_SELECTED;
4498 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4500 return io_put_kbuf(req, req->sr_msg.kbuf);
4503 static int io_recvmsg_prep_async(struct io_kiocb *req)
4507 if (!io_op_defs[req->opcode].needs_async_data)
4509 ret = io_recvmsg_copy_hdr(req, req->async_data);
4511 req->flags |= REQ_F_NEED_CLEANUP;
4515 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4517 struct io_sr_msg *sr = &req->sr_msg;
4519 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4522 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4523 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4524 sr->len = READ_ONCE(sqe->len);
4525 sr->bgid = READ_ONCE(sqe->buf_group);
4527 #ifdef CONFIG_COMPAT
4528 if (req->ctx->compat)
4529 sr->msg_flags |= MSG_CMSG_COMPAT;
4534 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4536 struct io_async_msghdr iomsg, *kmsg;
4537 struct socket *sock;
4538 struct io_buffer *kbuf;
4540 int ret, cflags = 0;
4541 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4543 sock = sock_from_file(req->file);
4544 if (unlikely(!sock))
4547 kmsg = req->async_data;
4549 ret = io_recvmsg_copy_hdr(req, &iomsg);
4555 if (req->flags & REQ_F_BUFFER_SELECT) {
4556 kbuf = io_recv_buffer_select(req, !force_nonblock);
4558 return PTR_ERR(kbuf);
4559 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4560 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4561 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4562 1, req->sr_msg.len);
4565 flags = req->sr_msg.msg_flags;
4566 if (flags & MSG_DONTWAIT)
4567 req->flags |= REQ_F_NOWAIT;
4568 else if (force_nonblock)
4569 flags |= MSG_DONTWAIT;
4571 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4572 kmsg->uaddr, flags);
4573 if (force_nonblock && ret == -EAGAIN)
4574 return io_setup_async_msg(req, kmsg);
4575 if (ret == -ERESTARTSYS)
4578 if (req->flags & REQ_F_BUFFER_SELECTED)
4579 cflags = io_put_recv_kbuf(req);
4580 /* fast path, check for non-NULL to avoid function call */
4582 kfree(kmsg->free_iov);
4583 req->flags &= ~REQ_F_NEED_CLEANUP;
4585 req_set_fail_links(req);
4586 __io_req_complete(req, issue_flags, ret, cflags);
4590 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4592 struct io_buffer *kbuf;
4593 struct io_sr_msg *sr = &req->sr_msg;
4595 void __user *buf = sr->buf;
4596 struct socket *sock;
4599 int ret, cflags = 0;
4600 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4602 sock = sock_from_file(req->file);
4603 if (unlikely(!sock))
4606 if (req->flags & REQ_F_BUFFER_SELECT) {
4607 kbuf = io_recv_buffer_select(req, !force_nonblock);
4609 return PTR_ERR(kbuf);
4610 buf = u64_to_user_ptr(kbuf->addr);
4613 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4617 msg.msg_name = NULL;
4618 msg.msg_control = NULL;
4619 msg.msg_controllen = 0;
4620 msg.msg_namelen = 0;
4621 msg.msg_iocb = NULL;
4624 flags = req->sr_msg.msg_flags;
4625 if (flags & MSG_DONTWAIT)
4626 req->flags |= REQ_F_NOWAIT;
4627 else if (force_nonblock)
4628 flags |= MSG_DONTWAIT;
4630 ret = sock_recvmsg(sock, &msg, flags);
4631 if (force_nonblock && ret == -EAGAIN)
4633 if (ret == -ERESTARTSYS)
4636 if (req->flags & REQ_F_BUFFER_SELECTED)
4637 cflags = io_put_recv_kbuf(req);
4639 req_set_fail_links(req);
4640 __io_req_complete(req, issue_flags, ret, cflags);
4644 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4646 struct io_accept *accept = &req->accept;
4648 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4650 if (sqe->ioprio || sqe->len || sqe->buf_index)
4653 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4654 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4655 accept->flags = READ_ONCE(sqe->accept_flags);
4656 accept->nofile = rlimit(RLIMIT_NOFILE);
4660 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4662 struct io_accept *accept = &req->accept;
4663 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4664 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4667 if (req->file->f_flags & O_NONBLOCK)
4668 req->flags |= REQ_F_NOWAIT;
4670 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4671 accept->addr_len, accept->flags,
4673 if (ret == -EAGAIN && force_nonblock)
4676 if (ret == -ERESTARTSYS)
4678 req_set_fail_links(req);
4680 __io_req_complete(req, issue_flags, ret, 0);
4684 static int io_connect_prep_async(struct io_kiocb *req)
4686 struct io_async_connect *io = req->async_data;
4687 struct io_connect *conn = &req->connect;
4689 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4692 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4694 struct io_connect *conn = &req->connect;
4696 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4698 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4701 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4702 conn->addr_len = READ_ONCE(sqe->addr2);
4706 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4708 struct io_async_connect __io, *io;
4709 unsigned file_flags;
4711 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4713 if (req->async_data) {
4714 io = req->async_data;
4716 ret = move_addr_to_kernel(req->connect.addr,
4717 req->connect.addr_len,
4724 file_flags = force_nonblock ? O_NONBLOCK : 0;
4726 ret = __sys_connect_file(req->file, &io->address,
4727 req->connect.addr_len, file_flags);
4728 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4729 if (req->async_data)
4731 if (io_alloc_async_data(req)) {
4735 io = req->async_data;
4736 memcpy(req->async_data, &__io, sizeof(__io));
4739 if (ret == -ERESTARTSYS)
4743 req_set_fail_links(req);
4744 __io_req_complete(req, issue_flags, ret, 0);
4747 #else /* !CONFIG_NET */
4748 #define IO_NETOP_FN(op) \
4749 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4751 return -EOPNOTSUPP; \
4754 #define IO_NETOP_PREP(op) \
4756 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4758 return -EOPNOTSUPP; \
4761 #define IO_NETOP_PREP_ASYNC(op) \
4763 static int io_##op##_prep_async(struct io_kiocb *req) \
4765 return -EOPNOTSUPP; \
4768 IO_NETOP_PREP_ASYNC(sendmsg);
4769 IO_NETOP_PREP_ASYNC(recvmsg);
4770 IO_NETOP_PREP_ASYNC(connect);
4771 IO_NETOP_PREP(accept);
4774 #endif /* CONFIG_NET */
4776 struct io_poll_table {
4777 struct poll_table_struct pt;
4778 struct io_kiocb *req;
4782 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4783 __poll_t mask, task_work_func_t func)
4787 /* for instances that support it check for an event match first: */
4788 if (mask && !(mask & poll->events))
4791 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4793 list_del_init(&poll->wait.entry);
4796 req->task_work.func = func;
4797 percpu_ref_get(&req->ctx->refs);
4800 * If this fails, then the task is exiting. When a task exits, the
4801 * work gets canceled, so just cancel this request as well instead
4802 * of executing it. We can't safely execute it anyway, as we may not
4803 * have the needed state needed for it anyway.
4805 ret = io_req_task_work_add(req);
4806 if (unlikely(ret)) {
4807 WRITE_ONCE(poll->canceled, true);
4808 io_req_task_work_add_fallback(req, func);
4813 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4814 __acquires(&req->ctx->completion_lock)
4816 struct io_ring_ctx *ctx = req->ctx;
4818 if (!req->result && !READ_ONCE(poll->canceled)) {
4819 struct poll_table_struct pt = { ._key = poll->events };
4821 req->result = vfs_poll(req->file, &pt) & poll->events;
4824 spin_lock_irq(&ctx->completion_lock);
4825 if (!req->result && !READ_ONCE(poll->canceled)) {
4826 add_wait_queue(poll->head, &poll->wait);
4833 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4835 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4836 if (req->opcode == IORING_OP_POLL_ADD)
4837 return req->async_data;
4838 return req->apoll->double_poll;
4841 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4843 if (req->opcode == IORING_OP_POLL_ADD)
4845 return &req->apoll->poll;
4848 static void io_poll_remove_double(struct io_kiocb *req)
4850 struct io_poll_iocb *poll = io_poll_get_double(req);
4852 lockdep_assert_held(&req->ctx->completion_lock);
4854 if (poll && poll->head) {
4855 struct wait_queue_head *head = poll->head;
4857 spin_lock(&head->lock);
4858 list_del_init(&poll->wait.entry);
4859 if (poll->wait.private)
4860 refcount_dec(&req->refs);
4862 spin_unlock(&head->lock);
4866 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4868 struct io_ring_ctx *ctx = req->ctx;
4870 io_poll_remove_double(req);
4871 req->poll.done = true;
4872 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4873 io_commit_cqring(ctx);
4876 static void io_poll_task_func(struct callback_head *cb)
4878 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4879 struct io_ring_ctx *ctx = req->ctx;
4880 struct io_kiocb *nxt;
4882 if (io_poll_rewait(req, &req->poll)) {
4883 spin_unlock_irq(&ctx->completion_lock);
4885 hash_del(&req->hash_node);
4886 io_poll_complete(req, req->result, 0);
4887 spin_unlock_irq(&ctx->completion_lock);
4889 nxt = io_put_req_find_next(req);
4890 io_cqring_ev_posted(ctx);
4892 __io_req_task_submit(nxt);
4895 percpu_ref_put(&ctx->refs);
4898 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4899 int sync, void *key)
4901 struct io_kiocb *req = wait->private;
4902 struct io_poll_iocb *poll = io_poll_get_single(req);
4903 __poll_t mask = key_to_poll(key);
4905 /* for instances that support it check for an event match first: */
4906 if (mask && !(mask & poll->events))
4909 list_del_init(&wait->entry);
4911 if (poll && poll->head) {
4914 spin_lock(&poll->head->lock);
4915 done = list_empty(&poll->wait.entry);
4917 list_del_init(&poll->wait.entry);
4918 /* make sure double remove sees this as being gone */
4919 wait->private = NULL;
4920 spin_unlock(&poll->head->lock);
4922 /* use wait func handler, so it matches the rq type */
4923 poll->wait.func(&poll->wait, mode, sync, key);
4926 refcount_dec(&req->refs);
4930 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4931 wait_queue_func_t wake_func)
4935 poll->canceled = false;
4936 poll->events = events;
4937 INIT_LIST_HEAD(&poll->wait.entry);
4938 init_waitqueue_func_entry(&poll->wait, wake_func);
4941 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4942 struct wait_queue_head *head,
4943 struct io_poll_iocb **poll_ptr)
4945 struct io_kiocb *req = pt->req;
4948 * If poll->head is already set, it's because the file being polled
4949 * uses multiple waitqueues for poll handling (eg one for read, one
4950 * for write). Setup a separate io_poll_iocb if this happens.
4952 if (unlikely(poll->head)) {
4953 struct io_poll_iocb *poll_one = poll;
4955 /* already have a 2nd entry, fail a third attempt */
4957 pt->error = -EINVAL;
4960 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4962 pt->error = -ENOMEM;
4965 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
4966 refcount_inc(&req->refs);
4967 poll->wait.private = req;
4974 if (poll->events & EPOLLEXCLUSIVE)
4975 add_wait_queue_exclusive(head, &poll->wait);
4977 add_wait_queue(head, &poll->wait);
4980 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4981 struct poll_table_struct *p)
4983 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4984 struct async_poll *apoll = pt->req->apoll;
4986 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
4989 static void io_async_task_func(struct callback_head *cb)
4991 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4992 struct async_poll *apoll = req->apoll;
4993 struct io_ring_ctx *ctx = req->ctx;
4995 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4997 if (io_poll_rewait(req, &apoll->poll)) {
4998 spin_unlock_irq(&ctx->completion_lock);
4999 percpu_ref_put(&ctx->refs);
5003 /* If req is still hashed, it cannot have been canceled. Don't check. */
5004 if (hash_hashed(&req->hash_node))
5005 hash_del(&req->hash_node);
5007 io_poll_remove_double(req);
5008 spin_unlock_irq(&ctx->completion_lock);
5010 if (!READ_ONCE(apoll->poll.canceled))
5011 __io_req_task_submit(req);
5013 __io_req_task_cancel(req, -ECANCELED);
5015 percpu_ref_put(&ctx->refs);
5016 kfree(apoll->double_poll);
5020 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5023 struct io_kiocb *req = wait->private;
5024 struct io_poll_iocb *poll = &req->apoll->poll;
5026 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5029 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5032 static void io_poll_req_insert(struct io_kiocb *req)
5034 struct io_ring_ctx *ctx = req->ctx;
5035 struct hlist_head *list;
5037 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5038 hlist_add_head(&req->hash_node, list);
5041 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5042 struct io_poll_iocb *poll,
5043 struct io_poll_table *ipt, __poll_t mask,
5044 wait_queue_func_t wake_func)
5045 __acquires(&ctx->completion_lock)
5047 struct io_ring_ctx *ctx = req->ctx;
5048 bool cancel = false;
5050 INIT_HLIST_NODE(&req->hash_node);
5051 io_init_poll_iocb(poll, mask, wake_func);
5052 poll->file = req->file;
5053 poll->wait.private = req;
5055 ipt->pt._key = mask;
5057 ipt->error = -EINVAL;
5059 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5061 spin_lock_irq(&ctx->completion_lock);
5062 if (likely(poll->head)) {
5063 spin_lock(&poll->head->lock);
5064 if (unlikely(list_empty(&poll->wait.entry))) {
5070 if (mask || ipt->error)
5071 list_del_init(&poll->wait.entry);
5073 WRITE_ONCE(poll->canceled, true);
5074 else if (!poll->done) /* actually waiting for an event */
5075 io_poll_req_insert(req);
5076 spin_unlock(&poll->head->lock);
5082 static bool io_arm_poll_handler(struct io_kiocb *req)
5084 const struct io_op_def *def = &io_op_defs[req->opcode];
5085 struct io_ring_ctx *ctx = req->ctx;
5086 struct async_poll *apoll;
5087 struct io_poll_table ipt;
5091 if (!req->file || !file_can_poll(req->file))
5093 if (req->flags & REQ_F_POLLED)
5097 else if (def->pollout)
5101 /* if we can't nonblock try, then no point in arming a poll handler */
5102 if (!io_file_supports_async(req->file, rw))
5105 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5106 if (unlikely(!apoll))
5108 apoll->double_poll = NULL;
5110 req->flags |= REQ_F_POLLED;
5115 mask |= POLLIN | POLLRDNORM;
5117 mask |= POLLOUT | POLLWRNORM;
5119 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5120 if ((req->opcode == IORING_OP_RECVMSG) &&
5121 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5124 mask |= POLLERR | POLLPRI;
5126 ipt.pt._qproc = io_async_queue_proc;
5128 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5130 if (ret || ipt.error) {
5131 io_poll_remove_double(req);
5132 spin_unlock_irq(&ctx->completion_lock);
5133 kfree(apoll->double_poll);
5137 spin_unlock_irq(&ctx->completion_lock);
5138 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5139 apoll->poll.events);
5143 static bool __io_poll_remove_one(struct io_kiocb *req,
5144 struct io_poll_iocb *poll)
5146 bool do_complete = false;
5148 spin_lock(&poll->head->lock);
5149 WRITE_ONCE(poll->canceled, true);
5150 if (!list_empty(&poll->wait.entry)) {
5151 list_del_init(&poll->wait.entry);
5154 spin_unlock(&poll->head->lock);
5155 hash_del(&req->hash_node);
5159 static bool io_poll_remove_one(struct io_kiocb *req)
5163 io_poll_remove_double(req);
5165 if (req->opcode == IORING_OP_POLL_ADD) {
5166 do_complete = __io_poll_remove_one(req, &req->poll);
5168 struct async_poll *apoll = req->apoll;
5170 /* non-poll requests have submit ref still */
5171 do_complete = __io_poll_remove_one(req, &apoll->poll);
5174 kfree(apoll->double_poll);
5180 io_cqring_fill_event(req, -ECANCELED);
5181 io_commit_cqring(req->ctx);
5182 req_set_fail_links(req);
5183 io_put_req_deferred(req, 1);
5190 * Returns true if we found and killed one or more poll requests
5192 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5193 struct files_struct *files)
5195 struct hlist_node *tmp;
5196 struct io_kiocb *req;
5199 spin_lock_irq(&ctx->completion_lock);
5200 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5201 struct hlist_head *list;
5203 list = &ctx->cancel_hash[i];
5204 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5205 if (io_match_task(req, tsk, files))
5206 posted += io_poll_remove_one(req);
5209 spin_unlock_irq(&ctx->completion_lock);
5212 io_cqring_ev_posted(ctx);
5217 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5219 struct hlist_head *list;
5220 struct io_kiocb *req;
5222 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5223 hlist_for_each_entry(req, list, hash_node) {
5224 if (sqe_addr != req->user_data)
5226 if (io_poll_remove_one(req))
5234 static int io_poll_remove_prep(struct io_kiocb *req,
5235 const struct io_uring_sqe *sqe)
5237 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5239 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5243 req->poll_remove.addr = READ_ONCE(sqe->addr);
5248 * Find a running poll command that matches one specified in sqe->addr,
5249 * and remove it if found.
5251 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5253 struct io_ring_ctx *ctx = req->ctx;
5256 spin_lock_irq(&ctx->completion_lock);
5257 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5258 spin_unlock_irq(&ctx->completion_lock);
5261 req_set_fail_links(req);
5262 io_req_complete(req, ret);
5266 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5269 struct io_kiocb *req = wait->private;
5270 struct io_poll_iocb *poll = &req->poll;
5272 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5275 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5276 struct poll_table_struct *p)
5278 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5280 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5283 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5285 struct io_poll_iocb *poll = &req->poll;
5288 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5290 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5293 events = READ_ONCE(sqe->poll32_events);
5295 events = swahw32(events);
5297 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5298 (events & EPOLLEXCLUSIVE);
5302 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5304 struct io_poll_iocb *poll = &req->poll;
5305 struct io_ring_ctx *ctx = req->ctx;
5306 struct io_poll_table ipt;
5309 ipt.pt._qproc = io_poll_queue_proc;
5311 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5314 if (mask) { /* no async, we'd stolen it */
5316 io_poll_complete(req, mask, 0);
5318 spin_unlock_irq(&ctx->completion_lock);
5321 io_cqring_ev_posted(ctx);
5327 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5329 struct io_timeout_data *data = container_of(timer,
5330 struct io_timeout_data, timer);
5331 struct io_kiocb *req = data->req;
5332 struct io_ring_ctx *ctx = req->ctx;
5333 unsigned long flags;
5335 spin_lock_irqsave(&ctx->completion_lock, flags);
5336 list_del_init(&req->timeout.list);
5337 atomic_set(&req->ctx->cq_timeouts,
5338 atomic_read(&req->ctx->cq_timeouts) + 1);
5340 io_cqring_fill_event(req, -ETIME);
5341 io_commit_cqring(ctx);
5342 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5344 io_cqring_ev_posted(ctx);
5345 req_set_fail_links(req);
5347 return HRTIMER_NORESTART;
5350 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5353 struct io_timeout_data *io;
5354 struct io_kiocb *req;
5357 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5358 if (user_data == req->user_data) {
5365 return ERR_PTR(ret);
5367 io = req->async_data;
5368 ret = hrtimer_try_to_cancel(&io->timer);
5370 return ERR_PTR(-EALREADY);
5371 list_del_init(&req->timeout.list);
5375 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5377 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5380 return PTR_ERR(req);
5382 req_set_fail_links(req);
5383 io_cqring_fill_event(req, -ECANCELED);
5384 io_put_req_deferred(req, 1);
5388 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5389 struct timespec64 *ts, enum hrtimer_mode mode)
5391 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5392 struct io_timeout_data *data;
5395 return PTR_ERR(req);
5397 req->timeout.off = 0; /* noseq */
5398 data = req->async_data;
5399 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5400 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5401 data->timer.function = io_timeout_fn;
5402 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5406 static int io_timeout_remove_prep(struct io_kiocb *req,
5407 const struct io_uring_sqe *sqe)
5409 struct io_timeout_rem *tr = &req->timeout_rem;
5411 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5413 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5415 if (sqe->ioprio || sqe->buf_index || sqe->len)
5418 tr->addr = READ_ONCE(sqe->addr);
5419 tr->flags = READ_ONCE(sqe->timeout_flags);
5420 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5421 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5423 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5425 } else if (tr->flags) {
5426 /* timeout removal doesn't support flags */
5433 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5435 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5440 * Remove or update an existing timeout command
5442 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5444 struct io_timeout_rem *tr = &req->timeout_rem;
5445 struct io_ring_ctx *ctx = req->ctx;
5448 spin_lock_irq(&ctx->completion_lock);
5449 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5450 ret = io_timeout_cancel(ctx, tr->addr);
5452 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5453 io_translate_timeout_mode(tr->flags));
5455 io_cqring_fill_event(req, ret);
5456 io_commit_cqring(ctx);
5457 spin_unlock_irq(&ctx->completion_lock);
5458 io_cqring_ev_posted(ctx);
5460 req_set_fail_links(req);
5465 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5466 bool is_timeout_link)
5468 struct io_timeout_data *data;
5470 u32 off = READ_ONCE(sqe->off);
5472 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5474 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5476 if (off && is_timeout_link)
5478 flags = READ_ONCE(sqe->timeout_flags);
5479 if (flags & ~IORING_TIMEOUT_ABS)
5482 req->timeout.off = off;
5484 if (!req->async_data && io_alloc_async_data(req))
5487 data = req->async_data;
5490 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5493 data->mode = io_translate_timeout_mode(flags);
5494 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5498 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5500 struct io_ring_ctx *ctx = req->ctx;
5501 struct io_timeout_data *data = req->async_data;
5502 struct list_head *entry;
5503 u32 tail, off = req->timeout.off;
5505 spin_lock_irq(&ctx->completion_lock);
5508 * sqe->off holds how many events that need to occur for this
5509 * timeout event to be satisfied. If it isn't set, then this is
5510 * a pure timeout request, sequence isn't used.
5512 if (io_is_timeout_noseq(req)) {
5513 entry = ctx->timeout_list.prev;
5517 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5518 req->timeout.target_seq = tail + off;
5520 /* Update the last seq here in case io_flush_timeouts() hasn't.
5521 * This is safe because ->completion_lock is held, and submissions
5522 * and completions are never mixed in the same ->completion_lock section.
5524 ctx->cq_last_tm_flush = tail;
5527 * Insertion sort, ensuring the first entry in the list is always
5528 * the one we need first.
5530 list_for_each_prev(entry, &ctx->timeout_list) {
5531 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5534 if (io_is_timeout_noseq(nxt))
5536 /* nxt.seq is behind @tail, otherwise would've been completed */
5537 if (off >= nxt->timeout.target_seq - tail)
5541 list_add(&req->timeout.list, entry);
5542 data->timer.function = io_timeout_fn;
5543 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5544 spin_unlock_irq(&ctx->completion_lock);
5548 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5550 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5552 return req->user_data == (unsigned long) data;
5555 static int io_async_cancel_one(struct io_uring_task *tctx, void *sqe_addr)
5557 enum io_wq_cancel cancel_ret;
5563 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, sqe_addr, false);
5564 switch (cancel_ret) {
5565 case IO_WQ_CANCEL_OK:
5568 case IO_WQ_CANCEL_RUNNING:
5571 case IO_WQ_CANCEL_NOTFOUND:
5579 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5580 struct io_kiocb *req, __u64 sqe_addr,
5583 unsigned long flags;
5586 ret = io_async_cancel_one(req->task->io_uring,
5587 (void *) (unsigned long) sqe_addr);
5588 if (ret != -ENOENT) {
5589 spin_lock_irqsave(&ctx->completion_lock, flags);
5593 spin_lock_irqsave(&ctx->completion_lock, flags);
5594 ret = io_timeout_cancel(ctx, sqe_addr);
5597 ret = io_poll_cancel(ctx, sqe_addr);
5601 io_cqring_fill_event(req, ret);
5602 io_commit_cqring(ctx);
5603 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5604 io_cqring_ev_posted(ctx);
5607 req_set_fail_links(req);
5611 static int io_async_cancel_prep(struct io_kiocb *req,
5612 const struct io_uring_sqe *sqe)
5614 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5616 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5618 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5621 req->cancel.addr = READ_ONCE(sqe->addr);
5625 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5627 struct io_ring_ctx *ctx = req->ctx;
5629 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5633 static int io_rsrc_update_prep(struct io_kiocb *req,
5634 const struct io_uring_sqe *sqe)
5636 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5638 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5640 if (sqe->ioprio || sqe->rw_flags)
5643 req->rsrc_update.offset = READ_ONCE(sqe->off);
5644 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5645 if (!req->rsrc_update.nr_args)
5647 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5651 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5653 struct io_ring_ctx *ctx = req->ctx;
5654 struct io_uring_rsrc_update up;
5657 if (issue_flags & IO_URING_F_NONBLOCK)
5660 up.offset = req->rsrc_update.offset;
5661 up.data = req->rsrc_update.arg;
5663 mutex_lock(&ctx->uring_lock);
5664 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5665 mutex_unlock(&ctx->uring_lock);
5668 req_set_fail_links(req);
5669 __io_req_complete(req, issue_flags, ret, 0);
5673 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5675 switch (req->opcode) {
5678 case IORING_OP_READV:
5679 case IORING_OP_READ_FIXED:
5680 case IORING_OP_READ:
5681 return io_read_prep(req, sqe);
5682 case IORING_OP_WRITEV:
5683 case IORING_OP_WRITE_FIXED:
5684 case IORING_OP_WRITE:
5685 return io_write_prep(req, sqe);
5686 case IORING_OP_POLL_ADD:
5687 return io_poll_add_prep(req, sqe);
5688 case IORING_OP_POLL_REMOVE:
5689 return io_poll_remove_prep(req, sqe);
5690 case IORING_OP_FSYNC:
5691 return io_fsync_prep(req, sqe);
5692 case IORING_OP_SYNC_FILE_RANGE:
5693 return io_sfr_prep(req, sqe);
5694 case IORING_OP_SENDMSG:
5695 case IORING_OP_SEND:
5696 return io_sendmsg_prep(req, sqe);
5697 case IORING_OP_RECVMSG:
5698 case IORING_OP_RECV:
5699 return io_recvmsg_prep(req, sqe);
5700 case IORING_OP_CONNECT:
5701 return io_connect_prep(req, sqe);
5702 case IORING_OP_TIMEOUT:
5703 return io_timeout_prep(req, sqe, false);
5704 case IORING_OP_TIMEOUT_REMOVE:
5705 return io_timeout_remove_prep(req, sqe);
5706 case IORING_OP_ASYNC_CANCEL:
5707 return io_async_cancel_prep(req, sqe);
5708 case IORING_OP_LINK_TIMEOUT:
5709 return io_timeout_prep(req, sqe, true);
5710 case IORING_OP_ACCEPT:
5711 return io_accept_prep(req, sqe);
5712 case IORING_OP_FALLOCATE:
5713 return io_fallocate_prep(req, sqe);
5714 case IORING_OP_OPENAT:
5715 return io_openat_prep(req, sqe);
5716 case IORING_OP_CLOSE:
5717 return io_close_prep(req, sqe);
5718 case IORING_OP_FILES_UPDATE:
5719 return io_rsrc_update_prep(req, sqe);
5720 case IORING_OP_STATX:
5721 return io_statx_prep(req, sqe);
5722 case IORING_OP_FADVISE:
5723 return io_fadvise_prep(req, sqe);
5724 case IORING_OP_MADVISE:
5725 return io_madvise_prep(req, sqe);
5726 case IORING_OP_OPENAT2:
5727 return io_openat2_prep(req, sqe);
5728 case IORING_OP_EPOLL_CTL:
5729 return io_epoll_ctl_prep(req, sqe);
5730 case IORING_OP_SPLICE:
5731 return io_splice_prep(req, sqe);
5732 case IORING_OP_PROVIDE_BUFFERS:
5733 return io_provide_buffers_prep(req, sqe);
5734 case IORING_OP_REMOVE_BUFFERS:
5735 return io_remove_buffers_prep(req, sqe);
5737 return io_tee_prep(req, sqe);
5738 case IORING_OP_SHUTDOWN:
5739 return io_shutdown_prep(req, sqe);
5740 case IORING_OP_RENAMEAT:
5741 return io_renameat_prep(req, sqe);
5742 case IORING_OP_UNLINKAT:
5743 return io_unlinkat_prep(req, sqe);
5746 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5751 static int io_req_prep_async(struct io_kiocb *req)
5753 switch (req->opcode) {
5754 case IORING_OP_READV:
5755 case IORING_OP_READ_FIXED:
5756 case IORING_OP_READ:
5757 return io_rw_prep_async(req, READ);
5758 case IORING_OP_WRITEV:
5759 case IORING_OP_WRITE_FIXED:
5760 case IORING_OP_WRITE:
5761 return io_rw_prep_async(req, WRITE);
5762 case IORING_OP_SENDMSG:
5763 case IORING_OP_SEND:
5764 return io_sendmsg_prep_async(req);
5765 case IORING_OP_RECVMSG:
5766 case IORING_OP_RECV:
5767 return io_recvmsg_prep_async(req);
5768 case IORING_OP_CONNECT:
5769 return io_connect_prep_async(req);
5774 static int io_req_defer_prep(struct io_kiocb *req)
5776 if (!io_op_defs[req->opcode].needs_async_data)
5778 /* some opcodes init it during the inital prep */
5779 if (req->async_data)
5781 if (__io_alloc_async_data(req))
5783 return io_req_prep_async(req);
5786 static u32 io_get_sequence(struct io_kiocb *req)
5788 struct io_kiocb *pos;
5789 struct io_ring_ctx *ctx = req->ctx;
5790 u32 total_submitted, nr_reqs = 0;
5792 io_for_each_link(pos, req)
5795 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5796 return total_submitted - nr_reqs;
5799 static int io_req_defer(struct io_kiocb *req)
5801 struct io_ring_ctx *ctx = req->ctx;
5802 struct io_defer_entry *de;
5806 /* Still need defer if there is pending req in defer list. */
5807 if (likely(list_empty_careful(&ctx->defer_list) &&
5808 !(req->flags & REQ_F_IO_DRAIN)))
5811 seq = io_get_sequence(req);
5812 /* Still a chance to pass the sequence check */
5813 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5816 ret = io_req_defer_prep(req);
5819 io_prep_async_link(req);
5820 de = kmalloc(sizeof(*de), GFP_KERNEL);
5824 spin_lock_irq(&ctx->completion_lock);
5825 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5826 spin_unlock_irq(&ctx->completion_lock);
5828 io_queue_async_work(req);
5829 return -EIOCBQUEUED;
5832 trace_io_uring_defer(ctx, req, req->user_data);
5835 list_add_tail(&de->list, &ctx->defer_list);
5836 spin_unlock_irq(&ctx->completion_lock);
5837 return -EIOCBQUEUED;
5840 static void __io_clean_op(struct io_kiocb *req)
5842 if (req->flags & REQ_F_BUFFER_SELECTED) {
5843 switch (req->opcode) {
5844 case IORING_OP_READV:
5845 case IORING_OP_READ_FIXED:
5846 case IORING_OP_READ:
5847 kfree((void *)(unsigned long)req->rw.addr);
5849 case IORING_OP_RECVMSG:
5850 case IORING_OP_RECV:
5851 kfree(req->sr_msg.kbuf);
5854 req->flags &= ~REQ_F_BUFFER_SELECTED;
5857 if (req->flags & REQ_F_NEED_CLEANUP) {
5858 switch (req->opcode) {
5859 case IORING_OP_READV:
5860 case IORING_OP_READ_FIXED:
5861 case IORING_OP_READ:
5862 case IORING_OP_WRITEV:
5863 case IORING_OP_WRITE_FIXED:
5864 case IORING_OP_WRITE: {
5865 struct io_async_rw *io = req->async_data;
5867 kfree(io->free_iovec);
5870 case IORING_OP_RECVMSG:
5871 case IORING_OP_SENDMSG: {
5872 struct io_async_msghdr *io = req->async_data;
5874 kfree(io->free_iov);
5877 case IORING_OP_SPLICE:
5879 io_put_file(req, req->splice.file_in,
5880 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5882 case IORING_OP_OPENAT:
5883 case IORING_OP_OPENAT2:
5884 if (req->open.filename)
5885 putname(req->open.filename);
5887 case IORING_OP_RENAMEAT:
5888 putname(req->rename.oldpath);
5889 putname(req->rename.newpath);
5891 case IORING_OP_UNLINKAT:
5892 putname(req->unlink.filename);
5895 req->flags &= ~REQ_F_NEED_CLEANUP;
5899 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
5901 struct io_ring_ctx *ctx = req->ctx;
5902 const struct cred *creds = NULL;
5905 if (req->work.personality) {
5906 const struct cred *new_creds;
5908 if (!(issue_flags & IO_URING_F_NONBLOCK))
5909 mutex_lock(&ctx->uring_lock);
5910 new_creds = idr_find(&ctx->personality_idr, req->work.personality);
5911 if (!(issue_flags & IO_URING_F_NONBLOCK))
5912 mutex_unlock(&ctx->uring_lock);
5915 creds = override_creds(new_creds);
5918 switch (req->opcode) {
5920 ret = io_nop(req, issue_flags);
5922 case IORING_OP_READV:
5923 case IORING_OP_READ_FIXED:
5924 case IORING_OP_READ:
5925 ret = io_read(req, issue_flags);
5927 case IORING_OP_WRITEV:
5928 case IORING_OP_WRITE_FIXED:
5929 case IORING_OP_WRITE:
5930 ret = io_write(req, issue_flags);
5932 case IORING_OP_FSYNC:
5933 ret = io_fsync(req, issue_flags);
5935 case IORING_OP_POLL_ADD:
5936 ret = io_poll_add(req, issue_flags);
5938 case IORING_OP_POLL_REMOVE:
5939 ret = io_poll_remove(req, issue_flags);
5941 case IORING_OP_SYNC_FILE_RANGE:
5942 ret = io_sync_file_range(req, issue_flags);
5944 case IORING_OP_SENDMSG:
5945 ret = io_sendmsg(req, issue_flags);
5947 case IORING_OP_SEND:
5948 ret = io_send(req, issue_flags);
5950 case IORING_OP_RECVMSG:
5951 ret = io_recvmsg(req, issue_flags);
5953 case IORING_OP_RECV:
5954 ret = io_recv(req, issue_flags);
5956 case IORING_OP_TIMEOUT:
5957 ret = io_timeout(req, issue_flags);
5959 case IORING_OP_TIMEOUT_REMOVE:
5960 ret = io_timeout_remove(req, issue_flags);
5962 case IORING_OP_ACCEPT:
5963 ret = io_accept(req, issue_flags);
5965 case IORING_OP_CONNECT:
5966 ret = io_connect(req, issue_flags);
5968 case IORING_OP_ASYNC_CANCEL:
5969 ret = io_async_cancel(req, issue_flags);
5971 case IORING_OP_FALLOCATE:
5972 ret = io_fallocate(req, issue_flags);
5974 case IORING_OP_OPENAT:
5975 ret = io_openat(req, issue_flags);
5977 case IORING_OP_CLOSE:
5978 ret = io_close(req, issue_flags);
5980 case IORING_OP_FILES_UPDATE:
5981 ret = io_files_update(req, issue_flags);
5983 case IORING_OP_STATX:
5984 ret = io_statx(req, issue_flags);
5986 case IORING_OP_FADVISE:
5987 ret = io_fadvise(req, issue_flags);
5989 case IORING_OP_MADVISE:
5990 ret = io_madvise(req, issue_flags);
5992 case IORING_OP_OPENAT2:
5993 ret = io_openat2(req, issue_flags);
5995 case IORING_OP_EPOLL_CTL:
5996 ret = io_epoll_ctl(req, issue_flags);
5998 case IORING_OP_SPLICE:
5999 ret = io_splice(req, issue_flags);
6001 case IORING_OP_PROVIDE_BUFFERS:
6002 ret = io_provide_buffers(req, issue_flags);
6004 case IORING_OP_REMOVE_BUFFERS:
6005 ret = io_remove_buffers(req, issue_flags);
6008 ret = io_tee(req, issue_flags);
6010 case IORING_OP_SHUTDOWN:
6011 ret = io_shutdown(req, issue_flags);
6013 case IORING_OP_RENAMEAT:
6014 ret = io_renameat(req, issue_flags);
6016 case IORING_OP_UNLINKAT:
6017 ret = io_unlinkat(req, issue_flags);
6025 revert_creds(creds);
6030 /* If the op doesn't have a file, we're not polling for it */
6031 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6032 const bool in_async = io_wq_current_is_worker();
6034 /* workqueue context doesn't hold uring_lock, grab it now */
6036 mutex_lock(&ctx->uring_lock);
6038 io_iopoll_req_issued(req, in_async);
6041 mutex_unlock(&ctx->uring_lock);
6047 static void io_wq_submit_work(struct io_wq_work *work)
6049 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6050 struct io_kiocb *timeout;
6053 timeout = io_prep_linked_timeout(req);
6055 io_queue_linked_timeout(timeout);
6057 if (work->flags & IO_WQ_WORK_CANCEL)
6062 ret = io_issue_sqe(req, 0);
6064 * We can get EAGAIN for polled IO even though we're
6065 * forcing a sync submission from here, since we can't
6066 * wait for request slots on the block side.
6074 /* avoid locking problems by failing it from a clean context */
6076 /* io-wq is going to take one down */
6077 refcount_inc(&req->refs);
6078 io_req_task_queue_fail(req, ret);
6082 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6085 struct fixed_rsrc_table *table;
6087 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6088 return table->files[index & IORING_FILE_TABLE_MASK];
6091 static struct file *io_file_get(struct io_submit_state *state,
6092 struct io_kiocb *req, int fd, bool fixed)
6094 struct io_ring_ctx *ctx = req->ctx;
6098 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6100 fd = array_index_nospec(fd, ctx->nr_user_files);
6101 file = io_file_from_index(ctx, fd);
6102 io_set_resource_node(req);
6104 trace_io_uring_file_get(ctx, fd);
6105 file = __io_file_get(state, fd);
6108 if (file && unlikely(file->f_op == &io_uring_fops))
6109 io_req_track_inflight(req);
6113 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6115 struct io_timeout_data *data = container_of(timer,
6116 struct io_timeout_data, timer);
6117 struct io_kiocb *prev, *req = data->req;
6118 struct io_ring_ctx *ctx = req->ctx;
6119 unsigned long flags;
6121 spin_lock_irqsave(&ctx->completion_lock, flags);
6122 prev = req->timeout.head;
6123 req->timeout.head = NULL;
6126 * We don't expect the list to be empty, that will only happen if we
6127 * race with the completion of the linked work.
6129 if (prev && refcount_inc_not_zero(&prev->refs))
6130 io_remove_next_linked(prev);
6133 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6136 req_set_fail_links(prev);
6137 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6138 io_put_req_deferred(prev, 1);
6140 io_req_complete_post(req, -ETIME, 0);
6141 io_put_req_deferred(req, 1);
6143 return HRTIMER_NORESTART;
6146 static void __io_queue_linked_timeout(struct io_kiocb *req)
6149 * If the back reference is NULL, then our linked request finished
6150 * before we got a chance to setup the timer
6152 if (req->timeout.head) {
6153 struct io_timeout_data *data = req->async_data;
6155 data->timer.function = io_link_timeout_fn;
6156 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6161 static void io_queue_linked_timeout(struct io_kiocb *req)
6163 struct io_ring_ctx *ctx = req->ctx;
6165 spin_lock_irq(&ctx->completion_lock);
6166 __io_queue_linked_timeout(req);
6167 spin_unlock_irq(&ctx->completion_lock);
6169 /* drop submission reference */
6173 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6175 struct io_kiocb *nxt = req->link;
6177 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6178 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6181 nxt->timeout.head = req;
6182 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6183 req->flags |= REQ_F_LINK_TIMEOUT;
6187 static void __io_queue_sqe(struct io_kiocb *req)
6189 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6192 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6195 * We async punt it if the file wasn't marked NOWAIT, or if the file
6196 * doesn't support non-blocking read/write attempts
6198 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6199 if (!io_arm_poll_handler(req)) {
6201 * Queued up for async execution, worker will release
6202 * submit reference when the iocb is actually submitted.
6204 io_queue_async_work(req);
6206 } else if (likely(!ret)) {
6207 /* drop submission reference */
6208 if (req->flags & REQ_F_COMPLETE_INLINE) {
6209 struct io_ring_ctx *ctx = req->ctx;
6210 struct io_comp_state *cs = &ctx->submit_state.comp;
6212 cs->reqs[cs->nr++] = req;
6213 if (cs->nr == ARRAY_SIZE(cs->reqs))
6214 io_submit_flush_completions(cs, ctx);
6219 req_set_fail_links(req);
6221 io_req_complete(req, ret);
6224 io_queue_linked_timeout(linked_timeout);
6227 static void io_queue_sqe(struct io_kiocb *req)
6231 ret = io_req_defer(req);
6233 if (ret != -EIOCBQUEUED) {
6235 req_set_fail_links(req);
6237 io_req_complete(req, ret);
6239 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6240 ret = io_req_defer_prep(req);
6243 io_queue_async_work(req);
6245 __io_queue_sqe(req);
6250 * Check SQE restrictions (opcode and flags).
6252 * Returns 'true' if SQE is allowed, 'false' otherwise.
6254 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6255 struct io_kiocb *req,
6256 unsigned int sqe_flags)
6258 if (!ctx->restricted)
6261 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6264 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6265 ctx->restrictions.sqe_flags_required)
6268 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6269 ctx->restrictions.sqe_flags_required))
6275 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6276 const struct io_uring_sqe *sqe)
6278 struct io_submit_state *state;
6279 unsigned int sqe_flags;
6282 req->opcode = READ_ONCE(sqe->opcode);
6283 /* same numerical values with corresponding REQ_F_*, safe to copy */
6284 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6285 req->user_data = READ_ONCE(sqe->user_data);
6286 req->async_data = NULL;
6290 req->fixed_rsrc_refs = NULL;
6291 /* one is dropped after submission, the other at completion */
6292 refcount_set(&req->refs, 2);
6293 req->task = current;
6296 /* enforce forwards compatibility on users */
6297 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6302 if (unlikely(req->opcode >= IORING_OP_LAST))
6305 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6308 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6309 !io_op_defs[req->opcode].buffer_select)
6312 req->work.list.next = NULL;
6313 req->work.flags = 0;
6314 req->work.personality = READ_ONCE(sqe->personality);
6315 state = &ctx->submit_state;
6318 * Plug now if we have more than 1 IO left after this, and the target
6319 * is potentially a read/write to block based storage.
6321 if (!state->plug_started && state->ios_left > 1 &&
6322 io_op_defs[req->opcode].plug) {
6323 blk_start_plug(&state->plug);
6324 state->plug_started = true;
6327 if (io_op_defs[req->opcode].needs_file) {
6328 bool fixed = req->flags & REQ_F_FIXED_FILE;
6330 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6331 if (unlikely(!req->file))
6339 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6340 const struct io_uring_sqe *sqe)
6342 struct io_submit_link *link = &ctx->submit_state.link;
6345 ret = io_init_req(ctx, req, sqe);
6346 if (unlikely(ret)) {
6349 io_req_complete(req, ret);
6351 /* fail even hard links since we don't submit */
6352 link->head->flags |= REQ_F_FAIL_LINK;
6353 io_put_req(link->head);
6354 io_req_complete(link->head, -ECANCELED);
6359 ret = io_req_prep(req, sqe);
6363 /* don't need @sqe from now on */
6364 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6365 true, ctx->flags & IORING_SETUP_SQPOLL);
6368 * If we already have a head request, queue this one for async
6369 * submittal once the head completes. If we don't have a head but
6370 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6371 * submitted sync once the chain is complete. If none of those
6372 * conditions are true (normal request), then just queue it.
6375 struct io_kiocb *head = link->head;
6378 * Taking sequential execution of a link, draining both sides
6379 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6380 * requests in the link. So, it drains the head and the
6381 * next after the link request. The last one is done via
6382 * drain_next flag to persist the effect across calls.
6384 if (req->flags & REQ_F_IO_DRAIN) {
6385 head->flags |= REQ_F_IO_DRAIN;
6386 ctx->drain_next = 1;
6388 ret = io_req_defer_prep(req);
6391 trace_io_uring_link(ctx, req, head);
6392 link->last->link = req;
6395 /* last request of a link, enqueue the link */
6396 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6401 if (unlikely(ctx->drain_next)) {
6402 req->flags |= REQ_F_IO_DRAIN;
6403 ctx->drain_next = 0;
6405 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6417 * Batched submission is done, ensure local IO is flushed out.
6419 static void io_submit_state_end(struct io_submit_state *state,
6420 struct io_ring_ctx *ctx)
6422 if (state->link.head)
6423 io_queue_sqe(state->link.head);
6425 io_submit_flush_completions(&state->comp, ctx);
6426 if (state->plug_started)
6427 blk_finish_plug(&state->plug);
6428 io_state_file_put(state);
6432 * Start submission side cache.
6434 static void io_submit_state_start(struct io_submit_state *state,
6435 unsigned int max_ios)
6437 state->plug_started = false;
6438 state->ios_left = max_ios;
6439 /* set only head, no need to init link_last in advance */
6440 state->link.head = NULL;
6443 static void io_commit_sqring(struct io_ring_ctx *ctx)
6445 struct io_rings *rings = ctx->rings;
6448 * Ensure any loads from the SQEs are done at this point,
6449 * since once we write the new head, the application could
6450 * write new data to them.
6452 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6456 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6457 * that is mapped by userspace. This means that care needs to be taken to
6458 * ensure that reads are stable, as we cannot rely on userspace always
6459 * being a good citizen. If members of the sqe are validated and then later
6460 * used, it's important that those reads are done through READ_ONCE() to
6461 * prevent a re-load down the line.
6463 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6465 u32 *sq_array = ctx->sq_array;
6469 * The cached sq head (or cq tail) serves two purposes:
6471 * 1) allows us to batch the cost of updating the user visible
6473 * 2) allows the kernel side to track the head on its own, even
6474 * though the application is the one updating it.
6476 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6477 if (likely(head < ctx->sq_entries))
6478 return &ctx->sq_sqes[head];
6480 /* drop invalid entries */
6481 ctx->cached_sq_dropped++;
6482 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6486 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6490 /* if we have a backlog and couldn't flush it all, return BUSY */
6491 if (test_bit(0, &ctx->sq_check_overflow)) {
6492 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6496 /* make sure SQ entry isn't read before tail */
6497 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6499 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6502 percpu_counter_add(¤t->io_uring->inflight, nr);
6503 refcount_add(nr, ¤t->usage);
6504 io_submit_state_start(&ctx->submit_state, nr);
6506 while (submitted < nr) {
6507 const struct io_uring_sqe *sqe;
6508 struct io_kiocb *req;
6510 req = io_alloc_req(ctx);
6511 if (unlikely(!req)) {
6513 submitted = -EAGAIN;
6516 sqe = io_get_sqe(ctx);
6517 if (unlikely(!sqe)) {
6518 kmem_cache_free(req_cachep, req);
6521 /* will complete beyond this point, count as submitted */
6523 if (io_submit_sqe(ctx, req, sqe))
6527 if (unlikely(submitted != nr)) {
6528 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6529 struct io_uring_task *tctx = current->io_uring;
6530 int unused = nr - ref_used;
6532 percpu_ref_put_many(&ctx->refs, unused);
6533 percpu_counter_sub(&tctx->inflight, unused);
6534 put_task_struct_many(current, unused);
6537 io_submit_state_end(&ctx->submit_state, ctx);
6538 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6539 io_commit_sqring(ctx);
6544 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6546 /* Tell userspace we may need a wakeup call */
6547 spin_lock_irq(&ctx->completion_lock);
6548 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6549 spin_unlock_irq(&ctx->completion_lock);
6552 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6554 spin_lock_irq(&ctx->completion_lock);
6555 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6556 spin_unlock_irq(&ctx->completion_lock);
6559 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6561 unsigned int to_submit;
6564 to_submit = io_sqring_entries(ctx);
6565 /* if we're handling multiple rings, cap submit size for fairness */
6566 if (cap_entries && to_submit > 8)
6569 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6570 unsigned nr_events = 0;
6572 mutex_lock(&ctx->uring_lock);
6573 if (!list_empty(&ctx->iopoll_list))
6574 io_do_iopoll(ctx, &nr_events, 0);
6576 if (to_submit && !ctx->sqo_dead &&
6577 likely(!percpu_ref_is_dying(&ctx->refs)))
6578 ret = io_submit_sqes(ctx, to_submit);
6579 mutex_unlock(&ctx->uring_lock);
6582 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6583 wake_up(&ctx->sqo_sq_wait);
6588 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6590 struct io_ring_ctx *ctx;
6591 unsigned sq_thread_idle = 0;
6593 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6594 if (sq_thread_idle < ctx->sq_thread_idle)
6595 sq_thread_idle = ctx->sq_thread_idle;
6598 sqd->sq_thread_idle = sq_thread_idle;
6601 static void io_sqd_init_new(struct io_sq_data *sqd)
6603 struct io_ring_ctx *ctx;
6605 while (!list_empty(&sqd->ctx_new_list)) {
6606 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6607 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6608 complete(&ctx->sq_thread_comp);
6611 io_sqd_update_thread_idle(sqd);
6614 static bool io_sq_thread_should_stop(struct io_sq_data *sqd)
6616 return test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6619 static bool io_sq_thread_should_park(struct io_sq_data *sqd)
6621 return test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
6624 static void io_sq_thread_parkme(struct io_sq_data *sqd)
6628 * TASK_PARKED is a special state; we must serialize against
6629 * possible pending wakeups to avoid store-store collisions on
6632 * Such a collision might possibly result in the task state
6633 * changin from TASK_PARKED and us failing the
6634 * wait_task_inactive() in kthread_park().
6636 set_special_state(TASK_PARKED);
6637 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state))
6641 * Thread is going to call schedule(), do not preempt it,
6642 * or the caller of kthread_park() may spend more time in
6643 * wait_task_inactive().
6646 complete(&sqd->completion);
6647 schedule_preempt_disabled();
6650 __set_current_state(TASK_RUNNING);
6653 static int io_sq_thread(void *data)
6655 struct io_sq_data *sqd = data;
6656 struct io_ring_ctx *ctx;
6657 unsigned long timeout = 0;
6658 char buf[TASK_COMM_LEN];
6661 sprintf(buf, "iou-sqp-%d", sqd->task_pid);
6662 set_task_comm(current, buf);
6663 sqd->thread = current;
6664 current->pf_io_worker = NULL;
6666 if (sqd->sq_cpu != -1)
6667 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6669 set_cpus_allowed_ptr(current, cpu_online_mask);
6670 current->flags |= PF_NO_SETAFFINITY;
6672 complete(&sqd->completion);
6674 wait_for_completion(&sqd->startup);
6676 while (!io_sq_thread_should_stop(sqd)) {
6678 bool cap_entries, sqt_spin, needs_sched;
6681 * Any changes to the sqd lists are synchronized through the
6682 * thread parking. This synchronizes the thread vs users,
6683 * the users are synchronized on the sqd->ctx_lock.
6685 if (io_sq_thread_should_park(sqd)) {
6686 io_sq_thread_parkme(sqd);
6689 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
6690 io_sqd_init_new(sqd);
6691 timeout = jiffies + sqd->sq_thread_idle;
6693 if (fatal_signal_pending(current))
6696 cap_entries = !list_is_singular(&sqd->ctx_list);
6697 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6698 ret = __io_sq_thread(ctx, cap_entries);
6699 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6703 if (sqt_spin || !time_after(jiffies, timeout)) {
6707 timeout = jiffies + sqd->sq_thread_idle;
6712 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6713 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6714 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6715 !list_empty_careful(&ctx->iopoll_list)) {
6716 needs_sched = false;
6719 if (io_sqring_entries(ctx)) {
6720 needs_sched = false;
6725 if (needs_sched && !io_sq_thread_should_park(sqd)) {
6726 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6727 io_ring_set_wakeup_flag(ctx);
6730 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6731 io_ring_clear_wakeup_flag(ctx);
6734 finish_wait(&sqd->wait, &wait);
6735 timeout = jiffies + sqd->sq_thread_idle;
6738 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6739 io_uring_cancel_sqpoll(ctx);
6743 if (io_sq_thread_should_park(sqd))
6744 io_sq_thread_parkme(sqd);
6747 * Clear thread under lock so that concurrent parks work correctly
6749 complete(&sqd->completion);
6750 mutex_lock(&sqd->lock);
6752 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6754 io_ring_set_wakeup_flag(ctx);
6757 complete(&sqd->exited);
6758 mutex_unlock(&sqd->lock);
6762 struct io_wait_queue {
6763 struct wait_queue_entry wq;
6764 struct io_ring_ctx *ctx;
6766 unsigned nr_timeouts;
6769 static inline bool io_should_wake(struct io_wait_queue *iowq)
6771 struct io_ring_ctx *ctx = iowq->ctx;
6774 * Wake up if we have enough events, or if a timeout occurred since we
6775 * started waiting. For timeouts, we always want to return to userspace,
6776 * regardless of event count.
6778 return io_cqring_events(ctx) >= iowq->to_wait ||
6779 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6782 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6783 int wake_flags, void *key)
6785 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6789 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6790 * the task, and the next invocation will do it.
6792 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6793 return autoremove_wake_function(curr, mode, wake_flags, key);
6797 static int io_run_task_work_sig(void)
6799 if (io_run_task_work())
6801 if (!signal_pending(current))
6803 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
6804 return -ERESTARTSYS;
6808 /* when returns >0, the caller should retry */
6809 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6810 struct io_wait_queue *iowq,
6811 signed long *timeout)
6815 /* make sure we run task_work before checking for signals */
6816 ret = io_run_task_work_sig();
6817 if (ret || io_should_wake(iowq))
6819 /* let the caller flush overflows, retry */
6820 if (test_bit(0, &ctx->cq_check_overflow))
6823 *timeout = schedule_timeout(*timeout);
6824 return !*timeout ? -ETIME : 1;
6828 * Wait until events become available, if we don't already have some. The
6829 * application must reap them itself, as they reside on the shared cq ring.
6831 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6832 const sigset_t __user *sig, size_t sigsz,
6833 struct __kernel_timespec __user *uts)
6835 struct io_wait_queue iowq = {
6838 .func = io_wake_function,
6839 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6842 .to_wait = min_events,
6844 struct io_rings *rings = ctx->rings;
6845 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6849 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6850 if (io_cqring_events(ctx) >= min_events)
6852 if (!io_run_task_work())
6857 #ifdef CONFIG_COMPAT
6858 if (in_compat_syscall())
6859 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6863 ret = set_user_sigmask(sig, sigsz);
6870 struct timespec64 ts;
6872 if (get_timespec64(&ts, uts))
6874 timeout = timespec64_to_jiffies(&ts);
6877 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6878 trace_io_uring_cqring_wait(ctx, min_events);
6880 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6881 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6882 TASK_INTERRUPTIBLE);
6883 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
6884 finish_wait(&ctx->wait, &iowq.wq);
6887 restore_saved_sigmask_unless(ret == -EINTR);
6889 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6892 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6894 #if defined(CONFIG_UNIX)
6895 if (ctx->ring_sock) {
6896 struct sock *sock = ctx->ring_sock->sk;
6897 struct sk_buff *skb;
6899 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6905 for (i = 0; i < ctx->nr_user_files; i++) {
6908 file = io_file_from_index(ctx, i);
6915 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
6917 struct fixed_rsrc_data *data;
6919 data = container_of(ref, struct fixed_rsrc_data, refs);
6920 complete(&data->done);
6923 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
6925 spin_lock_bh(&ctx->rsrc_ref_lock);
6928 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
6930 spin_unlock_bh(&ctx->rsrc_ref_lock);
6933 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
6934 struct fixed_rsrc_data *rsrc_data,
6935 struct fixed_rsrc_ref_node *ref_node)
6937 io_rsrc_ref_lock(ctx);
6938 rsrc_data->node = ref_node;
6939 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
6940 io_rsrc_ref_unlock(ctx);
6941 percpu_ref_get(&rsrc_data->refs);
6944 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
6946 struct fixed_rsrc_ref_node *ref_node = NULL;
6948 io_rsrc_ref_lock(ctx);
6949 ref_node = data->node;
6951 io_rsrc_ref_unlock(ctx);
6953 percpu_ref_kill(&ref_node->refs);
6956 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
6957 struct io_ring_ctx *ctx,
6958 void (*rsrc_put)(struct io_ring_ctx *ctx,
6959 struct io_rsrc_put *prsrc))
6961 struct fixed_rsrc_ref_node *backup_node;
6967 data->quiesce = true;
6970 backup_node = alloc_fixed_rsrc_ref_node(ctx);
6973 backup_node->rsrc_data = data;
6974 backup_node->rsrc_put = rsrc_put;
6976 io_sqe_rsrc_kill_node(ctx, data);
6977 percpu_ref_kill(&data->refs);
6978 flush_delayed_work(&ctx->rsrc_put_work);
6980 ret = wait_for_completion_interruptible(&data->done);
6984 percpu_ref_resurrect(&data->refs);
6985 io_sqe_rsrc_set_node(ctx, data, backup_node);
6987 reinit_completion(&data->done);
6988 mutex_unlock(&ctx->uring_lock);
6989 ret = io_run_task_work_sig();
6990 mutex_lock(&ctx->uring_lock);
6992 data->quiesce = false;
6995 destroy_fixed_rsrc_ref_node(backup_node);
6999 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7001 struct fixed_rsrc_data *data;
7003 data = kzalloc(sizeof(*data), GFP_KERNEL);
7007 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7008 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7013 init_completion(&data->done);
7017 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7019 percpu_ref_exit(&data->refs);
7024 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7026 struct fixed_rsrc_data *data = ctx->file_data;
7027 unsigned nr_tables, i;
7031 * percpu_ref_is_dying() is to stop parallel files unregister
7032 * Since we possibly drop uring lock later in this function to
7035 if (!data || percpu_ref_is_dying(&data->refs))
7037 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7041 __io_sqe_files_unregister(ctx);
7042 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7043 for (i = 0; i < nr_tables; i++)
7044 kfree(data->table[i].files);
7045 free_fixed_rsrc_data(data);
7046 ctx->file_data = NULL;
7047 ctx->nr_user_files = 0;
7051 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7052 __releases(&sqd->lock)
7056 if (sqd->thread == current)
7058 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7059 wake_up_state(sqd->thread, TASK_PARKED);
7060 mutex_unlock(&sqd->lock);
7063 static bool io_sq_thread_park(struct io_sq_data *sqd)
7064 __acquires(&sqd->lock)
7066 if (sqd->thread == current)
7068 mutex_lock(&sqd->lock);
7070 mutex_unlock(&sqd->lock);
7073 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7074 wake_up_process(sqd->thread);
7075 wait_for_completion(&sqd->completion);
7079 static void io_sq_thread_stop(struct io_sq_data *sqd)
7081 if (test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state))
7083 mutex_lock(&sqd->lock);
7085 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7086 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state));
7087 wake_up_process(sqd->thread);
7088 mutex_unlock(&sqd->lock);
7089 wait_for_completion(&sqd->exited);
7090 WARN_ON_ONCE(sqd->thread);
7092 mutex_unlock(&sqd->lock);
7096 static void io_put_sq_data(struct io_sq_data *sqd)
7098 if (refcount_dec_and_test(&sqd->refs)) {
7099 io_sq_thread_stop(sqd);
7104 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7106 struct io_sq_data *sqd = ctx->sq_data;
7109 complete(&sqd->startup);
7111 wait_for_completion(&ctx->sq_thread_comp);
7112 io_sq_thread_park(sqd);
7115 mutex_lock(&sqd->ctx_lock);
7116 list_del(&ctx->sqd_list);
7117 io_sqd_update_thread_idle(sqd);
7118 mutex_unlock(&sqd->ctx_lock);
7121 io_sq_thread_unpark(sqd);
7123 io_put_sq_data(sqd);
7124 ctx->sq_data = NULL;
7128 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7130 struct io_ring_ctx *ctx_attach;
7131 struct io_sq_data *sqd;
7134 f = fdget(p->wq_fd);
7136 return ERR_PTR(-ENXIO);
7137 if (f.file->f_op != &io_uring_fops) {
7139 return ERR_PTR(-EINVAL);
7142 ctx_attach = f.file->private_data;
7143 sqd = ctx_attach->sq_data;
7146 return ERR_PTR(-EINVAL);
7149 refcount_inc(&sqd->refs);
7154 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7156 struct io_sq_data *sqd;
7158 if (p->flags & IORING_SETUP_ATTACH_WQ)
7159 return io_attach_sq_data(p);
7161 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7163 return ERR_PTR(-ENOMEM);
7165 refcount_set(&sqd->refs, 1);
7166 INIT_LIST_HEAD(&sqd->ctx_list);
7167 INIT_LIST_HEAD(&sqd->ctx_new_list);
7168 mutex_init(&sqd->ctx_lock);
7169 mutex_init(&sqd->lock);
7170 init_waitqueue_head(&sqd->wait);
7171 init_completion(&sqd->startup);
7172 init_completion(&sqd->completion);
7173 init_completion(&sqd->exited);
7177 #if defined(CONFIG_UNIX)
7179 * Ensure the UNIX gc is aware of our file set, so we are certain that
7180 * the io_uring can be safely unregistered on process exit, even if we have
7181 * loops in the file referencing.
7183 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7185 struct sock *sk = ctx->ring_sock->sk;
7186 struct scm_fp_list *fpl;
7187 struct sk_buff *skb;
7190 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7194 skb = alloc_skb(0, GFP_KERNEL);
7203 fpl->user = get_uid(current_user());
7204 for (i = 0; i < nr; i++) {
7205 struct file *file = io_file_from_index(ctx, i + offset);
7209 fpl->fp[nr_files] = get_file(file);
7210 unix_inflight(fpl->user, fpl->fp[nr_files]);
7215 fpl->max = SCM_MAX_FD;
7216 fpl->count = nr_files;
7217 UNIXCB(skb).fp = fpl;
7218 skb->destructor = unix_destruct_scm;
7219 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7220 skb_queue_head(&sk->sk_receive_queue, skb);
7222 for (i = 0; i < nr_files; i++)
7233 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7234 * causes regular reference counting to break down. We rely on the UNIX
7235 * garbage collection to take care of this problem for us.
7237 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7239 unsigned left, total;
7243 left = ctx->nr_user_files;
7245 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7247 ret = __io_sqe_files_scm(ctx, this_files, total);
7251 total += this_files;
7257 while (total < ctx->nr_user_files) {
7258 struct file *file = io_file_from_index(ctx, total);
7268 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7274 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7275 unsigned nr_tables, unsigned nr_files)
7279 for (i = 0; i < nr_tables; i++) {
7280 struct fixed_rsrc_table *table = &file_data->table[i];
7281 unsigned this_files;
7283 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7284 table->files = kcalloc(this_files, sizeof(struct file *),
7288 nr_files -= this_files;
7294 for (i = 0; i < nr_tables; i++) {
7295 struct fixed_rsrc_table *table = &file_data->table[i];
7296 kfree(table->files);
7301 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7303 struct file *file = prsrc->file;
7304 #if defined(CONFIG_UNIX)
7305 struct sock *sock = ctx->ring_sock->sk;
7306 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7307 struct sk_buff *skb;
7310 __skb_queue_head_init(&list);
7313 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7314 * remove this entry and rearrange the file array.
7316 skb = skb_dequeue(head);
7318 struct scm_fp_list *fp;
7320 fp = UNIXCB(skb).fp;
7321 for (i = 0; i < fp->count; i++) {
7324 if (fp->fp[i] != file)
7327 unix_notinflight(fp->user, fp->fp[i]);
7328 left = fp->count - 1 - i;
7330 memmove(&fp->fp[i], &fp->fp[i + 1],
7331 left * sizeof(struct file *));
7338 __skb_queue_tail(&list, skb);
7348 __skb_queue_tail(&list, skb);
7350 skb = skb_dequeue(head);
7353 if (skb_peek(&list)) {
7354 spin_lock_irq(&head->lock);
7355 while ((skb = __skb_dequeue(&list)) != NULL)
7356 __skb_queue_tail(head, skb);
7357 spin_unlock_irq(&head->lock);
7364 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7366 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7367 struct io_ring_ctx *ctx = rsrc_data->ctx;
7368 struct io_rsrc_put *prsrc, *tmp;
7370 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7371 list_del(&prsrc->list);
7372 ref_node->rsrc_put(ctx, prsrc);
7376 percpu_ref_exit(&ref_node->refs);
7378 percpu_ref_put(&rsrc_data->refs);
7381 static void io_rsrc_put_work(struct work_struct *work)
7383 struct io_ring_ctx *ctx;
7384 struct llist_node *node;
7386 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7387 node = llist_del_all(&ctx->rsrc_put_llist);
7390 struct fixed_rsrc_ref_node *ref_node;
7391 struct llist_node *next = node->next;
7393 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7394 __io_rsrc_put_work(ref_node);
7399 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7402 struct fixed_rsrc_table *table;
7404 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7405 return &table->files[i & IORING_FILE_TABLE_MASK];
7408 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7410 struct fixed_rsrc_ref_node *ref_node;
7411 struct fixed_rsrc_data *data;
7412 struct io_ring_ctx *ctx;
7413 bool first_add = false;
7416 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7417 data = ref_node->rsrc_data;
7420 io_rsrc_ref_lock(ctx);
7421 ref_node->done = true;
7423 while (!list_empty(&ctx->rsrc_ref_list)) {
7424 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7425 struct fixed_rsrc_ref_node, node);
7426 /* recycle ref nodes in order */
7427 if (!ref_node->done)
7429 list_del(&ref_node->node);
7430 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7432 io_rsrc_ref_unlock(ctx);
7434 if (percpu_ref_is_dying(&data->refs))
7438 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7440 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7443 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7444 struct io_ring_ctx *ctx)
7446 struct fixed_rsrc_ref_node *ref_node;
7448 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7452 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7457 INIT_LIST_HEAD(&ref_node->node);
7458 INIT_LIST_HEAD(&ref_node->rsrc_list);
7459 ref_node->done = false;
7463 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7464 struct fixed_rsrc_ref_node *ref_node)
7466 ref_node->rsrc_data = ctx->file_data;
7467 ref_node->rsrc_put = io_ring_file_put;
7470 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7472 percpu_ref_exit(&ref_node->refs);
7477 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7480 __s32 __user *fds = (__s32 __user *) arg;
7481 unsigned nr_tables, i;
7483 int fd, ret = -ENOMEM;
7484 struct fixed_rsrc_ref_node *ref_node;
7485 struct fixed_rsrc_data *file_data;
7491 if (nr_args > IORING_MAX_FIXED_FILES)
7494 file_data = alloc_fixed_rsrc_data(ctx);
7497 ctx->file_data = file_data;
7499 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7500 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7502 if (!file_data->table)
7505 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7508 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7509 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7513 /* allow sparse sets */
7523 * Don't allow io_uring instances to be registered. If UNIX
7524 * isn't enabled, then this causes a reference cycle and this
7525 * instance can never get freed. If UNIX is enabled we'll
7526 * handle it just fine, but there's still no point in allowing
7527 * a ring fd as it doesn't support regular read/write anyway.
7529 if (file->f_op == &io_uring_fops) {
7533 *io_fixed_file_slot(file_data, i) = file;
7536 ret = io_sqe_files_scm(ctx);
7538 io_sqe_files_unregister(ctx);
7542 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7544 io_sqe_files_unregister(ctx);
7547 init_fixed_file_ref_node(ctx, ref_node);
7549 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7552 for (i = 0; i < ctx->nr_user_files; i++) {
7553 file = io_file_from_index(ctx, i);
7557 for (i = 0; i < nr_tables; i++)
7558 kfree(file_data->table[i].files);
7559 ctx->nr_user_files = 0;
7561 free_fixed_rsrc_data(ctx->file_data);
7562 ctx->file_data = NULL;
7566 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7569 #if defined(CONFIG_UNIX)
7570 struct sock *sock = ctx->ring_sock->sk;
7571 struct sk_buff_head *head = &sock->sk_receive_queue;
7572 struct sk_buff *skb;
7575 * See if we can merge this file into an existing skb SCM_RIGHTS
7576 * file set. If there's no room, fall back to allocating a new skb
7577 * and filling it in.
7579 spin_lock_irq(&head->lock);
7580 skb = skb_peek(head);
7582 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7584 if (fpl->count < SCM_MAX_FD) {
7585 __skb_unlink(skb, head);
7586 spin_unlock_irq(&head->lock);
7587 fpl->fp[fpl->count] = get_file(file);
7588 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7590 spin_lock_irq(&head->lock);
7591 __skb_queue_head(head, skb);
7596 spin_unlock_irq(&head->lock);
7603 return __io_sqe_files_scm(ctx, 1, index);
7609 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7611 struct io_rsrc_put *prsrc;
7612 struct fixed_rsrc_ref_node *ref_node = data->node;
7614 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7619 list_add(&prsrc->list, &ref_node->rsrc_list);
7624 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7627 return io_queue_rsrc_removal(data, (void *)file);
7630 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7631 struct io_uring_rsrc_update *up,
7634 struct fixed_rsrc_data *data = ctx->file_data;
7635 struct fixed_rsrc_ref_node *ref_node;
7636 struct file *file, **file_slot;
7640 bool needs_switch = false;
7642 if (check_add_overflow(up->offset, nr_args, &done))
7644 if (done > ctx->nr_user_files)
7647 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7650 init_fixed_file_ref_node(ctx, ref_node);
7652 fds = u64_to_user_ptr(up->data);
7653 for (done = 0; done < nr_args; done++) {
7655 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7659 if (fd == IORING_REGISTER_FILES_SKIP)
7662 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7663 file_slot = io_fixed_file_slot(ctx->file_data, i);
7666 err = io_queue_file_removal(data, *file_slot);
7670 needs_switch = true;
7679 * Don't allow io_uring instances to be registered. If
7680 * UNIX isn't enabled, then this causes a reference
7681 * cycle and this instance can never get freed. If UNIX
7682 * is enabled we'll handle it just fine, but there's
7683 * still no point in allowing a ring fd as it doesn't
7684 * support regular read/write anyway.
7686 if (file->f_op == &io_uring_fops) {
7692 err = io_sqe_file_register(ctx, file, i);
7702 percpu_ref_kill(&data->node->refs);
7703 io_sqe_rsrc_set_node(ctx, data, ref_node);
7705 destroy_fixed_rsrc_ref_node(ref_node);
7707 return done ? done : err;
7710 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7713 struct io_uring_rsrc_update up;
7715 if (!ctx->file_data)
7719 if (copy_from_user(&up, arg, sizeof(up)))
7724 return __io_sqe_files_update(ctx, &up, nr_args);
7727 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7729 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7731 req = io_put_req_find_next(req);
7732 return req ? &req->work : NULL;
7735 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7737 struct io_wq_hash *hash;
7738 struct io_wq_data data;
7739 unsigned int concurrency;
7741 hash = ctx->hash_map;
7743 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7745 return ERR_PTR(-ENOMEM);
7746 refcount_set(&hash->refs, 1);
7747 init_waitqueue_head(&hash->wait);
7748 ctx->hash_map = hash;
7752 data.free_work = io_free_work;
7753 data.do_work = io_wq_submit_work;
7755 /* Do QD, or 4 * CPUS, whatever is smallest */
7756 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7758 return io_wq_create(concurrency, &data);
7761 static int io_uring_alloc_task_context(struct task_struct *task,
7762 struct io_ring_ctx *ctx)
7764 struct io_uring_task *tctx;
7767 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7768 if (unlikely(!tctx))
7771 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7772 if (unlikely(ret)) {
7777 tctx->io_wq = io_init_wq_offload(ctx);
7778 if (IS_ERR(tctx->io_wq)) {
7779 ret = PTR_ERR(tctx->io_wq);
7780 percpu_counter_destroy(&tctx->inflight);
7786 init_waitqueue_head(&tctx->wait);
7788 atomic_set(&tctx->in_idle, 0);
7789 tctx->sqpoll = false;
7790 task->io_uring = tctx;
7791 spin_lock_init(&tctx->task_lock);
7792 INIT_WQ_LIST(&tctx->task_list);
7793 tctx->task_state = 0;
7794 init_task_work(&tctx->task_work, tctx_task_work);
7798 void __io_uring_free(struct task_struct *tsk)
7800 struct io_uring_task *tctx = tsk->io_uring;
7802 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7803 WARN_ON_ONCE(tctx->io_wq);
7805 percpu_counter_destroy(&tctx->inflight);
7807 tsk->io_uring = NULL;
7810 static int io_sq_thread_fork(struct io_sq_data *sqd, struct io_ring_ctx *ctx)
7814 clear_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7815 reinit_completion(&sqd->completion);
7816 ctx->sqo_dead = ctx->sqo_exec = 0;
7817 sqd->task_pid = current->pid;
7818 current->flags |= PF_IO_WORKER;
7819 ret = io_wq_fork_thread(io_sq_thread, sqd);
7820 current->flags &= ~PF_IO_WORKER;
7825 wait_for_completion(&sqd->completion);
7826 return io_uring_alloc_task_context(sqd->thread, ctx);
7829 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7830 struct io_uring_params *p)
7834 /* Retain compatibility with failing for an invalid attach attempt */
7835 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7836 IORING_SETUP_ATTACH_WQ) {
7839 f = fdget(p->wq_fd);
7842 if (f.file->f_op != &io_uring_fops) {
7848 if (ctx->flags & IORING_SETUP_SQPOLL) {
7849 struct io_sq_data *sqd;
7852 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7855 sqd = io_get_sq_data(p);
7862 io_sq_thread_park(sqd);
7863 mutex_lock(&sqd->ctx_lock);
7864 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7865 mutex_unlock(&sqd->ctx_lock);
7866 io_sq_thread_unpark(sqd);
7868 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7869 if (!ctx->sq_thread_idle)
7870 ctx->sq_thread_idle = HZ;
7875 if (p->flags & IORING_SETUP_SQ_AFF) {
7876 int cpu = p->sq_thread_cpu;
7879 if (cpu >= nr_cpu_ids)
7881 if (!cpu_online(cpu))
7889 sqd->task_pid = current->pid;
7890 current->flags |= PF_IO_WORKER;
7891 ret = io_wq_fork_thread(io_sq_thread, sqd);
7892 current->flags &= ~PF_IO_WORKER;
7897 wait_for_completion(&sqd->completion);
7898 ret = io_uring_alloc_task_context(sqd->thread, ctx);
7901 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7902 /* Can't have SQ_AFF without SQPOLL */
7909 io_sq_thread_finish(ctx);
7913 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7915 struct io_sq_data *sqd = ctx->sq_data;
7917 if (ctx->flags & IORING_SETUP_SQPOLL)
7918 complete(&sqd->startup);
7921 static inline void __io_unaccount_mem(struct user_struct *user,
7922 unsigned long nr_pages)
7924 atomic_long_sub(nr_pages, &user->locked_vm);
7927 static inline int __io_account_mem(struct user_struct *user,
7928 unsigned long nr_pages)
7930 unsigned long page_limit, cur_pages, new_pages;
7932 /* Don't allow more pages than we can safely lock */
7933 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7936 cur_pages = atomic_long_read(&user->locked_vm);
7937 new_pages = cur_pages + nr_pages;
7938 if (new_pages > page_limit)
7940 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7941 new_pages) != cur_pages);
7946 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7949 __io_unaccount_mem(ctx->user, nr_pages);
7951 if (ctx->mm_account)
7952 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7955 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7960 ret = __io_account_mem(ctx->user, nr_pages);
7965 if (ctx->mm_account)
7966 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
7971 static void io_mem_free(void *ptr)
7978 page = virt_to_head_page(ptr);
7979 if (put_page_testzero(page))
7980 free_compound_page(page);
7983 static void *io_mem_alloc(size_t size)
7985 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7986 __GFP_NORETRY | __GFP_ACCOUNT;
7988 return (void *) __get_free_pages(gfp_flags, get_order(size));
7991 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7994 struct io_rings *rings;
7995 size_t off, sq_array_size;
7997 off = struct_size(rings, cqes, cq_entries);
7998 if (off == SIZE_MAX)
8002 off = ALIGN(off, SMP_CACHE_BYTES);
8010 sq_array_size = array_size(sizeof(u32), sq_entries);
8011 if (sq_array_size == SIZE_MAX)
8014 if (check_add_overflow(off, sq_array_size, &off))
8020 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8024 if (!ctx->user_bufs)
8027 for (i = 0; i < ctx->nr_user_bufs; i++) {
8028 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8030 for (j = 0; j < imu->nr_bvecs; j++)
8031 unpin_user_page(imu->bvec[j].bv_page);
8033 if (imu->acct_pages)
8034 io_unaccount_mem(ctx, imu->acct_pages);
8039 kfree(ctx->user_bufs);
8040 ctx->user_bufs = NULL;
8041 ctx->nr_user_bufs = 0;
8045 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8046 void __user *arg, unsigned index)
8048 struct iovec __user *src;
8050 #ifdef CONFIG_COMPAT
8052 struct compat_iovec __user *ciovs;
8053 struct compat_iovec ciov;
8055 ciovs = (struct compat_iovec __user *) arg;
8056 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8059 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8060 dst->iov_len = ciov.iov_len;
8064 src = (struct iovec __user *) arg;
8065 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8071 * Not super efficient, but this is just a registration time. And we do cache
8072 * the last compound head, so generally we'll only do a full search if we don't
8075 * We check if the given compound head page has already been accounted, to
8076 * avoid double accounting it. This allows us to account the full size of the
8077 * page, not just the constituent pages of a huge page.
8079 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8080 int nr_pages, struct page *hpage)
8084 /* check current page array */
8085 for (i = 0; i < nr_pages; i++) {
8086 if (!PageCompound(pages[i]))
8088 if (compound_head(pages[i]) == hpage)
8092 /* check previously registered pages */
8093 for (i = 0; i < ctx->nr_user_bufs; i++) {
8094 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8096 for (j = 0; j < imu->nr_bvecs; j++) {
8097 if (!PageCompound(imu->bvec[j].bv_page))
8099 if (compound_head(imu->bvec[j].bv_page) == hpage)
8107 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8108 int nr_pages, struct io_mapped_ubuf *imu,
8109 struct page **last_hpage)
8113 for (i = 0; i < nr_pages; i++) {
8114 if (!PageCompound(pages[i])) {
8119 hpage = compound_head(pages[i]);
8120 if (hpage == *last_hpage)
8122 *last_hpage = hpage;
8123 if (headpage_already_acct(ctx, pages, i, hpage))
8125 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8129 if (!imu->acct_pages)
8132 ret = io_account_mem(ctx, imu->acct_pages);
8134 imu->acct_pages = 0;
8138 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8139 struct io_mapped_ubuf *imu,
8140 struct page **last_hpage)
8142 struct vm_area_struct **vmas = NULL;
8143 struct page **pages = NULL;
8144 unsigned long off, start, end, ubuf;
8146 int ret, pret, nr_pages, i;
8148 ubuf = (unsigned long) iov->iov_base;
8149 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8150 start = ubuf >> PAGE_SHIFT;
8151 nr_pages = end - start;
8155 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8159 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8164 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8170 mmap_read_lock(current->mm);
8171 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8173 if (pret == nr_pages) {
8174 /* don't support file backed memory */
8175 for (i = 0; i < nr_pages; i++) {
8176 struct vm_area_struct *vma = vmas[i];
8179 !is_file_hugepages(vma->vm_file)) {
8185 ret = pret < 0 ? pret : -EFAULT;
8187 mmap_read_unlock(current->mm);
8190 * if we did partial map, or found file backed vmas,
8191 * release any pages we did get
8194 unpin_user_pages(pages, pret);
8199 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8201 unpin_user_pages(pages, pret);
8206 off = ubuf & ~PAGE_MASK;
8207 size = iov->iov_len;
8208 for (i = 0; i < nr_pages; i++) {
8211 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8212 imu->bvec[i].bv_page = pages[i];
8213 imu->bvec[i].bv_len = vec_len;
8214 imu->bvec[i].bv_offset = off;
8218 /* store original address for later verification */
8220 imu->len = iov->iov_len;
8221 imu->nr_bvecs = nr_pages;
8229 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8233 if (!nr_args || nr_args > UIO_MAXIOV)
8236 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8238 if (!ctx->user_bufs)
8244 static int io_buffer_validate(struct iovec *iov)
8247 * Don't impose further limits on the size and buffer
8248 * constraints here, we'll -EINVAL later when IO is
8249 * submitted if they are wrong.
8251 if (!iov->iov_base || !iov->iov_len)
8254 /* arbitrary limit, but we need something */
8255 if (iov->iov_len > SZ_1G)
8261 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8262 unsigned int nr_args)
8266 struct page *last_hpage = NULL;
8268 ret = io_buffers_map_alloc(ctx, nr_args);
8272 for (i = 0; i < nr_args; i++) {
8273 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8275 ret = io_copy_iov(ctx, &iov, arg, i);
8279 ret = io_buffer_validate(&iov);
8283 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8287 ctx->nr_user_bufs++;
8291 io_sqe_buffers_unregister(ctx);
8296 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8298 __s32 __user *fds = arg;
8304 if (copy_from_user(&fd, fds, sizeof(*fds)))
8307 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8308 if (IS_ERR(ctx->cq_ev_fd)) {
8309 int ret = PTR_ERR(ctx->cq_ev_fd);
8310 ctx->cq_ev_fd = NULL;
8317 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8319 if (ctx->cq_ev_fd) {
8320 eventfd_ctx_put(ctx->cq_ev_fd);
8321 ctx->cq_ev_fd = NULL;
8328 static int __io_destroy_buffers(int id, void *p, void *data)
8330 struct io_ring_ctx *ctx = data;
8331 struct io_buffer *buf = p;
8333 __io_remove_buffers(ctx, buf, id, -1U);
8337 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8339 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8340 idr_destroy(&ctx->io_buffer_idr);
8343 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8345 struct io_kiocb *req, *nxt;
8347 list_for_each_entry_safe(req, nxt, list, compl.list) {
8348 if (tsk && req->task != tsk)
8350 list_del(&req->compl.list);
8351 kmem_cache_free(req_cachep, req);
8355 static void io_req_caches_free(struct io_ring_ctx *ctx)
8357 struct io_submit_state *submit_state = &ctx->submit_state;
8358 struct io_comp_state *cs = &ctx->submit_state.comp;
8360 mutex_lock(&ctx->uring_lock);
8362 if (submit_state->free_reqs) {
8363 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8364 submit_state->reqs);
8365 submit_state->free_reqs = 0;
8368 spin_lock_irq(&ctx->completion_lock);
8369 list_splice_init(&cs->locked_free_list, &cs->free_list);
8370 cs->locked_free_nr = 0;
8371 spin_unlock_irq(&ctx->completion_lock);
8373 io_req_cache_free(&cs->free_list, NULL);
8375 mutex_unlock(&ctx->uring_lock);
8378 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8381 * Some may use context even when all refs and requests have been put,
8382 * and they are free to do so while still holding uring_lock, see
8383 * __io_req_task_submit(). Wait for them to finish.
8385 mutex_lock(&ctx->uring_lock);
8386 mutex_unlock(&ctx->uring_lock);
8388 io_sq_thread_finish(ctx);
8389 io_sqe_buffers_unregister(ctx);
8391 if (ctx->mm_account) {
8392 mmdrop(ctx->mm_account);
8393 ctx->mm_account = NULL;
8396 mutex_lock(&ctx->uring_lock);
8397 io_sqe_files_unregister(ctx);
8398 mutex_unlock(&ctx->uring_lock);
8399 io_eventfd_unregister(ctx);
8400 io_destroy_buffers(ctx);
8401 idr_destroy(&ctx->personality_idr);
8403 #if defined(CONFIG_UNIX)
8404 if (ctx->ring_sock) {
8405 ctx->ring_sock->file = NULL; /* so that iput() is called */
8406 sock_release(ctx->ring_sock);
8410 io_mem_free(ctx->rings);
8411 io_mem_free(ctx->sq_sqes);
8413 percpu_ref_exit(&ctx->refs);
8414 free_uid(ctx->user);
8415 io_req_caches_free(ctx);
8417 io_wq_put_hash(ctx->hash_map);
8418 kfree(ctx->cancel_hash);
8422 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8424 struct io_ring_ctx *ctx = file->private_data;
8427 poll_wait(file, &ctx->cq_wait, wait);
8429 * synchronizes with barrier from wq_has_sleeper call in
8433 if (!io_sqring_full(ctx))
8434 mask |= EPOLLOUT | EPOLLWRNORM;
8437 * Don't flush cqring overflow list here, just do a simple check.
8438 * Otherwise there could possible be ABBA deadlock:
8441 * lock(&ctx->uring_lock);
8443 * lock(&ctx->uring_lock);
8446 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8447 * pushs them to do the flush.
8449 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8450 mask |= EPOLLIN | EPOLLRDNORM;
8455 static int io_uring_fasync(int fd, struct file *file, int on)
8457 struct io_ring_ctx *ctx = file->private_data;
8459 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8462 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8464 const struct cred *creds;
8466 creds = idr_remove(&ctx->personality_idr, id);
8475 static int io_remove_personalities(int id, void *p, void *data)
8477 struct io_ring_ctx *ctx = data;
8479 io_unregister_personality(ctx, id);
8483 static bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8485 struct callback_head *work, *head, *next;
8486 bool executed = false;
8491 work = READ_ONCE(ctx->exit_task_work);
8492 } while (cmpxchg(&ctx->exit_task_work, work, head) != work);
8509 static void io_ring_exit_work(struct work_struct *work)
8511 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
8515 * If we're doing polled IO and end up having requests being
8516 * submitted async (out-of-line), then completions can come in while
8517 * we're waiting for refs to drop. We need to reap these manually,
8518 * as nobody else will be looking for them.
8521 io_uring_try_cancel_requests(ctx, NULL, NULL);
8522 io_run_ctx_fallback(ctx);
8523 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8524 io_ring_ctx_free(ctx);
8527 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8529 mutex_lock(&ctx->uring_lock);
8530 percpu_ref_kill(&ctx->refs);
8532 if (WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) && !ctx->sqo_dead))
8535 /* if force is set, the ring is going away. always drop after that */
8536 ctx->cq_overflow_flushed = 1;
8538 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8539 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8540 mutex_unlock(&ctx->uring_lock);
8542 io_kill_timeouts(ctx, NULL, NULL);
8543 io_poll_remove_all(ctx, NULL, NULL);
8545 /* if we failed setting up the ctx, we might not have any rings */
8546 io_iopoll_try_reap_events(ctx);
8548 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8550 * Use system_unbound_wq to avoid spawning tons of event kworkers
8551 * if we're exiting a ton of rings at the same time. It just adds
8552 * noise and overhead, there's no discernable change in runtime
8553 * over using system_wq.
8555 queue_work(system_unbound_wq, &ctx->exit_work);
8558 static int io_uring_release(struct inode *inode, struct file *file)
8560 struct io_ring_ctx *ctx = file->private_data;
8562 file->private_data = NULL;
8563 io_ring_ctx_wait_and_kill(ctx);
8567 struct io_task_cancel {
8568 struct task_struct *task;
8569 struct files_struct *files;
8572 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8574 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8575 struct io_task_cancel *cancel = data;
8578 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8579 unsigned long flags;
8580 struct io_ring_ctx *ctx = req->ctx;
8582 /* protect against races with linked timeouts */
8583 spin_lock_irqsave(&ctx->completion_lock, flags);
8584 ret = io_match_task(req, cancel->task, cancel->files);
8585 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8587 ret = io_match_task(req, cancel->task, cancel->files);
8592 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8593 struct task_struct *task,
8594 struct files_struct *files)
8596 struct io_defer_entry *de = NULL;
8599 spin_lock_irq(&ctx->completion_lock);
8600 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8601 if (io_match_task(de->req, task, files)) {
8602 list_cut_position(&list, &ctx->defer_list, &de->list);
8606 spin_unlock_irq(&ctx->completion_lock);
8608 while (!list_empty(&list)) {
8609 de = list_first_entry(&list, struct io_defer_entry, list);
8610 list_del_init(&de->list);
8611 req_set_fail_links(de->req);
8612 io_put_req(de->req);
8613 io_req_complete(de->req, -ECANCELED);
8618 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8619 struct task_struct *task,
8620 struct files_struct *files)
8622 struct io_task_cancel cancel = { .task = task, .files = files, };
8623 struct io_uring_task *tctx = current->io_uring;
8626 enum io_wq_cancel cret;
8629 if (tctx && tctx->io_wq) {
8630 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8632 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8635 /* SQPOLL thread does its own polling */
8636 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8637 while (!list_empty_careful(&ctx->iopoll_list)) {
8638 io_iopoll_try_reap_events(ctx);
8643 ret |= io_poll_remove_all(ctx, task, files);
8644 ret |= io_kill_timeouts(ctx, task, files);
8645 ret |= io_run_task_work();
8646 ret |= io_run_ctx_fallback(ctx);
8647 io_cqring_overflow_flush(ctx, true, task, files);
8654 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8655 struct task_struct *task,
8656 struct files_struct *files)
8658 struct io_kiocb *req;
8661 spin_lock_irq(&ctx->inflight_lock);
8662 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8663 cnt += io_match_task(req, task, files);
8664 spin_unlock_irq(&ctx->inflight_lock);
8668 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8669 struct task_struct *task,
8670 struct files_struct *files)
8672 while (!list_empty_careful(&ctx->inflight_list)) {
8676 inflight = io_uring_count_inflight(ctx, task, files);
8680 io_uring_try_cancel_requests(ctx, task, files);
8683 io_sq_thread_unpark(ctx->sq_data);
8684 prepare_to_wait(&task->io_uring->wait, &wait,
8685 TASK_UNINTERRUPTIBLE);
8686 if (inflight == io_uring_count_inflight(ctx, task, files))
8688 finish_wait(&task->io_uring->wait, &wait);
8690 io_sq_thread_park(ctx->sq_data);
8694 static void io_disable_sqo_submit(struct io_ring_ctx *ctx)
8696 mutex_lock(&ctx->uring_lock);
8698 mutex_unlock(&ctx->uring_lock);
8700 /* make sure callers enter the ring to get error */
8702 io_ring_set_wakeup_flag(ctx);
8706 * We need to iteratively cancel requests, in case a request has dependent
8707 * hard links. These persist even for failure of cancelations, hence keep
8708 * looping until none are found.
8710 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8711 struct files_struct *files)
8713 struct task_struct *task = current;
8714 bool did_park = false;
8716 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8717 io_disable_sqo_submit(ctx);
8718 did_park = io_sq_thread_park(ctx->sq_data);
8720 task = ctx->sq_data->thread;
8721 atomic_inc(&task->io_uring->in_idle);
8725 io_cancel_defer_files(ctx, task, files);
8727 io_uring_cancel_files(ctx, task, files);
8729 io_uring_try_cancel_requests(ctx, task, NULL);
8732 atomic_dec(&task->io_uring->in_idle);
8733 io_sq_thread_unpark(ctx->sq_data);
8738 * Note that this task has used io_uring. We use it for cancelation purposes.
8740 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8742 struct io_uring_task *tctx = current->io_uring;
8745 if (unlikely(!tctx)) {
8746 ret = io_uring_alloc_task_context(current, ctx);
8749 tctx = current->io_uring;
8751 if (tctx->last != file) {
8752 void *old = xa_load(&tctx->xa, (unsigned long)file);
8756 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8763 /* one and only SQPOLL file note, held by sqo_task */
8764 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
8765 current != ctx->sqo_task);
8771 * This is race safe in that the task itself is doing this, hence it
8772 * cannot be going through the exit/cancel paths at the same time.
8773 * This cannot be modified while exit/cancel is running.
8775 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8776 tctx->sqpoll = true;
8782 * Remove this io_uring_file -> task mapping.
8784 static void io_uring_del_task_file(struct file *file)
8786 struct io_uring_task *tctx = current->io_uring;
8788 if (tctx->last == file)
8790 file = xa_erase(&tctx->xa, (unsigned long)file);
8795 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8798 unsigned long index;
8800 xa_for_each(&tctx->xa, index, file)
8801 io_uring_del_task_file(file);
8803 io_wq_put_and_exit(tctx->io_wq);
8808 void __io_uring_files_cancel(struct files_struct *files)
8810 struct io_uring_task *tctx = current->io_uring;
8812 unsigned long index;
8814 /* make sure overflow events are dropped */
8815 atomic_inc(&tctx->in_idle);
8816 xa_for_each(&tctx->xa, index, file)
8817 io_uring_cancel_task_requests(file->private_data, files);
8818 atomic_dec(&tctx->in_idle);
8821 io_uring_clean_tctx(tctx);
8824 static s64 tctx_inflight(struct io_uring_task *tctx)
8826 return percpu_counter_sum(&tctx->inflight);
8829 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8831 struct io_sq_data *sqd = ctx->sq_data;
8832 struct io_uring_task *tctx;
8838 io_disable_sqo_submit(ctx);
8839 if (!io_sq_thread_park(sqd))
8841 tctx = ctx->sq_data->thread->io_uring;
8842 /* can happen on fork/alloc failure, just ignore that state */
8844 io_sq_thread_unpark(sqd);
8848 atomic_inc(&tctx->in_idle);
8850 /* read completions before cancelations */
8851 inflight = tctx_inflight(tctx);
8854 io_uring_cancel_task_requests(ctx, NULL);
8856 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8858 * If we've seen completions, retry without waiting. This
8859 * avoids a race where a completion comes in before we did
8860 * prepare_to_wait().
8862 if (inflight == tctx_inflight(tctx))
8864 finish_wait(&tctx->wait, &wait);
8866 atomic_dec(&tctx->in_idle);
8867 io_sq_thread_unpark(sqd);
8871 * Find any io_uring fd that this task has registered or done IO on, and cancel
8874 void __io_uring_task_cancel(void)
8876 struct io_uring_task *tctx = current->io_uring;
8880 /* make sure overflow events are dropped */
8881 atomic_inc(&tctx->in_idle);
8883 /* trigger io_disable_sqo_submit() */
8886 unsigned long index;
8888 xa_for_each(&tctx->xa, index, file)
8889 io_uring_cancel_sqpoll(file->private_data);
8893 /* read completions before cancelations */
8894 inflight = tctx_inflight(tctx);
8897 __io_uring_files_cancel(NULL);
8899 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8902 * If we've seen completions, retry without waiting. This
8903 * avoids a race where a completion comes in before we did
8904 * prepare_to_wait().
8906 if (inflight == tctx_inflight(tctx))
8908 finish_wait(&tctx->wait, &wait);
8911 atomic_dec(&tctx->in_idle);
8913 io_uring_clean_tctx(tctx);
8914 /* all current's requests should be gone, we can kill tctx */
8915 __io_uring_free(current);
8918 static int io_uring_flush(struct file *file, void *data)
8920 struct io_uring_task *tctx = current->io_uring;
8921 struct io_ring_ctx *ctx = file->private_data;
8923 /* Ignore helper thread files exit */
8924 if (current->flags & PF_IO_WORKER)
8927 if (fatal_signal_pending(current) || (current->flags & PF_EXITING)) {
8928 io_uring_cancel_task_requests(ctx, NULL);
8929 io_req_caches_free(ctx);
8932 io_run_ctx_fallback(ctx);
8937 /* we should have cancelled and erased it before PF_EXITING */
8938 WARN_ON_ONCE((current->flags & PF_EXITING) &&
8939 xa_load(&tctx->xa, (unsigned long)file));
8942 * fput() is pending, will be 2 if the only other ref is our potential
8943 * task file note. If the task is exiting, drop regardless of count.
8945 if (atomic_long_read(&file->f_count) != 2)
8948 if (ctx->flags & IORING_SETUP_SQPOLL) {
8949 /* there is only one file note, which is owned by sqo_task */
8950 WARN_ON_ONCE(ctx->sqo_task != current &&
8951 xa_load(&tctx->xa, (unsigned long)file));
8952 /* sqo_dead check is for when this happens after cancellation */
8953 WARN_ON_ONCE(ctx->sqo_task == current && !ctx->sqo_dead &&
8954 !xa_load(&tctx->xa, (unsigned long)file));
8956 io_disable_sqo_submit(ctx);
8959 if (!(ctx->flags & IORING_SETUP_SQPOLL) || ctx->sqo_task == current)
8960 io_uring_del_task_file(file);
8964 static void *io_uring_validate_mmap_request(struct file *file,
8965 loff_t pgoff, size_t sz)
8967 struct io_ring_ctx *ctx = file->private_data;
8968 loff_t offset = pgoff << PAGE_SHIFT;
8973 case IORING_OFF_SQ_RING:
8974 case IORING_OFF_CQ_RING:
8977 case IORING_OFF_SQES:
8981 return ERR_PTR(-EINVAL);
8984 page = virt_to_head_page(ptr);
8985 if (sz > page_size(page))
8986 return ERR_PTR(-EINVAL);
8993 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8995 size_t sz = vma->vm_end - vma->vm_start;
8999 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
9001 return PTR_ERR(ptr);
9003 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
9004 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
9007 #else /* !CONFIG_MMU */
9009 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
9011 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
9014 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
9016 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
9019 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
9020 unsigned long addr, unsigned long len,
9021 unsigned long pgoff, unsigned long flags)
9025 ptr = io_uring_validate_mmap_request(file, pgoff, len);
9027 return PTR_ERR(ptr);
9029 return (unsigned long) ptr;
9032 #endif /* !CONFIG_MMU */
9034 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
9040 if (!io_sqring_full(ctx))
9043 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
9045 if (unlikely(ctx->sqo_dead)) {
9050 if (!io_sqring_full(ctx))
9054 } while (!signal_pending(current));
9056 finish_wait(&ctx->sqo_sq_wait, &wait);
9061 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
9062 struct __kernel_timespec __user **ts,
9063 const sigset_t __user **sig)
9065 struct io_uring_getevents_arg arg;
9068 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9069 * is just a pointer to the sigset_t.
9071 if (!(flags & IORING_ENTER_EXT_ARG)) {
9072 *sig = (const sigset_t __user *) argp;
9078 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9079 * timespec and sigset_t pointers if good.
9081 if (*argsz != sizeof(arg))
9083 if (copy_from_user(&arg, argp, sizeof(arg)))
9085 *sig = u64_to_user_ptr(arg.sigmask);
9086 *argsz = arg.sigmask_sz;
9087 *ts = u64_to_user_ptr(arg.ts);
9091 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9092 u32, min_complete, u32, flags, const void __user *, argp,
9095 struct io_ring_ctx *ctx;
9102 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9103 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9111 if (f.file->f_op != &io_uring_fops)
9115 ctx = f.file->private_data;
9116 if (!percpu_ref_tryget(&ctx->refs))
9120 if (ctx->flags & IORING_SETUP_R_DISABLED)
9124 * For SQ polling, the thread will do all submissions and completions.
9125 * Just return the requested submit count, and wake the thread if
9129 if (ctx->flags & IORING_SETUP_SQPOLL) {
9130 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9132 if (unlikely(ctx->sqo_exec)) {
9133 ret = io_sq_thread_fork(ctx->sq_data, ctx);
9139 if (unlikely(ctx->sqo_dead))
9141 if (flags & IORING_ENTER_SQ_WAKEUP)
9142 wake_up(&ctx->sq_data->wait);
9143 if (flags & IORING_ENTER_SQ_WAIT) {
9144 ret = io_sqpoll_wait_sq(ctx);
9148 submitted = to_submit;
9149 } else if (to_submit) {
9150 ret = io_uring_add_task_file(ctx, f.file);
9153 mutex_lock(&ctx->uring_lock);
9154 submitted = io_submit_sqes(ctx, to_submit);
9155 mutex_unlock(&ctx->uring_lock);
9157 if (submitted != to_submit)
9160 if (flags & IORING_ENTER_GETEVENTS) {
9161 const sigset_t __user *sig;
9162 struct __kernel_timespec __user *ts;
9164 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9168 min_complete = min(min_complete, ctx->cq_entries);
9171 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9172 * space applications don't need to do io completion events
9173 * polling again, they can rely on io_sq_thread to do polling
9174 * work, which can reduce cpu usage and uring_lock contention.
9176 if (ctx->flags & IORING_SETUP_IOPOLL &&
9177 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9178 ret = io_iopoll_check(ctx, min_complete);
9180 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9185 percpu_ref_put(&ctx->refs);
9188 return submitted ? submitted : ret;
9191 #ifdef CONFIG_PROC_FS
9192 static int io_uring_show_cred(int id, void *p, void *data)
9194 const struct cred *cred = p;
9195 struct seq_file *m = data;
9196 struct user_namespace *uns = seq_user_ns(m);
9197 struct group_info *gi;
9202 seq_printf(m, "%5d\n", id);
9203 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9204 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9205 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9206 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9207 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9208 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9209 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9210 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9211 seq_puts(m, "\n\tGroups:\t");
9212 gi = cred->group_info;
9213 for (g = 0; g < gi->ngroups; g++) {
9214 seq_put_decimal_ull(m, g ? " " : "",
9215 from_kgid_munged(uns, gi->gid[g]));
9217 seq_puts(m, "\n\tCapEff:\t");
9218 cap = cred->cap_effective;
9219 CAP_FOR_EACH_U32(__capi)
9220 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9225 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9227 struct io_sq_data *sq = NULL;
9232 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9233 * since fdinfo case grabs it in the opposite direction of normal use
9234 * cases. If we fail to get the lock, we just don't iterate any
9235 * structures that could be going away outside the io_uring mutex.
9237 has_lock = mutex_trylock(&ctx->uring_lock);
9239 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9245 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9246 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9247 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9248 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9249 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9252 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9254 seq_printf(m, "%5u: <none>\n", i);
9256 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9257 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9258 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9260 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9261 (unsigned int) buf->len);
9263 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9264 seq_printf(m, "Personalities:\n");
9265 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9267 seq_printf(m, "PollList:\n");
9268 spin_lock_irq(&ctx->completion_lock);
9269 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9270 struct hlist_head *list = &ctx->cancel_hash[i];
9271 struct io_kiocb *req;
9273 hlist_for_each_entry(req, list, hash_node)
9274 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9275 req->task->task_works != NULL);
9277 spin_unlock_irq(&ctx->completion_lock);
9279 mutex_unlock(&ctx->uring_lock);
9282 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9284 struct io_ring_ctx *ctx = f->private_data;
9286 if (percpu_ref_tryget(&ctx->refs)) {
9287 __io_uring_show_fdinfo(ctx, m);
9288 percpu_ref_put(&ctx->refs);
9293 static const struct file_operations io_uring_fops = {
9294 .release = io_uring_release,
9295 .flush = io_uring_flush,
9296 .mmap = io_uring_mmap,
9298 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9299 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9301 .poll = io_uring_poll,
9302 .fasync = io_uring_fasync,
9303 #ifdef CONFIG_PROC_FS
9304 .show_fdinfo = io_uring_show_fdinfo,
9308 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9309 struct io_uring_params *p)
9311 struct io_rings *rings;
9312 size_t size, sq_array_offset;
9314 /* make sure these are sane, as we already accounted them */
9315 ctx->sq_entries = p->sq_entries;
9316 ctx->cq_entries = p->cq_entries;
9318 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9319 if (size == SIZE_MAX)
9322 rings = io_mem_alloc(size);
9327 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9328 rings->sq_ring_mask = p->sq_entries - 1;
9329 rings->cq_ring_mask = p->cq_entries - 1;
9330 rings->sq_ring_entries = p->sq_entries;
9331 rings->cq_ring_entries = p->cq_entries;
9332 ctx->sq_mask = rings->sq_ring_mask;
9333 ctx->cq_mask = rings->cq_ring_mask;
9335 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9336 if (size == SIZE_MAX) {
9337 io_mem_free(ctx->rings);
9342 ctx->sq_sqes = io_mem_alloc(size);
9343 if (!ctx->sq_sqes) {
9344 io_mem_free(ctx->rings);
9352 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9356 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9360 ret = io_uring_add_task_file(ctx, file);
9365 fd_install(fd, file);
9370 * Allocate an anonymous fd, this is what constitutes the application
9371 * visible backing of an io_uring instance. The application mmaps this
9372 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9373 * we have to tie this fd to a socket for file garbage collection purposes.
9375 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9378 #if defined(CONFIG_UNIX)
9381 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9384 return ERR_PTR(ret);
9387 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9388 O_RDWR | O_CLOEXEC);
9389 #if defined(CONFIG_UNIX)
9391 sock_release(ctx->ring_sock);
9392 ctx->ring_sock = NULL;
9394 ctx->ring_sock->file = file;
9400 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9401 struct io_uring_params __user *params)
9403 struct io_ring_ctx *ctx;
9409 if (entries > IORING_MAX_ENTRIES) {
9410 if (!(p->flags & IORING_SETUP_CLAMP))
9412 entries = IORING_MAX_ENTRIES;
9416 * Use twice as many entries for the CQ ring. It's possible for the
9417 * application to drive a higher depth than the size of the SQ ring,
9418 * since the sqes are only used at submission time. This allows for
9419 * some flexibility in overcommitting a bit. If the application has
9420 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9421 * of CQ ring entries manually.
9423 p->sq_entries = roundup_pow_of_two(entries);
9424 if (p->flags & IORING_SETUP_CQSIZE) {
9426 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9427 * to a power-of-two, if it isn't already. We do NOT impose
9428 * any cq vs sq ring sizing.
9432 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9433 if (!(p->flags & IORING_SETUP_CLAMP))
9435 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9437 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9438 if (p->cq_entries < p->sq_entries)
9441 p->cq_entries = 2 * p->sq_entries;
9444 ctx = io_ring_ctx_alloc(p);
9447 ctx->compat = in_compat_syscall();
9448 if (!capable(CAP_IPC_LOCK))
9449 ctx->user = get_uid(current_user());
9450 ctx->sqo_task = current;
9453 * This is just grabbed for accounting purposes. When a process exits,
9454 * the mm is exited and dropped before the files, hence we need to hang
9455 * on to this mm purely for the purposes of being able to unaccount
9456 * memory (locked/pinned vm). It's not used for anything else.
9458 mmgrab(current->mm);
9459 ctx->mm_account = current->mm;
9461 ret = io_allocate_scq_urings(ctx, p);
9465 ret = io_sq_offload_create(ctx, p);
9469 if (!(p->flags & IORING_SETUP_R_DISABLED))
9470 io_sq_offload_start(ctx);
9472 memset(&p->sq_off, 0, sizeof(p->sq_off));
9473 p->sq_off.head = offsetof(struct io_rings, sq.head);
9474 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9475 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9476 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9477 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9478 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9479 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9481 memset(&p->cq_off, 0, sizeof(p->cq_off));
9482 p->cq_off.head = offsetof(struct io_rings, cq.head);
9483 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9484 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9485 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9486 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9487 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9488 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9490 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9491 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9492 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9493 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9494 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9496 if (copy_to_user(params, p, sizeof(*p))) {
9501 file = io_uring_get_file(ctx);
9503 ret = PTR_ERR(file);
9508 * Install ring fd as the very last thing, so we don't risk someone
9509 * having closed it before we finish setup
9511 ret = io_uring_install_fd(ctx, file);
9513 io_disable_sqo_submit(ctx);
9514 /* fput will clean it up */
9519 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9522 io_disable_sqo_submit(ctx);
9523 io_ring_ctx_wait_and_kill(ctx);
9528 * Sets up an aio uring context, and returns the fd. Applications asks for a
9529 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9530 * params structure passed in.
9532 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9534 struct io_uring_params p;
9537 if (copy_from_user(&p, params, sizeof(p)))
9539 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9544 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9545 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9546 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9547 IORING_SETUP_R_DISABLED))
9550 return io_uring_create(entries, &p, params);
9553 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9554 struct io_uring_params __user *, params)
9556 return io_uring_setup(entries, params);
9559 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9561 struct io_uring_probe *p;
9565 size = struct_size(p, ops, nr_args);
9566 if (size == SIZE_MAX)
9568 p = kzalloc(size, GFP_KERNEL);
9573 if (copy_from_user(p, arg, size))
9576 if (memchr_inv(p, 0, size))
9579 p->last_op = IORING_OP_LAST - 1;
9580 if (nr_args > IORING_OP_LAST)
9581 nr_args = IORING_OP_LAST;
9583 for (i = 0; i < nr_args; i++) {
9585 if (!io_op_defs[i].not_supported)
9586 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9591 if (copy_to_user(arg, p, size))
9598 static int io_register_personality(struct io_ring_ctx *ctx)
9600 const struct cred *creds;
9603 creds = get_current_cred();
9605 ret = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9606 USHRT_MAX, GFP_KERNEL);
9612 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9613 unsigned int nr_args)
9615 struct io_uring_restriction *res;
9619 /* Restrictions allowed only if rings started disabled */
9620 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9623 /* We allow only a single restrictions registration */
9624 if (ctx->restrictions.registered)
9627 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9630 size = array_size(nr_args, sizeof(*res));
9631 if (size == SIZE_MAX)
9634 res = memdup_user(arg, size);
9636 return PTR_ERR(res);
9640 for (i = 0; i < nr_args; i++) {
9641 switch (res[i].opcode) {
9642 case IORING_RESTRICTION_REGISTER_OP:
9643 if (res[i].register_op >= IORING_REGISTER_LAST) {
9648 __set_bit(res[i].register_op,
9649 ctx->restrictions.register_op);
9651 case IORING_RESTRICTION_SQE_OP:
9652 if (res[i].sqe_op >= IORING_OP_LAST) {
9657 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9659 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9660 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9662 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9663 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9672 /* Reset all restrictions if an error happened */
9674 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9676 ctx->restrictions.registered = true;
9682 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9684 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9687 if (ctx->restrictions.registered)
9688 ctx->restricted = 1;
9690 ctx->flags &= ~IORING_SETUP_R_DISABLED;
9692 io_sq_offload_start(ctx);
9697 static bool io_register_op_must_quiesce(int op)
9700 case IORING_UNREGISTER_FILES:
9701 case IORING_REGISTER_FILES_UPDATE:
9702 case IORING_REGISTER_PROBE:
9703 case IORING_REGISTER_PERSONALITY:
9704 case IORING_UNREGISTER_PERSONALITY:
9711 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9712 void __user *arg, unsigned nr_args)
9713 __releases(ctx->uring_lock)
9714 __acquires(ctx->uring_lock)
9719 * We're inside the ring mutex, if the ref is already dying, then
9720 * someone else killed the ctx or is already going through
9721 * io_uring_register().
9723 if (percpu_ref_is_dying(&ctx->refs))
9726 if (io_register_op_must_quiesce(opcode)) {
9727 percpu_ref_kill(&ctx->refs);
9730 * Drop uring mutex before waiting for references to exit. If
9731 * another thread is currently inside io_uring_enter() it might
9732 * need to grab the uring_lock to make progress. If we hold it
9733 * here across the drain wait, then we can deadlock. It's safe
9734 * to drop the mutex here, since no new references will come in
9735 * after we've killed the percpu ref.
9737 mutex_unlock(&ctx->uring_lock);
9739 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9742 ret = io_run_task_work_sig();
9747 mutex_lock(&ctx->uring_lock);
9750 percpu_ref_resurrect(&ctx->refs);
9755 if (ctx->restricted) {
9756 if (opcode >= IORING_REGISTER_LAST) {
9761 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9768 case IORING_REGISTER_BUFFERS:
9769 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9771 case IORING_UNREGISTER_BUFFERS:
9775 ret = io_sqe_buffers_unregister(ctx);
9777 case IORING_REGISTER_FILES:
9778 ret = io_sqe_files_register(ctx, arg, nr_args);
9780 case IORING_UNREGISTER_FILES:
9784 ret = io_sqe_files_unregister(ctx);
9786 case IORING_REGISTER_FILES_UPDATE:
9787 ret = io_sqe_files_update(ctx, arg, nr_args);
9789 case IORING_REGISTER_EVENTFD:
9790 case IORING_REGISTER_EVENTFD_ASYNC:
9794 ret = io_eventfd_register(ctx, arg);
9797 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9798 ctx->eventfd_async = 1;
9800 ctx->eventfd_async = 0;
9802 case IORING_UNREGISTER_EVENTFD:
9806 ret = io_eventfd_unregister(ctx);
9808 case IORING_REGISTER_PROBE:
9810 if (!arg || nr_args > 256)
9812 ret = io_probe(ctx, arg, nr_args);
9814 case IORING_REGISTER_PERSONALITY:
9818 ret = io_register_personality(ctx);
9820 case IORING_UNREGISTER_PERSONALITY:
9824 ret = io_unregister_personality(ctx, nr_args);
9826 case IORING_REGISTER_ENABLE_RINGS:
9830 ret = io_register_enable_rings(ctx);
9832 case IORING_REGISTER_RESTRICTIONS:
9833 ret = io_register_restrictions(ctx, arg, nr_args);
9841 if (io_register_op_must_quiesce(opcode)) {
9842 /* bring the ctx back to life */
9843 percpu_ref_reinit(&ctx->refs);
9845 reinit_completion(&ctx->ref_comp);
9850 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9851 void __user *, arg, unsigned int, nr_args)
9853 struct io_ring_ctx *ctx;
9862 if (f.file->f_op != &io_uring_fops)
9865 ctx = f.file->private_data;
9869 mutex_lock(&ctx->uring_lock);
9870 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9871 mutex_unlock(&ctx->uring_lock);
9872 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9873 ctx->cq_ev_fd != NULL, ret);
9879 static int __init io_uring_init(void)
9881 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9882 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9883 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9886 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9887 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9888 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9889 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9890 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9891 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9892 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9893 BUILD_BUG_SQE_ELEM(8, __u64, off);
9894 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9895 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9896 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9897 BUILD_BUG_SQE_ELEM(24, __u32, len);
9898 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9899 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9900 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9901 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9902 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9903 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9904 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9905 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9906 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9907 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9908 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9909 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9910 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9911 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9912 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9913 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9914 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9915 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9916 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9918 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9919 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9920 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9924 __initcall(io_uring_init);