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_exec: 1;
344 * Ring buffer of indices into array of io_uring_sqe, which is
345 * mmapped by the application using the IORING_OFF_SQES offset.
347 * This indirection could e.g. be used to assign fixed
348 * io_uring_sqe entries to operations and only submit them to
349 * the queue when needed.
351 * The kernel modifies neither the indices array nor the entries
355 unsigned cached_sq_head;
358 unsigned sq_thread_idle;
359 unsigned cached_sq_dropped;
360 unsigned cached_cq_overflow;
361 unsigned long sq_check_overflow;
363 /* hashed buffered write serialization */
364 struct io_wq_hash *hash_map;
366 struct list_head defer_list;
367 struct list_head timeout_list;
368 struct list_head cq_overflow_list;
370 struct io_uring_sqe *sq_sqes;
371 } ____cacheline_aligned_in_smp;
374 struct mutex uring_lock;
375 wait_queue_head_t wait;
376 } ____cacheline_aligned_in_smp;
378 struct io_submit_state submit_state;
380 struct io_rings *rings;
385 struct task_struct *sqo_task;
387 /* Only used for accounting purposes */
388 struct mm_struct *mm_account;
390 struct io_sq_data *sq_data; /* if using sq thread polling */
392 struct wait_queue_head sqo_sq_wait;
393 struct list_head sqd_list;
396 * If used, fixed file set. Writers must ensure that ->refs is dead,
397 * readers must ensure that ->refs is alive as long as the file* is
398 * used. Only updated through io_uring_register(2).
400 struct fixed_rsrc_data *file_data;
401 unsigned nr_user_files;
403 /* if used, fixed mapped user buffers */
404 unsigned nr_user_bufs;
405 struct io_mapped_ubuf *user_bufs;
407 struct user_struct *user;
409 struct completion ref_comp;
410 struct completion sq_thread_comp;
412 #if defined(CONFIG_UNIX)
413 struct socket *ring_sock;
416 struct idr io_buffer_idr;
418 struct idr personality_idr;
421 unsigned cached_cq_tail;
424 atomic_t cq_timeouts;
425 unsigned cq_last_tm_flush;
426 unsigned long cq_check_overflow;
427 struct wait_queue_head cq_wait;
428 struct fasync_struct *cq_fasync;
429 struct eventfd_ctx *cq_ev_fd;
430 } ____cacheline_aligned_in_smp;
433 spinlock_t completion_lock;
436 * ->iopoll_list is protected by the ctx->uring_lock for
437 * io_uring instances that don't use IORING_SETUP_SQPOLL.
438 * For SQPOLL, only the single threaded io_sq_thread() will
439 * manipulate the list, hence no extra locking is needed there.
441 struct list_head iopoll_list;
442 struct hlist_head *cancel_hash;
443 unsigned cancel_hash_bits;
444 bool poll_multi_file;
446 spinlock_t inflight_lock;
447 struct list_head inflight_list;
448 } ____cacheline_aligned_in_smp;
450 struct delayed_work rsrc_put_work;
451 struct llist_head rsrc_put_llist;
452 struct list_head rsrc_ref_list;
453 spinlock_t rsrc_ref_lock;
455 struct io_restriction restrictions;
458 struct callback_head *exit_task_work;
460 struct wait_queue_head hash_wait;
462 /* Keep this last, we don't need it for the fast path */
463 struct work_struct exit_work;
467 * First field must be the file pointer in all the
468 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
470 struct io_poll_iocb {
472 struct wait_queue_head *head;
476 struct wait_queue_entry wait;
479 struct io_poll_remove {
489 struct io_timeout_data {
490 struct io_kiocb *req;
491 struct hrtimer timer;
492 struct timespec64 ts;
493 enum hrtimer_mode mode;
498 struct sockaddr __user *addr;
499 int __user *addr_len;
501 unsigned long nofile;
521 struct list_head list;
522 /* head of the link, used by linked timeouts only */
523 struct io_kiocb *head;
526 struct io_timeout_rem {
531 struct timespec64 ts;
536 /* NOTE: kiocb has the file as the first member, so don't do it here */
544 struct sockaddr __user *addr;
551 struct user_msghdr __user *umsg;
557 struct io_buffer *kbuf;
563 struct filename *filename;
565 unsigned long nofile;
568 struct io_rsrc_update {
594 struct epoll_event event;
598 struct file *file_out;
599 struct file *file_in;
606 struct io_provide_buf {
620 const char __user *filename;
621 struct statx __user *buffer;
633 struct filename *oldpath;
634 struct filename *newpath;
642 struct filename *filename;
645 struct io_completion {
647 struct list_head list;
651 struct io_async_connect {
652 struct sockaddr_storage address;
655 struct io_async_msghdr {
656 struct iovec fast_iov[UIO_FASTIOV];
657 /* points to an allocated iov, if NULL we use fast_iov instead */
658 struct iovec *free_iov;
659 struct sockaddr __user *uaddr;
661 struct sockaddr_storage addr;
665 struct iovec fast_iov[UIO_FASTIOV];
666 const struct iovec *free_iovec;
667 struct iov_iter iter;
669 struct wait_page_queue wpq;
673 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
674 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
675 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
676 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
677 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
678 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
684 REQ_F_LINK_TIMEOUT_BIT,
686 REQ_F_NEED_CLEANUP_BIT,
688 REQ_F_BUFFER_SELECTED_BIT,
689 REQ_F_NO_FILE_TABLE_BIT,
690 REQ_F_LTIMEOUT_ACTIVE_BIT,
691 REQ_F_COMPLETE_INLINE_BIT,
693 /* not a real bit, just to check we're not overflowing the space */
699 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
700 /* drain existing IO first */
701 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
703 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
704 /* doesn't sever on completion < 0 */
705 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
707 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
708 /* IOSQE_BUFFER_SELECT */
709 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
711 /* fail rest of links */
712 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
713 /* on inflight list */
714 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
715 /* read/write uses file position */
716 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
717 /* must not punt to workers */
718 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
719 /* has or had linked timeout */
720 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
722 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
724 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
725 /* already went through poll handler */
726 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
727 /* buffer already selected */
728 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
729 /* doesn't need file table for this request */
730 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
731 /* linked timeout is active, i.e. prepared by link's head */
732 REQ_F_LTIMEOUT_ACTIVE = BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
733 /* completion is deferred through io_comp_state */
734 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
738 struct io_poll_iocb poll;
739 struct io_poll_iocb *double_poll;
742 struct io_task_work {
743 struct io_wq_work_node node;
744 task_work_func_t func;
748 * NOTE! Each of the iocb union members has the file pointer
749 * as the first entry in their struct definition. So you can
750 * access the file pointer through any of the sub-structs,
751 * or directly as just 'ki_filp' in this struct.
757 struct io_poll_iocb poll;
758 struct io_poll_remove poll_remove;
759 struct io_accept accept;
761 struct io_cancel cancel;
762 struct io_timeout timeout;
763 struct io_timeout_rem timeout_rem;
764 struct io_connect connect;
765 struct io_sr_msg sr_msg;
767 struct io_close close;
768 struct io_rsrc_update rsrc_update;
769 struct io_fadvise fadvise;
770 struct io_madvise madvise;
771 struct io_epoll epoll;
772 struct io_splice splice;
773 struct io_provide_buf pbuf;
774 struct io_statx statx;
775 struct io_shutdown shutdown;
776 struct io_rename rename;
777 struct io_unlink unlink;
778 /* use only after cleaning per-op data, see io_clean_op() */
779 struct io_completion compl;
782 /* opcode allocated if it needs to store data for async defer */
785 /* polled IO has completed */
791 struct io_ring_ctx *ctx;
794 struct task_struct *task;
797 struct io_kiocb *link;
798 struct percpu_ref *fixed_rsrc_refs;
801 * 1. used with ctx->iopoll_list with reads/writes
802 * 2. to track reqs with ->files (see io_op_def::file_table)
804 struct list_head inflight_entry;
806 struct io_task_work io_task_work;
807 struct callback_head task_work;
809 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
810 struct hlist_node hash_node;
811 struct async_poll *apoll;
812 struct io_wq_work work;
815 struct io_defer_entry {
816 struct list_head list;
817 struct io_kiocb *req;
822 /* needs req->file assigned */
823 unsigned needs_file : 1;
824 /* hash wq insertion if file is a regular file */
825 unsigned hash_reg_file : 1;
826 /* unbound wq insertion if file is a non-regular file */
827 unsigned unbound_nonreg_file : 1;
828 /* opcode is not supported by this kernel */
829 unsigned not_supported : 1;
830 /* set if opcode supports polled "wait" */
832 unsigned pollout : 1;
833 /* op supports buffer selection */
834 unsigned buffer_select : 1;
835 /* must always have async data allocated */
836 unsigned needs_async_data : 1;
837 /* should block plug */
839 /* size of async data needed, if any */
840 unsigned short async_size;
843 static const struct io_op_def io_op_defs[] = {
844 [IORING_OP_NOP] = {},
845 [IORING_OP_READV] = {
847 .unbound_nonreg_file = 1,
850 .needs_async_data = 1,
852 .async_size = sizeof(struct io_async_rw),
854 [IORING_OP_WRITEV] = {
857 .unbound_nonreg_file = 1,
859 .needs_async_data = 1,
861 .async_size = sizeof(struct io_async_rw),
863 [IORING_OP_FSYNC] = {
866 [IORING_OP_READ_FIXED] = {
868 .unbound_nonreg_file = 1,
871 .async_size = sizeof(struct io_async_rw),
873 [IORING_OP_WRITE_FIXED] = {
876 .unbound_nonreg_file = 1,
879 .async_size = sizeof(struct io_async_rw),
881 [IORING_OP_POLL_ADD] = {
883 .unbound_nonreg_file = 1,
885 [IORING_OP_POLL_REMOVE] = {},
886 [IORING_OP_SYNC_FILE_RANGE] = {
889 [IORING_OP_SENDMSG] = {
891 .unbound_nonreg_file = 1,
893 .needs_async_data = 1,
894 .async_size = sizeof(struct io_async_msghdr),
896 [IORING_OP_RECVMSG] = {
898 .unbound_nonreg_file = 1,
901 .needs_async_data = 1,
902 .async_size = sizeof(struct io_async_msghdr),
904 [IORING_OP_TIMEOUT] = {
905 .needs_async_data = 1,
906 .async_size = sizeof(struct io_timeout_data),
908 [IORING_OP_TIMEOUT_REMOVE] = {
909 /* used by timeout updates' prep() */
911 [IORING_OP_ACCEPT] = {
913 .unbound_nonreg_file = 1,
916 [IORING_OP_ASYNC_CANCEL] = {},
917 [IORING_OP_LINK_TIMEOUT] = {
918 .needs_async_data = 1,
919 .async_size = sizeof(struct io_timeout_data),
921 [IORING_OP_CONNECT] = {
923 .unbound_nonreg_file = 1,
925 .needs_async_data = 1,
926 .async_size = sizeof(struct io_async_connect),
928 [IORING_OP_FALLOCATE] = {
931 [IORING_OP_OPENAT] = {},
932 [IORING_OP_CLOSE] = {},
933 [IORING_OP_FILES_UPDATE] = {},
934 [IORING_OP_STATX] = {},
937 .unbound_nonreg_file = 1,
941 .async_size = sizeof(struct io_async_rw),
943 [IORING_OP_WRITE] = {
945 .unbound_nonreg_file = 1,
948 .async_size = sizeof(struct io_async_rw),
950 [IORING_OP_FADVISE] = {
953 [IORING_OP_MADVISE] = {},
956 .unbound_nonreg_file = 1,
961 .unbound_nonreg_file = 1,
965 [IORING_OP_OPENAT2] = {
967 [IORING_OP_EPOLL_CTL] = {
968 .unbound_nonreg_file = 1,
970 [IORING_OP_SPLICE] = {
973 .unbound_nonreg_file = 1,
975 [IORING_OP_PROVIDE_BUFFERS] = {},
976 [IORING_OP_REMOVE_BUFFERS] = {},
980 .unbound_nonreg_file = 1,
982 [IORING_OP_SHUTDOWN] = {
985 [IORING_OP_RENAMEAT] = {},
986 [IORING_OP_UNLINKAT] = {},
989 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
990 struct task_struct *task,
991 struct files_struct *files);
992 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx);
993 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node);
994 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
995 struct io_ring_ctx *ctx);
996 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
998 static bool io_rw_reissue(struct io_kiocb *req);
999 static void io_cqring_fill_event(struct io_kiocb *req, long res);
1000 static void io_put_req(struct io_kiocb *req);
1001 static void io_put_req_deferred(struct io_kiocb *req, int nr);
1002 static void io_double_put_req(struct io_kiocb *req);
1003 static void io_dismantle_req(struct io_kiocb *req);
1004 static void io_put_task(struct task_struct *task, int nr);
1005 static void io_queue_next(struct io_kiocb *req);
1006 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1007 static void __io_queue_linked_timeout(struct io_kiocb *req);
1008 static void io_queue_linked_timeout(struct io_kiocb *req);
1009 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
1010 struct io_uring_rsrc_update *ip,
1012 static void __io_clean_op(struct io_kiocb *req);
1013 static struct file *io_file_get(struct io_submit_state *state,
1014 struct io_kiocb *req, int fd, bool fixed);
1015 static void __io_queue_sqe(struct io_kiocb *req);
1016 static void io_rsrc_put_work(struct work_struct *work);
1018 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
1019 struct iov_iter *iter, bool needs_lock);
1020 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
1021 const struct iovec *fast_iov,
1022 struct iov_iter *iter, bool force);
1023 static void io_req_task_queue(struct io_kiocb *req);
1024 static void io_submit_flush_completions(struct io_comp_state *cs,
1025 struct io_ring_ctx *ctx);
1027 static struct kmem_cache *req_cachep;
1029 static const struct file_operations io_uring_fops;
1031 struct sock *io_uring_get_socket(struct file *file)
1033 #if defined(CONFIG_UNIX)
1034 if (file->f_op == &io_uring_fops) {
1035 struct io_ring_ctx *ctx = file->private_data;
1037 return ctx->ring_sock->sk;
1042 EXPORT_SYMBOL(io_uring_get_socket);
1044 #define io_for_each_link(pos, head) \
1045 for (pos = (head); pos; pos = pos->link)
1047 static inline void io_clean_op(struct io_kiocb *req)
1049 if (req->flags & (REQ_F_NEED_CLEANUP | REQ_F_BUFFER_SELECTED))
1053 static inline void io_set_resource_node(struct io_kiocb *req)
1055 struct io_ring_ctx *ctx = req->ctx;
1057 if (!req->fixed_rsrc_refs) {
1058 req->fixed_rsrc_refs = &ctx->file_data->node->refs;
1059 percpu_ref_get(req->fixed_rsrc_refs);
1063 static bool io_match_task(struct io_kiocb *head,
1064 struct task_struct *task,
1065 struct files_struct *files)
1067 struct io_kiocb *req;
1069 if (task && head->task != task) {
1070 /* in terms of cancelation, always match if req task is dead */
1071 if (head->task->flags & PF_EXITING)
1078 io_for_each_link(req, head) {
1079 if (req->file && req->file->f_op == &io_uring_fops)
1081 if (req->task->files == files)
1087 static inline void req_set_fail_links(struct io_kiocb *req)
1089 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
1090 req->flags |= REQ_F_FAIL_LINK;
1093 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1095 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1097 complete(&ctx->ref_comp);
1100 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1102 return !req->timeout.off;
1105 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1107 struct io_ring_ctx *ctx;
1110 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1115 * Use 5 bits less than the max cq entries, that should give us around
1116 * 32 entries per hash list if totally full and uniformly spread.
1118 hash_bits = ilog2(p->cq_entries);
1122 ctx->cancel_hash_bits = hash_bits;
1123 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1125 if (!ctx->cancel_hash)
1127 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1129 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1130 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1133 ctx->flags = p->flags;
1134 init_waitqueue_head(&ctx->sqo_sq_wait);
1135 INIT_LIST_HEAD(&ctx->sqd_list);
1136 init_waitqueue_head(&ctx->cq_wait);
1137 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1138 init_completion(&ctx->ref_comp);
1139 init_completion(&ctx->sq_thread_comp);
1140 idr_init(&ctx->io_buffer_idr);
1141 idr_init(&ctx->personality_idr);
1142 mutex_init(&ctx->uring_lock);
1143 init_waitqueue_head(&ctx->wait);
1144 spin_lock_init(&ctx->completion_lock);
1145 INIT_LIST_HEAD(&ctx->iopoll_list);
1146 INIT_LIST_HEAD(&ctx->defer_list);
1147 INIT_LIST_HEAD(&ctx->timeout_list);
1148 spin_lock_init(&ctx->inflight_lock);
1149 INIT_LIST_HEAD(&ctx->inflight_list);
1150 spin_lock_init(&ctx->rsrc_ref_lock);
1151 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1152 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1153 init_llist_head(&ctx->rsrc_put_llist);
1154 INIT_LIST_HEAD(&ctx->submit_state.comp.free_list);
1155 INIT_LIST_HEAD(&ctx->submit_state.comp.locked_free_list);
1158 kfree(ctx->cancel_hash);
1163 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1165 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1166 struct io_ring_ctx *ctx = req->ctx;
1168 return seq != ctx->cached_cq_tail
1169 + READ_ONCE(ctx->cached_cq_overflow);
1175 static void io_req_clean_work(struct io_kiocb *req)
1177 if (req->flags & REQ_F_INFLIGHT) {
1178 struct io_ring_ctx *ctx = req->ctx;
1179 struct io_uring_task *tctx = req->task->io_uring;
1180 unsigned long flags;
1182 spin_lock_irqsave(&ctx->inflight_lock, flags);
1183 list_del(&req->inflight_entry);
1184 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1185 req->flags &= ~REQ_F_INFLIGHT;
1186 if (atomic_read(&tctx->in_idle))
1187 wake_up(&tctx->wait);
1191 static void io_req_track_inflight(struct io_kiocb *req)
1193 struct io_ring_ctx *ctx = req->ctx;
1195 if (!(req->flags & REQ_F_INFLIGHT)) {
1196 req->flags |= REQ_F_INFLIGHT;
1198 spin_lock_irq(&ctx->inflight_lock);
1199 list_add(&req->inflight_entry, &ctx->inflight_list);
1200 spin_unlock_irq(&ctx->inflight_lock);
1204 static void io_prep_async_work(struct io_kiocb *req)
1206 const struct io_op_def *def = &io_op_defs[req->opcode];
1207 struct io_ring_ctx *ctx = req->ctx;
1209 if (req->flags & REQ_F_FORCE_ASYNC)
1210 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1212 if (req->flags & REQ_F_ISREG) {
1213 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1214 io_wq_hash_work(&req->work, file_inode(req->file));
1216 if (def->unbound_nonreg_file)
1217 req->work.flags |= IO_WQ_WORK_UNBOUND;
1221 static void io_prep_async_link(struct io_kiocb *req)
1223 struct io_kiocb *cur;
1225 io_for_each_link(cur, req)
1226 io_prep_async_work(cur);
1229 static struct io_kiocb *__io_queue_async_work(struct io_kiocb *req)
1231 struct io_ring_ctx *ctx = req->ctx;
1232 struct io_kiocb *link = io_prep_linked_timeout(req);
1233 struct io_uring_task *tctx = req->task->io_uring;
1236 BUG_ON(!tctx->io_wq);
1238 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1239 &req->work, req->flags);
1240 io_wq_enqueue(tctx->io_wq, &req->work);
1244 static void io_queue_async_work(struct io_kiocb *req)
1246 struct io_kiocb *link;
1248 /* init ->work of the whole link before punting */
1249 io_prep_async_link(req);
1250 link = __io_queue_async_work(req);
1253 io_queue_linked_timeout(link);
1256 static void io_kill_timeout(struct io_kiocb *req)
1258 struct io_timeout_data *io = req->async_data;
1261 ret = hrtimer_try_to_cancel(&io->timer);
1263 atomic_set(&req->ctx->cq_timeouts,
1264 atomic_read(&req->ctx->cq_timeouts) + 1);
1265 list_del_init(&req->timeout.list);
1266 io_cqring_fill_event(req, 0);
1267 io_put_req_deferred(req, 1);
1272 * Returns true if we found and killed one or more timeouts
1274 static bool io_kill_timeouts(struct io_ring_ctx *ctx, struct task_struct *tsk,
1275 struct files_struct *files)
1277 struct io_kiocb *req, *tmp;
1280 spin_lock_irq(&ctx->completion_lock);
1281 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1282 if (io_match_task(req, tsk, files)) {
1283 io_kill_timeout(req);
1287 spin_unlock_irq(&ctx->completion_lock);
1288 return canceled != 0;
1291 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1294 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1295 struct io_defer_entry, list);
1297 if (req_need_defer(de->req, de->seq))
1299 list_del_init(&de->list);
1300 io_req_task_queue(de->req);
1302 } while (!list_empty(&ctx->defer_list));
1305 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1309 if (list_empty(&ctx->timeout_list))
1312 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1315 u32 events_needed, events_got;
1316 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1317 struct io_kiocb, timeout.list);
1319 if (io_is_timeout_noseq(req))
1323 * Since seq can easily wrap around over time, subtract
1324 * the last seq at which timeouts were flushed before comparing.
1325 * Assuming not more than 2^31-1 events have happened since,
1326 * these subtractions won't have wrapped, so we can check if
1327 * target is in [last_seq, current_seq] by comparing the two.
1329 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1330 events_got = seq - ctx->cq_last_tm_flush;
1331 if (events_got < events_needed)
1334 list_del_init(&req->timeout.list);
1335 io_kill_timeout(req);
1336 } while (!list_empty(&ctx->timeout_list));
1338 ctx->cq_last_tm_flush = seq;
1341 static void io_commit_cqring(struct io_ring_ctx *ctx)
1343 io_flush_timeouts(ctx);
1345 /* order cqe stores with ring update */
1346 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1348 if (unlikely(!list_empty(&ctx->defer_list)))
1349 __io_queue_deferred(ctx);
1352 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1354 struct io_rings *r = ctx->rings;
1356 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == r->sq_ring_entries;
1359 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1361 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1364 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1366 struct io_rings *rings = ctx->rings;
1370 * writes to the cq entry need to come after reading head; the
1371 * control dependency is enough as we're using WRITE_ONCE to
1374 if (__io_cqring_events(ctx) == rings->cq_ring_entries)
1377 tail = ctx->cached_cq_tail++;
1378 return &rings->cqes[tail & ctx->cq_mask];
1381 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1385 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1387 if (!ctx->eventfd_async)
1389 return io_wq_current_is_worker();
1392 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1394 /* see waitqueue_active() comment */
1397 if (waitqueue_active(&ctx->wait))
1398 wake_up(&ctx->wait);
1399 if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1400 wake_up(&ctx->sq_data->wait);
1401 if (io_should_trigger_evfd(ctx))
1402 eventfd_signal(ctx->cq_ev_fd, 1);
1403 if (waitqueue_active(&ctx->cq_wait)) {
1404 wake_up_interruptible(&ctx->cq_wait);
1405 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1409 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1411 /* see waitqueue_active() comment */
1414 if (ctx->flags & IORING_SETUP_SQPOLL) {
1415 if (waitqueue_active(&ctx->wait))
1416 wake_up(&ctx->wait);
1418 if (io_should_trigger_evfd(ctx))
1419 eventfd_signal(ctx->cq_ev_fd, 1);
1420 if (waitqueue_active(&ctx->cq_wait)) {
1421 wake_up_interruptible(&ctx->cq_wait);
1422 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1426 /* Returns true if there are no backlogged entries after the flush */
1427 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1428 struct task_struct *tsk,
1429 struct files_struct *files)
1431 struct io_rings *rings = ctx->rings;
1432 struct io_kiocb *req, *tmp;
1433 struct io_uring_cqe *cqe;
1434 unsigned long flags;
1435 bool all_flushed, posted;
1438 if (!force && __io_cqring_events(ctx) == rings->cq_ring_entries)
1442 spin_lock_irqsave(&ctx->completion_lock, flags);
1443 list_for_each_entry_safe(req, tmp, &ctx->cq_overflow_list, compl.list) {
1444 if (!io_match_task(req, tsk, files))
1447 cqe = io_get_cqring(ctx);
1451 list_move(&req->compl.list, &list);
1453 WRITE_ONCE(cqe->user_data, req->user_data);
1454 WRITE_ONCE(cqe->res, req->result);
1455 WRITE_ONCE(cqe->flags, req->compl.cflags);
1457 ctx->cached_cq_overflow++;
1458 WRITE_ONCE(ctx->rings->cq_overflow,
1459 ctx->cached_cq_overflow);
1464 all_flushed = list_empty(&ctx->cq_overflow_list);
1466 clear_bit(0, &ctx->sq_check_overflow);
1467 clear_bit(0, &ctx->cq_check_overflow);
1468 ctx->rings->sq_flags &= ~IORING_SQ_CQ_OVERFLOW;
1472 io_commit_cqring(ctx);
1473 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1475 io_cqring_ev_posted(ctx);
1477 while (!list_empty(&list)) {
1478 req = list_first_entry(&list, struct io_kiocb, compl.list);
1479 list_del(&req->compl.list);
1486 static void io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force,
1487 struct task_struct *tsk,
1488 struct files_struct *files)
1490 if (test_bit(0, &ctx->cq_check_overflow)) {
1491 /* iopoll syncs against uring_lock, not completion_lock */
1492 if (ctx->flags & IORING_SETUP_IOPOLL)
1493 mutex_lock(&ctx->uring_lock);
1494 __io_cqring_overflow_flush(ctx, force, tsk, files);
1495 if (ctx->flags & IORING_SETUP_IOPOLL)
1496 mutex_unlock(&ctx->uring_lock);
1500 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1502 struct io_ring_ctx *ctx = req->ctx;
1503 struct io_uring_cqe *cqe;
1505 trace_io_uring_complete(ctx, req->user_data, res);
1508 * If we can't get a cq entry, userspace overflowed the
1509 * submission (by quite a lot). Increment the overflow count in
1512 cqe = io_get_cqring(ctx);
1514 WRITE_ONCE(cqe->user_data, req->user_data);
1515 WRITE_ONCE(cqe->res, res);
1516 WRITE_ONCE(cqe->flags, cflags);
1517 } else if (ctx->cq_overflow_flushed ||
1518 atomic_read(&req->task->io_uring->in_idle)) {
1520 * If we're in ring overflow flush mode, or in task cancel mode,
1521 * then we cannot store the request for later flushing, we need
1522 * to drop it on the floor.
1524 ctx->cached_cq_overflow++;
1525 WRITE_ONCE(ctx->rings->cq_overflow, ctx->cached_cq_overflow);
1527 if (list_empty(&ctx->cq_overflow_list)) {
1528 set_bit(0, &ctx->sq_check_overflow);
1529 set_bit(0, &ctx->cq_check_overflow);
1530 ctx->rings->sq_flags |= IORING_SQ_CQ_OVERFLOW;
1534 req->compl.cflags = cflags;
1535 refcount_inc(&req->refs);
1536 list_add_tail(&req->compl.list, &ctx->cq_overflow_list);
1540 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1542 __io_cqring_fill_event(req, res, 0);
1545 static inline void io_req_complete_post(struct io_kiocb *req, long res,
1546 unsigned int cflags)
1548 struct io_ring_ctx *ctx = req->ctx;
1549 unsigned long flags;
1551 spin_lock_irqsave(&ctx->completion_lock, flags);
1552 __io_cqring_fill_event(req, res, cflags);
1553 io_commit_cqring(ctx);
1555 * If we're the last reference to this request, add to our locked
1558 if (refcount_dec_and_test(&req->refs)) {
1559 struct io_comp_state *cs = &ctx->submit_state.comp;
1561 io_dismantle_req(req);
1562 io_put_task(req->task, 1);
1563 list_add(&req->compl.list, &cs->locked_free_list);
1564 cs->locked_free_nr++;
1567 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1569 io_cqring_ev_posted(ctx);
1572 percpu_ref_put(&ctx->refs);
1576 static void io_req_complete_state(struct io_kiocb *req, long res,
1577 unsigned int cflags)
1581 req->compl.cflags = cflags;
1582 req->flags |= REQ_F_COMPLETE_INLINE;
1585 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1586 long res, unsigned cflags)
1588 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1589 io_req_complete_state(req, res, cflags);
1591 io_req_complete_post(req, res, cflags);
1594 static inline void io_req_complete(struct io_kiocb *req, long res)
1596 __io_req_complete(req, 0, res, 0);
1599 static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1601 struct io_submit_state *state = &ctx->submit_state;
1602 struct io_comp_state *cs = &state->comp;
1603 struct io_kiocb *req = NULL;
1606 * If we have more than a batch's worth of requests in our IRQ side
1607 * locked cache, grab the lock and move them over to our submission
1610 if (READ_ONCE(cs->locked_free_nr) > IO_COMPL_BATCH) {
1611 spin_lock_irq(&ctx->completion_lock);
1612 list_splice_init(&cs->locked_free_list, &cs->free_list);
1613 cs->locked_free_nr = 0;
1614 spin_unlock_irq(&ctx->completion_lock);
1617 while (!list_empty(&cs->free_list)) {
1618 req = list_first_entry(&cs->free_list, struct io_kiocb,
1620 list_del(&req->compl.list);
1621 state->reqs[state->free_reqs++] = req;
1622 if (state->free_reqs == ARRAY_SIZE(state->reqs))
1629 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1631 struct io_submit_state *state = &ctx->submit_state;
1633 BUILD_BUG_ON(IO_REQ_ALLOC_BATCH > ARRAY_SIZE(state->reqs));
1635 if (!state->free_reqs) {
1636 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1639 if (io_flush_cached_reqs(ctx))
1642 ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1646 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1647 * retry single alloc to be on the safe side.
1649 if (unlikely(ret <= 0)) {
1650 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1651 if (!state->reqs[0])
1655 state->free_reqs = ret;
1659 return state->reqs[state->free_reqs];
1662 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1669 static void io_dismantle_req(struct io_kiocb *req)
1673 if (req->async_data)
1674 kfree(req->async_data);
1676 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1677 if (req->fixed_rsrc_refs)
1678 percpu_ref_put(req->fixed_rsrc_refs);
1679 io_req_clean_work(req);
1682 static inline void io_put_task(struct task_struct *task, int nr)
1684 struct io_uring_task *tctx = task->io_uring;
1686 percpu_counter_sub(&tctx->inflight, nr);
1687 if (unlikely(atomic_read(&tctx->in_idle)))
1688 wake_up(&tctx->wait);
1689 put_task_struct_many(task, nr);
1692 static void __io_free_req(struct io_kiocb *req)
1694 struct io_ring_ctx *ctx = req->ctx;
1696 io_dismantle_req(req);
1697 io_put_task(req->task, 1);
1699 kmem_cache_free(req_cachep, req);
1700 percpu_ref_put(&ctx->refs);
1703 static inline void io_remove_next_linked(struct io_kiocb *req)
1705 struct io_kiocb *nxt = req->link;
1707 req->link = nxt->link;
1711 static void io_kill_linked_timeout(struct io_kiocb *req)
1713 struct io_ring_ctx *ctx = req->ctx;
1714 struct io_kiocb *link;
1715 bool cancelled = false;
1716 unsigned long flags;
1718 spin_lock_irqsave(&ctx->completion_lock, flags);
1722 * Can happen if a linked timeout fired and link had been like
1723 * req -> link t-out -> link t-out [-> ...]
1725 if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1726 struct io_timeout_data *io = link->async_data;
1729 io_remove_next_linked(req);
1730 link->timeout.head = NULL;
1731 ret = hrtimer_try_to_cancel(&io->timer);
1733 io_cqring_fill_event(link, -ECANCELED);
1734 io_commit_cqring(ctx);
1738 req->flags &= ~REQ_F_LINK_TIMEOUT;
1739 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1742 io_cqring_ev_posted(ctx);
1748 static void io_fail_links(struct io_kiocb *req)
1750 struct io_kiocb *link, *nxt;
1751 struct io_ring_ctx *ctx = req->ctx;
1752 unsigned long flags;
1754 spin_lock_irqsave(&ctx->completion_lock, flags);
1762 trace_io_uring_fail_link(req, link);
1763 io_cqring_fill_event(link, -ECANCELED);
1765 io_put_req_deferred(link, 2);
1768 io_commit_cqring(ctx);
1769 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1771 io_cqring_ev_posted(ctx);
1774 static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1776 if (req->flags & REQ_F_LINK_TIMEOUT)
1777 io_kill_linked_timeout(req);
1780 * If LINK is set, we have dependent requests in this chain. If we
1781 * didn't fail this request, queue the first one up, moving any other
1782 * dependencies to the next request. In case of failure, fail the rest
1785 if (likely(!(req->flags & REQ_F_FAIL_LINK))) {
1786 struct io_kiocb *nxt = req->link;
1795 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1797 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1799 return __io_req_find_next(req);
1802 static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1806 if (ctx->submit_state.comp.nr) {
1807 mutex_lock(&ctx->uring_lock);
1808 io_submit_flush_completions(&ctx->submit_state.comp, ctx);
1809 mutex_unlock(&ctx->uring_lock);
1811 percpu_ref_put(&ctx->refs);
1814 static bool __tctx_task_work(struct io_uring_task *tctx)
1816 struct io_ring_ctx *ctx = NULL;
1817 struct io_wq_work_list list;
1818 struct io_wq_work_node *node;
1820 if (wq_list_empty(&tctx->task_list))
1823 spin_lock_irq(&tctx->task_lock);
1824 list = tctx->task_list;
1825 INIT_WQ_LIST(&tctx->task_list);
1826 spin_unlock_irq(&tctx->task_lock);
1830 struct io_wq_work_node *next = node->next;
1831 struct io_kiocb *req;
1833 req = container_of(node, struct io_kiocb, io_task_work.node);
1834 if (req->ctx != ctx) {
1835 ctx_flush_and_put(ctx);
1837 percpu_ref_get(&ctx->refs);
1840 req->task_work.func(&req->task_work);
1844 ctx_flush_and_put(ctx);
1845 return list.first != NULL;
1848 static void tctx_task_work(struct callback_head *cb)
1850 struct io_uring_task *tctx = container_of(cb, struct io_uring_task, task_work);
1852 clear_bit(0, &tctx->task_state);
1854 while (__tctx_task_work(tctx))
1858 static int io_task_work_add(struct task_struct *tsk, struct io_kiocb *req,
1859 enum task_work_notify_mode notify)
1861 struct io_uring_task *tctx = tsk->io_uring;
1862 struct io_wq_work_node *node, *prev;
1863 unsigned long flags;
1866 WARN_ON_ONCE(!tctx);
1868 spin_lock_irqsave(&tctx->task_lock, flags);
1869 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
1870 spin_unlock_irqrestore(&tctx->task_lock, flags);
1872 /* task_work already pending, we're done */
1873 if (test_bit(0, &tctx->task_state) ||
1874 test_and_set_bit(0, &tctx->task_state))
1877 if (!task_work_add(tsk, &tctx->task_work, notify))
1881 * Slow path - we failed, find and delete work. if the work is not
1882 * in the list, it got run and we're fine.
1885 spin_lock_irqsave(&tctx->task_lock, flags);
1886 wq_list_for_each(node, prev, &tctx->task_list) {
1887 if (&req->io_task_work.node == node) {
1888 wq_list_del(&tctx->task_list, node, prev);
1893 spin_unlock_irqrestore(&tctx->task_lock, flags);
1894 clear_bit(0, &tctx->task_state);
1898 static int io_req_task_work_add(struct io_kiocb *req)
1900 struct task_struct *tsk = req->task;
1901 struct io_ring_ctx *ctx = req->ctx;
1902 enum task_work_notify_mode notify;
1905 if (tsk->flags & PF_EXITING)
1909 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
1910 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
1911 * processing task_work. There's no reliable way to tell if TWA_RESUME
1915 if (!(ctx->flags & IORING_SETUP_SQPOLL))
1916 notify = TWA_SIGNAL;
1918 ret = io_task_work_add(tsk, req, notify);
1920 wake_up_process(tsk);
1925 static void io_req_task_work_add_fallback(struct io_kiocb *req,
1926 task_work_func_t cb)
1928 struct io_ring_ctx *ctx = req->ctx;
1929 struct callback_head *head;
1931 init_task_work(&req->task_work, cb);
1933 head = READ_ONCE(ctx->exit_task_work);
1934 req->task_work.next = head;
1935 } while (cmpxchg(&ctx->exit_task_work, head, &req->task_work) != head);
1938 static void __io_req_task_cancel(struct io_kiocb *req, int error)
1940 struct io_ring_ctx *ctx = req->ctx;
1942 spin_lock_irq(&ctx->completion_lock);
1943 io_cqring_fill_event(req, error);
1944 io_commit_cqring(ctx);
1945 spin_unlock_irq(&ctx->completion_lock);
1947 io_cqring_ev_posted(ctx);
1948 req_set_fail_links(req);
1949 io_double_put_req(req);
1952 static void io_req_task_cancel(struct callback_head *cb)
1954 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1955 struct io_ring_ctx *ctx = req->ctx;
1957 mutex_lock(&ctx->uring_lock);
1958 __io_req_task_cancel(req, req->result);
1959 mutex_unlock(&ctx->uring_lock);
1960 percpu_ref_put(&ctx->refs);
1963 static void __io_req_task_submit(struct io_kiocb *req)
1965 struct io_ring_ctx *ctx = req->ctx;
1967 /* ctx stays valid until unlock, even if we drop all ours ctx->refs */
1968 mutex_lock(&ctx->uring_lock);
1969 if (!(current->flags & PF_EXITING) && !current->in_execve)
1970 __io_queue_sqe(req);
1972 __io_req_task_cancel(req, -EFAULT);
1973 mutex_unlock(&ctx->uring_lock);
1976 static void io_req_task_submit(struct callback_head *cb)
1978 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
1980 __io_req_task_submit(req);
1983 static void io_req_task_queue(struct io_kiocb *req)
1987 req->task_work.func = io_req_task_submit;
1988 ret = io_req_task_work_add(req);
1989 if (unlikely(ret)) {
1990 req->result = -ECANCELED;
1991 percpu_ref_get(&req->ctx->refs);
1992 io_req_task_work_add_fallback(req, io_req_task_cancel);
1996 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
1998 percpu_ref_get(&req->ctx->refs);
2000 req->task_work.func = io_req_task_cancel;
2002 if (unlikely(io_req_task_work_add(req)))
2003 io_req_task_work_add_fallback(req, io_req_task_cancel);
2006 static inline void io_queue_next(struct io_kiocb *req)
2008 struct io_kiocb *nxt = io_req_find_next(req);
2011 io_req_task_queue(nxt);
2014 static void io_free_req(struct io_kiocb *req)
2021 struct task_struct *task;
2026 static inline void io_init_req_batch(struct req_batch *rb)
2033 static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2034 struct req_batch *rb)
2037 io_put_task(rb->task, rb->task_refs);
2039 percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2042 static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2043 struct io_submit_state *state)
2047 if (req->task != rb->task) {
2049 io_put_task(rb->task, rb->task_refs);
2050 rb->task = req->task;
2056 io_dismantle_req(req);
2057 if (state->free_reqs != ARRAY_SIZE(state->reqs))
2058 state->reqs[state->free_reqs++] = req;
2060 list_add(&req->compl.list, &state->comp.free_list);
2063 static void io_submit_flush_completions(struct io_comp_state *cs,
2064 struct io_ring_ctx *ctx)
2067 struct io_kiocb *req;
2068 struct req_batch rb;
2070 io_init_req_batch(&rb);
2071 spin_lock_irq(&ctx->completion_lock);
2072 for (i = 0; i < nr; i++) {
2074 __io_cqring_fill_event(req, req->result, req->compl.cflags);
2076 io_commit_cqring(ctx);
2077 spin_unlock_irq(&ctx->completion_lock);
2079 io_cqring_ev_posted(ctx);
2080 for (i = 0; i < nr; i++) {
2083 /* submission and completion refs */
2084 if (refcount_sub_and_test(2, &req->refs))
2085 io_req_free_batch(&rb, req, &ctx->submit_state);
2088 io_req_free_batch_finish(ctx, &rb);
2093 * Drop reference to request, return next in chain (if there is one) if this
2094 * was the last reference to this request.
2096 static struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2098 struct io_kiocb *nxt = NULL;
2100 if (refcount_dec_and_test(&req->refs)) {
2101 nxt = io_req_find_next(req);
2107 static void io_put_req(struct io_kiocb *req)
2109 if (refcount_dec_and_test(&req->refs))
2113 static void io_put_req_deferred_cb(struct callback_head *cb)
2115 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2120 static void io_free_req_deferred(struct io_kiocb *req)
2124 req->task_work.func = io_put_req_deferred_cb;
2125 ret = io_req_task_work_add(req);
2127 io_req_task_work_add_fallback(req, io_put_req_deferred_cb);
2130 static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2132 if (refcount_sub_and_test(refs, &req->refs))
2133 io_free_req_deferred(req);
2136 static void io_double_put_req(struct io_kiocb *req)
2138 /* drop both submit and complete references */
2139 if (refcount_sub_and_test(2, &req->refs))
2143 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2145 /* See comment at the top of this file */
2147 return __io_cqring_events(ctx);
2150 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2152 struct io_rings *rings = ctx->rings;
2154 /* make sure SQ entry isn't read before tail */
2155 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2158 static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2160 unsigned int cflags;
2162 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2163 cflags |= IORING_CQE_F_BUFFER;
2164 req->flags &= ~REQ_F_BUFFER_SELECTED;
2169 static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2171 struct io_buffer *kbuf;
2173 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2174 return io_put_kbuf(req, kbuf);
2177 static inline bool io_run_task_work(void)
2180 * Not safe to run on exiting task, and the task_work handling will
2181 * not add work to such a task.
2183 if (unlikely(current->flags & PF_EXITING))
2185 if (current->task_works) {
2186 __set_current_state(TASK_RUNNING);
2195 * Find and free completed poll iocbs
2197 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2198 struct list_head *done)
2200 struct req_batch rb;
2201 struct io_kiocb *req;
2203 /* order with ->result store in io_complete_rw_iopoll() */
2206 io_init_req_batch(&rb);
2207 while (!list_empty(done)) {
2210 req = list_first_entry(done, struct io_kiocb, inflight_entry);
2211 list_del(&req->inflight_entry);
2213 if (READ_ONCE(req->result) == -EAGAIN) {
2214 req->iopoll_completed = 0;
2215 if (io_rw_reissue(req))
2219 if (req->flags & REQ_F_BUFFER_SELECTED)
2220 cflags = io_put_rw_kbuf(req);
2222 __io_cqring_fill_event(req, req->result, cflags);
2225 if (refcount_dec_and_test(&req->refs))
2226 io_req_free_batch(&rb, req, &ctx->submit_state);
2229 io_commit_cqring(ctx);
2230 io_cqring_ev_posted_iopoll(ctx);
2231 io_req_free_batch_finish(ctx, &rb);
2234 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2237 struct io_kiocb *req, *tmp;
2243 * Only spin for completions if we don't have multiple devices hanging
2244 * off our complete list, and we're under the requested amount.
2246 spin = !ctx->poll_multi_file && *nr_events < min;
2249 list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2250 struct kiocb *kiocb = &req->rw.kiocb;
2253 * Move completed and retryable entries to our local lists.
2254 * If we find a request that requires polling, break out
2255 * and complete those lists first, if we have entries there.
2257 if (READ_ONCE(req->iopoll_completed)) {
2258 list_move_tail(&req->inflight_entry, &done);
2261 if (!list_empty(&done))
2264 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2268 /* iopoll may have completed current req */
2269 if (READ_ONCE(req->iopoll_completed))
2270 list_move_tail(&req->inflight_entry, &done);
2277 if (!list_empty(&done))
2278 io_iopoll_complete(ctx, nr_events, &done);
2284 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
2285 * non-spinning poll check - we'll still enter the driver poll loop, but only
2286 * as a non-spinning completion check.
2288 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
2291 while (!list_empty(&ctx->iopoll_list) && !need_resched()) {
2294 ret = io_do_iopoll(ctx, nr_events, min);
2297 if (*nr_events >= min)
2305 * We can't just wait for polled events to come to us, we have to actively
2306 * find and complete them.
2308 static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2310 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2313 mutex_lock(&ctx->uring_lock);
2314 while (!list_empty(&ctx->iopoll_list)) {
2315 unsigned int nr_events = 0;
2317 io_do_iopoll(ctx, &nr_events, 0);
2319 /* let it sleep and repeat later if can't complete a request */
2323 * Ensure we allow local-to-the-cpu processing to take place,
2324 * in this case we need to ensure that we reap all events.
2325 * Also let task_work, etc. to progress by releasing the mutex
2327 if (need_resched()) {
2328 mutex_unlock(&ctx->uring_lock);
2330 mutex_lock(&ctx->uring_lock);
2333 mutex_unlock(&ctx->uring_lock);
2336 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2338 unsigned int nr_events = 0;
2339 int iters = 0, ret = 0;
2342 * We disallow the app entering submit/complete with polling, but we
2343 * still need to lock the ring to prevent racing with polled issue
2344 * that got punted to a workqueue.
2346 mutex_lock(&ctx->uring_lock);
2349 * Don't enter poll loop if we already have events pending.
2350 * If we do, we can potentially be spinning for commands that
2351 * already triggered a CQE (eg in error).
2353 if (test_bit(0, &ctx->cq_check_overflow))
2354 __io_cqring_overflow_flush(ctx, false, NULL, NULL);
2355 if (io_cqring_events(ctx))
2359 * If a submit got punted to a workqueue, we can have the
2360 * application entering polling for a command before it gets
2361 * issued. That app will hold the uring_lock for the duration
2362 * of the poll right here, so we need to take a breather every
2363 * now and then to ensure that the issue has a chance to add
2364 * the poll to the issued list. Otherwise we can spin here
2365 * forever, while the workqueue is stuck trying to acquire the
2368 if (!(++iters & 7)) {
2369 mutex_unlock(&ctx->uring_lock);
2371 mutex_lock(&ctx->uring_lock);
2374 ret = io_iopoll_getevents(ctx, &nr_events, min);
2378 } while (min && !nr_events && !need_resched());
2380 mutex_unlock(&ctx->uring_lock);
2384 static void kiocb_end_write(struct io_kiocb *req)
2387 * Tell lockdep we inherited freeze protection from submission
2390 if (req->flags & REQ_F_ISREG) {
2391 struct inode *inode = file_inode(req->file);
2393 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2395 file_end_write(req->file);
2399 static bool io_resubmit_prep(struct io_kiocb *req)
2401 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2403 struct iov_iter iter;
2405 /* already prepared */
2406 if (req->async_data)
2409 switch (req->opcode) {
2410 case IORING_OP_READV:
2411 case IORING_OP_READ_FIXED:
2412 case IORING_OP_READ:
2415 case IORING_OP_WRITEV:
2416 case IORING_OP_WRITE_FIXED:
2417 case IORING_OP_WRITE:
2421 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2426 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2429 return !io_setup_async_rw(req, iovec, inline_vecs, &iter, false);
2433 static bool io_rw_reissue(struct io_kiocb *req)
2436 umode_t mode = file_inode(req->file)->i_mode;
2438 if (!S_ISBLK(mode) && !S_ISREG(mode))
2440 if ((req->flags & REQ_F_NOWAIT) || io_wq_current_is_worker())
2443 * If ref is dying, we might be running poll reap from the exit work.
2444 * Don't attempt to reissue from that path, just let it fail with
2447 if (percpu_ref_is_dying(&req->ctx->refs))
2450 lockdep_assert_held(&req->ctx->uring_lock);
2452 if (io_resubmit_prep(req)) {
2453 refcount_inc(&req->refs);
2454 io_queue_async_work(req);
2457 req_set_fail_links(req);
2462 static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2463 unsigned int issue_flags)
2467 if ((res == -EAGAIN || res == -EOPNOTSUPP) && io_rw_reissue(req))
2469 if (res != req->result)
2470 req_set_fail_links(req);
2472 if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2473 kiocb_end_write(req);
2474 if (req->flags & REQ_F_BUFFER_SELECTED)
2475 cflags = io_put_rw_kbuf(req);
2476 __io_req_complete(req, issue_flags, res, cflags);
2479 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2481 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2483 __io_complete_rw(req, res, res2, 0);
2486 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2488 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2490 if (kiocb->ki_flags & IOCB_WRITE)
2491 kiocb_end_write(req);
2493 if (res != -EAGAIN && res != req->result)
2494 req_set_fail_links(req);
2496 WRITE_ONCE(req->result, res);
2497 /* order with io_poll_complete() checking ->result */
2499 WRITE_ONCE(req->iopoll_completed, 1);
2503 * After the iocb has been issued, it's safe to be found on the poll list.
2504 * Adding the kiocb to the list AFTER submission ensures that we don't
2505 * find it from a io_iopoll_getevents() thread before the issuer is done
2506 * accessing the kiocb cookie.
2508 static void io_iopoll_req_issued(struct io_kiocb *req, bool in_async)
2510 struct io_ring_ctx *ctx = req->ctx;
2513 * Track whether we have multiple files in our lists. This will impact
2514 * how we do polling eventually, not spinning if we're on potentially
2515 * different devices.
2517 if (list_empty(&ctx->iopoll_list)) {
2518 ctx->poll_multi_file = false;
2519 } else if (!ctx->poll_multi_file) {
2520 struct io_kiocb *list_req;
2522 list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2524 if (list_req->file != req->file)
2525 ctx->poll_multi_file = true;
2529 * For fast devices, IO may have already completed. If it has, add
2530 * it to the front so we find it first.
2532 if (READ_ONCE(req->iopoll_completed))
2533 list_add(&req->inflight_entry, &ctx->iopoll_list);
2535 list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2538 * If IORING_SETUP_SQPOLL is enabled, sqes are either handled in sq thread
2539 * task context or in io worker task context. If current task context is
2540 * sq thread, we don't need to check whether should wake up sq thread.
2542 if (in_async && (ctx->flags & IORING_SETUP_SQPOLL) &&
2543 wq_has_sleeper(&ctx->sq_data->wait))
2544 wake_up(&ctx->sq_data->wait);
2547 static inline void io_state_file_put(struct io_submit_state *state)
2549 if (state->file_refs) {
2550 fput_many(state->file, state->file_refs);
2551 state->file_refs = 0;
2556 * Get as many references to a file as we have IOs left in this submission,
2557 * assuming most submissions are for one file, or at least that each file
2558 * has more than one submission.
2560 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2565 if (state->file_refs) {
2566 if (state->fd == fd) {
2570 io_state_file_put(state);
2572 state->file = fget_many(fd, state->ios_left);
2573 if (unlikely(!state->file))
2577 state->file_refs = state->ios_left - 1;
2581 static bool io_bdev_nowait(struct block_device *bdev)
2583 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2587 * If we tracked the file through the SCM inflight mechanism, we could support
2588 * any file. For now, just ensure that anything potentially problematic is done
2591 static bool io_file_supports_async(struct file *file, int rw)
2593 umode_t mode = file_inode(file)->i_mode;
2595 if (S_ISBLK(mode)) {
2596 if (IS_ENABLED(CONFIG_BLOCK) &&
2597 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2601 if (S_ISCHR(mode) || S_ISSOCK(mode))
2603 if (S_ISREG(mode)) {
2604 if (IS_ENABLED(CONFIG_BLOCK) &&
2605 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2606 file->f_op != &io_uring_fops)
2611 /* any ->read/write should understand O_NONBLOCK */
2612 if (file->f_flags & O_NONBLOCK)
2615 if (!(file->f_mode & FMODE_NOWAIT))
2619 return file->f_op->read_iter != NULL;
2621 return file->f_op->write_iter != NULL;
2624 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2626 struct io_ring_ctx *ctx = req->ctx;
2627 struct kiocb *kiocb = &req->rw.kiocb;
2628 struct file *file = req->file;
2632 if (S_ISREG(file_inode(file)->i_mode))
2633 req->flags |= REQ_F_ISREG;
2635 kiocb->ki_pos = READ_ONCE(sqe->off);
2636 if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2637 req->flags |= REQ_F_CUR_POS;
2638 kiocb->ki_pos = file->f_pos;
2640 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2641 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2642 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2646 /* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2647 if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2648 req->flags |= REQ_F_NOWAIT;
2650 ioprio = READ_ONCE(sqe->ioprio);
2652 ret = ioprio_check_cap(ioprio);
2656 kiocb->ki_ioprio = ioprio;
2658 kiocb->ki_ioprio = get_current_ioprio();
2660 if (ctx->flags & IORING_SETUP_IOPOLL) {
2661 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2662 !kiocb->ki_filp->f_op->iopoll)
2665 kiocb->ki_flags |= IOCB_HIPRI;
2666 kiocb->ki_complete = io_complete_rw_iopoll;
2667 req->iopoll_completed = 0;
2669 if (kiocb->ki_flags & IOCB_HIPRI)
2671 kiocb->ki_complete = io_complete_rw;
2674 req->rw.addr = READ_ONCE(sqe->addr);
2675 req->rw.len = READ_ONCE(sqe->len);
2676 req->buf_index = READ_ONCE(sqe->buf_index);
2680 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2686 case -ERESTARTNOINTR:
2687 case -ERESTARTNOHAND:
2688 case -ERESTART_RESTARTBLOCK:
2690 * We can't just restart the syscall, since previously
2691 * submitted sqes may already be in progress. Just fail this
2697 kiocb->ki_complete(kiocb, ret, 0);
2701 static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2702 unsigned int issue_flags)
2704 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2705 struct io_async_rw *io = req->async_data;
2707 /* add previously done IO, if any */
2708 if (io && io->bytes_done > 0) {
2710 ret = io->bytes_done;
2712 ret += io->bytes_done;
2715 if (req->flags & REQ_F_CUR_POS)
2716 req->file->f_pos = kiocb->ki_pos;
2717 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2718 __io_complete_rw(req, ret, 0, issue_flags);
2720 io_rw_done(kiocb, ret);
2723 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2725 struct io_ring_ctx *ctx = req->ctx;
2726 size_t len = req->rw.len;
2727 struct io_mapped_ubuf *imu;
2728 u16 index, buf_index = req->buf_index;
2732 if (unlikely(buf_index >= ctx->nr_user_bufs))
2734 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2735 imu = &ctx->user_bufs[index];
2736 buf_addr = req->rw.addr;
2739 if (buf_addr + len < buf_addr)
2741 /* not inside the mapped region */
2742 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2746 * May not be a start of buffer, set size appropriately
2747 * and advance us to the beginning.
2749 offset = buf_addr - imu->ubuf;
2750 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2754 * Don't use iov_iter_advance() here, as it's really slow for
2755 * using the latter parts of a big fixed buffer - it iterates
2756 * over each segment manually. We can cheat a bit here, because
2759 * 1) it's a BVEC iter, we set it up
2760 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2761 * first and last bvec
2763 * So just find our index, and adjust the iterator afterwards.
2764 * If the offset is within the first bvec (or the whole first
2765 * bvec, just use iov_iter_advance(). This makes it easier
2766 * since we can just skip the first segment, which may not
2767 * be PAGE_SIZE aligned.
2769 const struct bio_vec *bvec = imu->bvec;
2771 if (offset <= bvec->bv_len) {
2772 iov_iter_advance(iter, offset);
2774 unsigned long seg_skip;
2776 /* skip first vec */
2777 offset -= bvec->bv_len;
2778 seg_skip = 1 + (offset >> PAGE_SHIFT);
2780 iter->bvec = bvec + seg_skip;
2781 iter->nr_segs -= seg_skip;
2782 iter->count -= bvec->bv_len + offset;
2783 iter->iov_offset = offset & ~PAGE_MASK;
2790 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2793 mutex_unlock(&ctx->uring_lock);
2796 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2799 * "Normal" inline submissions always hold the uring_lock, since we
2800 * grab it from the system call. Same is true for the SQPOLL offload.
2801 * The only exception is when we've detached the request and issue it
2802 * from an async worker thread, grab the lock for that case.
2805 mutex_lock(&ctx->uring_lock);
2808 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2809 int bgid, struct io_buffer *kbuf,
2812 struct io_buffer *head;
2814 if (req->flags & REQ_F_BUFFER_SELECTED)
2817 io_ring_submit_lock(req->ctx, needs_lock);
2819 lockdep_assert_held(&req->ctx->uring_lock);
2821 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2823 if (!list_empty(&head->list)) {
2824 kbuf = list_last_entry(&head->list, struct io_buffer,
2826 list_del(&kbuf->list);
2829 idr_remove(&req->ctx->io_buffer_idr, bgid);
2831 if (*len > kbuf->len)
2834 kbuf = ERR_PTR(-ENOBUFS);
2837 io_ring_submit_unlock(req->ctx, needs_lock);
2842 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2845 struct io_buffer *kbuf;
2848 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2849 bgid = req->buf_index;
2850 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2853 req->rw.addr = (u64) (unsigned long) kbuf;
2854 req->flags |= REQ_F_BUFFER_SELECTED;
2855 return u64_to_user_ptr(kbuf->addr);
2858 #ifdef CONFIG_COMPAT
2859 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2862 struct compat_iovec __user *uiov;
2863 compat_ssize_t clen;
2867 uiov = u64_to_user_ptr(req->rw.addr);
2868 if (!access_ok(uiov, sizeof(*uiov)))
2870 if (__get_user(clen, &uiov->iov_len))
2876 buf = io_rw_buffer_select(req, &len, needs_lock);
2878 return PTR_ERR(buf);
2879 iov[0].iov_base = buf;
2880 iov[0].iov_len = (compat_size_t) len;
2885 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2888 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2892 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2895 len = iov[0].iov_len;
2898 buf = io_rw_buffer_select(req, &len, needs_lock);
2900 return PTR_ERR(buf);
2901 iov[0].iov_base = buf;
2902 iov[0].iov_len = len;
2906 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2909 if (req->flags & REQ_F_BUFFER_SELECTED) {
2910 struct io_buffer *kbuf;
2912 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2913 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2914 iov[0].iov_len = kbuf->len;
2917 if (req->rw.len != 1)
2920 #ifdef CONFIG_COMPAT
2921 if (req->ctx->compat)
2922 return io_compat_import(req, iov, needs_lock);
2925 return __io_iov_buffer_select(req, iov, needs_lock);
2928 static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2929 struct iov_iter *iter, bool needs_lock)
2931 void __user *buf = u64_to_user_ptr(req->rw.addr);
2932 size_t sqe_len = req->rw.len;
2933 u8 opcode = req->opcode;
2936 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2938 return io_import_fixed(req, rw, iter);
2941 /* buffer index only valid with fixed read/write, or buffer select */
2942 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2945 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2946 if (req->flags & REQ_F_BUFFER_SELECT) {
2947 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2949 return PTR_ERR(buf);
2950 req->rw.len = sqe_len;
2953 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2958 if (req->flags & REQ_F_BUFFER_SELECT) {
2959 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2961 iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
2966 return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
2970 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
2972 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
2976 * For files that don't have ->read_iter() and ->write_iter(), handle them
2977 * by looping over ->read() or ->write() manually.
2979 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
2981 struct kiocb *kiocb = &req->rw.kiocb;
2982 struct file *file = req->file;
2986 * Don't support polled IO through this interface, and we can't
2987 * support non-blocking either. For the latter, this just causes
2988 * the kiocb to be handled from an async context.
2990 if (kiocb->ki_flags & IOCB_HIPRI)
2992 if (kiocb->ki_flags & IOCB_NOWAIT)
2995 while (iov_iter_count(iter)) {
2999 if (!iov_iter_is_bvec(iter)) {
3000 iovec = iov_iter_iovec(iter);
3002 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3003 iovec.iov_len = req->rw.len;
3007 nr = file->f_op->read(file, iovec.iov_base,
3008 iovec.iov_len, io_kiocb_ppos(kiocb));
3010 nr = file->f_op->write(file, iovec.iov_base,
3011 iovec.iov_len, io_kiocb_ppos(kiocb));
3020 if (nr != iovec.iov_len)
3024 iov_iter_advance(iter, nr);
3030 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3031 const struct iovec *fast_iov, struct iov_iter *iter)
3033 struct io_async_rw *rw = req->async_data;
3035 memcpy(&rw->iter, iter, sizeof(*iter));
3036 rw->free_iovec = iovec;
3038 /* can only be fixed buffers, no need to do anything */
3039 if (iov_iter_is_bvec(iter))
3042 unsigned iov_off = 0;
3044 rw->iter.iov = rw->fast_iov;
3045 if (iter->iov != fast_iov) {
3046 iov_off = iter->iov - fast_iov;
3047 rw->iter.iov += iov_off;
3049 if (rw->fast_iov != fast_iov)
3050 memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3051 sizeof(struct iovec) * iter->nr_segs);
3053 req->flags |= REQ_F_NEED_CLEANUP;
3057 static inline int __io_alloc_async_data(struct io_kiocb *req)
3059 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3060 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3061 return req->async_data == NULL;
3064 static int io_alloc_async_data(struct io_kiocb *req)
3066 if (!io_op_defs[req->opcode].needs_async_data)
3069 return __io_alloc_async_data(req);
3072 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3073 const struct iovec *fast_iov,
3074 struct iov_iter *iter, bool force)
3076 if (!force && !io_op_defs[req->opcode].needs_async_data)
3078 if (!req->async_data) {
3079 if (__io_alloc_async_data(req)) {
3084 io_req_map_rw(req, iovec, fast_iov, iter);
3089 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3091 struct io_async_rw *iorw = req->async_data;
3092 struct iovec *iov = iorw->fast_iov;
3095 ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3096 if (unlikely(ret < 0))
3099 iorw->bytes_done = 0;
3100 iorw->free_iovec = iov;
3102 req->flags |= REQ_F_NEED_CLEANUP;
3106 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3108 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3110 return io_prep_rw(req, sqe);
3114 * This is our waitqueue callback handler, registered through lock_page_async()
3115 * when we initially tried to do the IO with the iocb armed our waitqueue.
3116 * This gets called when the page is unlocked, and we generally expect that to
3117 * happen when the page IO is completed and the page is now uptodate. This will
3118 * queue a task_work based retry of the operation, attempting to copy the data
3119 * again. If the latter fails because the page was NOT uptodate, then we will
3120 * do a thread based blocking retry of the operation. That's the unexpected
3123 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3124 int sync, void *arg)
3126 struct wait_page_queue *wpq;
3127 struct io_kiocb *req = wait->private;
3128 struct wait_page_key *key = arg;
3130 wpq = container_of(wait, struct wait_page_queue, wait);
3132 if (!wake_page_match(wpq, key))
3135 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3136 list_del_init(&wait->entry);
3138 /* submit ref gets dropped, acquire a new one */
3139 refcount_inc(&req->refs);
3140 io_req_task_queue(req);
3145 * This controls whether a given IO request should be armed for async page
3146 * based retry. If we return false here, the request is handed to the async
3147 * worker threads for retry. If we're doing buffered reads on a regular file,
3148 * we prepare a private wait_page_queue entry and retry the operation. This
3149 * will either succeed because the page is now uptodate and unlocked, or it
3150 * will register a callback when the page is unlocked at IO completion. Through
3151 * that callback, io_uring uses task_work to setup a retry of the operation.
3152 * That retry will attempt the buffered read again. The retry will generally
3153 * succeed, or in rare cases where it fails, we then fall back to using the
3154 * async worker threads for a blocking retry.
3156 static bool io_rw_should_retry(struct io_kiocb *req)
3158 struct io_async_rw *rw = req->async_data;
3159 struct wait_page_queue *wait = &rw->wpq;
3160 struct kiocb *kiocb = &req->rw.kiocb;
3162 /* never retry for NOWAIT, we just complete with -EAGAIN */
3163 if (req->flags & REQ_F_NOWAIT)
3166 /* Only for buffered IO */
3167 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3171 * just use poll if we can, and don't attempt if the fs doesn't
3172 * support callback based unlocks
3174 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3177 wait->wait.func = io_async_buf_func;
3178 wait->wait.private = req;
3179 wait->wait.flags = 0;
3180 INIT_LIST_HEAD(&wait->wait.entry);
3181 kiocb->ki_flags |= IOCB_WAITQ;
3182 kiocb->ki_flags &= ~IOCB_NOWAIT;
3183 kiocb->ki_waitq = wait;
3187 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3189 if (req->file->f_op->read_iter)
3190 return call_read_iter(req->file, &req->rw.kiocb, iter);
3191 else if (req->file->f_op->read)
3192 return loop_rw_iter(READ, req, iter);
3197 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3199 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3200 struct kiocb *kiocb = &req->rw.kiocb;
3201 struct iov_iter __iter, *iter = &__iter;
3202 struct io_async_rw *rw = req->async_data;
3203 ssize_t io_size, ret, ret2;
3204 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3210 ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3214 io_size = iov_iter_count(iter);
3215 req->result = io_size;
3217 /* Ensure we clear previously set non-block flag */
3218 if (!force_nonblock)
3219 kiocb->ki_flags &= ~IOCB_NOWAIT;
3221 kiocb->ki_flags |= IOCB_NOWAIT;
3223 /* If the file doesn't support async, just async punt */
3224 if (force_nonblock && !io_file_supports_async(req->file, READ)) {
3225 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3226 return ret ?: -EAGAIN;
3229 ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3230 if (unlikely(ret)) {
3235 ret = io_iter_do_read(req, iter);
3237 if (ret == -EIOCBQUEUED) {
3239 } else if (ret == -EAGAIN) {
3240 /* IOPOLL retry should happen for io-wq threads */
3241 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3243 /* no retry on NONBLOCK nor RWF_NOWAIT */
3244 if (req->flags & REQ_F_NOWAIT)
3246 /* some cases will consume bytes even on error returns */
3247 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3249 } else if (ret <= 0 || ret == io_size || !force_nonblock ||
3250 (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3251 /* read all, failed, already did sync or don't want to retry */
3255 ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3260 rw = req->async_data;
3261 /* now use our persistent iterator, if we aren't already */
3266 rw->bytes_done += ret;
3267 /* if we can retry, do so with the callbacks armed */
3268 if (!io_rw_should_retry(req)) {
3269 kiocb->ki_flags &= ~IOCB_WAITQ;
3274 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3275 * we get -EIOCBQUEUED, then we'll get a notification when the
3276 * desired page gets unlocked. We can also get a partial read
3277 * here, and if we do, then just retry at the new offset.
3279 ret = io_iter_do_read(req, iter);
3280 if (ret == -EIOCBQUEUED)
3282 /* we got some bytes, but not all. retry. */
3283 } while (ret > 0 && ret < io_size);
3285 kiocb_done(kiocb, ret, issue_flags);
3287 /* it's faster to check here then delegate to kfree */
3293 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3295 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3297 return io_prep_rw(req, sqe);
3300 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3302 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3303 struct kiocb *kiocb = &req->rw.kiocb;
3304 struct iov_iter __iter, *iter = &__iter;
3305 struct io_async_rw *rw = req->async_data;
3306 ssize_t ret, ret2, io_size;
3307 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3313 ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3317 io_size = iov_iter_count(iter);
3318 req->result = io_size;
3320 /* Ensure we clear previously set non-block flag */
3321 if (!force_nonblock)
3322 kiocb->ki_flags &= ~IOCB_NOWAIT;
3324 kiocb->ki_flags |= IOCB_NOWAIT;
3326 /* If the file doesn't support async, just async punt */
3327 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3330 /* file path doesn't support NOWAIT for non-direct_IO */
3331 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3332 (req->flags & REQ_F_ISREG))
3335 ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3340 * Open-code file_start_write here to grab freeze protection,
3341 * which will be released by another thread in
3342 * io_complete_rw(). Fool lockdep by telling it the lock got
3343 * released so that it doesn't complain about the held lock when
3344 * we return to userspace.
3346 if (req->flags & REQ_F_ISREG) {
3347 sb_start_write(file_inode(req->file)->i_sb);
3348 __sb_writers_release(file_inode(req->file)->i_sb,
3351 kiocb->ki_flags |= IOCB_WRITE;
3353 if (req->file->f_op->write_iter)
3354 ret2 = call_write_iter(req->file, kiocb, iter);
3355 else if (req->file->f_op->write)
3356 ret2 = loop_rw_iter(WRITE, req, iter);
3361 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3362 * retry them without IOCB_NOWAIT.
3364 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3366 /* no retry on NONBLOCK nor RWF_NOWAIT */
3367 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3369 if (!force_nonblock || ret2 != -EAGAIN) {
3370 /* IOPOLL retry should happen for io-wq threads */
3371 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3374 kiocb_done(kiocb, ret2, issue_flags);
3377 /* some cases will consume bytes even on error returns */
3378 iov_iter_revert(iter, io_size - iov_iter_count(iter));
3379 ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3380 return ret ?: -EAGAIN;
3383 /* it's reportedly faster than delegating the null check to kfree() */
3389 static int io_renameat_prep(struct io_kiocb *req,
3390 const struct io_uring_sqe *sqe)
3392 struct io_rename *ren = &req->rename;
3393 const char __user *oldf, *newf;
3395 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3398 ren->old_dfd = READ_ONCE(sqe->fd);
3399 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3400 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3401 ren->new_dfd = READ_ONCE(sqe->len);
3402 ren->flags = READ_ONCE(sqe->rename_flags);
3404 ren->oldpath = getname(oldf);
3405 if (IS_ERR(ren->oldpath))
3406 return PTR_ERR(ren->oldpath);
3408 ren->newpath = getname(newf);
3409 if (IS_ERR(ren->newpath)) {
3410 putname(ren->oldpath);
3411 return PTR_ERR(ren->newpath);
3414 req->flags |= REQ_F_NEED_CLEANUP;
3418 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3420 struct io_rename *ren = &req->rename;
3423 if (issue_flags & IO_URING_F_NONBLOCK)
3426 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3427 ren->newpath, ren->flags);
3429 req->flags &= ~REQ_F_NEED_CLEANUP;
3431 req_set_fail_links(req);
3432 io_req_complete(req, ret);
3436 static int io_unlinkat_prep(struct io_kiocb *req,
3437 const struct io_uring_sqe *sqe)
3439 struct io_unlink *un = &req->unlink;
3440 const char __user *fname;
3442 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3445 un->dfd = READ_ONCE(sqe->fd);
3447 un->flags = READ_ONCE(sqe->unlink_flags);
3448 if (un->flags & ~AT_REMOVEDIR)
3451 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3452 un->filename = getname(fname);
3453 if (IS_ERR(un->filename))
3454 return PTR_ERR(un->filename);
3456 req->flags |= REQ_F_NEED_CLEANUP;
3460 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3462 struct io_unlink *un = &req->unlink;
3465 if (issue_flags & IO_URING_F_NONBLOCK)
3468 if (un->flags & AT_REMOVEDIR)
3469 ret = do_rmdir(un->dfd, un->filename);
3471 ret = do_unlinkat(un->dfd, un->filename);
3473 req->flags &= ~REQ_F_NEED_CLEANUP;
3475 req_set_fail_links(req);
3476 io_req_complete(req, ret);
3480 static int io_shutdown_prep(struct io_kiocb *req,
3481 const struct io_uring_sqe *sqe)
3483 #if defined(CONFIG_NET)
3484 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3486 if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3490 req->shutdown.how = READ_ONCE(sqe->len);
3497 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3499 #if defined(CONFIG_NET)
3500 struct socket *sock;
3503 if (issue_flags & IO_URING_F_NONBLOCK)
3506 sock = sock_from_file(req->file);
3507 if (unlikely(!sock))
3510 ret = __sys_shutdown_sock(sock, req->shutdown.how);
3512 req_set_fail_links(req);
3513 io_req_complete(req, ret);
3520 static int __io_splice_prep(struct io_kiocb *req,
3521 const struct io_uring_sqe *sqe)
3523 struct io_splice* sp = &req->splice;
3524 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3526 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3530 sp->len = READ_ONCE(sqe->len);
3531 sp->flags = READ_ONCE(sqe->splice_flags);
3533 if (unlikely(sp->flags & ~valid_flags))
3536 sp->file_in = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in),
3537 (sp->flags & SPLICE_F_FD_IN_FIXED));
3540 req->flags |= REQ_F_NEED_CLEANUP;
3542 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3544 * Splice operation will be punted aync, and here need to
3545 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3547 req->work.flags |= IO_WQ_WORK_UNBOUND;
3553 static int io_tee_prep(struct io_kiocb *req,
3554 const struct io_uring_sqe *sqe)
3556 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3558 return __io_splice_prep(req, sqe);
3561 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3563 struct io_splice *sp = &req->splice;
3564 struct file *in = sp->file_in;
3565 struct file *out = sp->file_out;
3566 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3569 if (issue_flags & IO_URING_F_NONBLOCK)
3572 ret = do_tee(in, out, sp->len, flags);
3574 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3575 req->flags &= ~REQ_F_NEED_CLEANUP;
3578 req_set_fail_links(req);
3579 io_req_complete(req, ret);
3583 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3585 struct io_splice* sp = &req->splice;
3587 sp->off_in = READ_ONCE(sqe->splice_off_in);
3588 sp->off_out = READ_ONCE(sqe->off);
3589 return __io_splice_prep(req, sqe);
3592 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3594 struct io_splice *sp = &req->splice;
3595 struct file *in = sp->file_in;
3596 struct file *out = sp->file_out;
3597 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3598 loff_t *poff_in, *poff_out;
3601 if (issue_flags & IO_URING_F_NONBLOCK)
3604 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3605 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3608 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3610 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3611 req->flags &= ~REQ_F_NEED_CLEANUP;
3614 req_set_fail_links(req);
3615 io_req_complete(req, ret);
3620 * IORING_OP_NOP just posts a completion event, nothing else.
3622 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3624 struct io_ring_ctx *ctx = req->ctx;
3626 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3629 __io_req_complete(req, issue_flags, 0, 0);
3633 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3635 struct io_ring_ctx *ctx = req->ctx;
3640 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3642 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3645 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3646 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3649 req->sync.off = READ_ONCE(sqe->off);
3650 req->sync.len = READ_ONCE(sqe->len);
3654 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3656 loff_t end = req->sync.off + req->sync.len;
3659 /* fsync always requires a blocking context */
3660 if (issue_flags & IO_URING_F_NONBLOCK)
3663 ret = vfs_fsync_range(req->file, req->sync.off,
3664 end > 0 ? end : LLONG_MAX,
3665 req->sync.flags & IORING_FSYNC_DATASYNC);
3667 req_set_fail_links(req);
3668 io_req_complete(req, ret);
3672 static int io_fallocate_prep(struct io_kiocb *req,
3673 const struct io_uring_sqe *sqe)
3675 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3677 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3680 req->sync.off = READ_ONCE(sqe->off);
3681 req->sync.len = READ_ONCE(sqe->addr);
3682 req->sync.mode = READ_ONCE(sqe->len);
3686 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3690 /* fallocate always requiring blocking context */
3691 if (issue_flags & IO_URING_F_NONBLOCK)
3693 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3696 req_set_fail_links(req);
3697 io_req_complete(req, ret);
3701 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3703 const char __user *fname;
3706 if (unlikely(sqe->ioprio || sqe->buf_index))
3708 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3711 /* open.how should be already initialised */
3712 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3713 req->open.how.flags |= O_LARGEFILE;
3715 req->open.dfd = READ_ONCE(sqe->fd);
3716 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3717 req->open.filename = getname(fname);
3718 if (IS_ERR(req->open.filename)) {
3719 ret = PTR_ERR(req->open.filename);
3720 req->open.filename = NULL;
3723 req->open.nofile = rlimit(RLIMIT_NOFILE);
3724 req->flags |= REQ_F_NEED_CLEANUP;
3728 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3732 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3734 mode = READ_ONCE(sqe->len);
3735 flags = READ_ONCE(sqe->open_flags);
3736 req->open.how = build_open_how(flags, mode);
3737 return __io_openat_prep(req, sqe);
3740 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3742 struct open_how __user *how;
3746 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3748 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3749 len = READ_ONCE(sqe->len);
3750 if (len < OPEN_HOW_SIZE_VER0)
3753 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3758 return __io_openat_prep(req, sqe);
3761 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3763 struct open_flags op;
3766 bool resolve_nonblock;
3769 ret = build_open_flags(&req->open.how, &op);
3772 nonblock_set = op.open_flag & O_NONBLOCK;
3773 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3774 if (issue_flags & IO_URING_F_NONBLOCK) {
3776 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3777 * it'll always -EAGAIN
3779 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3781 op.lookup_flags |= LOOKUP_CACHED;
3782 op.open_flag |= O_NONBLOCK;
3785 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3789 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3790 /* only retry if RESOLVE_CACHED wasn't already set by application */
3791 if ((!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)) &&
3792 file == ERR_PTR(-EAGAIN)) {
3794 * We could hang on to this 'fd', but seems like marginal
3795 * gain for something that is now known to be a slower path.
3796 * So just put it, and we'll get a new one when we retry.
3804 ret = PTR_ERR(file);
3806 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3807 file->f_flags &= ~O_NONBLOCK;
3808 fsnotify_open(file);
3809 fd_install(ret, file);
3812 putname(req->open.filename);
3813 req->flags &= ~REQ_F_NEED_CLEANUP;
3815 req_set_fail_links(req);
3816 io_req_complete(req, ret);
3820 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3822 return io_openat2(req, issue_flags & IO_URING_F_NONBLOCK);
3825 static int io_remove_buffers_prep(struct io_kiocb *req,
3826 const struct io_uring_sqe *sqe)
3828 struct io_provide_buf *p = &req->pbuf;
3831 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3834 tmp = READ_ONCE(sqe->fd);
3835 if (!tmp || tmp > USHRT_MAX)
3838 memset(p, 0, sizeof(*p));
3840 p->bgid = READ_ONCE(sqe->buf_group);
3844 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3845 int bgid, unsigned nbufs)
3849 /* shouldn't happen */
3853 /* the head kbuf is the list itself */
3854 while (!list_empty(&buf->list)) {
3855 struct io_buffer *nxt;
3857 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3858 list_del(&nxt->list);
3865 idr_remove(&ctx->io_buffer_idr, bgid);
3870 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3872 struct io_provide_buf *p = &req->pbuf;
3873 struct io_ring_ctx *ctx = req->ctx;
3874 struct io_buffer *head;
3876 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3878 io_ring_submit_lock(ctx, !force_nonblock);
3880 lockdep_assert_held(&ctx->uring_lock);
3883 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3885 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3887 req_set_fail_links(req);
3889 /* need to hold the lock to complete IOPOLL requests */
3890 if (ctx->flags & IORING_SETUP_IOPOLL) {
3891 __io_req_complete(req, issue_flags, ret, 0);
3892 io_ring_submit_unlock(ctx, !force_nonblock);
3894 io_ring_submit_unlock(ctx, !force_nonblock);
3895 __io_req_complete(req, issue_flags, ret, 0);
3900 static int io_provide_buffers_prep(struct io_kiocb *req,
3901 const struct io_uring_sqe *sqe)
3903 struct io_provide_buf *p = &req->pbuf;
3906 if (sqe->ioprio || sqe->rw_flags)
3909 tmp = READ_ONCE(sqe->fd);
3910 if (!tmp || tmp > USHRT_MAX)
3913 p->addr = READ_ONCE(sqe->addr);
3914 p->len = READ_ONCE(sqe->len);
3916 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3919 p->bgid = READ_ONCE(sqe->buf_group);
3920 tmp = READ_ONCE(sqe->off);
3921 if (tmp > USHRT_MAX)
3927 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3929 struct io_buffer *buf;
3930 u64 addr = pbuf->addr;
3931 int i, bid = pbuf->bid;
3933 for (i = 0; i < pbuf->nbufs; i++) {
3934 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3939 buf->len = pbuf->len;
3944 INIT_LIST_HEAD(&buf->list);
3947 list_add_tail(&buf->list, &(*head)->list);
3951 return i ? i : -ENOMEM;
3954 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3956 struct io_provide_buf *p = &req->pbuf;
3957 struct io_ring_ctx *ctx = req->ctx;
3958 struct io_buffer *head, *list;
3960 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3962 io_ring_submit_lock(ctx, !force_nonblock);
3964 lockdep_assert_held(&ctx->uring_lock);
3966 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3968 ret = io_add_buffers(p, &head);
3973 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3976 __io_remove_buffers(ctx, head, p->bgid, -1U);
3982 req_set_fail_links(req);
3984 /* need to hold the lock to complete IOPOLL requests */
3985 if (ctx->flags & IORING_SETUP_IOPOLL) {
3986 __io_req_complete(req, issue_flags, ret, 0);
3987 io_ring_submit_unlock(ctx, !force_nonblock);
3989 io_ring_submit_unlock(ctx, !force_nonblock);
3990 __io_req_complete(req, issue_flags, ret, 0);
3995 static int io_epoll_ctl_prep(struct io_kiocb *req,
3996 const struct io_uring_sqe *sqe)
3998 #if defined(CONFIG_EPOLL)
3999 if (sqe->ioprio || sqe->buf_index)
4001 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4004 req->epoll.epfd = READ_ONCE(sqe->fd);
4005 req->epoll.op = READ_ONCE(sqe->len);
4006 req->epoll.fd = READ_ONCE(sqe->off);
4008 if (ep_op_has_event(req->epoll.op)) {
4009 struct epoll_event __user *ev;
4011 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4012 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4022 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4024 #if defined(CONFIG_EPOLL)
4025 struct io_epoll *ie = &req->epoll;
4027 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4029 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4030 if (force_nonblock && ret == -EAGAIN)
4034 req_set_fail_links(req);
4035 __io_req_complete(req, issue_flags, ret, 0);
4042 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4044 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4045 if (sqe->ioprio || sqe->buf_index || sqe->off)
4047 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4050 req->madvise.addr = READ_ONCE(sqe->addr);
4051 req->madvise.len = READ_ONCE(sqe->len);
4052 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4059 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4061 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4062 struct io_madvise *ma = &req->madvise;
4065 if (issue_flags & IO_URING_F_NONBLOCK)
4068 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4070 req_set_fail_links(req);
4071 io_req_complete(req, ret);
4078 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4080 if (sqe->ioprio || sqe->buf_index || sqe->addr)
4082 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4085 req->fadvise.offset = READ_ONCE(sqe->off);
4086 req->fadvise.len = READ_ONCE(sqe->len);
4087 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4091 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4093 struct io_fadvise *fa = &req->fadvise;
4096 if (issue_flags & IO_URING_F_NONBLOCK) {
4097 switch (fa->advice) {
4098 case POSIX_FADV_NORMAL:
4099 case POSIX_FADV_RANDOM:
4100 case POSIX_FADV_SEQUENTIAL:
4107 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4109 req_set_fail_links(req);
4110 io_req_complete(req, ret);
4114 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4116 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL)))
4118 if (sqe->ioprio || sqe->buf_index)
4120 if (req->flags & REQ_F_FIXED_FILE)
4123 req->statx.dfd = READ_ONCE(sqe->fd);
4124 req->statx.mask = READ_ONCE(sqe->len);
4125 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4126 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4127 req->statx.flags = READ_ONCE(sqe->statx_flags);
4132 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4134 struct io_statx *ctx = &req->statx;
4137 if (issue_flags & IO_URING_F_NONBLOCK) {
4138 /* only need file table for an actual valid fd */
4139 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
4140 req->flags |= REQ_F_NO_FILE_TABLE;
4144 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4148 req_set_fail_links(req);
4149 io_req_complete(req, ret);
4153 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4155 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4157 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4158 sqe->rw_flags || sqe->buf_index)
4160 if (req->flags & REQ_F_FIXED_FILE)
4163 req->close.fd = READ_ONCE(sqe->fd);
4167 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4169 struct files_struct *files = current->files;
4170 struct io_close *close = &req->close;
4171 struct fdtable *fdt;
4177 spin_lock(&files->file_lock);
4178 fdt = files_fdtable(files);
4179 if (close->fd >= fdt->max_fds) {
4180 spin_unlock(&files->file_lock);
4183 file = fdt->fd[close->fd];
4185 spin_unlock(&files->file_lock);
4189 if (file->f_op == &io_uring_fops) {
4190 spin_unlock(&files->file_lock);
4195 /* if the file has a flush method, be safe and punt to async */
4196 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4197 spin_unlock(&files->file_lock);
4201 ret = __close_fd_get_file(close->fd, &file);
4202 spin_unlock(&files->file_lock);
4209 /* No ->flush() or already async, safely close from here */
4210 ret = filp_close(file, current->files);
4213 req_set_fail_links(req);
4216 __io_req_complete(req, issue_flags, ret, 0);
4220 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4222 struct io_ring_ctx *ctx = req->ctx;
4224 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4226 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4229 req->sync.off = READ_ONCE(sqe->off);
4230 req->sync.len = READ_ONCE(sqe->len);
4231 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4235 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4239 /* sync_file_range always requires a blocking context */
4240 if (issue_flags & IO_URING_F_NONBLOCK)
4243 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4246 req_set_fail_links(req);
4247 io_req_complete(req, ret);
4251 #if defined(CONFIG_NET)
4252 static int io_setup_async_msg(struct io_kiocb *req,
4253 struct io_async_msghdr *kmsg)
4255 struct io_async_msghdr *async_msg = req->async_data;
4259 if (io_alloc_async_data(req)) {
4260 kfree(kmsg->free_iov);
4263 async_msg = req->async_data;
4264 req->flags |= REQ_F_NEED_CLEANUP;
4265 memcpy(async_msg, kmsg, sizeof(*kmsg));
4266 async_msg->msg.msg_name = &async_msg->addr;
4267 /* if were using fast_iov, set it to the new one */
4268 if (!async_msg->free_iov)
4269 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4274 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4275 struct io_async_msghdr *iomsg)
4277 iomsg->msg.msg_name = &iomsg->addr;
4278 iomsg->free_iov = iomsg->fast_iov;
4279 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4280 req->sr_msg.msg_flags, &iomsg->free_iov);
4283 static int io_sendmsg_prep_async(struct io_kiocb *req)
4287 if (!io_op_defs[req->opcode].needs_async_data)
4289 ret = io_sendmsg_copy_hdr(req, req->async_data);
4291 req->flags |= REQ_F_NEED_CLEANUP;
4295 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4297 struct io_sr_msg *sr = &req->sr_msg;
4299 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4302 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4303 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4304 sr->len = READ_ONCE(sqe->len);
4306 #ifdef CONFIG_COMPAT
4307 if (req->ctx->compat)
4308 sr->msg_flags |= MSG_CMSG_COMPAT;
4313 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4315 struct io_async_msghdr iomsg, *kmsg;
4316 struct socket *sock;
4320 sock = sock_from_file(req->file);
4321 if (unlikely(!sock))
4324 kmsg = req->async_data;
4326 ret = io_sendmsg_copy_hdr(req, &iomsg);
4332 flags = req->sr_msg.msg_flags;
4333 if (flags & MSG_DONTWAIT)
4334 req->flags |= REQ_F_NOWAIT;
4335 else if (issue_flags & IO_URING_F_NONBLOCK)
4336 flags |= MSG_DONTWAIT;
4338 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4339 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4340 return io_setup_async_msg(req, kmsg);
4341 if (ret == -ERESTARTSYS)
4344 /* fast path, check for non-NULL to avoid function call */
4346 kfree(kmsg->free_iov);
4347 req->flags &= ~REQ_F_NEED_CLEANUP;
4349 req_set_fail_links(req);
4350 __io_req_complete(req, issue_flags, ret, 0);
4354 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4356 struct io_sr_msg *sr = &req->sr_msg;
4359 struct socket *sock;
4363 sock = sock_from_file(req->file);
4364 if (unlikely(!sock))
4367 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4371 msg.msg_name = NULL;
4372 msg.msg_control = NULL;
4373 msg.msg_controllen = 0;
4374 msg.msg_namelen = 0;
4376 flags = req->sr_msg.msg_flags;
4377 if (flags & MSG_DONTWAIT)
4378 req->flags |= REQ_F_NOWAIT;
4379 else if (issue_flags & IO_URING_F_NONBLOCK)
4380 flags |= MSG_DONTWAIT;
4382 msg.msg_flags = flags;
4383 ret = sock_sendmsg(sock, &msg);
4384 if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4386 if (ret == -ERESTARTSYS)
4390 req_set_fail_links(req);
4391 __io_req_complete(req, issue_flags, ret, 0);
4395 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4396 struct io_async_msghdr *iomsg)
4398 struct io_sr_msg *sr = &req->sr_msg;
4399 struct iovec __user *uiov;
4403 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4404 &iomsg->uaddr, &uiov, &iov_len);
4408 if (req->flags & REQ_F_BUFFER_SELECT) {
4411 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4413 sr->len = iomsg->fast_iov[0].iov_len;
4414 iomsg->free_iov = NULL;
4416 iomsg->free_iov = iomsg->fast_iov;
4417 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4418 &iomsg->free_iov, &iomsg->msg.msg_iter,
4427 #ifdef CONFIG_COMPAT
4428 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4429 struct io_async_msghdr *iomsg)
4431 struct compat_msghdr __user *msg_compat;
4432 struct io_sr_msg *sr = &req->sr_msg;
4433 struct compat_iovec __user *uiov;
4438 msg_compat = (struct compat_msghdr __user *) sr->umsg;
4439 ret = __get_compat_msghdr(&iomsg->msg, msg_compat, &iomsg->uaddr,
4444 uiov = compat_ptr(ptr);
4445 if (req->flags & REQ_F_BUFFER_SELECT) {
4446 compat_ssize_t clen;
4450 if (!access_ok(uiov, sizeof(*uiov)))
4452 if (__get_user(clen, &uiov->iov_len))
4457 iomsg->free_iov = NULL;
4459 iomsg->free_iov = iomsg->fast_iov;
4460 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4461 UIO_FASTIOV, &iomsg->free_iov,
4462 &iomsg->msg.msg_iter, true);
4471 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4472 struct io_async_msghdr *iomsg)
4474 iomsg->msg.msg_name = &iomsg->addr;
4476 #ifdef CONFIG_COMPAT
4477 if (req->ctx->compat)
4478 return __io_compat_recvmsg_copy_hdr(req, iomsg);
4481 return __io_recvmsg_copy_hdr(req, iomsg);
4484 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4487 struct io_sr_msg *sr = &req->sr_msg;
4488 struct io_buffer *kbuf;
4490 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4495 req->flags |= REQ_F_BUFFER_SELECTED;
4499 static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4501 return io_put_kbuf(req, req->sr_msg.kbuf);
4504 static int io_recvmsg_prep_async(struct io_kiocb *req)
4508 if (!io_op_defs[req->opcode].needs_async_data)
4510 ret = io_recvmsg_copy_hdr(req, req->async_data);
4512 req->flags |= REQ_F_NEED_CLEANUP;
4516 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4518 struct io_sr_msg *sr = &req->sr_msg;
4520 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4523 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4524 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4525 sr->len = READ_ONCE(sqe->len);
4526 sr->bgid = READ_ONCE(sqe->buf_group);
4528 #ifdef CONFIG_COMPAT
4529 if (req->ctx->compat)
4530 sr->msg_flags |= MSG_CMSG_COMPAT;
4535 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4537 struct io_async_msghdr iomsg, *kmsg;
4538 struct socket *sock;
4539 struct io_buffer *kbuf;
4541 int ret, cflags = 0;
4542 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4544 sock = sock_from_file(req->file);
4545 if (unlikely(!sock))
4548 kmsg = req->async_data;
4550 ret = io_recvmsg_copy_hdr(req, &iomsg);
4556 if (req->flags & REQ_F_BUFFER_SELECT) {
4557 kbuf = io_recv_buffer_select(req, !force_nonblock);
4559 return PTR_ERR(kbuf);
4560 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4561 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4562 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4563 1, req->sr_msg.len);
4566 flags = req->sr_msg.msg_flags;
4567 if (flags & MSG_DONTWAIT)
4568 req->flags |= REQ_F_NOWAIT;
4569 else if (force_nonblock)
4570 flags |= MSG_DONTWAIT;
4572 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4573 kmsg->uaddr, flags);
4574 if (force_nonblock && ret == -EAGAIN)
4575 return io_setup_async_msg(req, kmsg);
4576 if (ret == -ERESTARTSYS)
4579 if (req->flags & REQ_F_BUFFER_SELECTED)
4580 cflags = io_put_recv_kbuf(req);
4581 /* fast path, check for non-NULL to avoid function call */
4583 kfree(kmsg->free_iov);
4584 req->flags &= ~REQ_F_NEED_CLEANUP;
4586 req_set_fail_links(req);
4587 __io_req_complete(req, issue_flags, ret, cflags);
4591 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4593 struct io_buffer *kbuf;
4594 struct io_sr_msg *sr = &req->sr_msg;
4596 void __user *buf = sr->buf;
4597 struct socket *sock;
4600 int ret, cflags = 0;
4601 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4603 sock = sock_from_file(req->file);
4604 if (unlikely(!sock))
4607 if (req->flags & REQ_F_BUFFER_SELECT) {
4608 kbuf = io_recv_buffer_select(req, !force_nonblock);
4610 return PTR_ERR(kbuf);
4611 buf = u64_to_user_ptr(kbuf->addr);
4614 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4618 msg.msg_name = NULL;
4619 msg.msg_control = NULL;
4620 msg.msg_controllen = 0;
4621 msg.msg_namelen = 0;
4622 msg.msg_iocb = NULL;
4625 flags = req->sr_msg.msg_flags;
4626 if (flags & MSG_DONTWAIT)
4627 req->flags |= REQ_F_NOWAIT;
4628 else if (force_nonblock)
4629 flags |= MSG_DONTWAIT;
4631 ret = sock_recvmsg(sock, &msg, flags);
4632 if (force_nonblock && ret == -EAGAIN)
4634 if (ret == -ERESTARTSYS)
4637 if (req->flags & REQ_F_BUFFER_SELECTED)
4638 cflags = io_put_recv_kbuf(req);
4640 req_set_fail_links(req);
4641 __io_req_complete(req, issue_flags, ret, cflags);
4645 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4647 struct io_accept *accept = &req->accept;
4649 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4651 if (sqe->ioprio || sqe->len || sqe->buf_index)
4654 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4655 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4656 accept->flags = READ_ONCE(sqe->accept_flags);
4657 accept->nofile = rlimit(RLIMIT_NOFILE);
4661 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4663 struct io_accept *accept = &req->accept;
4664 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4665 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4668 if (req->file->f_flags & O_NONBLOCK)
4669 req->flags |= REQ_F_NOWAIT;
4671 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4672 accept->addr_len, accept->flags,
4674 if (ret == -EAGAIN && force_nonblock)
4677 if (ret == -ERESTARTSYS)
4679 req_set_fail_links(req);
4681 __io_req_complete(req, issue_flags, ret, 0);
4685 static int io_connect_prep_async(struct io_kiocb *req)
4687 struct io_async_connect *io = req->async_data;
4688 struct io_connect *conn = &req->connect;
4690 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4693 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4695 struct io_connect *conn = &req->connect;
4697 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4699 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4702 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4703 conn->addr_len = READ_ONCE(sqe->addr2);
4707 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4709 struct io_async_connect __io, *io;
4710 unsigned file_flags;
4712 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4714 if (req->async_data) {
4715 io = req->async_data;
4717 ret = move_addr_to_kernel(req->connect.addr,
4718 req->connect.addr_len,
4725 file_flags = force_nonblock ? O_NONBLOCK : 0;
4727 ret = __sys_connect_file(req->file, &io->address,
4728 req->connect.addr_len, file_flags);
4729 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4730 if (req->async_data)
4732 if (io_alloc_async_data(req)) {
4736 io = req->async_data;
4737 memcpy(req->async_data, &__io, sizeof(__io));
4740 if (ret == -ERESTARTSYS)
4744 req_set_fail_links(req);
4745 __io_req_complete(req, issue_flags, ret, 0);
4748 #else /* !CONFIG_NET */
4749 #define IO_NETOP_FN(op) \
4750 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
4752 return -EOPNOTSUPP; \
4755 #define IO_NETOP_PREP(op) \
4757 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4759 return -EOPNOTSUPP; \
4762 #define IO_NETOP_PREP_ASYNC(op) \
4764 static int io_##op##_prep_async(struct io_kiocb *req) \
4766 return -EOPNOTSUPP; \
4769 IO_NETOP_PREP_ASYNC(sendmsg);
4770 IO_NETOP_PREP_ASYNC(recvmsg);
4771 IO_NETOP_PREP_ASYNC(connect);
4772 IO_NETOP_PREP(accept);
4775 #endif /* CONFIG_NET */
4777 struct io_poll_table {
4778 struct poll_table_struct pt;
4779 struct io_kiocb *req;
4783 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4784 __poll_t mask, task_work_func_t func)
4788 /* for instances that support it check for an event match first: */
4789 if (mask && !(mask & poll->events))
4792 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4794 list_del_init(&poll->wait.entry);
4797 req->task_work.func = func;
4798 percpu_ref_get(&req->ctx->refs);
4801 * If this fails, then the task is exiting. When a task exits, the
4802 * work gets canceled, so just cancel this request as well instead
4803 * of executing it. We can't safely execute it anyway, as we may not
4804 * have the needed state needed for it anyway.
4806 ret = io_req_task_work_add(req);
4807 if (unlikely(ret)) {
4808 WRITE_ONCE(poll->canceled, true);
4809 io_req_task_work_add_fallback(req, func);
4814 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4815 __acquires(&req->ctx->completion_lock)
4817 struct io_ring_ctx *ctx = req->ctx;
4819 if (!req->result && !READ_ONCE(poll->canceled)) {
4820 struct poll_table_struct pt = { ._key = poll->events };
4822 req->result = vfs_poll(req->file, &pt) & poll->events;
4825 spin_lock_irq(&ctx->completion_lock);
4826 if (!req->result && !READ_ONCE(poll->canceled)) {
4827 add_wait_queue(poll->head, &poll->wait);
4834 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4836 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4837 if (req->opcode == IORING_OP_POLL_ADD)
4838 return req->async_data;
4839 return req->apoll->double_poll;
4842 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4844 if (req->opcode == IORING_OP_POLL_ADD)
4846 return &req->apoll->poll;
4849 static void io_poll_remove_double(struct io_kiocb *req)
4851 struct io_poll_iocb *poll = io_poll_get_double(req);
4853 lockdep_assert_held(&req->ctx->completion_lock);
4855 if (poll && poll->head) {
4856 struct wait_queue_head *head = poll->head;
4858 spin_lock(&head->lock);
4859 list_del_init(&poll->wait.entry);
4860 if (poll->wait.private)
4861 refcount_dec(&req->refs);
4863 spin_unlock(&head->lock);
4867 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4869 struct io_ring_ctx *ctx = req->ctx;
4871 io_poll_remove_double(req);
4872 req->poll.done = true;
4873 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4874 io_commit_cqring(ctx);
4877 static void io_poll_task_func(struct callback_head *cb)
4879 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4880 struct io_ring_ctx *ctx = req->ctx;
4881 struct io_kiocb *nxt;
4883 if (io_poll_rewait(req, &req->poll)) {
4884 spin_unlock_irq(&ctx->completion_lock);
4886 hash_del(&req->hash_node);
4887 io_poll_complete(req, req->result, 0);
4888 spin_unlock_irq(&ctx->completion_lock);
4890 nxt = io_put_req_find_next(req);
4891 io_cqring_ev_posted(ctx);
4893 __io_req_task_submit(nxt);
4896 percpu_ref_put(&ctx->refs);
4899 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4900 int sync, void *key)
4902 struct io_kiocb *req = wait->private;
4903 struct io_poll_iocb *poll = io_poll_get_single(req);
4904 __poll_t mask = key_to_poll(key);
4906 /* for instances that support it check for an event match first: */
4907 if (mask && !(mask & poll->events))
4910 list_del_init(&wait->entry);
4912 if (poll && poll->head) {
4915 spin_lock(&poll->head->lock);
4916 done = list_empty(&poll->wait.entry);
4918 list_del_init(&poll->wait.entry);
4919 /* make sure double remove sees this as being gone */
4920 wait->private = NULL;
4921 spin_unlock(&poll->head->lock);
4923 /* use wait func handler, so it matches the rq type */
4924 poll->wait.func(&poll->wait, mode, sync, key);
4927 refcount_dec(&req->refs);
4931 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4932 wait_queue_func_t wake_func)
4936 poll->canceled = false;
4937 poll->events = events;
4938 INIT_LIST_HEAD(&poll->wait.entry);
4939 init_waitqueue_func_entry(&poll->wait, wake_func);
4942 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4943 struct wait_queue_head *head,
4944 struct io_poll_iocb **poll_ptr)
4946 struct io_kiocb *req = pt->req;
4949 * If poll->head is already set, it's because the file being polled
4950 * uses multiple waitqueues for poll handling (eg one for read, one
4951 * for write). Setup a separate io_poll_iocb if this happens.
4953 if (unlikely(poll->head)) {
4954 struct io_poll_iocb *poll_one = poll;
4956 /* already have a 2nd entry, fail a third attempt */
4958 pt->error = -EINVAL;
4961 /* double add on the same waitqueue head, ignore */
4962 if (poll->head == head)
4964 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4966 pt->error = -ENOMEM;
4969 io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
4970 refcount_inc(&req->refs);
4971 poll->wait.private = req;
4978 if (poll->events & EPOLLEXCLUSIVE)
4979 add_wait_queue_exclusive(head, &poll->wait);
4981 add_wait_queue(head, &poll->wait);
4984 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4985 struct poll_table_struct *p)
4987 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4988 struct async_poll *apoll = pt->req->apoll;
4990 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
4993 static void io_async_task_func(struct callback_head *cb)
4995 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4996 struct async_poll *apoll = req->apoll;
4997 struct io_ring_ctx *ctx = req->ctx;
4999 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
5001 if (io_poll_rewait(req, &apoll->poll)) {
5002 spin_unlock_irq(&ctx->completion_lock);
5003 percpu_ref_put(&ctx->refs);
5007 /* If req is still hashed, it cannot have been canceled. Don't check. */
5008 if (hash_hashed(&req->hash_node))
5009 hash_del(&req->hash_node);
5011 io_poll_remove_double(req);
5012 spin_unlock_irq(&ctx->completion_lock);
5014 if (!READ_ONCE(apoll->poll.canceled))
5015 __io_req_task_submit(req);
5017 __io_req_task_cancel(req, -ECANCELED);
5019 percpu_ref_put(&ctx->refs);
5020 kfree(apoll->double_poll);
5024 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5027 struct io_kiocb *req = wait->private;
5028 struct io_poll_iocb *poll = &req->apoll->poll;
5030 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5033 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5036 static void io_poll_req_insert(struct io_kiocb *req)
5038 struct io_ring_ctx *ctx = req->ctx;
5039 struct hlist_head *list;
5041 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5042 hlist_add_head(&req->hash_node, list);
5045 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5046 struct io_poll_iocb *poll,
5047 struct io_poll_table *ipt, __poll_t mask,
5048 wait_queue_func_t wake_func)
5049 __acquires(&ctx->completion_lock)
5051 struct io_ring_ctx *ctx = req->ctx;
5052 bool cancel = false;
5054 INIT_HLIST_NODE(&req->hash_node);
5055 io_init_poll_iocb(poll, mask, wake_func);
5056 poll->file = req->file;
5057 poll->wait.private = req;
5059 ipt->pt._key = mask;
5061 ipt->error = -EINVAL;
5063 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5065 spin_lock_irq(&ctx->completion_lock);
5066 if (likely(poll->head)) {
5067 spin_lock(&poll->head->lock);
5068 if (unlikely(list_empty(&poll->wait.entry))) {
5074 if (mask || ipt->error)
5075 list_del_init(&poll->wait.entry);
5077 WRITE_ONCE(poll->canceled, true);
5078 else if (!poll->done) /* actually waiting for an event */
5079 io_poll_req_insert(req);
5080 spin_unlock(&poll->head->lock);
5086 static bool io_arm_poll_handler(struct io_kiocb *req)
5088 const struct io_op_def *def = &io_op_defs[req->opcode];
5089 struct io_ring_ctx *ctx = req->ctx;
5090 struct async_poll *apoll;
5091 struct io_poll_table ipt;
5095 if (!req->file || !file_can_poll(req->file))
5097 if (req->flags & REQ_F_POLLED)
5101 else if (def->pollout)
5105 /* if we can't nonblock try, then no point in arming a poll handler */
5106 if (!io_file_supports_async(req->file, rw))
5109 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5110 if (unlikely(!apoll))
5112 apoll->double_poll = NULL;
5114 req->flags |= REQ_F_POLLED;
5119 mask |= POLLIN | POLLRDNORM;
5121 mask |= POLLOUT | POLLWRNORM;
5123 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5124 if ((req->opcode == IORING_OP_RECVMSG) &&
5125 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5128 mask |= POLLERR | POLLPRI;
5130 ipt.pt._qproc = io_async_queue_proc;
5132 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5134 if (ret || ipt.error) {
5135 io_poll_remove_double(req);
5136 spin_unlock_irq(&ctx->completion_lock);
5137 kfree(apoll->double_poll);
5141 spin_unlock_irq(&ctx->completion_lock);
5142 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
5143 apoll->poll.events);
5147 static bool __io_poll_remove_one(struct io_kiocb *req,
5148 struct io_poll_iocb *poll)
5150 bool do_complete = false;
5152 spin_lock(&poll->head->lock);
5153 WRITE_ONCE(poll->canceled, true);
5154 if (!list_empty(&poll->wait.entry)) {
5155 list_del_init(&poll->wait.entry);
5158 spin_unlock(&poll->head->lock);
5159 hash_del(&req->hash_node);
5163 static bool io_poll_remove_one(struct io_kiocb *req)
5167 io_poll_remove_double(req);
5169 if (req->opcode == IORING_OP_POLL_ADD) {
5170 do_complete = __io_poll_remove_one(req, &req->poll);
5172 struct async_poll *apoll = req->apoll;
5174 /* non-poll requests have submit ref still */
5175 do_complete = __io_poll_remove_one(req, &apoll->poll);
5178 kfree(apoll->double_poll);
5184 io_cqring_fill_event(req, -ECANCELED);
5185 io_commit_cqring(req->ctx);
5186 req_set_fail_links(req);
5187 io_put_req_deferred(req, 1);
5194 * Returns true if we found and killed one or more poll requests
5196 static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5197 struct files_struct *files)
5199 struct hlist_node *tmp;
5200 struct io_kiocb *req;
5203 spin_lock_irq(&ctx->completion_lock);
5204 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5205 struct hlist_head *list;
5207 list = &ctx->cancel_hash[i];
5208 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5209 if (io_match_task(req, tsk, files))
5210 posted += io_poll_remove_one(req);
5213 spin_unlock_irq(&ctx->completion_lock);
5216 io_cqring_ev_posted(ctx);
5221 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
5223 struct hlist_head *list;
5224 struct io_kiocb *req;
5226 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5227 hlist_for_each_entry(req, list, hash_node) {
5228 if (sqe_addr != req->user_data)
5230 if (io_poll_remove_one(req))
5238 static int io_poll_remove_prep(struct io_kiocb *req,
5239 const struct io_uring_sqe *sqe)
5241 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5243 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
5247 req->poll_remove.addr = READ_ONCE(sqe->addr);
5252 * Find a running poll command that matches one specified in sqe->addr,
5253 * and remove it if found.
5255 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
5257 struct io_ring_ctx *ctx = req->ctx;
5260 spin_lock_irq(&ctx->completion_lock);
5261 ret = io_poll_cancel(ctx, req->poll_remove.addr);
5262 spin_unlock_irq(&ctx->completion_lock);
5265 req_set_fail_links(req);
5266 io_req_complete(req, ret);
5270 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5273 struct io_kiocb *req = wait->private;
5274 struct io_poll_iocb *poll = &req->poll;
5276 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5279 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5280 struct poll_table_struct *p)
5282 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5284 __io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5287 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5289 struct io_poll_iocb *poll = &req->poll;
5292 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5294 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
5297 events = READ_ONCE(sqe->poll32_events);
5299 events = swahw32(events);
5301 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
5302 (events & EPOLLEXCLUSIVE);
5306 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5308 struct io_poll_iocb *poll = &req->poll;
5309 struct io_ring_ctx *ctx = req->ctx;
5310 struct io_poll_table ipt;
5313 ipt.pt._qproc = io_poll_queue_proc;
5315 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5318 if (mask) { /* no async, we'd stolen it */
5320 io_poll_complete(req, mask, 0);
5322 spin_unlock_irq(&ctx->completion_lock);
5325 io_cqring_ev_posted(ctx);
5331 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5333 struct io_timeout_data *data = container_of(timer,
5334 struct io_timeout_data, timer);
5335 struct io_kiocb *req = data->req;
5336 struct io_ring_ctx *ctx = req->ctx;
5337 unsigned long flags;
5339 spin_lock_irqsave(&ctx->completion_lock, flags);
5340 list_del_init(&req->timeout.list);
5341 atomic_set(&req->ctx->cq_timeouts,
5342 atomic_read(&req->ctx->cq_timeouts) + 1);
5344 io_cqring_fill_event(req, -ETIME);
5345 io_commit_cqring(ctx);
5346 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5348 io_cqring_ev_posted(ctx);
5349 req_set_fail_links(req);
5351 return HRTIMER_NORESTART;
5354 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5357 struct io_timeout_data *io;
5358 struct io_kiocb *req;
5361 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5362 if (user_data == req->user_data) {
5369 return ERR_PTR(ret);
5371 io = req->async_data;
5372 ret = hrtimer_try_to_cancel(&io->timer);
5374 return ERR_PTR(-EALREADY);
5375 list_del_init(&req->timeout.list);
5379 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5381 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5384 return PTR_ERR(req);
5386 req_set_fail_links(req);
5387 io_cqring_fill_event(req, -ECANCELED);
5388 io_put_req_deferred(req, 1);
5392 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5393 struct timespec64 *ts, enum hrtimer_mode mode)
5395 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5396 struct io_timeout_data *data;
5399 return PTR_ERR(req);
5401 req->timeout.off = 0; /* noseq */
5402 data = req->async_data;
5403 list_add_tail(&req->timeout.list, &ctx->timeout_list);
5404 hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5405 data->timer.function = io_timeout_fn;
5406 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5410 static int io_timeout_remove_prep(struct io_kiocb *req,
5411 const struct io_uring_sqe *sqe)
5413 struct io_timeout_rem *tr = &req->timeout_rem;
5415 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5417 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5419 if (sqe->ioprio || sqe->buf_index || sqe->len)
5422 tr->addr = READ_ONCE(sqe->addr);
5423 tr->flags = READ_ONCE(sqe->timeout_flags);
5424 if (tr->flags & IORING_TIMEOUT_UPDATE) {
5425 if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5427 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5429 } else if (tr->flags) {
5430 /* timeout removal doesn't support flags */
5437 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5439 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5444 * Remove or update an existing timeout command
5446 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5448 struct io_timeout_rem *tr = &req->timeout_rem;
5449 struct io_ring_ctx *ctx = req->ctx;
5452 spin_lock_irq(&ctx->completion_lock);
5453 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5454 ret = io_timeout_cancel(ctx, tr->addr);
5456 ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5457 io_translate_timeout_mode(tr->flags));
5459 io_cqring_fill_event(req, ret);
5460 io_commit_cqring(ctx);
5461 spin_unlock_irq(&ctx->completion_lock);
5462 io_cqring_ev_posted(ctx);
5464 req_set_fail_links(req);
5469 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5470 bool is_timeout_link)
5472 struct io_timeout_data *data;
5474 u32 off = READ_ONCE(sqe->off);
5476 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5478 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5480 if (off && is_timeout_link)
5482 flags = READ_ONCE(sqe->timeout_flags);
5483 if (flags & ~IORING_TIMEOUT_ABS)
5486 req->timeout.off = off;
5488 if (!req->async_data && io_alloc_async_data(req))
5491 data = req->async_data;
5494 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5497 data->mode = io_translate_timeout_mode(flags);
5498 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5502 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5504 struct io_ring_ctx *ctx = req->ctx;
5505 struct io_timeout_data *data = req->async_data;
5506 struct list_head *entry;
5507 u32 tail, off = req->timeout.off;
5509 spin_lock_irq(&ctx->completion_lock);
5512 * sqe->off holds how many events that need to occur for this
5513 * timeout event to be satisfied. If it isn't set, then this is
5514 * a pure timeout request, sequence isn't used.
5516 if (io_is_timeout_noseq(req)) {
5517 entry = ctx->timeout_list.prev;
5521 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5522 req->timeout.target_seq = tail + off;
5524 /* Update the last seq here in case io_flush_timeouts() hasn't.
5525 * This is safe because ->completion_lock is held, and submissions
5526 * and completions are never mixed in the same ->completion_lock section.
5528 ctx->cq_last_tm_flush = tail;
5531 * Insertion sort, ensuring the first entry in the list is always
5532 * the one we need first.
5534 list_for_each_prev(entry, &ctx->timeout_list) {
5535 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5538 if (io_is_timeout_noseq(nxt))
5540 /* nxt.seq is behind @tail, otherwise would've been completed */
5541 if (off >= nxt->timeout.target_seq - tail)
5545 list_add(&req->timeout.list, entry);
5546 data->timer.function = io_timeout_fn;
5547 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5548 spin_unlock_irq(&ctx->completion_lock);
5552 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5554 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5556 return req->user_data == (unsigned long) data;
5559 static int io_async_cancel_one(struct io_uring_task *tctx, void *sqe_addr)
5561 enum io_wq_cancel cancel_ret;
5567 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, sqe_addr, false);
5568 switch (cancel_ret) {
5569 case IO_WQ_CANCEL_OK:
5572 case IO_WQ_CANCEL_RUNNING:
5575 case IO_WQ_CANCEL_NOTFOUND:
5583 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5584 struct io_kiocb *req, __u64 sqe_addr,
5587 unsigned long flags;
5590 ret = io_async_cancel_one(req->task->io_uring,
5591 (void *) (unsigned long) sqe_addr);
5592 if (ret != -ENOENT) {
5593 spin_lock_irqsave(&ctx->completion_lock, flags);
5597 spin_lock_irqsave(&ctx->completion_lock, flags);
5598 ret = io_timeout_cancel(ctx, sqe_addr);
5601 ret = io_poll_cancel(ctx, sqe_addr);
5605 io_cqring_fill_event(req, ret);
5606 io_commit_cqring(ctx);
5607 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5608 io_cqring_ev_posted(ctx);
5611 req_set_fail_links(req);
5615 static int io_async_cancel_prep(struct io_kiocb *req,
5616 const struct io_uring_sqe *sqe)
5618 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5620 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5622 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags)
5625 req->cancel.addr = READ_ONCE(sqe->addr);
5629 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
5631 struct io_ring_ctx *ctx = req->ctx;
5633 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5637 static int io_rsrc_update_prep(struct io_kiocb *req,
5638 const struct io_uring_sqe *sqe)
5640 if (unlikely(req->ctx->flags & IORING_SETUP_SQPOLL))
5642 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5644 if (sqe->ioprio || sqe->rw_flags)
5647 req->rsrc_update.offset = READ_ONCE(sqe->off);
5648 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
5649 if (!req->rsrc_update.nr_args)
5651 req->rsrc_update.arg = READ_ONCE(sqe->addr);
5655 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
5657 struct io_ring_ctx *ctx = req->ctx;
5658 struct io_uring_rsrc_update up;
5661 if (issue_flags & IO_URING_F_NONBLOCK)
5664 up.offset = req->rsrc_update.offset;
5665 up.data = req->rsrc_update.arg;
5667 mutex_lock(&ctx->uring_lock);
5668 ret = __io_sqe_files_update(ctx, &up, req->rsrc_update.nr_args);
5669 mutex_unlock(&ctx->uring_lock);
5672 req_set_fail_links(req);
5673 __io_req_complete(req, issue_flags, ret, 0);
5677 static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5679 switch (req->opcode) {
5682 case IORING_OP_READV:
5683 case IORING_OP_READ_FIXED:
5684 case IORING_OP_READ:
5685 return io_read_prep(req, sqe);
5686 case IORING_OP_WRITEV:
5687 case IORING_OP_WRITE_FIXED:
5688 case IORING_OP_WRITE:
5689 return io_write_prep(req, sqe);
5690 case IORING_OP_POLL_ADD:
5691 return io_poll_add_prep(req, sqe);
5692 case IORING_OP_POLL_REMOVE:
5693 return io_poll_remove_prep(req, sqe);
5694 case IORING_OP_FSYNC:
5695 return io_fsync_prep(req, sqe);
5696 case IORING_OP_SYNC_FILE_RANGE:
5697 return io_sfr_prep(req, sqe);
5698 case IORING_OP_SENDMSG:
5699 case IORING_OP_SEND:
5700 return io_sendmsg_prep(req, sqe);
5701 case IORING_OP_RECVMSG:
5702 case IORING_OP_RECV:
5703 return io_recvmsg_prep(req, sqe);
5704 case IORING_OP_CONNECT:
5705 return io_connect_prep(req, sqe);
5706 case IORING_OP_TIMEOUT:
5707 return io_timeout_prep(req, sqe, false);
5708 case IORING_OP_TIMEOUT_REMOVE:
5709 return io_timeout_remove_prep(req, sqe);
5710 case IORING_OP_ASYNC_CANCEL:
5711 return io_async_cancel_prep(req, sqe);
5712 case IORING_OP_LINK_TIMEOUT:
5713 return io_timeout_prep(req, sqe, true);
5714 case IORING_OP_ACCEPT:
5715 return io_accept_prep(req, sqe);
5716 case IORING_OP_FALLOCATE:
5717 return io_fallocate_prep(req, sqe);
5718 case IORING_OP_OPENAT:
5719 return io_openat_prep(req, sqe);
5720 case IORING_OP_CLOSE:
5721 return io_close_prep(req, sqe);
5722 case IORING_OP_FILES_UPDATE:
5723 return io_rsrc_update_prep(req, sqe);
5724 case IORING_OP_STATX:
5725 return io_statx_prep(req, sqe);
5726 case IORING_OP_FADVISE:
5727 return io_fadvise_prep(req, sqe);
5728 case IORING_OP_MADVISE:
5729 return io_madvise_prep(req, sqe);
5730 case IORING_OP_OPENAT2:
5731 return io_openat2_prep(req, sqe);
5732 case IORING_OP_EPOLL_CTL:
5733 return io_epoll_ctl_prep(req, sqe);
5734 case IORING_OP_SPLICE:
5735 return io_splice_prep(req, sqe);
5736 case IORING_OP_PROVIDE_BUFFERS:
5737 return io_provide_buffers_prep(req, sqe);
5738 case IORING_OP_REMOVE_BUFFERS:
5739 return io_remove_buffers_prep(req, sqe);
5741 return io_tee_prep(req, sqe);
5742 case IORING_OP_SHUTDOWN:
5743 return io_shutdown_prep(req, sqe);
5744 case IORING_OP_RENAMEAT:
5745 return io_renameat_prep(req, sqe);
5746 case IORING_OP_UNLINKAT:
5747 return io_unlinkat_prep(req, sqe);
5750 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5755 static int io_req_prep_async(struct io_kiocb *req)
5757 switch (req->opcode) {
5758 case IORING_OP_READV:
5759 case IORING_OP_READ_FIXED:
5760 case IORING_OP_READ:
5761 return io_rw_prep_async(req, READ);
5762 case IORING_OP_WRITEV:
5763 case IORING_OP_WRITE_FIXED:
5764 case IORING_OP_WRITE:
5765 return io_rw_prep_async(req, WRITE);
5766 case IORING_OP_SENDMSG:
5767 case IORING_OP_SEND:
5768 return io_sendmsg_prep_async(req);
5769 case IORING_OP_RECVMSG:
5770 case IORING_OP_RECV:
5771 return io_recvmsg_prep_async(req);
5772 case IORING_OP_CONNECT:
5773 return io_connect_prep_async(req);
5778 static int io_req_defer_prep(struct io_kiocb *req)
5780 if (!io_op_defs[req->opcode].needs_async_data)
5782 /* some opcodes init it during the inital prep */
5783 if (req->async_data)
5785 if (__io_alloc_async_data(req))
5787 return io_req_prep_async(req);
5790 static u32 io_get_sequence(struct io_kiocb *req)
5792 struct io_kiocb *pos;
5793 struct io_ring_ctx *ctx = req->ctx;
5794 u32 total_submitted, nr_reqs = 0;
5796 io_for_each_link(pos, req)
5799 total_submitted = ctx->cached_sq_head - ctx->cached_sq_dropped;
5800 return total_submitted - nr_reqs;
5803 static int io_req_defer(struct io_kiocb *req)
5805 struct io_ring_ctx *ctx = req->ctx;
5806 struct io_defer_entry *de;
5810 /* Still need defer if there is pending req in defer list. */
5811 if (likely(list_empty_careful(&ctx->defer_list) &&
5812 !(req->flags & REQ_F_IO_DRAIN)))
5815 seq = io_get_sequence(req);
5816 /* Still a chance to pass the sequence check */
5817 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list))
5820 ret = io_req_defer_prep(req);
5823 io_prep_async_link(req);
5824 de = kmalloc(sizeof(*de), GFP_KERNEL);
5828 spin_lock_irq(&ctx->completion_lock);
5829 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
5830 spin_unlock_irq(&ctx->completion_lock);
5832 io_queue_async_work(req);
5833 return -EIOCBQUEUED;
5836 trace_io_uring_defer(ctx, req, req->user_data);
5839 list_add_tail(&de->list, &ctx->defer_list);
5840 spin_unlock_irq(&ctx->completion_lock);
5841 return -EIOCBQUEUED;
5844 static void __io_clean_op(struct io_kiocb *req)
5846 if (req->flags & REQ_F_BUFFER_SELECTED) {
5847 switch (req->opcode) {
5848 case IORING_OP_READV:
5849 case IORING_OP_READ_FIXED:
5850 case IORING_OP_READ:
5851 kfree((void *)(unsigned long)req->rw.addr);
5853 case IORING_OP_RECVMSG:
5854 case IORING_OP_RECV:
5855 kfree(req->sr_msg.kbuf);
5858 req->flags &= ~REQ_F_BUFFER_SELECTED;
5861 if (req->flags & REQ_F_NEED_CLEANUP) {
5862 switch (req->opcode) {
5863 case IORING_OP_READV:
5864 case IORING_OP_READ_FIXED:
5865 case IORING_OP_READ:
5866 case IORING_OP_WRITEV:
5867 case IORING_OP_WRITE_FIXED:
5868 case IORING_OP_WRITE: {
5869 struct io_async_rw *io = req->async_data;
5871 kfree(io->free_iovec);
5874 case IORING_OP_RECVMSG:
5875 case IORING_OP_SENDMSG: {
5876 struct io_async_msghdr *io = req->async_data;
5878 kfree(io->free_iov);
5881 case IORING_OP_SPLICE:
5883 io_put_file(req, req->splice.file_in,
5884 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5886 case IORING_OP_OPENAT:
5887 case IORING_OP_OPENAT2:
5888 if (req->open.filename)
5889 putname(req->open.filename);
5891 case IORING_OP_RENAMEAT:
5892 putname(req->rename.oldpath);
5893 putname(req->rename.newpath);
5895 case IORING_OP_UNLINKAT:
5896 putname(req->unlink.filename);
5899 req->flags &= ~REQ_F_NEED_CLEANUP;
5903 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
5905 struct io_ring_ctx *ctx = req->ctx;
5906 const struct cred *creds = NULL;
5909 if (req->work.personality) {
5910 const struct cred *new_creds;
5912 if (!(issue_flags & IO_URING_F_NONBLOCK))
5913 mutex_lock(&ctx->uring_lock);
5914 new_creds = idr_find(&ctx->personality_idr, req->work.personality);
5915 if (!(issue_flags & IO_URING_F_NONBLOCK))
5916 mutex_unlock(&ctx->uring_lock);
5919 creds = override_creds(new_creds);
5922 switch (req->opcode) {
5924 ret = io_nop(req, issue_flags);
5926 case IORING_OP_READV:
5927 case IORING_OP_READ_FIXED:
5928 case IORING_OP_READ:
5929 ret = io_read(req, issue_flags);
5931 case IORING_OP_WRITEV:
5932 case IORING_OP_WRITE_FIXED:
5933 case IORING_OP_WRITE:
5934 ret = io_write(req, issue_flags);
5936 case IORING_OP_FSYNC:
5937 ret = io_fsync(req, issue_flags);
5939 case IORING_OP_POLL_ADD:
5940 ret = io_poll_add(req, issue_flags);
5942 case IORING_OP_POLL_REMOVE:
5943 ret = io_poll_remove(req, issue_flags);
5945 case IORING_OP_SYNC_FILE_RANGE:
5946 ret = io_sync_file_range(req, issue_flags);
5948 case IORING_OP_SENDMSG:
5949 ret = io_sendmsg(req, issue_flags);
5951 case IORING_OP_SEND:
5952 ret = io_send(req, issue_flags);
5954 case IORING_OP_RECVMSG:
5955 ret = io_recvmsg(req, issue_flags);
5957 case IORING_OP_RECV:
5958 ret = io_recv(req, issue_flags);
5960 case IORING_OP_TIMEOUT:
5961 ret = io_timeout(req, issue_flags);
5963 case IORING_OP_TIMEOUT_REMOVE:
5964 ret = io_timeout_remove(req, issue_flags);
5966 case IORING_OP_ACCEPT:
5967 ret = io_accept(req, issue_flags);
5969 case IORING_OP_CONNECT:
5970 ret = io_connect(req, issue_flags);
5972 case IORING_OP_ASYNC_CANCEL:
5973 ret = io_async_cancel(req, issue_flags);
5975 case IORING_OP_FALLOCATE:
5976 ret = io_fallocate(req, issue_flags);
5978 case IORING_OP_OPENAT:
5979 ret = io_openat(req, issue_flags);
5981 case IORING_OP_CLOSE:
5982 ret = io_close(req, issue_flags);
5984 case IORING_OP_FILES_UPDATE:
5985 ret = io_files_update(req, issue_flags);
5987 case IORING_OP_STATX:
5988 ret = io_statx(req, issue_flags);
5990 case IORING_OP_FADVISE:
5991 ret = io_fadvise(req, issue_flags);
5993 case IORING_OP_MADVISE:
5994 ret = io_madvise(req, issue_flags);
5996 case IORING_OP_OPENAT2:
5997 ret = io_openat2(req, issue_flags);
5999 case IORING_OP_EPOLL_CTL:
6000 ret = io_epoll_ctl(req, issue_flags);
6002 case IORING_OP_SPLICE:
6003 ret = io_splice(req, issue_flags);
6005 case IORING_OP_PROVIDE_BUFFERS:
6006 ret = io_provide_buffers(req, issue_flags);
6008 case IORING_OP_REMOVE_BUFFERS:
6009 ret = io_remove_buffers(req, issue_flags);
6012 ret = io_tee(req, issue_flags);
6014 case IORING_OP_SHUTDOWN:
6015 ret = io_shutdown(req, issue_flags);
6017 case IORING_OP_RENAMEAT:
6018 ret = io_renameat(req, issue_flags);
6020 case IORING_OP_UNLINKAT:
6021 ret = io_unlinkat(req, issue_flags);
6029 revert_creds(creds);
6034 /* If the op doesn't have a file, we're not polling for it */
6035 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
6036 const bool in_async = io_wq_current_is_worker();
6038 /* workqueue context doesn't hold uring_lock, grab it now */
6040 mutex_lock(&ctx->uring_lock);
6042 io_iopoll_req_issued(req, in_async);
6045 mutex_unlock(&ctx->uring_lock);
6051 static void io_wq_submit_work(struct io_wq_work *work)
6053 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
6054 struct io_kiocb *timeout;
6057 timeout = io_prep_linked_timeout(req);
6059 io_queue_linked_timeout(timeout);
6061 if (work->flags & IO_WQ_WORK_CANCEL)
6066 ret = io_issue_sqe(req, 0);
6068 * We can get EAGAIN for polled IO even though we're
6069 * forcing a sync submission from here, since we can't
6070 * wait for request slots on the block side.
6078 /* avoid locking problems by failing it from a clean context */
6080 /* io-wq is going to take one down */
6081 refcount_inc(&req->refs);
6082 io_req_task_queue_fail(req, ret);
6086 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
6089 struct fixed_rsrc_table *table;
6091 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
6092 return table->files[index & IORING_FILE_TABLE_MASK];
6095 static struct file *io_file_get(struct io_submit_state *state,
6096 struct io_kiocb *req, int fd, bool fixed)
6098 struct io_ring_ctx *ctx = req->ctx;
6102 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
6104 fd = array_index_nospec(fd, ctx->nr_user_files);
6105 file = io_file_from_index(ctx, fd);
6106 io_set_resource_node(req);
6108 trace_io_uring_file_get(ctx, fd);
6109 file = __io_file_get(state, fd);
6112 if (file && unlikely(file->f_op == &io_uring_fops))
6113 io_req_track_inflight(req);
6117 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
6119 struct io_timeout_data *data = container_of(timer,
6120 struct io_timeout_data, timer);
6121 struct io_kiocb *prev, *req = data->req;
6122 struct io_ring_ctx *ctx = req->ctx;
6123 unsigned long flags;
6125 spin_lock_irqsave(&ctx->completion_lock, flags);
6126 prev = req->timeout.head;
6127 req->timeout.head = NULL;
6130 * We don't expect the list to be empty, that will only happen if we
6131 * race with the completion of the linked work.
6133 if (prev && refcount_inc_not_zero(&prev->refs))
6134 io_remove_next_linked(prev);
6137 spin_unlock_irqrestore(&ctx->completion_lock, flags);
6140 req_set_fail_links(prev);
6141 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
6142 io_put_req_deferred(prev, 1);
6144 io_req_complete_post(req, -ETIME, 0);
6145 io_put_req_deferred(req, 1);
6147 return HRTIMER_NORESTART;
6150 static void __io_queue_linked_timeout(struct io_kiocb *req)
6153 * If the back reference is NULL, then our linked request finished
6154 * before we got a chance to setup the timer
6156 if (req->timeout.head) {
6157 struct io_timeout_data *data = req->async_data;
6159 data->timer.function = io_link_timeout_fn;
6160 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
6165 static void io_queue_linked_timeout(struct io_kiocb *req)
6167 struct io_ring_ctx *ctx = req->ctx;
6169 spin_lock_irq(&ctx->completion_lock);
6170 __io_queue_linked_timeout(req);
6171 spin_unlock_irq(&ctx->completion_lock);
6173 /* drop submission reference */
6177 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
6179 struct io_kiocb *nxt = req->link;
6181 if (!nxt || (req->flags & REQ_F_LINK_TIMEOUT) ||
6182 nxt->opcode != IORING_OP_LINK_TIMEOUT)
6185 nxt->timeout.head = req;
6186 nxt->flags |= REQ_F_LTIMEOUT_ACTIVE;
6187 req->flags |= REQ_F_LINK_TIMEOUT;
6191 static void __io_queue_sqe(struct io_kiocb *req)
6193 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
6196 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6199 * We async punt it if the file wasn't marked NOWAIT, or if the file
6200 * doesn't support non-blocking read/write attempts
6202 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
6203 if (!io_arm_poll_handler(req)) {
6205 * Queued up for async execution, worker will release
6206 * submit reference when the iocb is actually submitted.
6208 io_queue_async_work(req);
6210 } else if (likely(!ret)) {
6211 /* drop submission reference */
6212 if (req->flags & REQ_F_COMPLETE_INLINE) {
6213 struct io_ring_ctx *ctx = req->ctx;
6214 struct io_comp_state *cs = &ctx->submit_state.comp;
6216 cs->reqs[cs->nr++] = req;
6217 if (cs->nr == ARRAY_SIZE(cs->reqs))
6218 io_submit_flush_completions(cs, ctx);
6223 req_set_fail_links(req);
6225 io_req_complete(req, ret);
6228 io_queue_linked_timeout(linked_timeout);
6231 static void io_queue_sqe(struct io_kiocb *req)
6235 ret = io_req_defer(req);
6237 if (ret != -EIOCBQUEUED) {
6239 req_set_fail_links(req);
6241 io_req_complete(req, ret);
6243 } else if (req->flags & REQ_F_FORCE_ASYNC) {
6244 ret = io_req_defer_prep(req);
6247 io_queue_async_work(req);
6249 __io_queue_sqe(req);
6254 * Check SQE restrictions (opcode and flags).
6256 * Returns 'true' if SQE is allowed, 'false' otherwise.
6258 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
6259 struct io_kiocb *req,
6260 unsigned int sqe_flags)
6262 if (!ctx->restricted)
6265 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
6268 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
6269 ctx->restrictions.sqe_flags_required)
6272 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
6273 ctx->restrictions.sqe_flags_required))
6279 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6280 const struct io_uring_sqe *sqe)
6282 struct io_submit_state *state;
6283 unsigned int sqe_flags;
6286 req->opcode = READ_ONCE(sqe->opcode);
6287 /* same numerical values with corresponding REQ_F_*, safe to copy */
6288 req->flags = sqe_flags = READ_ONCE(sqe->flags);
6289 req->user_data = READ_ONCE(sqe->user_data);
6290 req->async_data = NULL;
6294 req->fixed_rsrc_refs = NULL;
6295 /* one is dropped after submission, the other at completion */
6296 refcount_set(&req->refs, 2);
6297 req->task = current;
6300 /* enforce forwards compatibility on users */
6301 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS)) {
6306 if (unlikely(req->opcode >= IORING_OP_LAST))
6309 if (unlikely(!io_check_restriction(ctx, req, sqe_flags)))
6312 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6313 !io_op_defs[req->opcode].buffer_select)
6316 req->work.list.next = NULL;
6317 req->work.flags = 0;
6318 req->work.personality = READ_ONCE(sqe->personality);
6319 state = &ctx->submit_state;
6322 * Plug now if we have more than 1 IO left after this, and the target
6323 * is potentially a read/write to block based storage.
6325 if (!state->plug_started && state->ios_left > 1 &&
6326 io_op_defs[req->opcode].plug) {
6327 blk_start_plug(&state->plug);
6328 state->plug_started = true;
6331 if (io_op_defs[req->opcode].needs_file) {
6332 bool fixed = req->flags & REQ_F_FIXED_FILE;
6334 req->file = io_file_get(state, req, READ_ONCE(sqe->fd), fixed);
6335 if (unlikely(!req->file))
6343 static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
6344 const struct io_uring_sqe *sqe)
6346 struct io_submit_link *link = &ctx->submit_state.link;
6349 ret = io_init_req(ctx, req, sqe);
6350 if (unlikely(ret)) {
6353 io_req_complete(req, ret);
6355 /* fail even hard links since we don't submit */
6356 link->head->flags |= REQ_F_FAIL_LINK;
6357 io_put_req(link->head);
6358 io_req_complete(link->head, -ECANCELED);
6363 ret = io_req_prep(req, sqe);
6367 /* don't need @sqe from now on */
6368 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6369 true, ctx->flags & IORING_SETUP_SQPOLL);
6372 * If we already have a head request, queue this one for async
6373 * submittal once the head completes. If we don't have a head but
6374 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
6375 * submitted sync once the chain is complete. If none of those
6376 * conditions are true (normal request), then just queue it.
6379 struct io_kiocb *head = link->head;
6382 * Taking sequential execution of a link, draining both sides
6383 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6384 * requests in the link. So, it drains the head and the
6385 * next after the link request. The last one is done via
6386 * drain_next flag to persist the effect across calls.
6388 if (req->flags & REQ_F_IO_DRAIN) {
6389 head->flags |= REQ_F_IO_DRAIN;
6390 ctx->drain_next = 1;
6392 ret = io_req_defer_prep(req);
6395 trace_io_uring_link(ctx, req, head);
6396 link->last->link = req;
6399 /* last request of a link, enqueue the link */
6400 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6405 if (unlikely(ctx->drain_next)) {
6406 req->flags |= REQ_F_IO_DRAIN;
6407 ctx->drain_next = 0;
6409 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6421 * Batched submission is done, ensure local IO is flushed out.
6423 static void io_submit_state_end(struct io_submit_state *state,
6424 struct io_ring_ctx *ctx)
6426 if (state->link.head)
6427 io_queue_sqe(state->link.head);
6429 io_submit_flush_completions(&state->comp, ctx);
6430 if (state->plug_started)
6431 blk_finish_plug(&state->plug);
6432 io_state_file_put(state);
6436 * Start submission side cache.
6438 static void io_submit_state_start(struct io_submit_state *state,
6439 unsigned int max_ios)
6441 state->plug_started = false;
6442 state->ios_left = max_ios;
6443 /* set only head, no need to init link_last in advance */
6444 state->link.head = NULL;
6447 static void io_commit_sqring(struct io_ring_ctx *ctx)
6449 struct io_rings *rings = ctx->rings;
6452 * Ensure any loads from the SQEs are done at this point,
6453 * since once we write the new head, the application could
6454 * write new data to them.
6456 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6460 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6461 * that is mapped by userspace. This means that care needs to be taken to
6462 * ensure that reads are stable, as we cannot rely on userspace always
6463 * being a good citizen. If members of the sqe are validated and then later
6464 * used, it's important that those reads are done through READ_ONCE() to
6465 * prevent a re-load down the line.
6467 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6469 u32 *sq_array = ctx->sq_array;
6473 * The cached sq head (or cq tail) serves two purposes:
6475 * 1) allows us to batch the cost of updating the user visible
6477 * 2) allows the kernel side to track the head on its own, even
6478 * though the application is the one updating it.
6480 head = READ_ONCE(sq_array[ctx->cached_sq_head++ & ctx->sq_mask]);
6481 if (likely(head < ctx->sq_entries))
6482 return &ctx->sq_sqes[head];
6484 /* drop invalid entries */
6485 ctx->cached_sq_dropped++;
6486 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6490 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
6494 /* if we have a backlog and couldn't flush it all, return BUSY */
6495 if (test_bit(0, &ctx->sq_check_overflow)) {
6496 if (!__io_cqring_overflow_flush(ctx, false, NULL, NULL))
6500 /* make sure SQ entry isn't read before tail */
6501 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6503 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6506 percpu_counter_add(¤t->io_uring->inflight, nr);
6507 refcount_add(nr, ¤t->usage);
6508 io_submit_state_start(&ctx->submit_state, nr);
6510 while (submitted < nr) {
6511 const struct io_uring_sqe *sqe;
6512 struct io_kiocb *req;
6514 req = io_alloc_req(ctx);
6515 if (unlikely(!req)) {
6517 submitted = -EAGAIN;
6520 sqe = io_get_sqe(ctx);
6521 if (unlikely(!sqe)) {
6522 kmem_cache_free(req_cachep, req);
6525 /* will complete beyond this point, count as submitted */
6527 if (io_submit_sqe(ctx, req, sqe))
6531 if (unlikely(submitted != nr)) {
6532 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6533 struct io_uring_task *tctx = current->io_uring;
6534 int unused = nr - ref_used;
6536 percpu_ref_put_many(&ctx->refs, unused);
6537 percpu_counter_sub(&tctx->inflight, unused);
6538 put_task_struct_many(current, unused);
6541 io_submit_state_end(&ctx->submit_state, ctx);
6542 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6543 io_commit_sqring(ctx);
6548 static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
6550 /* Tell userspace we may need a wakeup call */
6551 spin_lock_irq(&ctx->completion_lock);
6552 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6553 spin_unlock_irq(&ctx->completion_lock);
6556 static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
6558 spin_lock_irq(&ctx->completion_lock);
6559 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6560 spin_unlock_irq(&ctx->completion_lock);
6563 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6565 unsigned int to_submit;
6568 to_submit = io_sqring_entries(ctx);
6569 /* if we're handling multiple rings, cap submit size for fairness */
6570 if (cap_entries && to_submit > 8)
6573 if (!list_empty(&ctx->iopoll_list) || to_submit) {
6574 unsigned nr_events = 0;
6576 mutex_lock(&ctx->uring_lock);
6577 if (!list_empty(&ctx->iopoll_list))
6578 io_do_iopoll(ctx, &nr_events, 0);
6580 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)))
6581 ret = io_submit_sqes(ctx, to_submit);
6582 mutex_unlock(&ctx->uring_lock);
6585 if (!io_sqring_full(ctx) && wq_has_sleeper(&ctx->sqo_sq_wait))
6586 wake_up(&ctx->sqo_sq_wait);
6591 static void io_sqd_update_thread_idle(struct io_sq_data *sqd)
6593 struct io_ring_ctx *ctx;
6594 unsigned sq_thread_idle = 0;
6596 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6597 if (sq_thread_idle < ctx->sq_thread_idle)
6598 sq_thread_idle = ctx->sq_thread_idle;
6601 sqd->sq_thread_idle = sq_thread_idle;
6604 static void io_sqd_init_new(struct io_sq_data *sqd)
6606 struct io_ring_ctx *ctx;
6608 while (!list_empty(&sqd->ctx_new_list)) {
6609 ctx = list_first_entry(&sqd->ctx_new_list, struct io_ring_ctx, sqd_list);
6610 list_move_tail(&ctx->sqd_list, &sqd->ctx_list);
6611 complete(&ctx->sq_thread_comp);
6614 io_sqd_update_thread_idle(sqd);
6617 static bool io_sq_thread_should_stop(struct io_sq_data *sqd)
6619 return test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
6622 static bool io_sq_thread_should_park(struct io_sq_data *sqd)
6624 return test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
6627 static void io_sq_thread_parkme(struct io_sq_data *sqd)
6631 * TASK_PARKED is a special state; we must serialize against
6632 * possible pending wakeups to avoid store-store collisions on
6635 * Such a collision might possibly result in the task state
6636 * changin from TASK_PARKED and us failing the
6637 * wait_task_inactive() in kthread_park().
6639 set_special_state(TASK_PARKED);
6640 if (!test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state))
6644 * Thread is going to call schedule(), do not preempt it,
6645 * or the caller of kthread_park() may spend more time in
6646 * wait_task_inactive().
6649 complete(&sqd->completion);
6650 schedule_preempt_disabled();
6653 __set_current_state(TASK_RUNNING);
6656 static int io_sq_thread(void *data)
6658 struct io_sq_data *sqd = data;
6659 struct io_ring_ctx *ctx;
6660 unsigned long timeout = 0;
6661 char buf[TASK_COMM_LEN];
6664 sprintf(buf, "iou-sqp-%d", sqd->task_pid);
6665 set_task_comm(current, buf);
6666 sqd->thread = current;
6667 current->pf_io_worker = NULL;
6669 if (sqd->sq_cpu != -1)
6670 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
6672 set_cpus_allowed_ptr(current, cpu_online_mask);
6673 current->flags |= PF_NO_SETAFFINITY;
6675 complete(&sqd->completion);
6677 wait_for_completion(&sqd->startup);
6679 while (!io_sq_thread_should_stop(sqd)) {
6681 bool cap_entries, sqt_spin, needs_sched;
6684 * Any changes to the sqd lists are synchronized through the
6685 * thread parking. This synchronizes the thread vs users,
6686 * the users are synchronized on the sqd->ctx_lock.
6688 if (io_sq_thread_should_park(sqd)) {
6689 io_sq_thread_parkme(sqd);
6692 if (unlikely(!list_empty(&sqd->ctx_new_list))) {
6693 io_sqd_init_new(sqd);
6694 timeout = jiffies + sqd->sq_thread_idle;
6696 if (fatal_signal_pending(current))
6699 cap_entries = !list_is_singular(&sqd->ctx_list);
6700 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6701 ret = __io_sq_thread(ctx, cap_entries);
6702 if (!sqt_spin && (ret > 0 || !list_empty(&ctx->iopoll_list)))
6706 if (sqt_spin || !time_after(jiffies, timeout)) {
6710 timeout = jiffies + sqd->sq_thread_idle;
6715 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
6716 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6717 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6718 !list_empty_careful(&ctx->iopoll_list)) {
6719 needs_sched = false;
6722 if (io_sqring_entries(ctx)) {
6723 needs_sched = false;
6728 if (needs_sched && !io_sq_thread_should_park(sqd)) {
6729 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6730 io_ring_set_wakeup_flag(ctx);
6733 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6734 io_ring_clear_wakeup_flag(ctx);
6737 finish_wait(&sqd->wait, &wait);
6738 timeout = jiffies + sqd->sq_thread_idle;
6741 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
6742 io_uring_cancel_sqpoll(ctx);
6746 if (io_sq_thread_should_park(sqd))
6747 io_sq_thread_parkme(sqd);
6750 * Clear thread under lock so that concurrent parks work correctly
6752 complete(&sqd->completion);
6753 mutex_lock(&sqd->lock);
6755 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
6757 io_ring_set_wakeup_flag(ctx);
6760 complete(&sqd->exited);
6761 mutex_unlock(&sqd->lock);
6765 struct io_wait_queue {
6766 struct wait_queue_entry wq;
6767 struct io_ring_ctx *ctx;
6769 unsigned nr_timeouts;
6772 static inline bool io_should_wake(struct io_wait_queue *iowq)
6774 struct io_ring_ctx *ctx = iowq->ctx;
6777 * Wake up if we have enough events, or if a timeout occurred since we
6778 * started waiting. For timeouts, we always want to return to userspace,
6779 * regardless of event count.
6781 return io_cqring_events(ctx) >= iowq->to_wait ||
6782 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6785 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6786 int wake_flags, void *key)
6788 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6792 * Cannot safely flush overflowed CQEs from here, ensure we wake up
6793 * the task, and the next invocation will do it.
6795 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->cq_check_overflow))
6796 return autoremove_wake_function(curr, mode, wake_flags, key);
6800 static int io_run_task_work_sig(void)
6802 if (io_run_task_work())
6804 if (!signal_pending(current))
6806 if (test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))
6807 return -ERESTARTSYS;
6811 /* when returns >0, the caller should retry */
6812 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
6813 struct io_wait_queue *iowq,
6814 signed long *timeout)
6818 /* make sure we run task_work before checking for signals */
6819 ret = io_run_task_work_sig();
6820 if (ret || io_should_wake(iowq))
6822 /* let the caller flush overflows, retry */
6823 if (test_bit(0, &ctx->cq_check_overflow))
6826 *timeout = schedule_timeout(*timeout);
6827 return !*timeout ? -ETIME : 1;
6831 * Wait until events become available, if we don't already have some. The
6832 * application must reap them itself, as they reside on the shared cq ring.
6834 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6835 const sigset_t __user *sig, size_t sigsz,
6836 struct __kernel_timespec __user *uts)
6838 struct io_wait_queue iowq = {
6841 .func = io_wake_function,
6842 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6845 .to_wait = min_events,
6847 struct io_rings *rings = ctx->rings;
6848 signed long timeout = MAX_SCHEDULE_TIMEOUT;
6852 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6853 if (io_cqring_events(ctx) >= min_events)
6855 if (!io_run_task_work())
6860 #ifdef CONFIG_COMPAT
6861 if (in_compat_syscall())
6862 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6866 ret = set_user_sigmask(sig, sigsz);
6873 struct timespec64 ts;
6875 if (get_timespec64(&ts, uts))
6877 timeout = timespec64_to_jiffies(&ts);
6880 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6881 trace_io_uring_cqring_wait(ctx, min_events);
6883 io_cqring_overflow_flush(ctx, false, NULL, NULL);
6884 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6885 TASK_INTERRUPTIBLE);
6886 ret = io_cqring_wait_schedule(ctx, &iowq, &timeout);
6887 finish_wait(&ctx->wait, &iowq.wq);
6890 restore_saved_sigmask_unless(ret == -EINTR);
6892 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6895 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6897 #if defined(CONFIG_UNIX)
6898 if (ctx->ring_sock) {
6899 struct sock *sock = ctx->ring_sock->sk;
6900 struct sk_buff *skb;
6902 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6908 for (i = 0; i < ctx->nr_user_files; i++) {
6911 file = io_file_from_index(ctx, i);
6918 static void io_rsrc_data_ref_zero(struct percpu_ref *ref)
6920 struct fixed_rsrc_data *data;
6922 data = container_of(ref, struct fixed_rsrc_data, refs);
6923 complete(&data->done);
6926 static inline void io_rsrc_ref_lock(struct io_ring_ctx *ctx)
6928 spin_lock_bh(&ctx->rsrc_ref_lock);
6931 static inline void io_rsrc_ref_unlock(struct io_ring_ctx *ctx)
6933 spin_unlock_bh(&ctx->rsrc_ref_lock);
6936 static void io_sqe_rsrc_set_node(struct io_ring_ctx *ctx,
6937 struct fixed_rsrc_data *rsrc_data,
6938 struct fixed_rsrc_ref_node *ref_node)
6940 io_rsrc_ref_lock(ctx);
6941 rsrc_data->node = ref_node;
6942 list_add_tail(&ref_node->node, &ctx->rsrc_ref_list);
6943 io_rsrc_ref_unlock(ctx);
6944 percpu_ref_get(&rsrc_data->refs);
6947 static void io_sqe_rsrc_kill_node(struct io_ring_ctx *ctx, struct fixed_rsrc_data *data)
6949 struct fixed_rsrc_ref_node *ref_node = NULL;
6951 io_rsrc_ref_lock(ctx);
6952 ref_node = data->node;
6954 io_rsrc_ref_unlock(ctx);
6956 percpu_ref_kill(&ref_node->refs);
6959 static int io_rsrc_ref_quiesce(struct fixed_rsrc_data *data,
6960 struct io_ring_ctx *ctx,
6961 void (*rsrc_put)(struct io_ring_ctx *ctx,
6962 struct io_rsrc_put *prsrc))
6964 struct fixed_rsrc_ref_node *backup_node;
6970 data->quiesce = true;
6973 backup_node = alloc_fixed_rsrc_ref_node(ctx);
6976 backup_node->rsrc_data = data;
6977 backup_node->rsrc_put = rsrc_put;
6979 io_sqe_rsrc_kill_node(ctx, data);
6980 percpu_ref_kill(&data->refs);
6981 flush_delayed_work(&ctx->rsrc_put_work);
6983 ret = wait_for_completion_interruptible(&data->done);
6987 percpu_ref_resurrect(&data->refs);
6988 io_sqe_rsrc_set_node(ctx, data, backup_node);
6990 reinit_completion(&data->done);
6991 mutex_unlock(&ctx->uring_lock);
6992 ret = io_run_task_work_sig();
6993 mutex_lock(&ctx->uring_lock);
6995 data->quiesce = false;
6998 destroy_fixed_rsrc_ref_node(backup_node);
7002 static struct fixed_rsrc_data *alloc_fixed_rsrc_data(struct io_ring_ctx *ctx)
7004 struct fixed_rsrc_data *data;
7006 data = kzalloc(sizeof(*data), GFP_KERNEL);
7010 if (percpu_ref_init(&data->refs, io_rsrc_data_ref_zero,
7011 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
7016 init_completion(&data->done);
7020 static void free_fixed_rsrc_data(struct fixed_rsrc_data *data)
7022 percpu_ref_exit(&data->refs);
7027 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
7029 struct fixed_rsrc_data *data = ctx->file_data;
7030 unsigned nr_tables, i;
7034 * percpu_ref_is_dying() is to stop parallel files unregister
7035 * Since we possibly drop uring lock later in this function to
7038 if (!data || percpu_ref_is_dying(&data->refs))
7040 ret = io_rsrc_ref_quiesce(data, ctx, io_ring_file_put);
7044 __io_sqe_files_unregister(ctx);
7045 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
7046 for (i = 0; i < nr_tables; i++)
7047 kfree(data->table[i].files);
7048 free_fixed_rsrc_data(data);
7049 ctx->file_data = NULL;
7050 ctx->nr_user_files = 0;
7054 static void io_sq_thread_unpark(struct io_sq_data *sqd)
7055 __releases(&sqd->lock)
7059 if (sqd->thread == current)
7061 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7062 wake_up_state(sqd->thread, TASK_PARKED);
7063 mutex_unlock(&sqd->lock);
7066 static bool io_sq_thread_park(struct io_sq_data *sqd)
7067 __acquires(&sqd->lock)
7069 if (sqd->thread == current)
7071 mutex_lock(&sqd->lock);
7073 mutex_unlock(&sqd->lock);
7076 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
7077 wake_up_process(sqd->thread);
7078 wait_for_completion(&sqd->completion);
7082 static void io_sq_thread_stop(struct io_sq_data *sqd)
7084 if (test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state))
7086 mutex_lock(&sqd->lock);
7088 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7089 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state));
7090 wake_up_process(sqd->thread);
7091 mutex_unlock(&sqd->lock);
7092 wait_for_completion(&sqd->exited);
7093 WARN_ON_ONCE(sqd->thread);
7095 mutex_unlock(&sqd->lock);
7099 static void io_put_sq_data(struct io_sq_data *sqd)
7101 if (refcount_dec_and_test(&sqd->refs)) {
7102 io_sq_thread_stop(sqd);
7107 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
7109 struct io_sq_data *sqd = ctx->sq_data;
7112 complete(&sqd->startup);
7114 wait_for_completion(&ctx->sq_thread_comp);
7115 io_sq_thread_park(sqd);
7118 mutex_lock(&sqd->ctx_lock);
7119 list_del(&ctx->sqd_list);
7120 io_sqd_update_thread_idle(sqd);
7121 mutex_unlock(&sqd->ctx_lock);
7124 io_sq_thread_unpark(sqd);
7126 io_put_sq_data(sqd);
7127 ctx->sq_data = NULL;
7131 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
7133 struct io_ring_ctx *ctx_attach;
7134 struct io_sq_data *sqd;
7137 f = fdget(p->wq_fd);
7139 return ERR_PTR(-ENXIO);
7140 if (f.file->f_op != &io_uring_fops) {
7142 return ERR_PTR(-EINVAL);
7145 ctx_attach = f.file->private_data;
7146 sqd = ctx_attach->sq_data;
7149 return ERR_PTR(-EINVAL);
7152 refcount_inc(&sqd->refs);
7157 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p)
7159 struct io_sq_data *sqd;
7161 if (p->flags & IORING_SETUP_ATTACH_WQ)
7162 return io_attach_sq_data(p);
7164 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
7166 return ERR_PTR(-ENOMEM);
7168 refcount_set(&sqd->refs, 1);
7169 INIT_LIST_HEAD(&sqd->ctx_list);
7170 INIT_LIST_HEAD(&sqd->ctx_new_list);
7171 mutex_init(&sqd->ctx_lock);
7172 mutex_init(&sqd->lock);
7173 init_waitqueue_head(&sqd->wait);
7174 init_completion(&sqd->startup);
7175 init_completion(&sqd->completion);
7176 init_completion(&sqd->exited);
7180 #if defined(CONFIG_UNIX)
7182 * Ensure the UNIX gc is aware of our file set, so we are certain that
7183 * the io_uring can be safely unregistered on process exit, even if we have
7184 * loops in the file referencing.
7186 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
7188 struct sock *sk = ctx->ring_sock->sk;
7189 struct scm_fp_list *fpl;
7190 struct sk_buff *skb;
7193 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
7197 skb = alloc_skb(0, GFP_KERNEL);
7206 fpl->user = get_uid(current_user());
7207 for (i = 0; i < nr; i++) {
7208 struct file *file = io_file_from_index(ctx, i + offset);
7212 fpl->fp[nr_files] = get_file(file);
7213 unix_inflight(fpl->user, fpl->fp[nr_files]);
7218 fpl->max = SCM_MAX_FD;
7219 fpl->count = nr_files;
7220 UNIXCB(skb).fp = fpl;
7221 skb->destructor = unix_destruct_scm;
7222 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
7223 skb_queue_head(&sk->sk_receive_queue, skb);
7225 for (i = 0; i < nr_files; i++)
7236 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
7237 * causes regular reference counting to break down. We rely on the UNIX
7238 * garbage collection to take care of this problem for us.
7240 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7242 unsigned left, total;
7246 left = ctx->nr_user_files;
7248 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
7250 ret = __io_sqe_files_scm(ctx, this_files, total);
7254 total += this_files;
7260 while (total < ctx->nr_user_files) {
7261 struct file *file = io_file_from_index(ctx, total);
7271 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
7277 static int io_sqe_alloc_file_tables(struct fixed_rsrc_data *file_data,
7278 unsigned nr_tables, unsigned nr_files)
7282 for (i = 0; i < nr_tables; i++) {
7283 struct fixed_rsrc_table *table = &file_data->table[i];
7284 unsigned this_files;
7286 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
7287 table->files = kcalloc(this_files, sizeof(struct file *),
7291 nr_files -= this_files;
7297 for (i = 0; i < nr_tables; i++) {
7298 struct fixed_rsrc_table *table = &file_data->table[i];
7299 kfree(table->files);
7304 static void io_ring_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
7306 struct file *file = prsrc->file;
7307 #if defined(CONFIG_UNIX)
7308 struct sock *sock = ctx->ring_sock->sk;
7309 struct sk_buff_head list, *head = &sock->sk_receive_queue;
7310 struct sk_buff *skb;
7313 __skb_queue_head_init(&list);
7316 * Find the skb that holds this file in its SCM_RIGHTS. When found,
7317 * remove this entry and rearrange the file array.
7319 skb = skb_dequeue(head);
7321 struct scm_fp_list *fp;
7323 fp = UNIXCB(skb).fp;
7324 for (i = 0; i < fp->count; i++) {
7327 if (fp->fp[i] != file)
7330 unix_notinflight(fp->user, fp->fp[i]);
7331 left = fp->count - 1 - i;
7333 memmove(&fp->fp[i], &fp->fp[i + 1],
7334 left * sizeof(struct file *));
7341 __skb_queue_tail(&list, skb);
7351 __skb_queue_tail(&list, skb);
7353 skb = skb_dequeue(head);
7356 if (skb_peek(&list)) {
7357 spin_lock_irq(&head->lock);
7358 while ((skb = __skb_dequeue(&list)) != NULL)
7359 __skb_queue_tail(head, skb);
7360 spin_unlock_irq(&head->lock);
7367 static void __io_rsrc_put_work(struct fixed_rsrc_ref_node *ref_node)
7369 struct fixed_rsrc_data *rsrc_data = ref_node->rsrc_data;
7370 struct io_ring_ctx *ctx = rsrc_data->ctx;
7371 struct io_rsrc_put *prsrc, *tmp;
7373 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
7374 list_del(&prsrc->list);
7375 ref_node->rsrc_put(ctx, prsrc);
7379 percpu_ref_exit(&ref_node->refs);
7381 percpu_ref_put(&rsrc_data->refs);
7384 static void io_rsrc_put_work(struct work_struct *work)
7386 struct io_ring_ctx *ctx;
7387 struct llist_node *node;
7389 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
7390 node = llist_del_all(&ctx->rsrc_put_llist);
7393 struct fixed_rsrc_ref_node *ref_node;
7394 struct llist_node *next = node->next;
7396 ref_node = llist_entry(node, struct fixed_rsrc_ref_node, llist);
7397 __io_rsrc_put_work(ref_node);
7402 static struct file **io_fixed_file_slot(struct fixed_rsrc_data *file_data,
7405 struct fixed_rsrc_table *table;
7407 table = &file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7408 return &table->files[i & IORING_FILE_TABLE_MASK];
7411 static void io_rsrc_node_ref_zero(struct percpu_ref *ref)
7413 struct fixed_rsrc_ref_node *ref_node;
7414 struct fixed_rsrc_data *data;
7415 struct io_ring_ctx *ctx;
7416 bool first_add = false;
7419 ref_node = container_of(ref, struct fixed_rsrc_ref_node, refs);
7420 data = ref_node->rsrc_data;
7423 io_rsrc_ref_lock(ctx);
7424 ref_node->done = true;
7426 while (!list_empty(&ctx->rsrc_ref_list)) {
7427 ref_node = list_first_entry(&ctx->rsrc_ref_list,
7428 struct fixed_rsrc_ref_node, node);
7429 /* recycle ref nodes in order */
7430 if (!ref_node->done)
7432 list_del(&ref_node->node);
7433 first_add |= llist_add(&ref_node->llist, &ctx->rsrc_put_llist);
7435 io_rsrc_ref_unlock(ctx);
7437 if (percpu_ref_is_dying(&data->refs))
7441 mod_delayed_work(system_wq, &ctx->rsrc_put_work, 0);
7443 queue_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
7446 static struct fixed_rsrc_ref_node *alloc_fixed_rsrc_ref_node(
7447 struct io_ring_ctx *ctx)
7449 struct fixed_rsrc_ref_node *ref_node;
7451 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
7455 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
7460 INIT_LIST_HEAD(&ref_node->node);
7461 INIT_LIST_HEAD(&ref_node->rsrc_list);
7462 ref_node->done = false;
7466 static void init_fixed_file_ref_node(struct io_ring_ctx *ctx,
7467 struct fixed_rsrc_ref_node *ref_node)
7469 ref_node->rsrc_data = ctx->file_data;
7470 ref_node->rsrc_put = io_ring_file_put;
7473 static void destroy_fixed_rsrc_ref_node(struct fixed_rsrc_ref_node *ref_node)
7475 percpu_ref_exit(&ref_node->refs);
7480 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
7483 __s32 __user *fds = (__s32 __user *) arg;
7484 unsigned nr_tables, i;
7486 int fd, ret = -ENOMEM;
7487 struct fixed_rsrc_ref_node *ref_node;
7488 struct fixed_rsrc_data *file_data;
7494 if (nr_args > IORING_MAX_FIXED_FILES)
7497 file_data = alloc_fixed_rsrc_data(ctx);
7500 ctx->file_data = file_data;
7502 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
7503 file_data->table = kcalloc(nr_tables, sizeof(*file_data->table),
7505 if (!file_data->table)
7508 if (io_sqe_alloc_file_tables(file_data, nr_tables, nr_args))
7511 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
7512 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
7516 /* allow sparse sets */
7526 * Don't allow io_uring instances to be registered. If UNIX
7527 * isn't enabled, then this causes a reference cycle and this
7528 * instance can never get freed. If UNIX is enabled we'll
7529 * handle it just fine, but there's still no point in allowing
7530 * a ring fd as it doesn't support regular read/write anyway.
7532 if (file->f_op == &io_uring_fops) {
7536 *io_fixed_file_slot(file_data, i) = file;
7539 ret = io_sqe_files_scm(ctx);
7541 io_sqe_files_unregister(ctx);
7545 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7547 io_sqe_files_unregister(ctx);
7550 init_fixed_file_ref_node(ctx, ref_node);
7552 io_sqe_rsrc_set_node(ctx, file_data, ref_node);
7555 for (i = 0; i < ctx->nr_user_files; i++) {
7556 file = io_file_from_index(ctx, i);
7560 for (i = 0; i < nr_tables; i++)
7561 kfree(file_data->table[i].files);
7562 ctx->nr_user_files = 0;
7564 free_fixed_rsrc_data(ctx->file_data);
7565 ctx->file_data = NULL;
7569 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
7572 #if defined(CONFIG_UNIX)
7573 struct sock *sock = ctx->ring_sock->sk;
7574 struct sk_buff_head *head = &sock->sk_receive_queue;
7575 struct sk_buff *skb;
7578 * See if we can merge this file into an existing skb SCM_RIGHTS
7579 * file set. If there's no room, fall back to allocating a new skb
7580 * and filling it in.
7582 spin_lock_irq(&head->lock);
7583 skb = skb_peek(head);
7585 struct scm_fp_list *fpl = UNIXCB(skb).fp;
7587 if (fpl->count < SCM_MAX_FD) {
7588 __skb_unlink(skb, head);
7589 spin_unlock_irq(&head->lock);
7590 fpl->fp[fpl->count] = get_file(file);
7591 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7593 spin_lock_irq(&head->lock);
7594 __skb_queue_head(head, skb);
7599 spin_unlock_irq(&head->lock);
7606 return __io_sqe_files_scm(ctx, 1, index);
7612 static int io_queue_rsrc_removal(struct fixed_rsrc_data *data, void *rsrc)
7614 struct io_rsrc_put *prsrc;
7615 struct fixed_rsrc_ref_node *ref_node = data->node;
7617 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
7622 list_add(&prsrc->list, &ref_node->rsrc_list);
7627 static inline int io_queue_file_removal(struct fixed_rsrc_data *data,
7630 return io_queue_rsrc_removal(data, (void *)file);
7633 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7634 struct io_uring_rsrc_update *up,
7637 struct fixed_rsrc_data *data = ctx->file_data;
7638 struct fixed_rsrc_ref_node *ref_node;
7639 struct file *file, **file_slot;
7643 bool needs_switch = false;
7645 if (check_add_overflow(up->offset, nr_args, &done))
7647 if (done > ctx->nr_user_files)
7650 ref_node = alloc_fixed_rsrc_ref_node(ctx);
7653 init_fixed_file_ref_node(ctx, ref_node);
7655 fds = u64_to_user_ptr(up->data);
7656 for (done = 0; done < nr_args; done++) {
7658 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7662 if (fd == IORING_REGISTER_FILES_SKIP)
7665 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
7666 file_slot = io_fixed_file_slot(ctx->file_data, i);
7669 err = io_queue_file_removal(data, *file_slot);
7673 needs_switch = true;
7682 * Don't allow io_uring instances to be registered. If
7683 * UNIX isn't enabled, then this causes a reference
7684 * cycle and this instance can never get freed. If UNIX
7685 * is enabled we'll handle it just fine, but there's
7686 * still no point in allowing a ring fd as it doesn't
7687 * support regular read/write anyway.
7689 if (file->f_op == &io_uring_fops) {
7695 err = io_sqe_file_register(ctx, file, i);
7705 percpu_ref_kill(&data->node->refs);
7706 io_sqe_rsrc_set_node(ctx, data, ref_node);
7708 destroy_fixed_rsrc_ref_node(ref_node);
7710 return done ? done : err;
7713 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7716 struct io_uring_rsrc_update up;
7718 if (!ctx->file_data)
7722 if (copy_from_user(&up, arg, sizeof(up)))
7727 return __io_sqe_files_update(ctx, &up, nr_args);
7730 static struct io_wq_work *io_free_work(struct io_wq_work *work)
7732 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7734 req = io_put_req_find_next(req);
7735 return req ? &req->work : NULL;
7738 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx)
7740 struct io_wq_hash *hash;
7741 struct io_wq_data data;
7742 unsigned int concurrency;
7744 hash = ctx->hash_map;
7746 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
7748 return ERR_PTR(-ENOMEM);
7749 refcount_set(&hash->refs, 1);
7750 init_waitqueue_head(&hash->wait);
7751 ctx->hash_map = hash;
7755 data.free_work = io_free_work;
7756 data.do_work = io_wq_submit_work;
7758 /* Do QD, or 4 * CPUS, whatever is smallest */
7759 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7761 return io_wq_create(concurrency, &data);
7764 static int io_uring_alloc_task_context(struct task_struct *task,
7765 struct io_ring_ctx *ctx)
7767 struct io_uring_task *tctx;
7770 tctx = kmalloc(sizeof(*tctx), GFP_KERNEL);
7771 if (unlikely(!tctx))
7774 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
7775 if (unlikely(ret)) {
7780 tctx->io_wq = io_init_wq_offload(ctx);
7781 if (IS_ERR(tctx->io_wq)) {
7782 ret = PTR_ERR(tctx->io_wq);
7783 percpu_counter_destroy(&tctx->inflight);
7789 init_waitqueue_head(&tctx->wait);
7791 atomic_set(&tctx->in_idle, 0);
7792 tctx->sqpoll = false;
7793 task->io_uring = tctx;
7794 spin_lock_init(&tctx->task_lock);
7795 INIT_WQ_LIST(&tctx->task_list);
7796 tctx->task_state = 0;
7797 init_task_work(&tctx->task_work, tctx_task_work);
7801 void __io_uring_free(struct task_struct *tsk)
7803 struct io_uring_task *tctx = tsk->io_uring;
7805 WARN_ON_ONCE(!xa_empty(&tctx->xa));
7806 WARN_ON_ONCE(tctx->io_wq);
7808 percpu_counter_destroy(&tctx->inflight);
7810 tsk->io_uring = NULL;
7813 static int io_sq_thread_fork(struct io_sq_data *sqd, struct io_ring_ctx *ctx)
7817 clear_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7818 reinit_completion(&sqd->completion);
7820 sqd->task_pid = current->pid;
7821 current->flags |= PF_IO_WORKER;
7822 ret = io_wq_fork_thread(io_sq_thread, sqd);
7823 current->flags &= ~PF_IO_WORKER;
7828 wait_for_completion(&sqd->completion);
7829 return io_uring_alloc_task_context(sqd->thread, ctx);
7832 static int io_sq_offload_create(struct io_ring_ctx *ctx,
7833 struct io_uring_params *p)
7837 /* Retain compatibility with failing for an invalid attach attempt */
7838 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
7839 IORING_SETUP_ATTACH_WQ) {
7842 f = fdget(p->wq_fd);
7845 if (f.file->f_op != &io_uring_fops) {
7851 if (ctx->flags & IORING_SETUP_SQPOLL) {
7852 struct io_sq_data *sqd;
7855 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE))
7858 sqd = io_get_sq_data(p);
7865 io_sq_thread_park(sqd);
7866 mutex_lock(&sqd->ctx_lock);
7867 list_add(&ctx->sqd_list, &sqd->ctx_new_list);
7868 mutex_unlock(&sqd->ctx_lock);
7869 io_sq_thread_unpark(sqd);
7871 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7872 if (!ctx->sq_thread_idle)
7873 ctx->sq_thread_idle = HZ;
7878 if (p->flags & IORING_SETUP_SQ_AFF) {
7879 int cpu = p->sq_thread_cpu;
7882 if (cpu >= nr_cpu_ids)
7884 if (!cpu_online(cpu))
7892 sqd->task_pid = current->pid;
7893 current->flags |= PF_IO_WORKER;
7894 ret = io_wq_fork_thread(io_sq_thread, sqd);
7895 current->flags &= ~PF_IO_WORKER;
7900 wait_for_completion(&sqd->completion);
7901 ret = io_uring_alloc_task_context(sqd->thread, ctx);
7904 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7905 /* Can't have SQ_AFF without SQPOLL */
7912 io_sq_thread_finish(ctx);
7916 static void io_sq_offload_start(struct io_ring_ctx *ctx)
7918 struct io_sq_data *sqd = ctx->sq_data;
7920 ctx->flags &= ~IORING_SETUP_R_DISABLED;
7921 if (ctx->flags & IORING_SETUP_SQPOLL)
7922 complete(&sqd->startup);
7925 static inline void __io_unaccount_mem(struct user_struct *user,
7926 unsigned long nr_pages)
7928 atomic_long_sub(nr_pages, &user->locked_vm);
7931 static inline int __io_account_mem(struct user_struct *user,
7932 unsigned long nr_pages)
7934 unsigned long page_limit, cur_pages, new_pages;
7936 /* Don't allow more pages than we can safely lock */
7937 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7940 cur_pages = atomic_long_read(&user->locked_vm);
7941 new_pages = cur_pages + nr_pages;
7942 if (new_pages > page_limit)
7944 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7945 new_pages) != cur_pages);
7950 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7953 __io_unaccount_mem(ctx->user, nr_pages);
7955 if (ctx->mm_account)
7956 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
7959 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
7964 ret = __io_account_mem(ctx->user, nr_pages);
7969 if (ctx->mm_account)
7970 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
7975 static void io_mem_free(void *ptr)
7982 page = virt_to_head_page(ptr);
7983 if (put_page_testzero(page))
7984 free_compound_page(page);
7987 static void *io_mem_alloc(size_t size)
7989 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7990 __GFP_NORETRY | __GFP_ACCOUNT;
7992 return (void *) __get_free_pages(gfp_flags, get_order(size));
7995 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7998 struct io_rings *rings;
7999 size_t off, sq_array_size;
8001 off = struct_size(rings, cqes, cq_entries);
8002 if (off == SIZE_MAX)
8006 off = ALIGN(off, SMP_CACHE_BYTES);
8014 sq_array_size = array_size(sizeof(u32), sq_entries);
8015 if (sq_array_size == SIZE_MAX)
8018 if (check_add_overflow(off, sq_array_size, &off))
8024 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
8028 if (!ctx->user_bufs)
8031 for (i = 0; i < ctx->nr_user_bufs; i++) {
8032 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8034 for (j = 0; j < imu->nr_bvecs; j++)
8035 unpin_user_page(imu->bvec[j].bv_page);
8037 if (imu->acct_pages)
8038 io_unaccount_mem(ctx, imu->acct_pages);
8043 kfree(ctx->user_bufs);
8044 ctx->user_bufs = NULL;
8045 ctx->nr_user_bufs = 0;
8049 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
8050 void __user *arg, unsigned index)
8052 struct iovec __user *src;
8054 #ifdef CONFIG_COMPAT
8056 struct compat_iovec __user *ciovs;
8057 struct compat_iovec ciov;
8059 ciovs = (struct compat_iovec __user *) arg;
8060 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
8063 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
8064 dst->iov_len = ciov.iov_len;
8068 src = (struct iovec __user *) arg;
8069 if (copy_from_user(dst, &src[index], sizeof(*dst)))
8075 * Not super efficient, but this is just a registration time. And we do cache
8076 * the last compound head, so generally we'll only do a full search if we don't
8079 * We check if the given compound head page has already been accounted, to
8080 * avoid double accounting it. This allows us to account the full size of the
8081 * page, not just the constituent pages of a huge page.
8083 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
8084 int nr_pages, struct page *hpage)
8088 /* check current page array */
8089 for (i = 0; i < nr_pages; i++) {
8090 if (!PageCompound(pages[i]))
8092 if (compound_head(pages[i]) == hpage)
8096 /* check previously registered pages */
8097 for (i = 0; i < ctx->nr_user_bufs; i++) {
8098 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8100 for (j = 0; j < imu->nr_bvecs; j++) {
8101 if (!PageCompound(imu->bvec[j].bv_page))
8103 if (compound_head(imu->bvec[j].bv_page) == hpage)
8111 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
8112 int nr_pages, struct io_mapped_ubuf *imu,
8113 struct page **last_hpage)
8117 for (i = 0; i < nr_pages; i++) {
8118 if (!PageCompound(pages[i])) {
8123 hpage = compound_head(pages[i]);
8124 if (hpage == *last_hpage)
8126 *last_hpage = hpage;
8127 if (headpage_already_acct(ctx, pages, i, hpage))
8129 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
8133 if (!imu->acct_pages)
8136 ret = io_account_mem(ctx, imu->acct_pages);
8138 imu->acct_pages = 0;
8142 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
8143 struct io_mapped_ubuf *imu,
8144 struct page **last_hpage)
8146 struct vm_area_struct **vmas = NULL;
8147 struct page **pages = NULL;
8148 unsigned long off, start, end, ubuf;
8150 int ret, pret, nr_pages, i;
8152 ubuf = (unsigned long) iov->iov_base;
8153 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
8154 start = ubuf >> PAGE_SHIFT;
8155 nr_pages = end - start;
8159 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
8163 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
8168 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
8174 mmap_read_lock(current->mm);
8175 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
8177 if (pret == nr_pages) {
8178 /* don't support file backed memory */
8179 for (i = 0; i < nr_pages; i++) {
8180 struct vm_area_struct *vma = vmas[i];
8183 !is_file_hugepages(vma->vm_file)) {
8189 ret = pret < 0 ? pret : -EFAULT;
8191 mmap_read_unlock(current->mm);
8194 * if we did partial map, or found file backed vmas,
8195 * release any pages we did get
8198 unpin_user_pages(pages, pret);
8203 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
8205 unpin_user_pages(pages, pret);
8210 off = ubuf & ~PAGE_MASK;
8211 size = iov->iov_len;
8212 for (i = 0; i < nr_pages; i++) {
8215 vec_len = min_t(size_t, size, PAGE_SIZE - off);
8216 imu->bvec[i].bv_page = pages[i];
8217 imu->bvec[i].bv_len = vec_len;
8218 imu->bvec[i].bv_offset = off;
8222 /* store original address for later verification */
8224 imu->len = iov->iov_len;
8225 imu->nr_bvecs = nr_pages;
8233 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
8237 if (!nr_args || nr_args > UIO_MAXIOV)
8240 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
8242 if (!ctx->user_bufs)
8248 static int io_buffer_validate(struct iovec *iov)
8251 * Don't impose further limits on the size and buffer
8252 * constraints here, we'll -EINVAL later when IO is
8253 * submitted if they are wrong.
8255 if (!iov->iov_base || !iov->iov_len)
8258 /* arbitrary limit, but we need something */
8259 if (iov->iov_len > SZ_1G)
8265 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
8266 unsigned int nr_args)
8270 struct page *last_hpage = NULL;
8272 ret = io_buffers_map_alloc(ctx, nr_args);
8276 for (i = 0; i < nr_args; i++) {
8277 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
8279 ret = io_copy_iov(ctx, &iov, arg, i);
8283 ret = io_buffer_validate(&iov);
8287 ret = io_sqe_buffer_register(ctx, &iov, imu, &last_hpage);
8291 ctx->nr_user_bufs++;
8295 io_sqe_buffers_unregister(ctx);
8300 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
8302 __s32 __user *fds = arg;
8308 if (copy_from_user(&fd, fds, sizeof(*fds)))
8311 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
8312 if (IS_ERR(ctx->cq_ev_fd)) {
8313 int ret = PTR_ERR(ctx->cq_ev_fd);
8314 ctx->cq_ev_fd = NULL;
8321 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
8323 if (ctx->cq_ev_fd) {
8324 eventfd_ctx_put(ctx->cq_ev_fd);
8325 ctx->cq_ev_fd = NULL;
8332 static int __io_destroy_buffers(int id, void *p, void *data)
8334 struct io_ring_ctx *ctx = data;
8335 struct io_buffer *buf = p;
8337 __io_remove_buffers(ctx, buf, id, -1U);
8341 static void io_destroy_buffers(struct io_ring_ctx *ctx)
8343 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
8344 idr_destroy(&ctx->io_buffer_idr);
8347 static void io_req_cache_free(struct list_head *list, struct task_struct *tsk)
8349 struct io_kiocb *req, *nxt;
8351 list_for_each_entry_safe(req, nxt, list, compl.list) {
8352 if (tsk && req->task != tsk)
8354 list_del(&req->compl.list);
8355 kmem_cache_free(req_cachep, req);
8359 static void io_req_caches_free(struct io_ring_ctx *ctx)
8361 struct io_submit_state *submit_state = &ctx->submit_state;
8362 struct io_comp_state *cs = &ctx->submit_state.comp;
8364 mutex_lock(&ctx->uring_lock);
8366 if (submit_state->free_reqs) {
8367 kmem_cache_free_bulk(req_cachep, submit_state->free_reqs,
8368 submit_state->reqs);
8369 submit_state->free_reqs = 0;
8372 spin_lock_irq(&ctx->completion_lock);
8373 list_splice_init(&cs->locked_free_list, &cs->free_list);
8374 cs->locked_free_nr = 0;
8375 spin_unlock_irq(&ctx->completion_lock);
8377 io_req_cache_free(&cs->free_list, NULL);
8379 mutex_unlock(&ctx->uring_lock);
8382 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
8385 * Some may use context even when all refs and requests have been put,
8386 * and they are free to do so while still holding uring_lock, see
8387 * __io_req_task_submit(). Wait for them to finish.
8389 mutex_lock(&ctx->uring_lock);
8390 mutex_unlock(&ctx->uring_lock);
8392 io_sq_thread_finish(ctx);
8393 io_sqe_buffers_unregister(ctx);
8395 if (ctx->mm_account) {
8396 mmdrop(ctx->mm_account);
8397 ctx->mm_account = NULL;
8400 mutex_lock(&ctx->uring_lock);
8401 io_sqe_files_unregister(ctx);
8402 mutex_unlock(&ctx->uring_lock);
8403 io_eventfd_unregister(ctx);
8404 io_destroy_buffers(ctx);
8405 idr_destroy(&ctx->personality_idr);
8407 #if defined(CONFIG_UNIX)
8408 if (ctx->ring_sock) {
8409 ctx->ring_sock->file = NULL; /* so that iput() is called */
8410 sock_release(ctx->ring_sock);
8414 io_mem_free(ctx->rings);
8415 io_mem_free(ctx->sq_sqes);
8417 percpu_ref_exit(&ctx->refs);
8418 free_uid(ctx->user);
8419 io_req_caches_free(ctx);
8421 io_wq_put_hash(ctx->hash_map);
8422 kfree(ctx->cancel_hash);
8426 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
8428 struct io_ring_ctx *ctx = file->private_data;
8431 poll_wait(file, &ctx->cq_wait, wait);
8433 * synchronizes with barrier from wq_has_sleeper call in
8437 if (!io_sqring_full(ctx))
8438 mask |= EPOLLOUT | EPOLLWRNORM;
8441 * Don't flush cqring overflow list here, just do a simple check.
8442 * Otherwise there could possible be ABBA deadlock:
8445 * lock(&ctx->uring_lock);
8447 * lock(&ctx->uring_lock);
8450 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
8451 * pushs them to do the flush.
8453 if (io_cqring_events(ctx) || test_bit(0, &ctx->cq_check_overflow))
8454 mask |= EPOLLIN | EPOLLRDNORM;
8459 static int io_uring_fasync(int fd, struct file *file, int on)
8461 struct io_ring_ctx *ctx = file->private_data;
8463 return fasync_helper(fd, file, on, &ctx->cq_fasync);
8466 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8468 const struct cred *creds;
8470 creds = idr_remove(&ctx->personality_idr, id);
8479 static int io_remove_personalities(int id, void *p, void *data)
8481 struct io_ring_ctx *ctx = data;
8483 io_unregister_personality(ctx, id);
8487 static bool io_run_ctx_fallback(struct io_ring_ctx *ctx)
8489 struct callback_head *work, *next;
8490 bool executed = false;
8493 work = xchg(&ctx->exit_task_work, NULL);
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 } while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20));
8523 io_ring_ctx_free(ctx);
8526 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
8528 mutex_lock(&ctx->uring_lock);
8529 percpu_ref_kill(&ctx->refs);
8530 /* if force is set, the ring is going away. always drop after that */
8531 ctx->cq_overflow_flushed = 1;
8533 __io_cqring_overflow_flush(ctx, true, NULL, NULL);
8534 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
8535 mutex_unlock(&ctx->uring_lock);
8537 io_kill_timeouts(ctx, NULL, NULL);
8538 io_poll_remove_all(ctx, NULL, NULL);
8540 /* if we failed setting up the ctx, we might not have any rings */
8541 io_iopoll_try_reap_events(ctx);
8543 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
8545 * Use system_unbound_wq to avoid spawning tons of event kworkers
8546 * if we're exiting a ton of rings at the same time. It just adds
8547 * noise and overhead, there's no discernable change in runtime
8548 * over using system_wq.
8550 queue_work(system_unbound_wq, &ctx->exit_work);
8553 static int io_uring_release(struct inode *inode, struct file *file)
8555 struct io_ring_ctx *ctx = file->private_data;
8557 file->private_data = NULL;
8558 io_ring_ctx_wait_and_kill(ctx);
8562 struct io_task_cancel {
8563 struct task_struct *task;
8564 struct files_struct *files;
8567 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
8569 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8570 struct io_task_cancel *cancel = data;
8573 if (cancel->files && (req->flags & REQ_F_LINK_TIMEOUT)) {
8574 unsigned long flags;
8575 struct io_ring_ctx *ctx = req->ctx;
8577 /* protect against races with linked timeouts */
8578 spin_lock_irqsave(&ctx->completion_lock, flags);
8579 ret = io_match_task(req, cancel->task, cancel->files);
8580 spin_unlock_irqrestore(&ctx->completion_lock, flags);
8582 ret = io_match_task(req, cancel->task, cancel->files);
8587 static void io_cancel_defer_files(struct io_ring_ctx *ctx,
8588 struct task_struct *task,
8589 struct files_struct *files)
8591 struct io_defer_entry *de = NULL;
8594 spin_lock_irq(&ctx->completion_lock);
8595 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
8596 if (io_match_task(de->req, task, files)) {
8597 list_cut_position(&list, &ctx->defer_list, &de->list);
8601 spin_unlock_irq(&ctx->completion_lock);
8603 while (!list_empty(&list)) {
8604 de = list_first_entry(&list, struct io_defer_entry, list);
8605 list_del_init(&de->list);
8606 req_set_fail_links(de->req);
8607 io_put_req(de->req);
8608 io_req_complete(de->req, -ECANCELED);
8613 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
8614 struct task_struct *task,
8615 struct files_struct *files)
8617 struct io_task_cancel cancel = { .task = task, .files = files, };
8618 struct io_uring_task *tctx = current->io_uring;
8621 enum io_wq_cancel cret;
8624 if (tctx && tctx->io_wq) {
8625 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
8627 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
8630 /* SQPOLL thread does its own polling */
8631 if (!(ctx->flags & IORING_SETUP_SQPOLL) && !files) {
8632 while (!list_empty_careful(&ctx->iopoll_list)) {
8633 io_iopoll_try_reap_events(ctx);
8638 ret |= io_poll_remove_all(ctx, task, files);
8639 ret |= io_kill_timeouts(ctx, task, files);
8640 ret |= io_run_task_work();
8641 ret |= io_run_ctx_fallback(ctx);
8642 io_cqring_overflow_flush(ctx, true, task, files);
8649 static int io_uring_count_inflight(struct io_ring_ctx *ctx,
8650 struct task_struct *task,
8651 struct files_struct *files)
8653 struct io_kiocb *req;
8656 spin_lock_irq(&ctx->inflight_lock);
8657 list_for_each_entry(req, &ctx->inflight_list, inflight_entry)
8658 cnt += io_match_task(req, task, files);
8659 spin_unlock_irq(&ctx->inflight_lock);
8663 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
8664 struct task_struct *task,
8665 struct files_struct *files)
8667 while (!list_empty_careful(&ctx->inflight_list)) {
8671 inflight = io_uring_count_inflight(ctx, task, files);
8675 io_uring_try_cancel_requests(ctx, task, files);
8678 io_sq_thread_unpark(ctx->sq_data);
8679 prepare_to_wait(&task->io_uring->wait, &wait,
8680 TASK_UNINTERRUPTIBLE);
8681 if (inflight == io_uring_count_inflight(ctx, task, files))
8683 finish_wait(&task->io_uring->wait, &wait);
8685 io_sq_thread_park(ctx->sq_data);
8690 * We need to iteratively cancel requests, in case a request has dependent
8691 * hard links. These persist even for failure of cancelations, hence keep
8692 * looping until none are found.
8694 static void io_uring_cancel_task_requests(struct io_ring_ctx *ctx,
8695 struct files_struct *files)
8697 struct task_struct *task = current;
8698 bool did_park = false;
8700 if ((ctx->flags & IORING_SETUP_SQPOLL) && ctx->sq_data) {
8701 /* never started, nothing to cancel */
8702 if (ctx->flags & IORING_SETUP_R_DISABLED) {
8703 io_sq_offload_start(ctx);
8706 did_park = io_sq_thread_park(ctx->sq_data);
8708 task = ctx->sq_data->thread;
8709 atomic_inc(&task->io_uring->in_idle);
8713 io_cancel_defer_files(ctx, task, files);
8715 io_uring_cancel_files(ctx, task, files);
8717 io_uring_try_cancel_requests(ctx, task, NULL);
8720 atomic_dec(&task->io_uring->in_idle);
8721 io_sq_thread_unpark(ctx->sq_data);
8726 * Note that this task has used io_uring. We use it for cancelation purposes.
8728 static int io_uring_add_task_file(struct io_ring_ctx *ctx, struct file *file)
8730 struct io_uring_task *tctx = current->io_uring;
8733 if (unlikely(!tctx)) {
8734 ret = io_uring_alloc_task_context(current, ctx);
8737 tctx = current->io_uring;
8739 if (tctx->last != file) {
8740 void *old = xa_load(&tctx->xa, (unsigned long)file);
8744 ret = xa_err(xa_store(&tctx->xa, (unsigned long)file,
8751 /* one and only SQPOLL file note, held by sqo_task */
8752 WARN_ON_ONCE((ctx->flags & IORING_SETUP_SQPOLL) &&
8753 current != ctx->sqo_task);
8759 * This is race safe in that the task itself is doing this, hence it
8760 * cannot be going through the exit/cancel paths at the same time.
8761 * This cannot be modified while exit/cancel is running.
8763 if (!tctx->sqpoll && (ctx->flags & IORING_SETUP_SQPOLL))
8764 tctx->sqpoll = true;
8770 * Remove this io_uring_file -> task mapping.
8772 static void io_uring_del_task_file(struct file *file)
8774 struct io_uring_task *tctx = current->io_uring;
8776 if (tctx->last == file)
8778 file = xa_erase(&tctx->xa, (unsigned long)file);
8783 static void io_uring_clean_tctx(struct io_uring_task *tctx)
8786 unsigned long index;
8788 xa_for_each(&tctx->xa, index, file)
8789 io_uring_del_task_file(file);
8791 io_wq_put_and_exit(tctx->io_wq);
8796 void __io_uring_files_cancel(struct files_struct *files)
8798 struct io_uring_task *tctx = current->io_uring;
8800 unsigned long index;
8802 /* make sure overflow events are dropped */
8803 atomic_inc(&tctx->in_idle);
8804 xa_for_each(&tctx->xa, index, file)
8805 io_uring_cancel_task_requests(file->private_data, files);
8806 atomic_dec(&tctx->in_idle);
8809 io_uring_clean_tctx(tctx);
8812 static s64 tctx_inflight(struct io_uring_task *tctx)
8814 return percpu_counter_sum(&tctx->inflight);
8817 static void io_uring_cancel_sqpoll(struct io_ring_ctx *ctx)
8819 struct io_sq_data *sqd = ctx->sq_data;
8820 struct io_uring_task *tctx;
8826 if (!io_sq_thread_park(sqd))
8828 tctx = ctx->sq_data->thread->io_uring;
8829 /* can happen on fork/alloc failure, just ignore that state */
8831 io_sq_thread_unpark(sqd);
8835 atomic_inc(&tctx->in_idle);
8837 /* read completions before cancelations */
8838 inflight = tctx_inflight(tctx);
8841 io_uring_cancel_task_requests(ctx, NULL);
8843 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8845 * If we've seen completions, retry without waiting. This
8846 * avoids a race where a completion comes in before we did
8847 * prepare_to_wait().
8849 if (inflight == tctx_inflight(tctx))
8851 finish_wait(&tctx->wait, &wait);
8853 atomic_dec(&tctx->in_idle);
8854 io_sq_thread_unpark(sqd);
8858 * Find any io_uring fd that this task has registered or done IO on, and cancel
8861 void __io_uring_task_cancel(void)
8863 struct io_uring_task *tctx = current->io_uring;
8867 /* make sure overflow events are dropped */
8868 atomic_inc(&tctx->in_idle);
8872 unsigned long index;
8874 xa_for_each(&tctx->xa, index, file)
8875 io_uring_cancel_sqpoll(file->private_data);
8879 /* read completions before cancelations */
8880 inflight = tctx_inflight(tctx);
8883 __io_uring_files_cancel(NULL);
8885 prepare_to_wait(&tctx->wait, &wait, TASK_UNINTERRUPTIBLE);
8888 * If we've seen completions, retry without waiting. This
8889 * avoids a race where a completion comes in before we did
8890 * prepare_to_wait().
8892 if (inflight == tctx_inflight(tctx))
8894 finish_wait(&tctx->wait, &wait);
8897 atomic_dec(&tctx->in_idle);
8899 io_uring_clean_tctx(tctx);
8900 /* all current's requests should be gone, we can kill tctx */
8901 __io_uring_free(current);
8904 static void *io_uring_validate_mmap_request(struct file *file,
8905 loff_t pgoff, size_t sz)
8907 struct io_ring_ctx *ctx = file->private_data;
8908 loff_t offset = pgoff << PAGE_SHIFT;
8913 case IORING_OFF_SQ_RING:
8914 case IORING_OFF_CQ_RING:
8917 case IORING_OFF_SQES:
8921 return ERR_PTR(-EINVAL);
8924 page = virt_to_head_page(ptr);
8925 if (sz > page_size(page))
8926 return ERR_PTR(-EINVAL);
8933 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8935 size_t sz = vma->vm_end - vma->vm_start;
8939 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
8941 return PTR_ERR(ptr);
8943 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
8944 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
8947 #else /* !CONFIG_MMU */
8949 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
8951 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
8954 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
8956 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
8959 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
8960 unsigned long addr, unsigned long len,
8961 unsigned long pgoff, unsigned long flags)
8965 ptr = io_uring_validate_mmap_request(file, pgoff, len);
8967 return PTR_ERR(ptr);
8969 return (unsigned long) ptr;
8972 #endif /* !CONFIG_MMU */
8974 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
8980 if (!io_sqring_full(ctx))
8982 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
8984 if (!io_sqring_full(ctx))
8987 } while (!signal_pending(current));
8989 finish_wait(&ctx->sqo_sq_wait, &wait);
8993 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
8994 struct __kernel_timespec __user **ts,
8995 const sigset_t __user **sig)
8997 struct io_uring_getevents_arg arg;
9000 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
9001 * is just a pointer to the sigset_t.
9003 if (!(flags & IORING_ENTER_EXT_ARG)) {
9004 *sig = (const sigset_t __user *) argp;
9010 * EXT_ARG is set - ensure we agree on the size of it and copy in our
9011 * timespec and sigset_t pointers if good.
9013 if (*argsz != sizeof(arg))
9015 if (copy_from_user(&arg, argp, sizeof(arg)))
9017 *sig = u64_to_user_ptr(arg.sigmask);
9018 *argsz = arg.sigmask_sz;
9019 *ts = u64_to_user_ptr(arg.ts);
9023 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
9024 u32, min_complete, u32, flags, const void __user *, argp,
9027 struct io_ring_ctx *ctx;
9034 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
9035 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG))
9043 if (f.file->f_op != &io_uring_fops)
9047 ctx = f.file->private_data;
9048 if (!percpu_ref_tryget(&ctx->refs))
9052 if (ctx->flags & IORING_SETUP_R_DISABLED)
9056 * For SQ polling, the thread will do all submissions and completions.
9057 * Just return the requested submit count, and wake the thread if
9061 if (ctx->flags & IORING_SETUP_SQPOLL) {
9062 io_cqring_overflow_flush(ctx, false, NULL, NULL);
9064 if (unlikely(ctx->sqo_exec)) {
9065 ret = io_sq_thread_fork(ctx->sq_data, ctx);
9071 if (flags & IORING_ENTER_SQ_WAKEUP)
9072 wake_up(&ctx->sq_data->wait);
9073 if (flags & IORING_ENTER_SQ_WAIT) {
9074 ret = io_sqpoll_wait_sq(ctx);
9078 submitted = to_submit;
9079 } else if (to_submit) {
9080 ret = io_uring_add_task_file(ctx, f.file);
9083 mutex_lock(&ctx->uring_lock);
9084 submitted = io_submit_sqes(ctx, to_submit);
9085 mutex_unlock(&ctx->uring_lock);
9087 if (submitted != to_submit)
9090 if (flags & IORING_ENTER_GETEVENTS) {
9091 const sigset_t __user *sig;
9092 struct __kernel_timespec __user *ts;
9094 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
9098 min_complete = min(min_complete, ctx->cq_entries);
9101 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
9102 * space applications don't need to do io completion events
9103 * polling again, they can rely on io_sq_thread to do polling
9104 * work, which can reduce cpu usage and uring_lock contention.
9106 if (ctx->flags & IORING_SETUP_IOPOLL &&
9107 !(ctx->flags & IORING_SETUP_SQPOLL)) {
9108 ret = io_iopoll_check(ctx, min_complete);
9110 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
9115 percpu_ref_put(&ctx->refs);
9118 return submitted ? submitted : ret;
9121 #ifdef CONFIG_PROC_FS
9122 static int io_uring_show_cred(int id, void *p, void *data)
9124 const struct cred *cred = p;
9125 struct seq_file *m = data;
9126 struct user_namespace *uns = seq_user_ns(m);
9127 struct group_info *gi;
9132 seq_printf(m, "%5d\n", id);
9133 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
9134 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
9135 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
9136 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
9137 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
9138 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
9139 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
9140 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
9141 seq_puts(m, "\n\tGroups:\t");
9142 gi = cred->group_info;
9143 for (g = 0; g < gi->ngroups; g++) {
9144 seq_put_decimal_ull(m, g ? " " : "",
9145 from_kgid_munged(uns, gi->gid[g]));
9147 seq_puts(m, "\n\tCapEff:\t");
9148 cap = cred->cap_effective;
9149 CAP_FOR_EACH_U32(__capi)
9150 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
9155 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
9157 struct io_sq_data *sq = NULL;
9162 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
9163 * since fdinfo case grabs it in the opposite direction of normal use
9164 * cases. If we fail to get the lock, we just don't iterate any
9165 * structures that could be going away outside the io_uring mutex.
9167 has_lock = mutex_trylock(&ctx->uring_lock);
9169 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
9175 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
9176 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
9177 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
9178 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
9179 struct file *f = *io_fixed_file_slot(ctx->file_data, i);
9182 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
9184 seq_printf(m, "%5u: <none>\n", i);
9186 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
9187 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
9188 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
9190 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
9191 (unsigned int) buf->len);
9193 if (has_lock && !idr_is_empty(&ctx->personality_idr)) {
9194 seq_printf(m, "Personalities:\n");
9195 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
9197 seq_printf(m, "PollList:\n");
9198 spin_lock_irq(&ctx->completion_lock);
9199 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
9200 struct hlist_head *list = &ctx->cancel_hash[i];
9201 struct io_kiocb *req;
9203 hlist_for_each_entry(req, list, hash_node)
9204 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
9205 req->task->task_works != NULL);
9207 spin_unlock_irq(&ctx->completion_lock);
9209 mutex_unlock(&ctx->uring_lock);
9212 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
9214 struct io_ring_ctx *ctx = f->private_data;
9216 if (percpu_ref_tryget(&ctx->refs)) {
9217 __io_uring_show_fdinfo(ctx, m);
9218 percpu_ref_put(&ctx->refs);
9223 static const struct file_operations io_uring_fops = {
9224 .release = io_uring_release,
9225 .mmap = io_uring_mmap,
9227 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
9228 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
9230 .poll = io_uring_poll,
9231 .fasync = io_uring_fasync,
9232 #ifdef CONFIG_PROC_FS
9233 .show_fdinfo = io_uring_show_fdinfo,
9237 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
9238 struct io_uring_params *p)
9240 struct io_rings *rings;
9241 size_t size, sq_array_offset;
9243 /* make sure these are sane, as we already accounted them */
9244 ctx->sq_entries = p->sq_entries;
9245 ctx->cq_entries = p->cq_entries;
9247 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
9248 if (size == SIZE_MAX)
9251 rings = io_mem_alloc(size);
9256 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
9257 rings->sq_ring_mask = p->sq_entries - 1;
9258 rings->cq_ring_mask = p->cq_entries - 1;
9259 rings->sq_ring_entries = p->sq_entries;
9260 rings->cq_ring_entries = p->cq_entries;
9261 ctx->sq_mask = rings->sq_ring_mask;
9262 ctx->cq_mask = rings->cq_ring_mask;
9264 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
9265 if (size == SIZE_MAX) {
9266 io_mem_free(ctx->rings);
9271 ctx->sq_sqes = io_mem_alloc(size);
9272 if (!ctx->sq_sqes) {
9273 io_mem_free(ctx->rings);
9281 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
9285 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
9289 ret = io_uring_add_task_file(ctx, file);
9294 fd_install(fd, file);
9299 * Allocate an anonymous fd, this is what constitutes the application
9300 * visible backing of an io_uring instance. The application mmaps this
9301 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
9302 * we have to tie this fd to a socket for file garbage collection purposes.
9304 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
9307 #if defined(CONFIG_UNIX)
9310 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
9313 return ERR_PTR(ret);
9316 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
9317 O_RDWR | O_CLOEXEC);
9318 #if defined(CONFIG_UNIX)
9320 sock_release(ctx->ring_sock);
9321 ctx->ring_sock = NULL;
9323 ctx->ring_sock->file = file;
9329 static int io_uring_create(unsigned entries, struct io_uring_params *p,
9330 struct io_uring_params __user *params)
9332 struct io_ring_ctx *ctx;
9338 if (entries > IORING_MAX_ENTRIES) {
9339 if (!(p->flags & IORING_SETUP_CLAMP))
9341 entries = IORING_MAX_ENTRIES;
9345 * Use twice as many entries for the CQ ring. It's possible for the
9346 * application to drive a higher depth than the size of the SQ ring,
9347 * since the sqes are only used at submission time. This allows for
9348 * some flexibility in overcommitting a bit. If the application has
9349 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
9350 * of CQ ring entries manually.
9352 p->sq_entries = roundup_pow_of_two(entries);
9353 if (p->flags & IORING_SETUP_CQSIZE) {
9355 * If IORING_SETUP_CQSIZE is set, we do the same roundup
9356 * to a power-of-two, if it isn't already. We do NOT impose
9357 * any cq vs sq ring sizing.
9361 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
9362 if (!(p->flags & IORING_SETUP_CLAMP))
9364 p->cq_entries = IORING_MAX_CQ_ENTRIES;
9366 p->cq_entries = roundup_pow_of_two(p->cq_entries);
9367 if (p->cq_entries < p->sq_entries)
9370 p->cq_entries = 2 * p->sq_entries;
9373 ctx = io_ring_ctx_alloc(p);
9376 ctx->compat = in_compat_syscall();
9377 if (!capable(CAP_IPC_LOCK))
9378 ctx->user = get_uid(current_user());
9379 ctx->sqo_task = current;
9382 * This is just grabbed for accounting purposes. When a process exits,
9383 * the mm is exited and dropped before the files, hence we need to hang
9384 * on to this mm purely for the purposes of being able to unaccount
9385 * memory (locked/pinned vm). It's not used for anything else.
9387 mmgrab(current->mm);
9388 ctx->mm_account = current->mm;
9390 ret = io_allocate_scq_urings(ctx, p);
9394 ret = io_sq_offload_create(ctx, p);
9398 if (!(p->flags & IORING_SETUP_R_DISABLED))
9399 io_sq_offload_start(ctx);
9401 memset(&p->sq_off, 0, sizeof(p->sq_off));
9402 p->sq_off.head = offsetof(struct io_rings, sq.head);
9403 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
9404 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
9405 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
9406 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
9407 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
9408 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
9410 memset(&p->cq_off, 0, sizeof(p->cq_off));
9411 p->cq_off.head = offsetof(struct io_rings, cq.head);
9412 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
9413 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
9414 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
9415 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
9416 p->cq_off.cqes = offsetof(struct io_rings, cqes);
9417 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
9419 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
9420 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
9421 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
9422 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9423 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS;
9425 if (copy_to_user(params, p, sizeof(*p))) {
9430 file = io_uring_get_file(ctx);
9432 ret = PTR_ERR(file);
9437 * Install ring fd as the very last thing, so we don't risk someone
9438 * having closed it before we finish setup
9440 ret = io_uring_install_fd(ctx, file);
9442 /* fput will clean it up */
9447 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
9450 io_ring_ctx_wait_and_kill(ctx);
9455 * Sets up an aio uring context, and returns the fd. Applications asks for a
9456 * ring size, we return the actual sq/cq ring sizes (among other things) in the
9457 * params structure passed in.
9459 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
9461 struct io_uring_params p;
9464 if (copy_from_user(&p, params, sizeof(p)))
9466 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
9471 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
9472 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
9473 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
9474 IORING_SETUP_R_DISABLED))
9477 return io_uring_create(entries, &p, params);
9480 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
9481 struct io_uring_params __user *, params)
9483 return io_uring_setup(entries, params);
9486 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
9488 struct io_uring_probe *p;
9492 size = struct_size(p, ops, nr_args);
9493 if (size == SIZE_MAX)
9495 p = kzalloc(size, GFP_KERNEL);
9500 if (copy_from_user(p, arg, size))
9503 if (memchr_inv(p, 0, size))
9506 p->last_op = IORING_OP_LAST - 1;
9507 if (nr_args > IORING_OP_LAST)
9508 nr_args = IORING_OP_LAST;
9510 for (i = 0; i < nr_args; i++) {
9512 if (!io_op_defs[i].not_supported)
9513 p->ops[i].flags = IO_URING_OP_SUPPORTED;
9518 if (copy_to_user(arg, p, size))
9525 static int io_register_personality(struct io_ring_ctx *ctx)
9527 const struct cred *creds;
9530 creds = get_current_cred();
9532 ret = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
9533 USHRT_MAX, GFP_KERNEL);
9539 static int io_register_restrictions(struct io_ring_ctx *ctx, void __user *arg,
9540 unsigned int nr_args)
9542 struct io_uring_restriction *res;
9546 /* Restrictions allowed only if rings started disabled */
9547 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9550 /* We allow only a single restrictions registration */
9551 if (ctx->restrictions.registered)
9554 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
9557 size = array_size(nr_args, sizeof(*res));
9558 if (size == SIZE_MAX)
9561 res = memdup_user(arg, size);
9563 return PTR_ERR(res);
9567 for (i = 0; i < nr_args; i++) {
9568 switch (res[i].opcode) {
9569 case IORING_RESTRICTION_REGISTER_OP:
9570 if (res[i].register_op >= IORING_REGISTER_LAST) {
9575 __set_bit(res[i].register_op,
9576 ctx->restrictions.register_op);
9578 case IORING_RESTRICTION_SQE_OP:
9579 if (res[i].sqe_op >= IORING_OP_LAST) {
9584 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
9586 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
9587 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
9589 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
9590 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
9599 /* Reset all restrictions if an error happened */
9601 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
9603 ctx->restrictions.registered = true;
9609 static int io_register_enable_rings(struct io_ring_ctx *ctx)
9611 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
9614 if (ctx->restrictions.registered)
9615 ctx->restricted = 1;
9617 io_sq_offload_start(ctx);
9621 static bool io_register_op_must_quiesce(int op)
9624 case IORING_UNREGISTER_FILES:
9625 case IORING_REGISTER_FILES_UPDATE:
9626 case IORING_REGISTER_PROBE:
9627 case IORING_REGISTER_PERSONALITY:
9628 case IORING_UNREGISTER_PERSONALITY:
9635 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
9636 void __user *arg, unsigned nr_args)
9637 __releases(ctx->uring_lock)
9638 __acquires(ctx->uring_lock)
9643 * We're inside the ring mutex, if the ref is already dying, then
9644 * someone else killed the ctx or is already going through
9645 * io_uring_register().
9647 if (percpu_ref_is_dying(&ctx->refs))
9650 if (io_register_op_must_quiesce(opcode)) {
9651 percpu_ref_kill(&ctx->refs);
9654 * Drop uring mutex before waiting for references to exit. If
9655 * another thread is currently inside io_uring_enter() it might
9656 * need to grab the uring_lock to make progress. If we hold it
9657 * here across the drain wait, then we can deadlock. It's safe
9658 * to drop the mutex here, since no new references will come in
9659 * after we've killed the percpu ref.
9661 mutex_unlock(&ctx->uring_lock);
9663 ret = wait_for_completion_interruptible(&ctx->ref_comp);
9666 ret = io_run_task_work_sig();
9671 mutex_lock(&ctx->uring_lock);
9674 percpu_ref_resurrect(&ctx->refs);
9679 if (ctx->restricted) {
9680 if (opcode >= IORING_REGISTER_LAST) {
9685 if (!test_bit(opcode, ctx->restrictions.register_op)) {
9692 case IORING_REGISTER_BUFFERS:
9693 ret = io_sqe_buffers_register(ctx, arg, nr_args);
9695 case IORING_UNREGISTER_BUFFERS:
9699 ret = io_sqe_buffers_unregister(ctx);
9701 case IORING_REGISTER_FILES:
9702 ret = io_sqe_files_register(ctx, arg, nr_args);
9704 case IORING_UNREGISTER_FILES:
9708 ret = io_sqe_files_unregister(ctx);
9710 case IORING_REGISTER_FILES_UPDATE:
9711 ret = io_sqe_files_update(ctx, arg, nr_args);
9713 case IORING_REGISTER_EVENTFD:
9714 case IORING_REGISTER_EVENTFD_ASYNC:
9718 ret = io_eventfd_register(ctx, arg);
9721 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
9722 ctx->eventfd_async = 1;
9724 ctx->eventfd_async = 0;
9726 case IORING_UNREGISTER_EVENTFD:
9730 ret = io_eventfd_unregister(ctx);
9732 case IORING_REGISTER_PROBE:
9734 if (!arg || nr_args > 256)
9736 ret = io_probe(ctx, arg, nr_args);
9738 case IORING_REGISTER_PERSONALITY:
9742 ret = io_register_personality(ctx);
9744 case IORING_UNREGISTER_PERSONALITY:
9748 ret = io_unregister_personality(ctx, nr_args);
9750 case IORING_REGISTER_ENABLE_RINGS:
9754 ret = io_register_enable_rings(ctx);
9756 case IORING_REGISTER_RESTRICTIONS:
9757 ret = io_register_restrictions(ctx, arg, nr_args);
9765 if (io_register_op_must_quiesce(opcode)) {
9766 /* bring the ctx back to life */
9767 percpu_ref_reinit(&ctx->refs);
9769 reinit_completion(&ctx->ref_comp);
9774 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
9775 void __user *, arg, unsigned int, nr_args)
9777 struct io_ring_ctx *ctx;
9786 if (f.file->f_op != &io_uring_fops)
9789 ctx = f.file->private_data;
9793 mutex_lock(&ctx->uring_lock);
9794 ret = __io_uring_register(ctx, opcode, arg, nr_args);
9795 mutex_unlock(&ctx->uring_lock);
9796 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
9797 ctx->cq_ev_fd != NULL, ret);
9803 static int __init io_uring_init(void)
9805 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
9806 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
9807 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
9810 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
9811 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
9812 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
9813 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
9814 BUILD_BUG_SQE_ELEM(1, __u8, flags);
9815 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
9816 BUILD_BUG_SQE_ELEM(4, __s32, fd);
9817 BUILD_BUG_SQE_ELEM(8, __u64, off);
9818 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
9819 BUILD_BUG_SQE_ELEM(16, __u64, addr);
9820 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
9821 BUILD_BUG_SQE_ELEM(24, __u32, len);
9822 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
9823 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
9824 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
9825 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
9826 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
9827 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
9828 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
9829 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
9830 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
9831 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
9832 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
9833 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
9834 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
9835 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
9836 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
9837 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
9838 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
9839 BUILD_BUG_SQE_ELEM(42, __u16, personality);
9840 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
9842 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
9843 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
9844 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
9848 __initcall(io_uring_init);